How to check the exists of a name?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
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"
else:
    process(myname)


(2) Try it and see:

try:
    myname
except NameError:
    print "myname does not exist"
else:
    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()




-- 
Steven



More information about the Python-list mailing list