问题
What is the correct type annotation for a function that returns a generator expression?
e.g.:
def foo():
return (x*x for x in range(10))
I can't figure out if this is -> Iterator[int]
, -> Iterable[int]
, -> Generator[int, None, None]
, or something else.
If there should be one-- and preferably only one --obvious way to do it, then what is the obvious way here?
回答1:
All three forms mentioned by you in question are listed as valid alternatives in documentation, Generator expression simply creates a generator that only yields.
Quote 1:
A generator can be annotated by the generic type
Generator[YieldType, SendType, ReturnType]
.
Quote 2:
If your generator will only yield values, set the
SendType
andReturnType
toNone
Quote 3:
Alternatively, annotate your generator as having a return type of either
Iterable[YieldType]
orIterator[YieldType]
:
来源:https://stackoverflow.com/questions/42227288/pythons-pep-484-type-annotation-for-generator-expression