[Tutor] Private attributes [was Re: What on earth is happening here ???]

Steven D'Aprano steve at pearwood.info
Thu Jul 26 03:29:33 CEST 2012


Prasad, Ramit wrote:

> Trying to make things "private" is a throwback to Java. In Python
> the tendency is to just leave everything "public". And "private" is with
> one underbar/underscore.

Yes, and no.

It is true that Python encourages a "consenting adults" philosophy, where 
private attributes are not encouraged. But they're not exactly *discouraged* 
either.

In my opinion, private attributes are best used to clearly mark methods or 
functions as *implementation details*, not for access control. Python will 
give you no help whatsoever if you want to restrict access to a method or 
other object -- there are no hidden or secret names in pure Python code.

But for the purpose of marking methods as private in the sense of "not part of 
the public API", the single leading underscore convention is more than strong 
enough. Unless otherwise documented as safe to use[1], a single leading 
underscore means "if you use this, you're going to have a bad time".

Double leading underscores are different. They do double duty as marking the 
method as private, and to tell the compiler to mangle their name so as 
(almost) avoid *accidental* name clashes in subclasses. Since the caller knows 
the name mangling algorithm, Python cannot prevent deliberate name clashes. 
Nor should it -- again, the Python philosophy here is that we're all adults, 
and if a subclass wants to override a private method, who are we to say it 
shouldn't?

In general, I recommend that beginners avoid double leading underscore methods 
until they are no longer beginners, because (1) they can be confusing to 
people still trying to learn the language; (2) you aren't going to need them; 
and (3) if you do need them, you can add them in later.



[1] E.g. the collections.namedtuple API defines a number of single underscore 
names as public. They have a single underscore to avoid clashing with field 
names the caller may define.



-- 
Steven


More information about the Tutor mailing list