Unable to set a property of a class as a default parameter for a subclass
Closed this issue · 3 comments
Bug report
Bug description:
While developing one of my personal projects I encountered this unexpected and unintuitive behaviour:
I could not use a class variable of a parent class as a default argument of one of his sub classes.
class Parent_Class:
a = 1
class Sub_Class:
def method(x = Parent_Class.a): #! "Parent_Class" is not defined
...
I think this is not intended as it is not intuitive nor logical, therefore I frame it as a bug.
Hoping to help.
CPython versions tested on:
3.13
Operating systems tested on:
Windows
A class is only created after evaluating the body of the class statement, because of this Parent_Class
does not exist yet when defining Sub_Class.method
.
This cannot be changed because of the flexibility of Python's class model. In particular, the actual creation of the class is done by calling the meta class (in general type
) with a dictionary containing all naming bindings from the class body (the actual protocol is more complicated, see the language reference for a more detailed explanation)
Right, this is a misunderstanding, not a bug. We don't need more info from the OP to decide whether to change code. On the other hand, this misunderstanding is not unique. Should we follow "The class name is bound to this class object in the original local namespace." with "Thus, the class name cannot be used in the class body to define class attributes." Or is this either too obvious or still too obscure? I am on the fence and quite willing to leave as is.
Right, this is a misunderstanding, not a bug. We don't need more info from the OP to decide whether to change code. On the other hand, this misunderstanding is not unique. Should we follow "The class name is bound to this class object in the original local namespace." with "Thus, the class name cannot be used in the class body to define class attributes." Or is this either too obvious or still too obscure? I am on the fence and quite willing to leave as is.
I'd leave the text as is. The text is terse, but is the language reference after all.