2016-05-23 17 views
16

Voglio usare Type Hints nel mio programma Python. Come posso creare Suggerimenti tipo di strutture dati complesse comeCome posso creare un suggerimento sul tipo che il mio elenco restituito contiene stringhe?

  • liste con stringhe
  • un generatore di numeri interi di ritorno?

Esempio

def names() -> list: 
    # I would like to specify that the list contains strings? 
    return ['Amelie', 'John', 'Carmen'] 

def numbers(): 
    # Which type should I specify for `numbers()`? 
    for num in range(100): 
     yield num  

risposta

19

Utilizzare il typing module; contiene generici, tipo di oggetti è possibile utilizzare per specificare i contenitori con vincoli sul loro contenuto:

import typing 

def names() -> typing.List[str]: # list object with strings 
    return ['Amelie', 'John', 'Carmen'] 

def numbers() -> typing.Iterator[int]: # iterator yielding integers 
    for num in range(100): 
     yield num 

A seconda di come si progetta il codice e come si desidera utilizzare il valore di ritorno di names(), si potrebbe anche usare i tipi types.Sequence e types.MutableSequence qui, a seconda che si aspettino o meno di poter mutare il risultato.

Un generatore è un tipo specifico di iteratore, quindi typing.Iterator è appropriato qui. Se il generatore accetta anche send() valori e usa return per impostare un valore StopIteration, è possibile utilizzare il typing.Generator object troppo:

def filtered_numbers(filter) -> typing.Generator[int, int, float]: 
    # contrived generator that filters numbers; returns percentage filtered. 
    # first send a limit! 
    matched = 0 
    limit = yield 
    yield # one more yield to pause after sending 
    for num in range(limit): 
     if filter(num): 
      yield num 
      matched += 1 
    return (matched/limit) * 100 

Se siete nuovi a digitare accennando, poi PEP 483 – The Theory of Type Hints può essere utile.

Problemi correlati