How can I tell if variable is defined

Peter Otten __peter__ at web.de
Tue Sep 22 17:01:50 EDT 2009


Mel wrote:

> 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

Superfluous global statement.

> ...     return b
> ...
>>>> a = A()
>>>> try:
> ...   a
> ... except NameError:
> ...   print "`a` is not defined"
> ...
> `a` is not defined

This is an artifact of the interactive interpreter, like the following way 
to print 42:

>>> for i in range(3): 42
...
42
42
42

Peter




More information about the Python-list mailing list