python / python/mypy

Generic class clone method using property variable for type arg produces name-defined error

Open
#17,302 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

My Python code is running fine for what I want it to do, but I've had to silence this mypy error in this case, where it does not appear to be correct. A property is used to access the __orig_class__ variable.

To reproduce:
mypy playground - https://mypy-play.net/?mypy=1.10.0&python=3.12&gist=063c6160fe6d1bf37973f47906a6d997

from __future__ import annotations
from typing import Generic, TypeVar, get_args

T = TypeVar("T", bound=int)

class Foo(Generic[T]):
    @property
    def t(self) -> type[T]:
        return get_args(self.__orig_class__)[0]  # Get the type arg, (int)
    
    def clone(self) -> Foo[T]:
        return Foo[self.t]()  # test.py:12: error: Name "self.t" is not defined  [name-defined]
    
    def no_complaint(self) -> None:
        print(self.t("1"))


foo = Foo[int]()
foo.no_complaint()  # `1`
r = foo.clone()
r.no_complaint()    # `1`

Expected behaviour
Mypy reports no errors, python code runs correctly.

Actual behaviour
Python code runs correctly.
Mypy returns
test.py:12: error: Name "self.t" is not defined [name-defined]

Environment
Base install with:
mypy==1.10.0
python==3.11.4

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked mypy playground using the reported Python 3.12 and mypy 1.10.0 example in test.py, then trace how the name-defined diagnostic is produced for self.t inside Foo.clone. Done means the reproduction reports no errors while preserving the shown runtime behavior.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.