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?
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.
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.
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.
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.
Generator
Generator[str, None, None]
or Iterator[str]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With