python / python/mypy

Inference in the `else` block of a try-except-else

Open
#14,527 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

In the else branch of a try-except-else, mypy ought to be able to infer that no except branch was taken.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=306f5b87e1b2eadc3f7692718a21f6b5

import random


def maybe_int() -> int:
    if random.choice([True, False]):
        return 42
    else:
        raise ValueError


def main() -> None:
    try:
        x = maybe_int()
    except ValueError:
        x = None
    else:
        x += 1  # mypy error occurs here

Expected Behavior

At the last line of the example, I expected mypy to infer that the except branch hadn't been taken, and therefore x was of type int, just as it is at the end of the try branch.

Actual Behavior

test.py:17: error: Unsupported operand types for + ("None" and "int")  [operator]
test.py:17: note: Left operand is of type "Optional[int]"

Your Environment

  • Mypy version used: 0.991 (compiled: yes)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10.7

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 linked mypy-play reproducer and confirm the Optional[int] error in the try-except-else example. Trace how mypy handles the try, except, and else branches, then add regression coverage showing that x is inferred as int in the else branch and the reported error is removed.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.