-
-
Notifications
You must be signed in to change notification settings - Fork 33.8k
Closed as not planned
Closed as not planned
Copy link
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
Description
Bug report
Bug description:
Hello,
The documentation says:
__init_subclass__(cls, **kwds)
A classmethod that is used to further configure subsequent subclasses. By default, does nothing.
This would be useful for configuring Enum subclasses and enum members, but it doesn't work as I expected. This method is called after the __new__ or __init__ methods are called, which makes it practically useless for Enum classes.
Even if this is expected behavior, there are questions:
- The documentation does not mention this, or it is written too vaguely (used to further configure).
- This contradicts how this method works in normal classes. It is clear that in normal classes, the
__new__and__init__methods are called when instances are created, and in this respect their behavior also differs from Enum classes. However, the order of__init_subclass__method calls in Enum classes still does not seem logical.
Here is a minimal example what I mean:
from enum import Enum
class Foo(Enum):
def __init_subclass__(cls, /, **kwargs):
super().__init_subclass__(**kwargs)
print('222:', cls)
def __init__(self, value):
print('111:', value)
class Bar(Foo):
a = 1
b = 2For this code, we get:
111: 1
111: 2
222: <enum 'Bar'>
Therefore, I cannot use __init_subclass__ method before the Enum class and its members are configured.
For example, I would like to do something like that:
class Foo(Enum):
def __init_subclass__(cls, /, prefix, **kwargs):
super().__init_subclass__(**kwargs)
cls._prefix = prefix
def __init__(self, value):
self._value_ = f'{type(self)._prefix}{value}'
class Bar(Foo, prefix='bar/'):
a = 'a'
b = 'b'
print(Bar.a)
<Bar.a: 'bar/a'>
print(Bar.a.value)
'bar/a'I am currently implementing similar logic through nonmember.
CPython versions tested on:
3.13
Operating systems tested on:
No response
Metadata
Metadata
Assignees
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory