confusing behavior with TypeVars and multiple inheritance checks in 0.770
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Hi, I was just testing out 0.770 and I'm getting a surprising result:
from typing import TypeVar
class Foo(object):
pass
FooOrStr = TypeVar('FooOrStr', Foo, str)
def doit(reset: bool, arg: FooOrStr) -> FooOrStr:
if reset:
if isinstance(arg, Foo):
reveal_type(arg)
arg = Foo()
elif isinstance(arg, str):
reveal_type(arg)
arg = ''
else:
raise TypeError()
return arg
test.py:12: note: Revealed type is 'test.Foo*'
test.py:12: note: Revealed type is 'test.<subclass of "str" and "Foo">'
test.py:13: error: Incompatible types in assignment (expression has type "Foo", variable has type "str") [assignment]
test.py:15: note: Revealed type is 'builtins.str*'
Based on the latest blog post about 0.770 I suspect this is by design, but what can I do to work around it (short of adding some artificial method to make Foo incompatible with str)?
It would be good to add something to the docs about this, because I think it could be a fairly common trap. Also, I think adjusting the error message to clarify the relationship to multiple inheritance would help, e.g. variable has type Foo and 'test.<subclass of "str" and "Foo">'.
Thanks!
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 mypy 0.770 or the issue's TypeVar and multiple-inheritance example to reproduce the revealed types and assignment error. Read the relevant TypeVar and type-narrowing documentation and diagnostic tests, then document the behavior, a workaround, and clearer wording for the relationship between Foo and the inferred subclass type.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools, tooling
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100