Calling a method of Union of two classes with class's attribute results in incompatible type error
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Honestly didn't know how to name this issue...
Issue type: Bug
Problematic code:
from typing import Union
class UserTypeA: ...
class UserTypeB: ...
class A:
def permissions_for(self, user: UserTypeA) -> bool: ...
@property
def me(self) -> UserTypeA: ...
class B:
def permissions_for(self, user: UserTypeB) -> bool: ...
@property
def me(self) -> UserTypeB: ...
def func(x: Union[A, B]) -> bool:
return x.permissions_for(x.me)
Error message:
main.py:20: error: Argument 1 to "permissions_for" of "A" has incompatible type "Union[UserTypeA, UserTypeB]"; expected "UserTypeA"
main.py:20: error: Argument 1 to "permissions_for" of "B" has incompatible type "Union[UserTypeA, UserTypeB]"; expected "UserTypeB"
Expected behaviour:
No error as x.me matches the type expected by x.permissions_for - if instance of A is passed x.me will have type UserTypeA and x.permissions_for will expect UserTypeA and same for instance of B.
Also, if func looks like this, the errors are gone so if mypy could infer this without isinstance it would be great:
def func(x: Union[A, B]) -> bool:
if isinstance(x, A):
return x.permissions_for(x.me)
else:
return x.permissions_for(x.me)
Python version:: 3.8.1
Mypy version: 0.761, occurs on master as well
Mypy flags: No flags
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
Reproduziere das minimale Beispiel in main.py mit mypy 0.761 oder dem aktuellen master, wobei der Aufruf von Union[A, B] über x.permissions_for(x.me) im Mittelpunkt steht. Fertig ist die Aufgabe, wenn func ohne isinstance typgeprüft wird, sobald die Property jeder Klasse zu ihrem Methodenparameter passt, während tatsächlich inkompatible Aufrufe weiterhin Fehler bleiben.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 35/100