python / python/mypy

Platform check is not remembered after `return`

Open
#14,940 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

A platform check that is working fine in if and else is not working after if ... return.

To Reproduce

import sys

def works() -> None:
    if sys.platform != "win32":
        return
    else:
        from winreg import REG_SZ

def fails() -> None:
    if sys.platform != "win32":
        return
    from winreg import REG_SZ

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

Expected Behavior

No error.

Actual Behavior

main.py:12: error: Module "winreg" has no attribute "REG_SZ" [attr-defined]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Failure is on Linux
  • Mypy version used: 1.1.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.2

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 provided Python reproducer and mypy-play link, then trace how platform checks and early returns affect type narrowing. Compare the if/else and if ... return cases; done means the second form no longer reports a false winreg.REG_SZ attribute error.

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.