Mypy fails to infer the type of the decorated function used in the decorator
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Hi mypy team,
Bug Report
I'm looking into the issue with design-by-contract library icontract which heavily uses decorators to formalize contracts. For many functions and methods, the contracts involve the decorated function (or method) itself.
See the example from the issue https://github.com/Parquery/icontract/issues/243:
from icontract import ensure
@ensure(
lambda a, b, result:
result == myadd(b, a),
"Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
return a + b
Mypy 0.960 says:
tests_3_10\deleteme.py:5: error: Cannot determine type of "myadd"
If I add # type: ignore:
from icontract import ensure
@ensure(
lambda a, b, result:
result == myadd(b, a), # type: ignore
"Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
return a + b
mypy does not complain any more.
I was actually a bit surprised that mypy tried to infer the types in the lambda. @claudio-ebel tried a couple of fixes using casting (see his comment https://github.com/Parquery/icontract/issues/243#issue-1229622746), but none of them worked.
I am actually not sure if this is a misunderstanding on our part or a bug in mypy. Any pointers about how to resolve the issue are very much appreciated! Please let us know if you need more information, or if there is anything we can do to help to fix this.
Your Environment
- Mypy version used: 0.960
- Mypy command-line flags: `--strict``
- Python version used: 3.10.0
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
Beginnen Sie damit, das bereitgestellte icontract-Beispiel mit mypy 0.960 und --strict zu reproduzieren, und verfolgen Sie anschließend die durch den Fehler betroffenen Einstiegspunkte für die Typinferenz von Decorator und Lambda. Vergleichen Sie das Verhalten mit und ohne den type: ignore-Kommentar; abgeschlossen ist die Aufgabe, wenn festgestellt wurde, ob die Diagnose erwartet wird, oder die Inferenz so korrigiert wurde, dass das Beispiel ohne diese Unterdrückung geprüft wird.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- tooling
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100