Skip to content

Type inference of arguments like default: TDefault = None #9432

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

Closed
Strilanc opened this issue Sep 10, 2020 · 1 comment
Closed

Type inference of arguments like default: TDefault = None #9432

Strilanc opened this issue Sep 10, 2020 · 1 comment
Labels
bug mypy got something wrong

Comments

@Strilanc
Copy link

🐛 Bug Report

  1. Create a file tmp.py with this code:
from typing import TypeVar, Union
TDefault = TypeVar('TDefault')

def f(flag: int, default: TDefault = None) -> Union[int, TDefault]:
    if flag == 0:
        return default
    return flag
  1. Run mypy on the file.

Expected Behavior

No type errors.

Actual Behavior

tmp.py:6: error: Incompatible return value type (got "Optional[TDefault]", expected "Union[int, TDefault]")
Found 1 error in 1 file (checked 1 source file)

To be more specific, mypy fails to realize that the none-returning-path is just a different default-returning-path (where TDefault happens to correspond to NoneType), rather than a mistake.

To avoid the error I have to specify the type information in each case manually using overloads:

from typing import TypeVar, Union, overload
TDefault = TypeVar('TDefault')

@overload
def f(flag: int) -> Union[int, None]:
    pass
def f(flag: int, default: TDefault) -> Union[int, TDefault]:
    pass
def f(flag, default = None):
    if flag == 0:
        return default
    return flag

Your Environment

  • Mypy version used: 0.782
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.8.5
  • Operating system and version: gLinux
@Strilanc Strilanc added the bug mypy got something wrong label Sep 10, 2020
@hauntsaninja
Copy link
Collaborator

hauntsaninja commented Sep 10, 2020

Dupe of #3737, #8708, #8739 and others. First of those has the most discussion (see Guido's and Anders' comments)

Also for future searchers, if you run with --strict note you get a different error message:

main.py:4: error: Incompatible default for argument "default" (default has type "None", argument has type "TDefault")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants