Skip to content

Attribute writes inside a loop are ignored after the loop #5767

Todo

Description

@synnks

Describe the Bug

When a loop assigns to an attribute, Pyrefly ignores that assignment after the loop and keeps the attribute's type from before the loop. This causes false positives and hides real errors.

class Stats:
    def mean(self, values: list[int]) -> float:
        self.count = 0
        for _ in values:
            self.count += 1
        return 10 / self.count if self.count > 0 else 0.0
        # warning: Cannot divide by zero: `/` with a literal zero divisor


class Slot:
    value: int | None = None


def bump(slot: Slot, items: list[int]) -> int:
    slot.value = 0
    for _ in items:
        slot.value = None
    return slot.value + 1
    # no error, but this raises TypeError when `items` is not empty

Expected:

  • self.count is int after the loop, so the guarded division is accepted.
  • slot.value is int | None after the loop, so slot.value + 1 is an error.

reveal_type(self.count) shows Literal[0] both inside the loop and after it. Item assignments such as values[0] = None are ignored the same way. Plain local variables work as expected.

Sandbox Link

https://pyrefly.org/sandbox/?project=v2.jZVNDoIwEIWvMgkLTDC0LNyY6BlM2GpMRUQTbYktnt_pH21FiTtoZ8pM53uPX5ZppVIrpvztWrQZj0XiBYb3fjCzvqAlxXQbpTRi4Aqrp2Fdj_Co5-eOCTsfWcUGqgmSFQUSByE80dsWqCEVaIlfDLqv78KX5pSFZaeysuG609Pw6BdSZ5i8ZeInY7v44E7UoaMluEbHJmNIJ8FBlq67aLfQzU9By2BnF8DNDC0WCe0GNHIkr9zzDD28hatSvVwT4tPFsyMtJ2fRSJJkEFMre7Gb-T2kx4EwwpB47HfCV38RnlvA8zm-c403Rswi-wY

(Only applicable for extension issues) IDE Information

No response

Activity

  1. synnks commented on Nov 25, 2026

    @synnks
    ContributorAuthor

    #claim

  2. github-actions commented on Nov 25, 2026

    @github-actions

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions