Skip to content

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

Closed
@Strilanc

Description

@Strilanc

🐛 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions