Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type signature do generators have in Python?

Given that the new Python 3.5 allows type hinting with type signatures I want to use the new feature, but I don't know how to fully annotate a function with the following structure:

def yieldMoreIfA(text:str):
    if text == "A":
        yield text
        yield text
        return
    else:
        yield text
        return

What's the correct signature?

like image 799
Christian Avatar asked Nov 25 '15 13:11

Christian


People also ask

What is type signature in Python?

Using signature() function We can get function Signature with the help of signature() Function. It takes callable as a parameter and returns the annotation. It raises a value Error if no signature is provided. If the Invalid type object is given then it throws a Type Error.

What type is a generator Python?

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.

What are the signs that a function is a generator function?

If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator function. Both yield and return will return some value from a function.

What is generator expression in Python?

A generator expression is an expression that returns a generator object. Basically, a generator function is a function that contains a yield statement and returns a generator object. For example, the following defines a generator function: def squares(length): for n in range(length): yield n ** 2.


1 Answers

There is a Generator[yield_type, send_type, return_type] type:

from typing import Generator

def yieldMoreIfA(text: str) -> Generator[str, None, None]:
    if text == "A":
        yield text
        yield text
        return
    else:
        yield text
        return
like image 56
Martijn Pieters Avatar answered Oct 01 '22 11:10

Martijn Pieters