KEMBAR78
Bug when type checking dynamic enum creation in a metaclass · Issue #18736 · python/mypy · GitHub
Skip to content

Bug when type checking dynamic enum creation in a metaclass #18736

@ahernot

Description

@ahernot

Ran into this bug while type-checking a meta class which dynamically creates and stores an enum of all the target class' properties which are also decorated with a custom @ocr_series:

from pydantic import BaseModel
from pydantic._internal._model_construction import ModelMetaclass
from enum import Enum

class OCRContentMeta(ModelMetaclass):
    def __new__(mcs, name, bases, namespace):
        cls = super().__new__(mcs, name, bases, namespace)

        # Collect all ocr_series cached_properties
        series_names = [
            name
            for name, value in namespace.items()
            if isinstance(value, cached_property)
            and hasattr(value.func, "is_ocr_series")
        ]

        # Create enum dynamically
        cls.OCRValidationKind = Enum("OCRValidationKind", {name: name for name in series_names})  #! THIS IS src/my_project/core/document.py:94

        return cls
from functools import cached_property

class OCRSeries[T]:
    ...

class OCRContent(BaseModel, metaclass=OCRContentMeta):
    text: str

    @ocr_series  # type: ignore[prop-decorator]
    @cached_property
    def numbers_float(self) -> OCRSeries[float]:
        return OCRSeries[float]([float(x) for x in self.numbers.list])

    ...

MyPy traceback:

~ uv run mypy --config-file pyproject.toml src/my_project --show-traceback

src/my_project/core/document.py:94: error: Enum type as attribute is not supported  [misc]
src/my_project/core/document.py:94: error: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members  [misc]
src/my_project/core/document.py:97: error: Type cannot be declared in assignment to non-self attribute  [misc]
src/my_project/core/document.py:94: error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 1.13.0
Traceback (most recent call last):
  File "mypy/semanal.py", line 7113, in accept
  File "mypy/nodes.py", line 1351, in accept
  File "mypy/semanal.py", line 3141, in visit_assignment_stmt
  File "mypy/semanal.py", line 3372, in record_special_form_lvalue
AssertionError: 
src/my_project/core/document.py:94: : note: use --pdb to drop into pdb

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions