0

In one file I define a class and a private function. I want to call this function within a method. What is the syntax to reference the "outerscope" of the class and tell python where my function lives? (:

Actual example that do not work:

def __private_function():
    pass

class MyClass:
    def my_method(self):
        __private_function()

Error: NameError: name '_MyClass__private_function' is not defined

Nb:

Similar but not a duplicate of Calling private function within the same class python.

Jeremy Cochoy
  • 2,480
  • 2
  • 24
  • 39
  • 3
    have you tried using single underscore? it would avoid name mangling. – Sheng Zhuang Dec 19 '19 at 09:52
  • 2
    I have to say I'm actually quite surprised by this behaviour :-/ Now there are actually very few reasons to use the double-leading-underscores name mangling mechanism, and specially not for plain functions. The convention is to use one single leading underscore for "implementation" stuff (consider this as the python equivalent of "protected"). – bruno desthuilliers Dec 19 '19 at 09:55

2 Answers2

2

Use single underscore to avoid name mangling.

def _private_function():
    print('use single underscore to avoid name mangling.')

class MyClass:
    def my_method(self):
        _private_function()

a = MyClass()
a.my_method()
Sheng Zhuang
  • 647
  • 5
  • 10
1

This works:

globals()['__private_function']()

But if you can, just don't name the function with two underscores. I don't think there's any good reason outside of a class.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89