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.
fonte
2016-05-23 08:53:08