4

I understand that to write python module private/protected functions you use

def _func():
    ...

but I have an object hierarchy with specialized overrides. Also I want to hide the internal implementation(since its not meant for outside use, and so I can hopefully improve it without breaking code, not that I think anybody will use it except me). 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) give me a warning. 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.

edit:

IntelliJ IDEA warning:

access to a protected member of a class _method

4
  • What does the "offending" call look like? Commented Apr 18, 2014 at 9:40
  • 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
  • Possible duplicate: stackoverflow.com/questions/1301346/… Commented Apr 18, 2014 at 14:09
  • I don't think it's a duplicate. Commented Apr 19, 2014 at 9:53

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...

That said, what is the warning you get? 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.