How to check the exists of a name?

Steven D'Aprano steve at
Sun Oct 18 10:19:50 CEST 2009

On Sat, 17 Oct 2009 23:30:02 -0700, StarWing wrote:

> Sometimes I want to make a simple flags. and i need to check there is a
> name in current scope or not (that is, we can visit this name, no matter
> where is it). and how to do that in python?

(1) Use a sentinel:

myname = None  # always exists
# much later
if myname is None:
    print "initialising myname"

(2) Try it and see:

except NameError:
    print "myname does not exist"
    print "myname exists"

(3) Look Before You Leap:

# inside a class:
'myname' in self.__dict__ or self.__class__.__dict__

# better, because it uses inheritance and supports __slots__:
hasattr(self, 'myname')

# inside a function
'myname' in locals()
'myname' in globals()


More information about the Python-list mailing list