Reputation: 134
Python typing documentation includes examples for typing of generator functions. Yield is still a concept I struggle to understand, but I have a scenario where I'm not quite sure, how to properly use typing. The code is a very basic example of my current struggle and shows where my question arises from. If I have two yields in a function, how would I use typing for that function? The documentation on typing gives me no clear answer, my current preference would be, to use Iterator[dict].
def yield_func() -> ?:
A: dict = {}
B: dict = {}
yield A
yield B
I would currently use Iterator[dict] as typing annotations for the given function.
Upvotes: 1
Views: 2919
Reputation: 18663
The most flexible form is the one explained here already and alluded to again by @tomerar. It was already mentioned in PEP 484 way back in the day. The generic alias Generator
from collections.abc
is what you can use.
Since your example generator is very simple in that it does not have a return value and does not utilize sending anything to it, you can use the more basic Iterator
type, which is a supertype of Generator
(see here). An Iterator
is generic only in terms of the type its __next__
method returns, which is equivalent to the type you yield in a generator function.
I would suggest always using those generic alias types from collections.abc
and not from typing
(unless you are on Python <3.9
) because the typing equivalents are deprecated (see for example here).
By the way, if you are already taking the time to annotate your functions (which is great), you should properly utilize generic types, which include dict
. Here is how I would annotate your example function assuming the keys in your dictionaries are str
and without knowing anything about the value-type:
from collections.abc import Iterator
MyDictT = dict[str, object] # for example
def yield_func() -> Iterator[MyDictT]:
a: MyDictT = {}
b: MyDictT = {}
...
yield a
yield b
Upvotes: 3