Why less emphasis on private data?

Paul Boddie paul at boddie.org.uk
Mon Jan 8 12:28:24 CET 2007

Steven D'Aprano wrote:
> The truth of the matter is, MyClass.__private is not private at all. It is
> still a public attribute with a slightly unexpected name. In other words,
> if you want to code defensively, you should simply assume that Python has
> no private attributes, and code accordingly.
> Problem solved.

Well, it isn't really solved - it's more avoided than anything else.

Still, if one deconstructs the use of private data in various
programming languages, one can identify the following roles (amongst

 1. The prevention of access to data from program sections
    not belonging to a particular component.
    (The classic "keep out" mechanism.)
 2. The enforcement of distinct namespaces within components.
    (Making sure that subclass attributes and superclass attributes
    can co-exist.)
 3. To support stable storage layouts and binary compatibility.

Most Python adherents don't care too much about #1, and Python isn't
driven by the need for #3, mostly due to the way structures (modules,
classes, objects) are accessed by the virtual machine. However, one
thing which does worry some people is #2, and in a way it's the
forgotten but more significant benefit of private data.

Before I became completely aware of the significance of #2, I remember
using various standard library classes which are meant to be subclassed
and built upon, thinking that if I accidentally re-used an attribute
name then the operation of such classes would be likely to fail in
fairly bizarre ways. Of course, a quick browse of the source code for
sgmllib.SGMLParser informed me of the pitfalls, and I'm sure that
various tools could also be informative without the need to load
sgmllib.py into a text editor, but if I had been fully aware of the
benefits of private attributes and could have been sure that such
attributes had been used (again, a tool might have given such
assurances) then I wouldn't have needed to worry.

So I suppose that to "code accordingly" in the context of your advice
involves a manual inspection of the source code of superclasses or the
usage of additional tools. Yet I suppose that this isn't necessarily
unusual behaviour when working with large systems.


More information about the Python-list mailing list