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

Wrong return type inferred for overload with a type variable #18233

Open
eltoder opened this issue Dec 2, 2024 · 1 comment
Open

Wrong return type inferred for overload with a type variable #18233

eltoder opened this issue Dec 2, 2024 · 1 comment
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference

Comments

@eltoder
Copy link

eltoder commented Dec 2, 2024

Bug Report

from typing import TypeVar, overload

_T = TypeVar("_T")

@overload
def getenv(key: str) -> str | None: ...

@overload
def getenv(key: str, default: _T) -> str | _T: ...

def getenv(key, default):
    return key


def test(custom_var: str) -> str:
    return getenv(custom_var) or getenv("V", "D")

https://mypy-play.net/?mypy=latest&python=3.12&gist=4d959cd7069a8495533bfeca1cd40729

Actual Behavior

main.py:16: error: Incompatible return value type (got "str | None", expected "str")  [return-value]

Expected Behavior

This should type check without errors, since we have an or with a call that always returns str.

It works if I replace type variable with just str:

@overload
def getenv(key: str, default: str) -> str: ...

but something about _T and the union upsets it.

Your Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10-3.13
@eltoder eltoder added the bug mypy got something wrong label Dec 2, 2024
@brianschubert brianschubert added the topic-type-context Type context / bidirectional inference label Dec 2, 2024
@eltoder
Copy link
Author

eltoder commented Dec 4, 2024

A slightly simpler example without @overload:

from typing import TypeVar

_T = TypeVar("_T")

def foo(key: str) -> str | None: return key

def bar(key: str, default: _T) -> str | _T: return key


def test(custom_var: str) -> str:
    return foo(custom_var) or bar("V", "D")

https://mypy-play.net/?mypy=latest&python=3.12&gist=0afee5cdbf09752bb5f6a5ee9f3e35f4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference
Projects
None yet
Development

No branches or pull requests

2 participants