How can I tell if variable is defined

Mel mwilson at the-wire.com
Tue Sep 22 16:48:09 EDT 2009


Grant Edwards wrote:

> On 2009-09-22, Brown, Rodrick <rodrick.brown at citi.com> wrote:
> 
>> How could I do the following check in Python
>>
>> In Perl I could do something like if ((defined($a)) { ... }
> 
> try:
>     yourNameHere
> except NameError:
>     print "undefined"
> else:
>     print "defined"

This being Python, however, it can be fooled:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A():
...   def __repr__ (self):
...     global b
...     return b
... 
>>> a = A()
>>> try:
...   a
... except NameError:
...   print "`a` is not defined"
... 
`a` is not defined




	Mel.




More information about the Python-list mailing list