python / python/mypy

Assignment to Any doesn't make it more precise

Open
#9,040 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation needs discussion
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

  • 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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal reproducer shown as main.py and run mypy with --warn-return-any, comparing the reveal_type output before and after baz = foo(baz). Done means the assignment is treated as narrowing baz to int and the return-any error is no longer reported, while the existing Optional[Any] behavior remains understood.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.