How can I tell if variable is defined

Dave Angel davea at
Tue Sep 22 22:16:45 CEST 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.
> Thanks.

Or look up the attribute in the appropriate dictionary(ies).

def test():
    newvar = 42
    if "newvar" in locals():
        print "yes"


More information about the Python-list mailing list