views:

92

answers:

2

I am reading a million plus files to scrape out some data. The files are generally pretty uniform but there are occasional problems where something that I expected to find is not present.

For example, I expect some sgml code to identify a value I need

for data_line in temp  #temp is a list of lines from a file
    if <VARIABLENAME> in data_line:
        VARIABLE_VAL=data_line.split('>')[-1]

Later on I use VARIABLE_VAL in a dictionary that I am using to preserve the data I have extracted.

myDict['identifier']=[VARIABLE_VAL]

So I am humming along and I get to an exception- no line in the file that has

<VARIABLENAME>theName

So to handle this I have added this line after all the lines have been processed

try:
    if VARIABLE_VAL:
        pass
except NameError:
    VARIABLE_VAL=somethingELSE

The reason I posted this is I was sure that I have seen somewhere a solution that looks like

if not VARIABLE_VAL:
    VARIABLE_VAL=somethingELSE

But I could not get that to work after beating my head against the monitor for thirty minutes.

Any help would be appreciated

+7  A: 

Just initialize your variable to its default value before the loop:

VARIABLE_VAL = somethingELSE
for dataline in temp: ...

this way, VARIABLE_VAL will keep its initial, default value unless bound to something else within the loop, and you need no weird testing whatsoever to ensure that.

Alex Martelli
Thanks Alex, so given that you gave the answer the construct I imagined was just that, imagination
PyNEwbie
+2  A: 

Alex's solution is correct. But just in case you do want to test if a variable exists, try:

if 'VARIABLE_VAL' in locals():
    ....
catchmeifyoutry
What about if 'VARIABLE_VAL' not in locals() - this is a great answer because now I have something new to play with. I mean now I get to learn what locals is and can do for me Thanks a lot.
PyNEwbie
There is also globals() which contains variables from the global namespace. Take a look here for some more info: http://www.faqs.org/docs/diveintopython/dialect_locals.htmlGood luck!
catchmeifyoutry
Thanks a lot, that is really neat and I see that it deserves some poking around
PyNEwbie