python / python/mypy

False negative: Context manager which suppresses errors doesn't trigger `[possibly-undefined]`

Open
#17,664 2 comments 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, To Reproduce, & Actual Behaviour

The following snippet will fail at runtime, which mypy should catch with [possibly-undefined] (see mypy Playground):

# mypy: enable-error-code=possibly-undefined

from typing import Literal

class ExceptionSuppressor:
    def __enter__(self) -> None:
        return

    def __exit__(self, *args: object, **kwargs: object) -> Literal[True]:
        return True

def get_num() -> int:
    raise RuntimeError

with ExceptionSuppressor():
    var = get_num()

print(var)  # Runtime failure

Expected Behavior

print(var)  # mypy: Name "var" may be undefined [possibly-undefined]

Your Environment

  • Mypy version used: 1.10.1, 1.11.1
  • Mypy command-line flags: enable-error-code=possibly-undefined
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10, 3.12

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

Run the provided Python snippet with mypy and the enabled possibly-undefined error code, then inspect how context managers and suppressed exceptions affect control-flow analysis. Add a regression test for this case; done means mypy reports that var may be undefined after the with block.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.