python / python/mypy

Fails to infer Literal when required by return type

Open
#17,572 0 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

When a return type requires a Literal, the value in a return type does not seem to infer a Literal when the code is correct.

To Reproduce

This could be reduced further, but this should fully demonstrate what I'm trying to achieve, in case there are any other intricacies:

from typing import Generic, Literal, TypeVar, overload

_T = TypeVar("_T")
_Code = TypeVar("_Code", bound=int, default=Literal[200])

class APIResponse(Generic[_T, _Code]):
    @overload
    def __init__(self, body: _T):
        ...
    @overload
    def __init__(self, body: _T, status: _Code):
        ...
    def __init__(self, body: _T, status: int = 200):
        ...


def foo(b: bool) -> APIResponse[int, Literal[200]] | APIResponse[str, Literal[404]]:
    if b:
        return APIResponse(5)
    return APIResponse("FOO", status=404)  # return-value error

Expected Behavior

While it may be difficult to infer Literal everywhere, I expected mypy to correctly infer the type when defined in the return statement. Atleast, mypy seems to do this for TypedDict.

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 reproducing the supplied APIResponse example in mypy and compare its behavior with the TypedDict case mentioned in the report. Trace the return-value checking and generic type inference involved in the return statement; done means the shown function type-checks without the return-value error while preserving the declared Literal alternatives.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.