Skip to content

Closure narrowing loss after reassignment #2739

@grievejia

Description

@grievejia

Describe the Bug

Minimal repro:

from typing import Callable

class Connection:
    def __init__(self, host: str) -> None:
        self.host = host

    def clone(self) -> "Connection":
        return Connection(self.host)


def get_connection() -> Connection | None:
    return Connection("localhost")


def make_query_func() -> Callable[[], str]:
    conn = get_connection()
    assert conn is not None, "connection required"
    # Reassign after assert narrowing
    conn = conn.clone()

    def query() -> str:
        # FP: `Connection | None` is not assignable to `Connection`
        current: Connection = conn  # E: bad-assignment
        return f"querying {current.host}"

    return query

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0BhVFCipssADropAY1Fw4g3OnQwZDCMsRS6uuphhg6AfWOsIDUwAo4MKGAA0dABa44DRHXeUAlHQC0AHx0AHLKMNroetFedmCEru50ALwubgxSOnoGRnLhNnF%2BQXQSIALKquqa0khZMXSUMAwArpRR5SpqGsoF9gnpPpnSWIZ0bE3GMhVd1VZFwR2V3VEAPqHhkdGNLW1KnVU9pVC4MsKJGSCDw1I5dDSoANYwxgCOzTCUpMZgzegycwEFsJROIYABtMEAXSc3khmz0UxUKTGE0RS1mV2iqAUH34aM4inQuH4YVUTlKaJmygaMDeEEamFKdToAGI6AAlGDYuAQNhRVBgBgfOjc3F0dCoSjUADurDYzPxqTRhDyqjmQ2itzeH1IAOK3nh9TZZEaYCgpE8AANFlTVutVJaCeLiSKFLyJaDGLg6Nbpgd0JbmdEZK1GugPHt0dSlRVdGyAKKebCoTD%2BbnumgwcNBvTbVpRMClbWfOV0YAhqVZhj9dwAXyZwy2TXzdGL5AcIGaGigcBI5EQIDZAFVuxZSHQfn9lnAhrcwLx7pZ0M0aNgPlZ8J5WAx5l4GJRDTSdgXSiEV2uD2X8PWQFIQB2TYZzYQGLQoBQ2QAFUim81eDA4AQdCIpAbCtKgyyEFIbIAMowDALgMAwxBwIgAD0aGPmapCELwbBoVmaGYCccBoSBvLgcsaETrwIoAG6oNAYiwMByigZR1R0LgxDTlB6BkAwrjoP4dEfDy0YlCAADMhAAIwAEwNiAtYdqgVSiQAYtAMAUGgWB4EQZDKUAA

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    narrowingIssues with narrowing - root cause is usually narrowing, flow handling, or bothscoping-control-flowissues related to scoping and control flowtypecheckingusabilityUsability & readiness issues identified with running Pyrefly on top OSS projectsv1-consider-addingTop-ranked but not in V1 milestone (consider adding)

    Type

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions