python / python/mypy

Making a variable optional in an `else` block doesn't work for `try`/`else`

Open
#12,782 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

#11002 allowed making a variable optional in an else block; this appears not to work in an else block from a try.

To Reproduce

# t.py
def __() -> None:
    try:
        ...
    except ValueError as exc:
        e = exc
    else:
        e = None

$ mypy t.py
t.py:7: error: Incompatible types in assignment (expression has type "None", variable has type "ValueError")
Found 1 error in 1 file (checked 1 source file)

Expected Behavior

I expect this to pass, as it would if it were an if/else

Actual Behavior

As above.

Your Environment

  • Mypy version used: 0.950
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: Python 3.10.4 (main, Apr 26 2022, 19:42:59) [Clang 13.1.6 (clang-1316.0.21.2)]
  • Operating system and version: MacOS 12.3.1 (21E258)

I'm not sure if this is expected, and try/except was out of scope for the original feature, or whether this is a bug.

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 by running the reported t.py example with mypy 0.950 and compare its try/except/else behavior with the if/else behavior described in issue #11002. Trace the type-checking path for assignments across try blocks, then add a regression test for the example and confirm mypy accepts the None assignment without introducing errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.