annotations on `self` are not understood with `Protocol`s
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When interpreting a given type as a given Protocol, annotations on self in the Protocol are apparently ignored.
To Reproduce
from __future__ import annotations
from typing import *
#━━━━━━━━━━━━━━━━━#
# EXISTING CODE #
#━━━━━━━━━━━━━━━━━#
class ConcreteClass:
# here 'transform()' is used, but we might use '__neg__()' or
# '__invert__()' in a similar way (so many built-in/third-party
# classes would qualify as 'TransformAware')
def transform(self) -> int:
return id(self)
#━━━━━━━━━━━━━━━━#
# LIBRARY CODE #
#━━━━━━━━━━━━━━━━#
# this can be changed
Ico = TypeVar('Ico', covariant=True) # input, covariant
Oco = TypeVar('Oco', covariant=True) # output, covariant
class TransformAware(Protocol[Ico, Oco]):
def transform(self: Ico) -> Oco: ...
#━━━━━━━━━━━━━━━━━━━━━━━━━#
# DEMONSTRATE PROBLEMS: #
#━━━━━━━━━━━━━━━━━━━━━━━━━#
I = TypeVar('I') # input
O = TypeVar('O') # output
def interpret_transform_aware(_: Type[TransformAware[I, O]]) -> Tuple[I, O]:
i: I
o: O
return i, o
reveal_type(interpret_transform_aware(ConcreteClass))
# actual output:
# note: Revealed type is "Tuple[<nothing>, builtins.int]"
# expected output:
# note: Revealed type is "Tuple[ConcreteClass, int]"
#───────────────#
# MOTIVATION: #
#───────────────#
class TransformDriver(Generic[I, O]):
def __init__(self, klass: Type[TransformAware[I, O]]): ...
def transform_value(self, value: I) -> O:
use_value = cast(TransformAware[I, O], value)
return use_value.transform()
Expected Behavior
(See: inline comments.)
Interpreting ConcreteClass as TransformAware should correctly infer both type variables.
Actual Behavior
(See: inline comments.)
Mypy gives the type of Ico as <nothing>.
Your Environment
- Mypy version used: 1.6.1
- Mypy command-line flags: (none necessary)
- Mypy configuration options from
mypy.ini(and other config files): (none necessary) - Python version used: 3.8, 3.11
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 with the mypy-play.net reproducer and the Protocol handling code; the payload names no repository file or test. Trace how annotations on self are used when interpreting ConcreteClass as TransformAware, then add coverage showing that both type variables are inferred as ConcreteClass and int.
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
- 38/100