How do I annotate a generator in python3?

Python 3.x supports (optional) function annotations:

def add_ints(x:int, y:int) -> int :
    return x+y

      

I sometimes run into problems with the representation of a given "type", and this time I have a function that returns a generator:

def myfunc(x: [int]) -> "generator that returns ints":
    #                     ^~~~~~~~~~~~~~~~~~~~~~~~~~
    return (n for n in x if n%2 == 0)

      

How do I annotate the return value? Is there a link that I can handle?

+3


source to share


2 answers


Annotations in Python 3 can be any valid expression, not just a type, and are not actually used for anything internally (for more information on annotations, https://www.python.org/dev/peps/pep-3107 ). There are no guidelines or standards on how to use these annotations so that they can be used in whatever way is easiest for the coder (see https://www.python.org/dev/peps/pep-0008#programming-recommendations ) ...



In your specific case, you can use a string or global variable to indicate your type, or perhaps types.GeneratorType

, although there is no way to indicate that the generator produces int

s.

+1


source


The module defines the type of generator you can use as follows:

Generator[yield_type, send_type, return_type] 

      



See also PEP 0484 .

+12


source







All Articles