Skip to content

Redefinition without reassignment doesn't check existing valueΒ #12866

Open
@Zeckie

Description

@Zeckie

With --allow-redefinition, mypy allows a variable to be redefined, without checking that the existing value is the correct type.

a: str = "foo"
print(a)  # value needs to be used before redefinition
a: int  # but it is really still str
if a > 1:
    ...

https://mypy-play.net/?mypy=latest&python=3.10&flags=allow-redefinition&gist=79d1e9219d66da441050ba730a7c2842

Expected Behaviour

In this example, mypy should detect that a is still a str, and not allow this redefinition.

It could treat the redefinition as though it is a new variable, being assigned the value of the existing one. That would result in an error like:
error: Incompatible types in assignment (expression has type "str", variable has type "int")

Or it could be a new error, like:
error: Redefinition incompatible with existing type (existing type "str", new type "int")

Actual Behaviour

mypy:

Success: no issues found in 1 source file

python:

TypeError: '>' not supported between instances of 'str' and 'int'

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions