Skip to content

Assignment to Any doesn't make it more precise #9040

@pmeier

Description

@pmeier
  • Are you reporting a bug, or opening a feature request?

Bug report.

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
from typing import Any, Optional


def foo(baz: Any) -> int:
    return 1


def bar1(baz: Any = 0) -> int:
    reveal_type(baz)
    baz = foo(baz)
    reveal_type(baz)
    return baz


def bar2(baz: Optional[Any] = 0) -> int:
    reveal_type(baz)
    baz = foo(baz)
    reveal_type(baz)
    return baz
  • What is the actual behavior/output?
main.py:9: note: Revealed type is 'Any'
main.py:11: note: Revealed type is 'Any'
main.py:12: error: Returning Any from function declared to return "int"
main.py:16: note: Revealed type is 'Union[Any, None]'
main.py:18: note: Revealed type is 'builtins.int'
Found 1 error in 1 file (checked 1 source file)
  • What is the behavior/output you expect?

After baz = foo(baz) the type of baz should be int. Redefinition should not be a problem here since this assignment makes the type of baz more precise.

By trial-and-error I found that annotating bar as a Union of Any and anything else (here Optional[Any] == Union[Any, None]) fixes this behavior.

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

mypy: 0.780 / 0.790+dev.95eff27adb1fae7b1ec4a7315524ebfdcebf6e2b
python: 3.6.9

  • What are the mypy flags you are using? (For example --strict-optional)

--warn-return-any

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions