Establishing if an Object is Defined

Bruno Desthuilliers bruno.desthuilliers at websiteburo.com
Wed Jan 10 10:42:09 CET 2007


bg_ie at yahoo.com a écrit :
> Hi,
> 
> The following code works -
> 
> one = 1
> if one == 1:
>   ok = 1
> print ok
> 
> but this does not, without exception -
> 
> one = 2

Are you competing for the Most Misleading Name Award(tm) ?-)

> if one == 1:
>   ok = 1
> print ok
> 
> How do I establish before printing ok if it actually exists so as to
> avoid this exception?

The simplest way is to make sure the name will be defined whatever the 
value of the test:

one = 42
# ...
ok = (one == 1)
print ok


As a side note, if you want to check wether a name exists in the current 
namespace, you can use a try/except block:

try:
   toto
   print "toto is defined"
except NameError:
   print "toto is not defined"



More information about the Python-list mailing list