ruff icon indicating copy to clipboard operation
ruff copied to clipboard

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

Open nktrnv opened this issue 1 year ago • 3 comments

Is this a bug or do I understand something wrong?

class Foo:
    def __init__(self) -> None:
        self._value = 0
    
    def get_new_instance_with_another_value(self, value: int) -> "Foo":
        foo = Foo()
        foo._value = value  # SLF001 Private member accessed: `_value`
        return foo

For example, in Java, such code will be valid:

public class Foo {
    private int value = 0;
    
    public Foo getNewInstanceWithAnotherValue(int value) {
        Foo foo = new Foo();
        foo.value = value; // No issues
        return foo;
    }
}

nktrnv avatar Dec 06 '23 11:12 nktrnv

I think it would be reasonable to allow this.

charliermarsh avatar Dec 07 '23 02:12 charliermarsh

self-like variables in __new__ should also be exempted:

class C:
	def __new__(cls):
		instance = super().__new__(cls)
		instance._foo = 42
		return instance
$ ruff check --select SLF001 foo.py
foo.py:4:3: SLF001 Private member accessed: `_foo`
Found 1 error.

InSyncWithFoo avatar Feb 01 '24 18:02 InSyncWithFoo

FWIW, it seems SLF001 is already suppressed in some cases like __lt__ (or, perhaps it's not processing correctly in the first place?)

class Wrap:
    def __init__(self, other: Any) -> None:
        if isinstance(other, Wrap):
            self._value = other._value  # SLF001 Private member accessed: `_value`
        else:
            self._value = other

    def __lt__(self, other: Wrap) -> None:
        return id(self._value) < id(other._value)
$ ruff check --select SLF001 /tmp/t.py
/tmp/t.py:4:27: SLF001 Private member accessed: `_value`
Found 1 error.
$ ruff --version
ruff 0.4.1

sbrudenell avatar Apr 22 '24 19:04 sbrudenell