Skip to content

Walrus assignment after and loses an earlier narrowing #5763

Backlog

Description

@matejker

Describe the Bug

A walrus assignment on the right of and drops an earlier narrowing. The variable was already narrowed to C. After if flag and (c := find()) is None: return, Pyrefly treats it as C | None again.

On every path past the if, c is a C:

  • If flag is false, the walrus never runs, so c keeps its earlier narrowed type C.
  • If flag is true and the walrus result is None, the function returns.
  • If flag is true and the walrus result is not None, c is C.
class C: ...
def find() -> C | None: ...
def use(c: C) -> None: ...

def f(flag: bool) -> None:
    c = find()
    if c is None:
        return
    if flag and (c := find()) is None:
        return
    use(c)
$ pyrefly check --preset default min.py
ERROR Argument `C | None` is not assignable to parameter `c` with type `C` in function `use` [bad-argument-type]
  --> min.py:11:9

Expected: no error. mypy accepts this code.

  • Version: pyrefly 1.5.0
  • It reproduces with --preset default, legacy and strict. --preset basic reports no error.
  • It also reproduces when the condition is an attribute check, such as c.r.seed is None and (c := await stamp(c)) is None, inside an async def.

This may be related to #826, which is closed.

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

Activity

  1. added
    narrowing
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    narrowingtypechecking

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions