Skip to content

[flake8-self] Recognize Self-typed expressions in SLF001#24148

Closed
chinar-amrutkar wants to merge 1 commit intoastral-sh:mainfrom
chinar-amrutkar:fix/24140-slf001-self-type
Closed

[flake8-self] Recognize Self-typed expressions in SLF001#24148
chinar-amrutkar wants to merge 1 commit intoastral-sh:mainfrom
chinar-amrutkar:fix/24140-slf001-self-type

Conversation

@chinar-amrutkar
Copy link
Copy Markdown
Contributor

Summary

Fixes #24140

Variables annotated with Self (from typing or typing_extensions) are now recognized as same-class instances and no longer trigger SLF001 for private member access.

from typing import Self

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

    def foo(self) -> None:
        this: Self = self
        print(this._x)  # previously SLF001, now OK

Changes

Added Self type check in SameClassInstanceChecker::match_annotation using semantic.match_typing_expr(annotation, "Self")
Added test fixture SLF001_self.py covering: Self annotation on variable, Self annotation on parameter, Self in classmethod, and cross-class access (still flagged)

Test Plan

this: Self = self accessing this._private -> no diagnostic
other: Self as parameter accessing other._private -> no diagnostic
other: DifferentClass accessing other._private -> SLF001 still flagged

Variables annotated with  (from  or )
are now recognized as same-class instances and no longer trigger SLF001
for private member access.

Fixes astral-sh#24140
@MichaReiser
Copy link
Copy Markdown
Member

Thank you. There's already a PR for the very same issue, see #24144

I'll close this one but if you have time, would you mind taking a look at the other PR to see if there's something missing

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants