Having to add type hint 2nd time on AnyStr when assigning as instance attribute
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
I am reporting a potential bug/improvement in mypy.
I assign a class's instance attribute to be an argument from the __init__ signature.
I noticed that when the argument is type hinted as a AnyStr, mypy raises an error unless the instance attribute receives a second type hint.
from typing import AnyStr, Generic
class A(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case A... error: Need type annotation for 'attr'
self.attr = arg
reveal_type(arg)
# note: Revealed type is 'builtins.str*'
# note: Revealed type is 'builtins.bytes*'
reveal_type(self.attr)
# note: Revealed type is 'builtins.str'
# note: Revealed type is 'Any'
# Observation: 'builtins.bytes*' doesn't seem to propagate
class B(Generic[AnyStr]):
def __init__(self, arg: AnyStr):
# Case B... Success
self.attr = arg # type: AnyStr
The desirable behavior is not to have to supply a second type hint.
What's going on here? Is there some way I can not supply a second type hint?
I am invoking mypy from the command line with no flags. Here are my versions:
python==3.6.5
mypy==0.770
Aside
I am coming here from Stack Overflow, where a community member thought it was a bug: Python mypy why does class instance attribute require type hint if expression already has type hint
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 reproducing the issue from the included Python snippet with mypy 0.770, comparing Case A and Case B and their revealed types. Trace instance-attribute inference for Generic[AnyStr] and determine whether the type variable should propagate without the inline annotation. Done means Case A no longer requires a second type hint, with regression coverage for the demonstrated 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
- 35/100