Encapsulation unpythonic?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Aug 31 07:46:52 EDT 2013


On Fri, 30 Aug 2013 23:07:47 -0700, Fabrice Pombet wrote:

> well, look at that:
> 
> a=(1,2)
> a=2+3 ->a is an object and I have changed its type and value from
> outside. 

Incorrect. You have not changed the type or value of any object. "a" is 
not an object, it is a *name*, and while you can change the object bound 
to the name, the objects remain unchanged.

When you do this:

x = 23
x = 42

the *object* 23 does not change, only the name binding changes. To do 
otherwise would cause all sorts of surprises:

# THIS DOES NOT HAPPEN IN PYTHON
# or any other language, as far as I am aware
x = 23
y = x  # y now has the value 23
x = 42  # change the value of the object  ### NOT SO! ###
print y
=> prints 42

Name binding (assignment) does not change objects. It changes the link 
between a name and the object, but the object remains untouched (unless 
it is unbound, and garbage collected). Assignment is not mutation. 
Assigning to a name does not modify the object that was previously bound.


But even if you were right about changing the type and value of objects 
in place -- Python allows you to mutate lists and dicts in place, and 
even mutate the type of some objects, although not built-ins -- your 
understanding is still confused. Re-assignment (re-binding) of local 
variables is hardly a violation of encapsulation. But if it was, then 
Java and C++ have no encapsulation either, because you can re-assign to 
local variables inside a function too.

If you want to see a language without encapsulation, you need to look at 
something like 1970s-style BASIC, a language where all variables are 
global, where there is no support for grouping related code into separate 
modules or files, where the closest thing to a function call is GOTO or 
GOSUB.

Of course, languages can have *more* or *less* encapsulation than other 
languages. C lets you encapsulate related functions into a file, but it 
has no way of grouping data and functions together except loosely, in a 
file. C++ adds classes, which has more encapsulation since you can group 
functions and their data together.



> As far as I am concerned this is one hell of an encapsulation
> violation... Could you do this -strictly speaking- in Java or C++?

Of course you could. All you need is a way to tell the compiler not to 
type-check the variable "a". Or more practically, some way to declare 
variable "a" as a reference to an untyped or generic value. C# has the 
dynamic keyword for this functionality. I don't know about Java or C++, 
but the JVM is certainly capable of implementing dynamic typing as there 
are various dynamically-typed languages built on top of the JVM, such as 
OpenXION and Cobra.



-- 
Steven



More information about the Python-list mailing list