41

In Python, prefixing with one underscore indicates that a member should not be accessed outside of its class. This seems to be on a per-class basis like Java and C++.

However, pylint seems to enforce this convention on a per-object basis. Is there a way to allow per-class access without resorting to #pylint: disable=protected-access?

class A:
    def __init__(self):
        self._b = 5

    def __eq__(self, other):
        return self._b == other._b

Result:

pylint a.py
a.py:6: W0212(protected-access) Access to a protected member _b of a client class

Pylint describes the message here.

3

2 Answers 2

34

pylint doesn't know of which type other is (how should it, you can compare an instance of A to everything), therefore the warning. I don't think there is a way around disabling the warning.

You can disable the warning for only that one line with appending # pylint: disable=W0212 to that line.

3
  • 35
    Or # pylint: disable=protected-access Commented Mar 26, 2020 at 4:02
  • @DavidBeauchemin Is pylint able to perform introspection like mypy? The error in the example still issues for me even if I put assert isinstance(other, A) before the return statement. Commented Aug 31, 2022 at 21:47
  • This should be resolved in 3.11 with the Self type, but Pylint is still reporting it. Please +1 here if you have same problem.
    – davetapley
    Commented Apr 2 at 19:16
3

Christian Geier is right about why you're getting the error, and how to disable it.

I'd encourage you to consider changing your code, though: pylint is telling you something important. From your example code looks like you want to use eq compare objects of class A to other objects of class A, but your example won't guarantee that a caller won't try A() == C(). Returning True when you check Circle()._radius == Sphere._radius seems likely to cause problems.

See this stackoverflow thread for discussion of how to handle this.

Not the answer you're looking for? Browse other questions tagged or ask your own question.