Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to test for existence of a variable in Python [duplicate]

Tags:

python

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. But I sometimes get an exception: no line in the file that has

<VARIABLENAME>theName

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

I have seen somewhere (but I can't find it anymore) a solution that looks like

if not VARIABLE_VAL:
    VARIABLE_VAL=somethingELSE

Any help would be appreciated

like image 280
PyNEwbie Avatar asked Dec 12 '22 20:12

PyNEwbie


1 Answers

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.

like image 198
Alex Martelli Avatar answered Feb 01 '23 08:02

Alex Martelli