Type[...] doesn't work correctly with unions

Aperta
#4,625 4 commenti 4 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
25/100
Tipo di issue
Funzionalità
Chiarezza
Da chiarire
Stato di attività
Ferma
Stack tecnologico
python
Ambito
devtools

Direzione di ricerca

No files or tests are named. Start by reproducing the two reveal_type examples for str and Optional[str], then investigate how mypy handles generic Type[T] calls with Union types. Done means the reported structure call infers the union or optional type instead of Any without requiring typing.cast.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug priority-1-normal topic-union-types

I have a function called structure(json_obj, type) it takes a json like object and does some stuff to it and, if it can, returns an instance of type, otherwise it raises an error.

But it also supports Union and Optional which means a type annotation like
def structure(obj: Any, type: Type[T]) -> T:... doesn't work. (It returns Any for Unions) I see that typing.cast works correctly but I don't really want to have to write x = cast(Optional[str], structure(foo, Optional[str])) all over my code.

Here's some example code:

from typing import Optional, Type, Any, TypeVar
T = TypeVar('T')
def structure(obj: Any, type: Type[T]) -> T:...

reveal_type(structure('foo', str))  #  Revealed type is 'builtins.str*'
reveal_type(structure('foo', Optional[str]))  # Revealed type is 'Any'

I don't know how this signaling would be done though, without adding something to typing or telling mypy about your method through some other channel, e.g. config file (eww)

@typing.castlike
def structure(obj: Any, type: Type[T]) -> T:...
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Merge medio
1g 18h
PR unite (30g)
54

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di python/mypy

Tutte le issue di python/mypy

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.