How to annotate a generator in python3?

天涯浪子 提交于 2020-08-24 05:11:43

问题


Python 3.x supports (optional) function annotations:

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

I sometimes encounter problems as to how to represent a given "type" can be represented, 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 should I annotate the return value? Is there any reference I can consult to?


回答1:


The typing module defines the Generator type, which you can use like:

Generator[yield_type, send_type, return_type] 

See also PEP 0484.




回答2:


While Generator[x, y, z] exists, most of the time, you might want to use the less verbose Iterator:

def add_ints(x:int, y:int) -> Iterator[int]:
    return (n for n in x if n%2 == 0)



回答3:


Annotations in Python 3 can be any valid expression, not just a type, and are not actually used for anything internally (for more on annotations, https://www.python.org/dev/peps/pep-3107). There are no guidelines or standards as to how to use these annotations so 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 could use a string or global variable to indicate your type, or perhaps the types.GeneratorType, although there is no way to indicate that the generator produces ints.



来源:https://stackoverflow.com/questions/27264250/how-to-annotate-a-generator-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!