Assignment to Any doesn't make it more precise
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
- Are you reporting a bug, or opening a feature request?
Bug report.
- Please insert below the code you are checking with mypy,
or a mock-up repro if the source is private. We would appreciate
if you try to simplify your case to a minimal repro.
from typing import Any, Optional
def foo(baz: Any) -> int:
return 1
def bar1(baz: Any = 0) -> int:
reveal_type(baz)
baz = foo(baz)
reveal_type(baz)
return baz
def bar2(baz: Optional[Any] = 0) -> int:
reveal_type(baz)
baz = foo(baz)
reveal_type(baz)
return baz
- What is the actual behavior/output?
main.py:9: note: Revealed type is 'Any'
main.py:11: note: Revealed type is 'Any'
main.py:12: error: Returning Any from function declared to return "int"
main.py:16: note: Revealed type is 'Union[Any, None]'
main.py:18: note: Revealed type is 'builtins.int'
Found 1 error in 1 file (checked 1 source file)
- What is the behavior/output you expect?
After baz = foo(baz) the type of baz should be int. Redefinition should not be a problem here since this assignment makes the type of baz more precise.
By trial-and-error I found that annotating bar as a Union of Any and anything else (here Optional[Any] == Union[Any, None]) fixes this behavior.
- What are the versions of mypy and Python you are using?
Do you see the same issue after installing mypy from Git master?
mypy: 0.780 / 0.790+dev.95eff27adb1fae7b1ec4a7315524ebfdcebf6e2b
python: 3.6.9
- What are the mypy flags you are using? (For example --strict-optional)
--warn-return-any
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem als main.py gezeigten minimalen Reproducer und führe mypy mit --warn-return-any aus; vergleiche die reveal_type-Ausgabe vor und nach baz = foo(baz). Als erledigt gilt, dass die Zuweisung so behandelt wird, dass baz auf int eingeengt wird und der return-any-Fehler nicht mehr gemeldet wird, während das bestehende Verhalten von Optional[Any] weiterhin verstanden bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100