4

I understand that to write private/protected functions or methods, you use names with a leading underscore:

def _func():
    ...

but I have an object hierarchy with specialized overrides. Also, I want to hide the internal implementation (since it's not meant for outside use, and so I can hopefully improve it without breaking code). If I use

class Paragraph(Tag):
    def _method(self):
        ...

and try calling _method from a different class that subclasses Tag, IntelliJ IDEA (and probably pylint/other checkers would also) gives me a warning:

access to a protected member of a class _method

Is there any way to fix this?

My use case is a set of markdown tag objects to generate a "Tree"-like structure that can be transformed into the correct markdown string. Each tag overrides a protected method to transform itself and the tags it contains and some override a method to check whether the sub-tags are valid (example no nested Bolds). Only the top level tag context has a public method to transform the tree.

1
  • 2
    Why not just ignore the Intellij warning? Pylint won't give a damn about such calls, btw. It's just a convention, and you are using the convention correctly, by the sounds of it. Commented Apr 18, 2014 at 9:48

1 Answer 1

8

To clarify:

  • If a name starts with one underscore, it is 'protected'.
  • If a name starts with two underscores but does not end with two underscores, it is 'private'.

'Protected' is just a convention, but syntax checkers do nag about accessing them outside the class hierarchy.

'Private' is implemented by name mangling, so that the element can only be used from within the class where it was defined. The two underscores are replaced with _<name of class>__. There are tricks to circumvent this...

In the example below, pylint does not warn me for using _func inside the Test class, but I do get a warning (W0212) at the last line. Did you forget to define the protected function in the base class?

class Test(object):
    def _func(self):
        raise NotImplementedError()

    def fun(self):
        self._func()
  
class Demo(Test):
    def _func(self):
        print 'Hi'

t = Demo()
t._func()
Sign up to request clarification or add additional context in comments.

1 Comment

The problem is the lack of type hints in python, it probably can't tell that they are part of the hierarchy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.