Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ReturnType-like utility for getting function return types #8385

Open
strokirk opened this issue Feb 10, 2020 · 4 comments
Open

Add ReturnType-like utility for getting function return types #8385

strokirk opened this issue Feb 10, 2020 · 4 comments

Comments

@strokirk
Copy link

strokirk commented Feb 10, 2020

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 (#4409) was implemented, most of my usages would be covered.

@JelleZijlstra
Copy link
Member

PEP 612 (https://www.python.org/dev/peps/pep-0612/) may cover some of your use case.

@intgr
Copy link
Contributor

intgr commented Feb 25, 2020

If both foo.py and bar.py live in the same project, you can create a type alias and use that multiple times. I find that it makes code clearer too.

@JukkaL
Copy link
Collaborator

JukkaL commented Feb 28, 2020

I can see how this would be useful, at least occasionally. However, this is not easy to implement in full generality, primarily because of decorators that can change the signature of a function. One option would be to only support functions with simple decorators as targets.

We'd be more likely to prioritize this if there was at least a draft PEP about the feature.

@strokirk
Copy link
Author

strokirk commented Mar 3, 2020

I think if a PEP were to be written, it would be nice to consider more general type introspection, from which a ReturnType-like utility could be built, as well as other useful utilities.

Thanks for the response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants