Protected Methods and Python

Jp Calderone exarkun at intarweb.us
Sun Apr 13 19:04:33 EDT 2003


On Sun, Apr 13, 2003 at 09:26:37PM +0200, Mads Orbesen Troest wrote:
> On Sun, 13 Apr 2003 21:24:24 +0200, Mads Orbesen Troest wrote:
> 
> >> Or may be it is possible to emulated Protected Methods in Python.
> > 
> > It can be "emulated" by prepending the method/attribute name with 2 
> > underscores. 
> 
> Whoops, I was too quick and didn't see that you wrote "protected" and not 
> "private".
> 
> At any rate: the mangling scheme can be used for "protected" methods, since 
> you know the mangled name is _classname__attribute/method. You can then be 
> one of the "evil" persons I talked about in the previous post, and access 
> the "private" member that way.
> 

  Double underscore prefix is for avoiding name collisions in inheritance,
not preventing people from touching things you consider private to the
implementation.

  Language enforced private attributes are a Wrong idea because they
needlessly increase the difficulty of people trying to use code which
employs this feature.

  There are a few possible scenarios:

  1) I am a skillful coder and I am using a library written by a skillful
coder.  The library is bug-free (for the purpose which I use it) and I have
no need to touch the implementation's internal variables.  In this scenario,
runtime protected private attributes are not useful.

  2) I am not a skillful coder and I am using a library written by a
skullful coder.  The library is bug-free (for the purpose which I use it)
but I feel the need to touch the implementation's internal variables anyway. 
Whether or not they are protected by the runtime environment, I will
probably find a way to screw up my application, because I am not skilled. 
In this scenario, runtime protected private attributes are not useful.

  3) I am a skillful coder and I am using a library written by someone who
is not skillful.  The library contains bugs which disrupt my application. 
In this scenario, runtime protected private attributes make it impossible
for me to work around bugs in the library, and so are worse than useless.

  Since Python provides no real runtime protection of private attributes,
the best you can hope to do is make it excessively painful for people using
your code to work around your bugs.  I can't imagine why anyone would want
to do this.

  If an attribute is private to your implementation, document it this way
and prefix it with a single underscore.  Nothing else is necessary.

  high-and-mightily y'rs,

  Jp

-- 
"There is no reason for any individual to have a computer in their
home."
                -- Ken Olson, President of DEC, World Future Society
                   Convention, 1977
-- 
 up 24 days, 19:01, 7 users, load average: 1.07, 1.20, 1.45





More information about the Python-list mailing list