python / python/typing

a way to refer to result type of an overloaded function

Open
#641 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: feature
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

I am looking for a way to refer to result type of an overloaded function.

To illustrate:

import typing as tp


T = tp.TypeVar("T")


@tp.overload
def gf1(i: int, j: tp.Any) -> str:
    ...


@tp.overload
def gf1(i: tp.Iterable[T], j: bool) -> tp.Dict[T, T]:
    ...


def gf1(i: tp.Union[int, tp.Iterable[T]], j: tp.Any) -> tp.Union[str, tp.Dict[T, T]]:
    pass


gf1.resultType = lambda *a: None



class C(tp.Generic[T]):
    def f1(self) -> gf1.resultType(T, bool):
        pass

    def f2(self) -> gf1.resultType(tp.List[T], bool):
        pass


if not tp.TYPE_CHECKING:
    def reveal_type(x):
        pass


# outputs: builtins.str
reveal_type(gf1(1, True))
# wanted: builtins.str
reveal_type(C[int]().f1())

# outputs: builtins.dict[builtins.int*, builtins.int*]
reveal_type(gf1([1], True))
# wanted: builtins.dict[builtins.int*, builtins.int*]
reveal_type(C[int]().f2())

The f.resultOf syntax is, of course, tentative.

Issue #623 seems to suggest that this may be achievable with a clever use of of Protocol but I just cannot twist my head around that.

Upon request I can elaborate on my specific use case for this but I believe it would suffice to say that in real code gf1.resultType would be used multiple times. Specific argument types for gf1 were chosen arbitrarily for the sake of example.

Not sure whether #548 is anyhow related.

Contributor guide

No contributing guide indexed for this repository

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 with the overloaded-function examples in this issue and review the related discussions in issues #623 and #548. No repository file or test is identified; done would require an agreed, implementable scope for referring to an overloaded function's result type.

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
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.