mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Metaclass defined class attribute raise "name-defined" error when used as a type

Open superlevure opened this issue 1 year ago • 0 comments

Using a Metaclass to define dynamic class (not instance) attributes raises name-defined error when trying to use an attribute as a type.

To Reproduce

Gist URL: https://gist.github.com/mypy-play/bb0277c6f339cbf374a1d2288cb7d5e6

Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=bb0277c6f339cbf374a1d2288cb7d5e6

from enum import Enum

class Message:
    class Direction(Enum):
        IN = "IN"
        OUT = "OUT"


class MetaProtoWrapper(type):
    def __getattribute__(cls, name: str):
        try:
            return super().__getattribute__(name)
        except AttributeError:
            return getattr(cls.Meta.protocol_buffer_type, name)


class ProtoWrapper(metaclass=MetaProtoWrapper):
    class Meta:
        protocol_buffer_type = Message


direction_in = ProtoWrapper.Direction.IN  # OK
direction_in: ProtoWrapper.Direction = ProtoWrapper.Direction.IN   # Name "ProtoWrapper.Direction" is not defined  [name-defined]

Expected Behavior

ProtoWrapper.Direction should be a valid type

Actual Behavior

ProtoWrapper.Direction raises name-defined error

Your Environment

  • Mypy version used: mypy 1.10.0 (compiled: yes)
  • Mypy command-line flags: NA
  • Mypy configuration options from mypy.ini (and other config files): NA
  • Python version used: 3.12

superlevure avatar Jun 24 '24 11:06 superlevure