Skip to content

__init_subclass__ method is called after __new__ and __init__ methods in Enum classes #142082

@espdev

Description

@espdev

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:

  1. The documentation does not mention this, or it is written too vaguely (used to further configure).
  2. 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 = 2

For 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/ directory

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions