Python 3 doesn't allow you to reference a class inside its body (except in methods):
class A:
static_attribute = A()
def __init__(self):
...
This raises a NameError
in the second line because 'A' is not defined
.
Alternatives
I have quickly found one workaround:
class A:
@property
@classmethod
def static_property(cls):
return A()
def __init__(self):
...
Although this isn't exactly the same since it returns a different instance every time (you could prevent this by saving the instance to a static variable the first time).
Are there simpler and/or more elegant alternatives?
EDIT: I have moved the question about the reasons for this restriction to a separate question