Skip to content

Walrus assignment after and loses an earlier narrowing #5763

In review

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
  2. github-actions commented on Nov 26, 2026

    @github-actions

    @dibrinsofor we couldn't find a merged PR from you, and we only allow multiple simultaneous claims from repeat contributors. You're already assigned to #5647.

  3. TimonGaertner commented on Nov 26, 2026

    @TimonGaertner
    Contributor

    #claim

  4. github-actions commented on Nov 26, 2026

    @github-actions

    @TimonGaertner you've claimed this issue — it's now assigned to you. Thanks for picking it up! 🎉

  5. added a commit that references this issue on Nov 26, 2026
    cca4837
  6. stroxler commented on Nov 28, 2026

    @stroxler
    Contributor

    Taking this issue along with @TimonGaertner

    I think it touches on some major problems in Pyrefly, including ones related to our binding graph where any mistakes could lead to nondeterminism. I suspect that this is going to have to be solved as part of a major project (as in weeks of full-time work) from someone on the team, likely me.

  7. added theissue type on Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

has-open-prnarrowingtypechecking

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions