Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 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 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?

like image 707
Yosh Avatar asked Dec 03 '14 05:12

Yosh


2 Answers

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

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

Also works for yield

def fn(x: int) -> Iterator[int]:     for n in range(x):         yield n 
like image 59
Conchylicultor Avatar answered Sep 23 '22 18:09

Conchylicultor


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

Generator[yield_type, send_type, return_type]  

See also PEP 0484.

like image 36
pfp.meijers Avatar answered Sep 21 '22 18:09

pfp.meijers