Newbie: is a variable defined?

Lemniscate d_blade8 at hotmail.com
Fri Dec 20 17:57:05 EST 2002


Hmmm, Nicodemus is correct, however, in this case, I would lean more
towards querying dir() as in "blah" in dir.

I ran into a similar issue a while back.  My boss wanted to be able to
generate an XML table that could take a unlimited number and type of
entries.  There would be a dozen or so 'common' data types that should
be handled specially, but there was no way to know if a variable
existed.  For example, somebody might enter a datatype
'JohnBonJovi_BirthDay'.  Since arbitrary names could be added at any
point, I couldn't initialize everything to None (actually, I could, I
just had to redo some of the code, which I did later, but I digress). 
I thought about throwing in some error handling (something like
try:...except NameError) but in the end I did something like:

>>> a = 'ten'
>>> b = 'twenty'
>>> if 'a' in dir():
... 	print a
... 	
ten
>>> if 'c' in dir():
... 	print c
... 	
>>> if 'b' in dir():
... 	print b
... 	
twenty
>>> 

This way, no errors popped up if a variable didn't exist.  On a
similar note, if you use something like Bulgarian notation (i.e., all
variables of a certain type start off in a similar fashion, you can
query the list returned by dir() directly and move on from there as in
(untested):
for x in dir():
        if x[0] == 'q':
                print "%s is a type 'q' variable" % x

Just my $0.02.

Lem






Nicodemus <nicodemus at globalite.com.br> wrote in message news:<mailman.1040413473.24131.python-list at python.org>...
> Christopher Swingley wrote:
> 
> >Greetings,
> >
> >
> >Longer version: What I'm trying to do is parse a file that may or may 
> >not contain an email address.  If it does, I use regular expressions to 
> >extract the username portion of the email address and place this in a 
> >variable named 'efrom'.  Later, I want to search a SQL database, and if 
> >'efrom' has been defined it will perform one SELECT and if it's not 
> >it'll do something else.
> >
> >I could set up a seperate flag 'efrom_defined = 0', update it when efrom 
> >gets a value, and then test this flag.  Or I could use a 'try: except 
> >NameError:' block.  Or I could do 'efrom = ""' at the beginning of the 
> >program and then test 'if len(efrom):'
> >
> >How would you do this?
> >
> 
> Hail!
> 
> You can do what you want by checking if the variable has an entry in the 
> locals dir:
> 
>  >>> 'efrom' in locals()
>  0
>  >>> efrom = 10
>  >>> 'efrom' in locals()
> 1
> 
> But I would recommend against that.
> 
> The standard way is to initialize all the variables with None, and then 
> check later if they were
> initialized with something else.
> 
>  >>> efrom = None
>  >>> efrom = 'xx at xx.com'
>  # later...
>  >>> if efrom is not None:
> ...    # use 'efrom' variable here
> 
> 
> 
> Farewell,
> Nicodemus.



More information about the Python-list mailing list