Metaclass defined class attribute raise "name-defined" error when used as a type
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Run the linked mypy-play reproduction or the code in the issue to confirm the name-defined error with a metaclass-provided class attribute used as a type. Trace the relevant mypy behavior from that reproduction, then verify that ProtoWrapper.Direction is accepted as a type without the error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100