Check if variable is defined

Fredrik Lundh fredrik at pythonware.com
Thu May 17 05:06:07 EDT 2001


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.

while you use reflection to do this, the right way is to *initialize*
the variable to a known sentinel value (e.g None), and test for that
value.

NameError and UnboundLocalError exceptions should be treated as
bugs.  They're no different than SyntaxErrors.

(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).

Cheers /F





More information about the Python-list mailing list