4

consider the following pattern:

'''some module body'''

def __foo():
    '''module method foo'''
    pass

class Dummy(object):
    @staticmethod
    def bar():
        __foo()

__foo() # No Error.
Dummy.bar() #NameError: Global name "_Dummy__foo" is not defined.

Why is this happening?

--

And if it's bad to name it with "__", what is the best practice in Python to make module methods available only for inner-module functions/methods?

5
  • 1
    Welcome to the concept of name mangling. Commented Jul 5, 2013 at 3:42
  • 1
    cf. the Python documentation. "Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is now textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped." Commented Jul 5, 2013 at 3:43
  • 1
    Better reference to the docs (not for an obsolete version): docs.python.org/2/tutorial/… Commented Jul 5, 2013 at 3:44
  • 1
    The "best practice in Python to make module methods available only to inner-module functions/methods" is don't do it at all. Commented Jul 5, 2013 at 3:57
  • 4
    It is nearly impossible to make anything truly private in Python. This is by design. Instead, put a single underscore in front of anything clients of the module shouldn't touch, and don't touch anything from other modules that starts with an underscore. Commented Jul 5, 2013 at 4:00

1 Answer 1

5

Don't start names with double underscores. Any identifier found in a class statement, starting with at least 2 underscores and ending with less than 2 underscores, gets _Classname prepended to it, where Classname is the name of the class. This is supposed to provide limited support for private-ish variables, but using it is often considered bad practice.

Sign up to request clarification or add additional context in comments.

1 Comment

Technically it's for MI collision prevention (not that MI is such a great idea regardless...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.