data hiding/namespace pollution

Alex Hunsley lard at tardis.ed.ac.molar.uk
Mon Oct 31 05:35:19 EST 2005


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) 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?

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). 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!)

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.

thanks,
alex




More information about the Python-list mailing list