[`flake8-self`] Fix False Negative Issue on Rule `SLF001` (#2527)

This commit is contained in:
Maksudul Haque 2023-02-03 18:39:24 +06:00 committed by GitHub
parent 0f8f250bea
commit c96ba6dec4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 63 additions and 11 deletions

View File

@ -1,13 +1,40 @@
class Foo:
class BazMeta(type):
_private_count = 1
def __new__(mcs, name, bases, attrs):
if mcs._private_count <= 5:
mcs.some_method()
return super().__new__(mcs, name, bases, attrs)
def some_method():
pass
class Bar:
_private = True
@classmethod
def is_private(cls):
return cls._private
class Foo(metaclass=BazMeta):
def __init__(self):
self.public_thing = "foo"
self._private_thing = "bar"
self.__really_private_thing = "baz"
self.bar = Bar()
def __str__(self):
return "foo"
def get_bar():
if self.bar._private: # SLF001
return None
return self.bar
def public_func(self):
pass
@ -29,3 +56,4 @@ print(foo._private_thing) # SLF001
print(foo.__really_private_thing) # SLF001
print(foo._private_func()) # SLF001
print(foo.__really_private_func(1)) # SLF001
print(foo.bar._private) # SLF001

View File

@ -26,8 +26,10 @@ const VALID_IDS: [&str; 3] = ["self", "cls", "mcs"];
pub fn private_member_access(checker: &mut Checker, expr: &Expr) {
if let ExprKind::Attribute { value, attr, .. } = &expr.node {
if !attr.ends_with("__") && (attr.starts_with('_') || attr.starts_with("__")) {
let ExprKind::Name { id, .. } = &value.node else {
return;
let id = match &value.node {
ExprKind::Name { id, .. } => id,
ExprKind::Attribute { attr, .. } => attr,
_ => return,
};
if !VALID_IDS.contains(&id.as_str()) {

View File

@ -2,14 +2,25 @@
source: src/rules/flake8_self/mod.rs
expression: diagnostics
---
- kind:
PrivateMemberAccess:
access: bar._private
location:
row: 34
column: 11
end_location:
row: 34
column: 28
fix: ~
parent: ~
- kind:
PrivateMemberAccess:
access: foo._private_thing
location:
row: 28
row: 55
column: 6
end_location:
row: 28
row: 55
column: 24
fix: ~
parent: ~
@ -17,10 +28,10 @@ expression: diagnostics
PrivateMemberAccess:
access: foo.__really_private_thing
location:
row: 29
row: 56
column: 6
end_location:
row: 29
row: 56
column: 32
fix: ~
parent: ~
@ -28,10 +39,10 @@ expression: diagnostics
PrivateMemberAccess:
access: foo._private_func
location:
row: 30
row: 57
column: 6
end_location:
row: 30
row: 57
column: 23
fix: ~
parent: ~
@ -39,11 +50,22 @@ expression: diagnostics
PrivateMemberAccess:
access: foo.__really_private_func
location:
row: 31
row: 58
column: 6
end_location:
row: 31
row: 58
column: 31
fix: ~
parent: ~
- kind:
PrivateMemberAccess:
access: bar._private
location:
row: 59
column: 6
end_location:
row: 59
column: 22
fix: ~
parent: ~