Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type hint of a generator function? [duplicate]

I'm trying to write a :rtype: type hint for a generator function. What is the type it returns?

For example, say I have this functions which yields strings:

def read_text_file(fn):     """     Yields the lines of the text file one by one.     :param fn: Path of text file to read.     :type fn: str     :rtype: ???????????????? <======================= what goes here?     """     with open(fn, 'rt') as text_file:         for line in text_file:             yield line 

The return type isn't just a string, it's some kind of iterable of strings? So I can't just write :rtype: str. What's the right hint?

like image 649
Jean-François Corbett Avatar asked Apr 27 '17 13:04

Jean-François Corbett


People also ask

What is the return type of a generator?

A generator is a special type of function which does not return a single value, instead, it returns an iterator object with a sequence of values. In a generator function, a yield statement is used rather than a return statement. The following is a simple generator function.

Does generator function has a return statement?

A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true ). If a value is returned, it will be set as the value property of the object returned by the generator.

What is the return type of yield?

The yield type of an iterator that returns IEnumerable or IEnumerator is object . If the iterator returns IEnumerable<T> or IEnumerator<T>, there must be an implicit conversion from the type of the expression in the yield return statement to the generic type parameter.

Does yield return a generator?

When you use a yield keyword inside a generator function, it returns a generator object instead of values. In fact, it stores all the returned values inside this generator object in a local state.


1 Answers

Generator

Generator[str, None, None] or Iterator[str]

like image 87
aristotll Avatar answered Oct 10 '22 17:10

aristotll