How can I tell if variable is defined
Peter Otten
__peter__ at web.de
Tue Sep 22 16:55:20 EDT 2009
Brown, Rodrick wrote:
> How could I do the following check in Python
>
> In Perl I could do something like if ((defined($a)) { ... }
>
> I tried if var is not None:
> However this doesn't seem to work as described.
But in Python this often is the most idiomatic way to check whether a
variable was set explicitly. Example:
>>> def foo(a=None):
... if a is None:
... print "using default"
... else:
... print "using a =", a
...
>>> foo()
using default
>>> foo(42)
using a = 42
If you tell us what you are actually trying to do we can probably come up
with a solution that is better than the literal answer
try:
a
except NameError:
a_is_defined = False
else:
a_is_defined = True
Peter
More information about the Python-list
mailing list