Skip to content

Variable type is not narrowed after "if" containing both call to "Never-returning" function and "raise" #5186

Description

@Feuermurmel

Describe the Bug

from __future__ import annotations
from typing import Never

def fail() -> Never:
    raise Exception()

def foo(x: str | None) -> str:
    if x is None:
        try:
            fail()
        except Exception:
            raise Exception()

    return x

Python: 3.12

IIUC, the code above should be considered correctly typed. The body of the if statement in foo() never terminates normally. It either calls a function that returns Never or raises an exception. Thus, x should be narrowed to str after the if statement.

Sandbox Link

https://pyrefly.org/sandbox/?project=v2.jZVRDsIgDIavQrIHfJJ3T-EBTBaiOE3MWIAZju9PAdkIEve2pi2l_frTlcxxvK9gIMwkr3YoTqZVbsgq6eAXZPl8JQSCedvQ0u84UnLX-uBpgxPrFIrfQrhv0F0Gmr94brHVI67cmwVtFsBTt6tZD-wcDSy1DSoHSKYVWookx8s8QEYVezi32JMQOVybSahZ3PTVil2EwP0Nk2_UHnR5n45pKs0ibQeyxSirHEwcTcNjwv_gjkfs4PqbOh6gg0cXpA8

(Only applicable for extension issues) IDE Information

No response

Activity

  1. changed the title [-]Bug Report[/-] [+]Variable type is not narrowed after "if" containing both call to "Never-returning" function and "raise"[/+] on Oct 10, 2026
  2. added
    narrowingIssues with narrowing - root cause is usually narrowing, flow handling, or both
    on Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

narrowingIssues with narrowing - root cause is usually narrowing, flow handling, or bothscoping-control-flowissues related to scoping and control flow

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions