Idea: `ReturnType` to refer to function's return type

Noticed a pattern of repeating a type annotation in functions returning a bit verbose generic container and having a way to duplicate the return type would be helpful.

Would it make sense for this case to have something like ReturnType as a shortcut to refer from function body to it’s return type? Any other similar cases where this could be useful?

Haven’t found this proposed. There was an idea of ReturnType for mypy (Add ReturnType-like utility for getting function return types · Issue #8385 · python/mypy · GitHub) but it was about a tool to introspect other functions return type. Maybe those ideas can be combined and ReturnType without any arguments would refer to return type from the current scope.

# Currently:
def foo() -> dict[str, tuple[float, float, float]]:
    lst: dict[str, tuple[float, float, float]] = {}
    lst["5"] = (1, 2, 3) # OK
    lst[2] = (4, 5, 6) # Error
    return lst

# With ReturnType:
from typing import ReturnType

def foo() -> dict[str, tuple[float, float, float]]:
    lst: ReturnType = {}
    lst["5"] = (1, 2, 3) # OK
    lst[2] = (4, 5, 6) # Error
    return lst
2 Likes