Skip to content

different treatment of untyped defs, typed defs, and lambdas #5746

@hashbrowncipher

Description

@hashbrowncipher

Edit: see first comment

Test case:

  1 from typing import Callable
  2 from typing import Union
  3
  4
  5 def works(arg: Union[int, str]) -> Callable[[], int]:
  6     if isinstance(arg, str):
  7         def ret():
  8             return len(arg)
  9         return ret
 10     elif isinstance(arg, int):
 11         def ret():
 12             return arg + 8
 13         return ret
 14
 15
 16 def fails1(arg: Union[int, str]) -> Callable[[], int]:
 17     if isinstance(arg, str):
 18         def ret() -> int:
 19             return len(arg)
 20         return ret
 21     elif isinstance(arg, int):
 22         def ret() -> int:
 23             return arg + 8
 24         return ret
 25
 26
 27 def fails2(arg: Union[int, str]) -> Callable[[], int]:
 28     if isinstance(arg, str):
 29         return lambda: len(arg)
 30     elif isinstance(arg, int):
 31         return lambda: arg + 8

Actual output:

$ mypy --version
mypy 0.640+dev.e12be3ba9e6be3e9242e3a81ffaa9b3a136876fe
$ python3 --version
Python 3.7.0
$ mypy lambdas_n_defs.py
lambdas_n_defs.py:19: error: Argument 1 to "len" has incompatible type "Union[int, str]"; expected "Sized"
lambdas_n_defs.py:23: error: Unsupported operand types for + ("str" and "int")
lambdas_n_defs.py:23: note: Left operand is of type "Union[int, str]"
lambdas_n_defs.py:29: error: Argument 1 to "len" has incompatible type "Union[int, str]"; expected "Sized"
lambdas_n_defs.py:31: error: Unsupported operand types for + ("str" and "int")
lambdas_n_defs.py:31: note: Left operand is of type "Union[int, str]"

Expected output: none, because I believe mypy should treat fails1() and fails2() identically to works()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions