3 ms·
Why would you want to actually enforce privacy? That makes it harder for the user to patch. Better to provide a mild discouragement via "_name".
by xapata 8y ago
Why would you want to actually enforce privacy? That makes it harder for the user to patch. Better to provide a mild discouragement via "_name".
- twblalock 8y agoBecause in traditional object-oriented design you would extend rather than patch. It's the open-closed principle. There are many benefits to enforcing privacy, and one of the biggest ones is that you can make changes to the internals of your library without breaking your users' code, because they never had access to the internals.
- xapata 8y agoYou can get that benefit with Python. Name mangling helps. It gets the benefits of `final` without the annoying enforcement. Don't stop me from patching your buggy code. If writing an extension is more efficient, that's how I'd solve the problem.
- marvin 8y agoThat's an eternal ideological debate where there is always a rebuttal on the form "a-ha - but you could just...", but the rationale is this: Your class will probably be doing things with the private variables that aren't obvious, and will break things if you access them from outside. (Either by them having a different value than you expect, or expecting a different value than you set). Of course, if you have a perfect understanding of the code, this will never be a problem, as the program is always executed as it is written. But most likely, not everyone in your organization will be as patient, smart and attentive to the details as you are.
- StavrosK 8y agoI don't understand the argument, though. Python's underscore variables are meant to not be accessed from outside. The argument against them isn't that you might be doing some non-obvious things inside the class, that's the whole point of them! It's a way for the class user to say "I know this is terrible, I know this might break, I want to do it anyway".
- ychen306 8y agoThe obvious usage of privacy is so you don't expose an API you don't want to maintain. It's also occasionally used to maintain some invariants; for instance, you can have a public method that wraps around some protected interface that does input checking/clean up. Having the compiler enforcing privacy, in this case, guarantees that whatever actual method you dynamically dispatches to has the "right" input (accidentally calling the interface directly won't compile).