11

I have a class, but every method in it should be private (apart form __init__ and __str__). Should I denote every method with a double underscore, or is that deemed bad practice?

3
  • I hear that anything in Python is public, and you should organize yourself, when to use them. I'm not really into the advanced part of the OO, but this is what's left in my mind about that.
    – dragons
    Sep 30, 2013 at 22:20
  • 2
    Just FYI, name mangling is designed to avoid collisions with commonly used names, not for privacy.
    – detly
    Oct 3, 2013 at 5:17
  • To precise @detly 's answer: not "commonly used names", but names used in subclasses. "Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling." docs.python.org/3/tutorial/classes.html#private-variables To avoid collision with a builtin name one uses a trailing underscore (list_). Aug 18, 2019 at 12:27

1 Answer 1

18

True private methods - those that can't be seen or used from outside of a class - do not exist in Python. What we have are conventions that are merely suggestions to not touch things you shouldn't.

The closest you get to privacy is name mangling. An attribute of MyClass named __some_attr will just be renamed to _MyClass__some_attr internally, making it slightly awkward to reference it from outside the class. This is seldom used. What most people do is simply prefix a single underscore (_attr) as a notation that something should not be relied upon & is not part of the public interface.

Using double underscores before and after the identifier, while not prohibited, is considered reserved for internal language details (like 'magic' methods). You shouldn't go around coming up with new __attr__s (unless you're hacking on the interpreter).

3
  • 10
    These guidelines are documented in Pep 8.
    – Brian
    Oct 2, 2013 at 17:31
  • What about cases where __some_attr will not be referenced at all outside the class? Wouldn't it be fine to use double leading underscore?
    – user
    Jul 31, 2015 at 18:40
  • @user5061 - technically a correct use but frowned on. It makes introspection more difficult. Jul 31, 2015 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy