Skip to content

SLF001: access to private field of another instance of the same class typed as Self #24140

@abrahammurciano

Description

@abrahammurciano

Summary

Similar request to #9022, which was resolved with #16149. But the fix only recognizes the following patterns:

SLF001 now recognizes the following as instance-like and will not report them:

  • cls()/mcs()
  • super().__new__()
  • SameClass()/SameClass[int]()/Annotated[SameClass[int], ...]()
  • a: SameClass/a: SameClass[int]/a: Annotated[SameClass[int], ...]

It would be great if any expression typed as Self could also be recognized.

Here's a link to an example: https://play.ruff.rs/915c7db2-e843-4f50-8861-8dd0f61e79a8

class Foo:
    def __init__(self, x: int) -> None:
        self._x = x

    def foo(self) -> None:
        this = self
        print(this._x) # Private member accessed: `_x` (SLF001)
        print(self._x)

Metadata

Metadata

Assignees

No one assigned

    Labels

    ruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions