Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private functions / Variables enforcement in python

Tags:

python

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!

like image 447
rhinoinrepose Avatar asked Apr 06 '26 17:04

rhinoinrepose


2 Answers

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.

like image 53
ThiefMaster Avatar answered Apr 09 '26 08:04

ThiefMaster


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.

like image 28
Mike Lewis Avatar answered Apr 09 '26 09:04

Mike Lewis