Python – Usage of __ While Declaring Variables or Class Members

python

Is it good practice to use __ convention while declaring the member variable?

This also imparts private kind of feature of that data member. There have been cases when I found that its good to have hidden members of a class. This is certainly exposes only that feature that will help the the object to behave in more protected manner.

Best Answer

A lot of people erroneously use double underscores to simulate "private" members, because double underscores invokes code mangling and makes those members harder to reference outside the class. However, it does not actually make them inaccessible.

Most of the time, it mainly adds a road bump to unit testing.

Really the double underscore mangling mechanism is to hide those members from subclasses that you don't want clobbering the values inadvertently. Name mangling isn't intended to hide the member from other programmers; the mangling scheme is simple, and referencing the variables anyway is easy.

Single underscore is the common convention for internal members. That's saying, we're all adults here, and although you can see it, this variable is intended for internal use. If you reference it, there's no guarantee it will still be there in future versions.

The Pep8 doc talks about that, and says use of the double underscores for variables and functions should really be rare.

Related Topic