How can I tell if variable is defined

Mel mwilson at the-wire.com
Tue Sep 22 17:33:46 EDT 2009


Peter Otten wrote:
> 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)) { ... }
>>> 
[ ... ]
> This is an artifact of the interactive interpreter,

True.  You can avoid the artifact by wrapping the test in a function:

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):
...     return b
... 
>>> def is_defined (obj):
...   try:
...     obj
...   except NameError:
...     return False
...   return True
... 
>>> a = A()
>>> if is_defined (a):
...   print "`a` is defined"
... else:
...   print "`a` is not defined"
... 
`a` is defined
>>> if is_defined (b):
...   print "`b` is defined"
... else:
...   print "`b` is not defined"
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> 

At the cost of it not quite working when the function is called with an 
undefined name.  I suppose the print statements could be crafted to make it 
look better.


	Mel.






More information about the Python-list mailing list