Skip to content

TypeError when raising an exception inside the __init__ method of an enum class #125259

Closed

Description

@Viicos

Bug report

Bug description:

With #111815, any exception raised inside the __init__ method of an enum class 1 is expected to be:

  1. instantiable (not the case with Pydantic ValidationErrors, see Python 3.12 Enum Class Validated Initialization TypeError pydantic/pydantic#10593)
  2. instantiable and expected to take a single argument.

cpython/Lib/enum.py

Lines 556 to 566 in 120b891

try:
exc = None
classdict['_%s__in_progress' % cls] = True
enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
classdict['_%s__in_progress' % cls] = False
delattr(enum_class, '_%s__in_progress' % cls)
except Exception as e:
# since 3.12 the line "Error calling __set_name__ on '_proto_member' instance ..."
# is tacked on to the error instead of raising a RuntimeError
# recreate the exception to discard
exc = type(e)(str(e))

Meaning the following raises a TypeError instead of the expected MyValueError:

class MyValueError(ValueError):
    def __init__(self, t: str, v: int) -> None:
        self.t = t
        self.v = v

class ValidatedEnum(Enum):
    def __init__(self, value):
        raise MyValueError("", 1)


class MyValidatedEnum(ValidatedEnum):
    FOO = "foo"

# TypeError: MyValueError.__init__() missing 1 required positional argument: 'v'

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Linked PRs

Footnotes

  1. An example is documented as an example here. ↩

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on Oct 10, 2024
  2. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Oct 21, 2024
  3. added a commit that references this issue on Oct 22, 2024
  4. added a commit that references this issue on Oct 22, 2024
  5. added 3 commits that reference this issue on Oct 25, 2024
  6. added a commit that references this issue on Jan 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.12only security fixes3.13only security fixes3.14bugs and security fixesstdlibStandard 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