Calling a method of Union of two classes with class's attribute results in incompatible type error
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Riprodurre l’esempio minimo in main.py con mypy 0.761 o il master corrente, concentrandosi sulla chiamata Union[A, B] tramite x.permissions_for(x.me). Il lavoro è concluso quando func supera il type-checking senza isinstance quando la proprietà di ciascuna classe corrisponde al parametro del suo metodo, mentre le chiamate realmente incompatibili continuano a produrre errori.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 35/100