data hiding/namespace pollution

bruno at modulix onurb at xiludom.gro
Mon Oct 31 11:51:44 CET 2005

Alex Hunsley wrote:
> There's no really specific questions in this post, but I'm looking for
> people's thought on the issues within...
> The two main versions I've encountered for data pseudo-hiding
> (encapsulation) 

Hmmm... Are data-hiding and encapsulation really the same things ?

> in python are:
> method 1:
> _X  - (single underscore) - just cosmetic, a convention to let someone
>       know that this data should be private.
> method 2:
> __X - (double underscore) - mangles the name (in a predictable way).
>       Avoids name pollution.
> How often does either tend to get used? Personally, I'd be a little
> worried about using method 1, because namespace clashes could happen. Is
> this overly paranoid?


Note that prefixing names with a single underscore have a 'protected'
semantic - which means that such names (well, the objects that are bound
to...) can be overriden/extends by child classes.

I personnally only use the double-underscore notation only for things
that are *really* implementation-specific *and* should *really not* be

> Also, I presume that rather than people writing their own manual getter
> and setter methods, they tend to use either overloading on __getattr__
> and __setattr__, or the Property class (which itself uses aforementioned
>  methods). 

Yeps... This is the pythonic way.

> Overloading __getattr__ etc. seems more attractive to me, as
> then I can capture access to unknown names, and raise an exception!
> (I really don't like the idea of random attribute name typos going
> unnoticed when accessing attributes in a class!)

Err... Have you *really* tried to access an inexistant attribute ?  This
is usually not 'unnoticed' (unless you consider the raising of an
AttributeError as being the same as 'unnoticed' !-)

I personnaly use 'magic' accessors only for delegation or like, and
properties (or custom descriptors) for anything else (that requires
it...). This avoid the Big-Switch-Syndrom in __getattr__ and setattr__,
and is much more explicit (API, documentation, introspection etc...).

> Note: I do know that the use of the above things is quite dependent on
> what exactly you're coding, the size of the project etc., but what I'm
> trying to find out about is the python communities' recognised good
> practices.

Then launch your python interactive shell and type "import this"

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list