defined test?

François Pinard pinard at iro.umontreal.ca
Wed May 24 21:56:17 CEST 2000


msoulier at nortelnetworks.com (Michael P. Soulier) writes:

> Ok, I'm currently a Perl programmer who's looking into Python.  I was
> wondering, is there an equivalent of the defined() function in Python,
> to test if a given variable name is defined?

You surely can.  For example:

   >>> def zorglub():
   ...      print locals().has_key('x')
   ...      x = 3
   ...      print locals().has_key('x')
   ...
   >>> zorglub()
   0
   1

But I would advise against such trickery.  What I often do is initialising
variables to `None', which is some kind of neutral value, and check whether
`x is None' or `x is not None', as needed.  I did not find a case so far
(and I surely wrote a lot of Python by now) where I _really_ needed to
distinguish between None and not defined.  Working around the difficulty
invariably yields nicer code, and this is a worthy side effect in itself.

You'll discover that Python is better than Perl, if you allow it to be! :-)

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list