Skip to content

type is not recalculated when it was previously a List[Any] #8540

Description

@dpinol
  • Are you reporting a bug, or opening a feature request?
    A bug
  • Please insert below the code you are checking with mypy,
from typing import Any

def get_any() -> Any:
    return {}

def fun(message_json) -> int:
    messages = [get_any()]
    messages = get_any()
    if not isinstance(messages, list):
        print(messages)
    return 2
  • What is the actual behavior/output?
:12 error: Statement is unreachable  [unreachable]
            print(messages)
  • What is the behavior/output you expect?
    I would expect one the following:
    a) Either I get an error because "messages" is reassigned to Any afetr it was a list in the previous line
    b) Or I don't get the "unreachable" error because before the "if", "messages" can indeed not be a list

Curiously with the code below, I don't get any error

from typing import Any

def get_any() -> Any:
    return {}

def fun(message_json) -> int:
    messages = [3] # <=== only this line changes
    messages = get_any()
    if not isinstance(messages, list):
        print(messages)
    return 2

  • What are the versions of mypy and Python you are using?
    0.770 (with 0.761 I got the same error message but with "misc" code)

  • What are the mypy flags you are using? (For example --strict-optional)
    --show-error-codes --warn-unreachable

Activity

  1. JukkaL commented on Mar 20, 2020

    @JukkaL
    Collaborator

    The issue here is that an assigning an Any values does not update the inferred type of messages. The current behavior is somewhat incorrect, but it increases type checking precision in the common case. We could try out the change on semantics and estimate whether the precision loss is small enough to make this worthwhile.

    The second example not generating error seems to be a separate issue.

    Sometimes --allow-redefinition would help (but not in the above examples).

  2. hauntsaninja commented on Dec 30, 2025

    @hauntsaninja
    Collaborator

    Fixed by #18538

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions