Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Open
Labels
stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error
@espdev

Description

@espdev

Bug report

Bug description:

Hello,

The documentationsays:

__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 tofurther 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 wheninstances 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:

fromenumimportEnumclassFoo(Enum):def__init_subclass__(cls,/,**kwargs):super().__init_subclass__(**kwargs)print('222:',cls)def__init__(self,value):print('111:',value)classBar(Foo):a=1b=2

For this code, we get:

111: 1111: 2222: <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:

classFoo(Enum):def__init_subclass__(cls,/,prefix,**kwargs):super().__init_subclass__(**kwargs)cls._prefix=prefixdef__init__(self,value):self._value_=f'{type(self)._prefix}{value}'classBar(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 throughnonmember.

CPython versions tested on:

3.13

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp