2

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?

Community
  • 1
  • 1
Sait
  • 19,045
  • 18
  • 72
  • 99
  • 2
    Python doesn't have static variables, so... you don't. – Wooble Feb 28 '14 at 14:52
  • There's no such thing as a static variable in python - a variable on a class is simply called a class variable. No `null` either (it's called `None`). Also, you're looking for `hasattr`. – l4mpi Feb 28 '14 at 14:53
  • also, how can a class' attribute be assigned before the `__init__` function call? – Dunno Feb 28 '14 at 14:53
  • Technically `A.var` is a class variable, not a static variable. – holdenweb Feb 28 '14 at 14:54

1 Answers1

10

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)

bereal
  • 32,519
  • 6
  • 58
  • 104
  • the `try... except` approach is so easy and simple I can't understand why someone would look for anything else – Dunno Feb 28 '14 at 14:55
  • 2
    Upvoted for `hasattr`, although I disagree with prefering the `try/except` approach - `hasattr` is shorter, more readable and more explicit. – l4mpi Feb 28 '14 at 14:55
  • After a little more thought I think the EAFP approach is not only disagreeable but simply wrong in this case. You're not doing anything that requires permission as setting the attribute is always possible (given `A` has no restrictions on setting attributes of course). Thus you even have to use a nonsensical statement, accessing the attribute without using it in any way, to test for "permission". But actually you just want to check if a condition is met, with the condition being "attribute x has been set" - which directly translates to the above if statement. – l4mpi Feb 28 '14 at 16:20
  • @l4mpi yes, apparently, in this case you're right. On the other hand, if we had a function than returns `A.var` and sets the attribute if it's missing, `try...catch` would make more sense. – bereal Feb 28 '14 at 17:20