Specialized methods on generic classes
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Let's say I have a generic class G.
from __future__ import annotations
from collections.abc import Sized
from typing import Generic, TypeVar
T = TypeVar("T")
class G(Generic[T]):
pass
I want to have a single method on this class that's only legal for a subset of T.
If I want to limit it to, say, int, it works:
class G(Generic[T]):
def test(self: G[int]) -> G[int]:
return self
G[int]().test() # Works, as it should
G[str]().test() # Error, as it should
But if I want to limit it to, say, a protocol like Sized, I get a false negative:
S = TypeVar("S", bound=Sized)
class G(Generic[T]):
def test(self: G[S]) -> G[S]:
return self
G[int]().test() # False negative - works, but it shouldn't
This is a pity, since it'd unlock some cool features I was working on vis-a-vis using attrs attributes. Are there any workarounds? Would this be handled by intersection types maybe?
Your Environment
- Mypy version used: mypy 1.0.0+dev.b8c03ab6809aab56928f3cd865edb44944a600a2
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: Python 3.10.6
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
Start by running the supplied Python reproducer with the reported mypy version and compare the behavior for the int specialization with the Sized-bound specialization. Trace the generic self-type checking path, then add or update a regression test so protocol-bound specialized methods are accepted or rejected according to the intended behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools, tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100