python / python/mypy

How to type result based on constructor parameters?

Open
#10,207 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I am trying to type code like this:

class A:

    def __init__(self, return_tuple=False):
        self.return_tuple = return_tuple
    
    def __call__(self):
        if self.return_tuple:
            return (1, 2)
        return 1

I have tried to make A generic and use overloads on the self parameter in several ways but none seems to work:

class A(Generic[T]):

    def __init__(self, return_tuple: T = False) -> None:
        self.return_tuple = return_tuple

    @overload
    def __call__(self: A[Literal[True]]) -> Tuple[int, int]:
        pass

    @overload
    def __call__(self: A[Literal[False]]) -> int
        pass
    
    def __call__(self) -> Union[int, Tuple[int, int]]:
        if self.return_tuple:
            return (1, 2)
        return 1

where T is either

T = TypeVar("T", bool)

or

T = TypeVar("T", Literal[True], Literal[False])

The first case mark errors in the definition of the TypeVar, the Generic and the optional parameter in __init__. The second one marks an error only in the optional parameter (even if it is essentially the same type). reveal_type does not have the expected result in both cases.

Am I doing something wrong or is this case just not currently taken into consideration?

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

No files or tests are named. Start with the Generic[T], Literal overloads, constructor parameter, and reveal_type examples in the issue; trace how mypy handles these patterns and determine what behavior is expected. Done means establishing whether this typing pattern is supported and identifying the relevant limitation or requested change.

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.