Why less emphasis on private data?

John Nagle nagle at animats.com
Sun Jan 7 14:13:57 EST 2007


sturlamolden wrote:
> time.swift at gmail.com wrote:
> 
>>Coming from a C++ / C# background, the lack of emphasis on private data
>>seems weird to me. I've often found wrapping private data useful to
>>prevent bugs and enforce error checking..
>>
>>It appears to me (perhaps wrongly) that Python prefers to leave class
>>data public.  What is the logic behind that choice?
> 
> 
> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that
> if an object's 'internal' variables or states cannot be kept private,
> programmers get an irresistible temptation to mess with them in
> malicious ways.

     If you're not clear on encapsulation issues, you probably haven't
done extensive maintenance programming on code written by others.
Finding out who can mess with a variable when debugging the code of
others is not fun.

     Because Python doesn't have explicit declarations, scope of variables is
a touchy issue.  If you write "x = 1" within a function, that will
create a local "x" if "x" doesn't exist, or alter a global "x" if "x" was
previously created in the global context.  But at least global variables
are local to the namespace; we don't have clashes across files.  So
it's not too bad.  JavaScript has the convention that newly created
variables are global by default.  Big mistake.

     The underscore thing makes sense.  Single underscore
variables are "protected" in the C++ sense, and double underscore
variables are "private", not visible from inherited classes.
It's hard to misuse such variables by accident.  I'd be tempted
to prohibit access to underscore variables other than via "self._x"
forms, so they'd be inaccessable outside the object.  It's undesirable
from a maintenance standpoint to have an unenforced convention like
a lead underscore.  The maintenance programmer can't trust its meaning.

     As Python grows up, and larger systems are written in it, these
issues become more important.

				John Nagle
				Animats



More information about the Python-list mailing list