Jsevillamol
Jsevillamol

Reputation: 2563

Initializing a static field in a Python class

I want to initialize a static field on declaration.

class Test:

    def _init_foo(): return 3

    foo = { _init_foo() for i in range(10)}

However, the interpreter is complaining

NameError: name '_init_foo' is not defined

How do I fix this?

Upvotes: 3

Views: 1253

Answers (2)

Ferran Maylinch
Ferran Maylinch

Reputation: 11529

Before finding the class decorator option, I was initialising fields after the class declaration. I don't know which one I like less... :) I miss a static init block like in Java.

class Box:

    def __init__(self, x):
        self.x = x
        Box.count += 1  # static field usage

    @staticmethod
    def instance_count():
        return Box.count  # static field usage

Box.count = 0  # static field initialisation

b1 = Box(10)
b2 = Box(20)
print(Box.count)  # 2

Upvotes: 2

unutbu
unutbu

Reputation: 880547

Why this fails is explained here.

You could work around the problem by defining foo via a class decorator. This works because by the time add_foo is called, the class has been defined and _init_foo in then accessible as cls._init_foo:

def add_foo(cls):
    cls.foo = { cls._init_foo() for i in range(10) }
    return cls

@add_foo
class Test:

    def _init_foo(): return 3


print(Test.foo)
# {3}

Upvotes: 4

Related Questions