Python private method for public usage

Question:

I have a class A that need to implement a method meth().
Now, I don’t want this method to be called by the end-user of my package. Thus, I have to make this method private (i.e. _meth(). I know that it’s not really, private, but conventions matter.)

The problem though is that I have yet another class B in my package that has to call that method _meth(). Problem is that I now get the warning method that say that B tries to access a protected method of a class. Thus, I have to make the method public, i.e. without the leading underscore. This contradicts my intentions.

What is the most pythonic way to solve this dilemma?


  • I know I can re-implement that method outside of A, but it will lead to code duplication and, as meth() uses private attributes of A, will lead to the same problem.

  • Inheriting from a single metaclass is not an option as those classes have entirely different purposes and that will be contributing towards a ghastly mess.

Asked By: Anton Bohdanov

||

Answers:

The fact that pylint/your editor/whatever external tool gives you a warning doesn’t prevent code execution. I don’t know about your editor but pylint warnings can be disabled on a case-by-case basis using special comments (nb: “case by case” meaning: “do not warn me for this line or block”, not “totally disable this warning”).

And it’s perfectly ok for your own code to access protected attributes and methods in the same package – the “_protected” naming convention does not mean “None shall pass”, just “are you sure you understand what you’re doing and willing to take responsability if you break something ?”. Since you’re the author/maintainer of the package and those are intra-package access you are obviously entitled to take this responsability 😉

Answered By: bruno desthuilliers

The "most pythonic way" would be to not care about private and protected, as these concepts do not exist in Python.
Everything is public. Adding a underscore in the name does not make it private, it just indicates the method is for internal use in the class (not to prevent usage by some end-user).

If you need to use the method from another class (without instantiating), it shows that you’re not using classes and objects correctly, and you probably come from a different language like Java where classes are used to group methods together in some namespace.

Just move the function to the module level (outside the class), as you’re not using the object (self) anyway.

Answered By: Alex