Skip to content

Redefinition doesn't work in else branch of try #18514

@hannes-ucsc

Description

@hannes-ucsc

Bug Report

To Reproduce

https://mypy-play.net/?mypy=1.13.0&python=3.13&flags=allow-redefinition&gist=62f6a12961c14755216efcd52137fee0

import json

def f() -> str:
    try:
        pass
    except ValueError:
        return ''
    else:
        x = b"{'k':'v'}"
        x = json.loads(x)
        return x['k']  # error

def g() -> str:
    if False:
        pass
    else:
        x = b"{'k':'v'}"
        x = json.loads(x)
        return x['k']  # pass

Expected Behavior

No type errors should be reported when running mypy --allow-redefinition.

Actual Behavior

An error is reported after the redefinition of x in the else branch of the try statement even though

the redefinition is in the same block and nesting level as the original definition

quoting the documentation.

main.py:11: error: No overload variant of "__getitem__" of "bytes" matches argument type "str"  [call-overload]
main.py:11: note: Possible overload variants:
main.py:11: note:     def __getitem__(self, SupportsIndex, /) -> int
main.py:11: note:     def __getitem__(self, slice[Any, Any, Any], /) -> bytes
Found 1 error in 1 file (checked 1 source file)

The redefinition in the else branch of an if statement is accepted as documented.

Your Environment

  • Mypy versions used: 1.14.1 and master
  • Mypy command-line flags: --allow-redefinition
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python versions used: 3.12 and 3.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongfalse-positivemypy gave an error on correct code

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions