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.
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
Generatorfromcollections.abcis 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
Iteratortype, which is a supertype ofGenerator(see here). AnIteratoris 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.abcand not fromtyping(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 arestrand without knowing anything about the value-type: