Joseph Wahba Joseph Wahba - 9 months ago 72
Python Question

Calling a private class member function in python from another module

Is it possible to call private functions declared in another class ? If yes, I need to call a function inside my main file. This function has to be imported from another module. This function is defined inside a class as follows.

class ConfLoader(object):
def _set_config_value(self, section, attribute, value):

Any suggestions ?

Answer Source

Python does not have "enforced" private functions, but it does have a naming convention that makes it harder to do accidentally. This is usually done by prepending a double underscore (not, as in your example, a single one, which functions as a normal method name). For example:

class X(object):
    def __f(self):

If I attempt to use the same name this outside the class definition, it will fail:

>>> x = X()
>>> x.__f()
Traceback (most recent call last):
  File "", line 7, in <module>
AttributeError: 'X' object has no attribute '__f'

Instead, Python uses _ClassName__PrivateMethod. I can still call this pseudo-private function outside the class definition using the following:

>>> x._X__f()

See Why are Python's 'private' methods not actually private? for some more useful information.

Note, of course, that just because something is possible does not mean it is a good idea. There is a reason why a well-designed class has private functions: these are internals that are not meant to be safely interacted with by outside functions.