python / python/mypy

Add ReturnType-like utility for getting function return types

Open
#8,385 5 comments 28 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature needs discussion priority-2-low topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

This is a feature request, so if there is a way to achieve this already, please point me and future me in the right way.

In TypeScript, we can use the ReturnType utility type to get the return type of a function to reuse in other places. This is very useful to make the code short, readable, and easy to change if necessary, especially in cases where I want to wrap the call of a function from another module in some other function.

An example of how it might be used:

# module: foo.py
def foo() -> None | baz.Baz | tuple[int, int]:
    ...

# module: bar.py
def bar() -> ReturnType[foo.foo]:
    ...

In this case, I could maybe give the return type a name like FooReturn and import that in bar, but that seems less elegant rather than just reusing the function I'm already using.


Note that if automatic or manual type inference (https://github.com/python/mypy/issues/4409) was implemented, most of my usages would be covered.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the requested ReturnType-like utility in this issue and the linked mypy issue #4409 on automatic or manual type inference. Determine the intended typing syntax and behavior for the foo.py and bar.py example; done should mean the requested return-type reuse is supported or the existing supported approach is documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.