Test the existence of a variable?

Jp Calderone exarkun at divmod.com
Fri Sep 3 09:28:20 EDT 2004


Robin Becker wrote:
> Thierry S. wrote:
> 
>> Hello.
>>
>> I would to test the existence of a variable before to use it (like
>> isset($myVar) in PHP).
>> I try using "if myVar: ", but there is the error meesage (naturally):
>> "NameError: name 'myVar' is not defined"
>>
>> Please, could you tell me what for function exist to test the variable 
>> with
>> Python?
>>
>> Regards,
> 
> if globals().has_key('myVar'):
>     ....
> 


 >>> def f(x):
...     if globals().has_key('x'):
...             print 'x is', x
...     else:
...             print 'x is not defined'
...
 >>> f(10)
x is not defined

   Before anyone points out locals(), I know all about it.

   Testing for the existence of a variable is something to avoid doing. 
  Variables should be bound unconditionally.  There is always a sentinel 
value that can be used as a place-holder.

   Instead of:

     # ...
     if not isset('x'):
         # initialize x
     # use x

   use:

     x = None
     # ...
     if x is None:
         # initialize x
     # use x

   If None is a valid value for x to take on, pick another sentinel. 
Even better is to pick a legitimate and useful value and just write the 
whole thing as:

     x = default
     # use x

   Often this is not possible... but often it is.

   If it is really necessary to check for the existence of a variable by 
name, for example if the variable name taken from user input, then you 
may actually wish to use a dict, instead of variables in your local scope:

     d = {}
     # Get user input, store it in x
     if x not in d:
         d[x] = initialize()
     # use d[x]

   Jp


   Jp



More information about the Python-list mailing list