Reputation: 19815
This is a related question: How do I check if a variable exists?
However, it did not work well for static variables.
What I am trying to do is the following,
class A:
def __init__(self):
if A.var is null: # this does not work, okay
A.var = 'foo'
print 'assigned'
Okay, since A.var
is not even assigned. It raises en error. So, I tried this:
class A:
def __init__(self):
if 'A.var' not in globals(): # this seems to okay, but ..
A.var = 'foo'
print 'assigned'
a = A()
b = A()
It results:
assigned
assigned
Which shows that if 'A.var' not in globals():
line not working properly.
So, how do I check if a static variable exists in Python?
Upvotes: 2
Views: 3156
Reputation: 34292
Either you use hasattr
:
if not hasattr(A, 'var'):
A.var = 'foo'
or, as some would prefer according to the "Easier to ask for forgiveness than permission" principle:
try:
A.var
except NameError:
A.var = 'foo'
Finally, you can simply define the default value in the class body:
class A(object):
var = None
...
if A.var is None:
a.var = 'foo'
(Note that neither approach is thread-safe)
Upvotes: 10