Check if variable is defined

François Pinard pinard at iro.umontreal.ca
Thu May 17 08:35:37 EDT 2001


[Fredrik Lundh]

> Todd A. Jacobs wrote:
> > I'm having a lot of trouble doing something that was simple in Perl:
> > specifically, I want to create if/else clauses that take action only if a
> > particular variable is undefined. How do I check to see if a variable or
> > object has already been defined?

> that's extremely bad style in Python, but you probably knew that.

The "extremely" might be debatable. :-)

> (there are exceptions to this rule, e.g. if you're using a module as
> a configuration file.  in that case, use vars() or getattr() to treat
> the module as a dictionary).

I once wondered if vars(), locals() or globals() have a time cost to
produce the dictionary in a usable format, and how this time cost would
compare with a "try ... except NameError: ...", but did not dare to run
small benchmarks.  Would someone already know?

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




More information about the Python-list mailing list