Christian
Christian

Reputation: 26427

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?

Upvotes: 15

Views: 2950

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123900

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

Upvotes: 15

Related Questions