2

I see a lot of python code that does "loose" private variables / functions. They'll declare functions / variables with one underscore (eg. _foo) and then use it just in the class / file. It really annoys me that they don't use the double underscore because eventually, someone will call this "private" member from outside the class.

Is there some way to enforce the privacy on single underscores (without changing to doubles)? Thanks!

rhinoinrepose
  • 2,110
  • 2
  • 19
  • 26
  • 3
    `__` has special significance. It mangles the names, makes debugging difficult and can lead to interesting issues with introspection. Your "loose" privacy is really all there is that makes sense. Who is this mysterious "someone" who will violate basic Python rules? And when the unit tests fail because they broke the rules, what more is needed? They violated the API and a test failed. Isn't that enough? – S.Lott Apr 05 '11 at 22:21
  • 1
    Nope, even that double underscore thing doesn't actually enforce `private`: http://docs.python.org/tutorial/classes.html#tut-private – Travis Gockel Apr 05 '11 at 22:21
  • Imagine trying to debug an object if you couldn't see some of its state. :-) – kindall Apr 05 '11 at 22:24

2 Answers2

9

No. And that's the philosophy of python: Do not make the compiler/parser enforce privacy since developers who want to access private members have ways to do so anyway (reflection etc.). The idea is telling people Hey, this is not part of the public API. If you use it improperly, it could breaks things or kill your cat. I might also change the signature often since it's not part of the public API and I don't have to care about people using it

And fyi, you can actually access double-underscore variables (same applies for methods) from outside using obj._ClassName__variableName. Besides that it's not encouraged to use double underscores except for mixin objects - you can never know if someone wants to subclass your class.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
6

In Python, there is no strict concept(like Java for example) of private methods. Even using double underscores is still accessible by doing _classname__method.

In short, don't go against the grain, rather go with the Python philosophy in which private is a convention, not a force.

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111