[Tutor] <mutable>.__mul__

Dave Angel davea at davea.name
Sat Aug 3 21:58:59 CEST 2013


Albert-Jan Roskam wrote:

     <snip>
>
> Thank you. If list.__mul__ is so tricky, why did they implement it the way they did? Are there situations where this behavior could be useful?
>
> Btw, this is one of the rare (very, very rare) cases where I find CRAN R better than Python:

Using "multiply" to pre-fill a list is very useful, and it's harmless if
the value used is immutable, which it usually is.  And the problem
described in this thread is not specific to a list being filled with
multiply..  Any time you bind the same mutable value to multiple
places, you need to be aware that changing one of them changes them all.

But this behavior is much safer than the alternative, not to mention
faster and more memory efficient.  Further, if the alternative (copy)
were the default, it would require a new syntax to specify that you
don't want a copy.

Most languages I know of have the same duality, but they expose it
differently.  And in many cases, you can hide the behavior under the
declarations.  So you have tricky declarations and if you get them
wrong, there are nasty surprises in store.  For example in C++, you can
declare a variable as a refernece to another one.  Now when you use the
first variable, you get value of the second one, changed or not.  But if
you forget the & in the declaration, the behavior changes in a subtle
way, perhaps far from the place you made the declaration.

One thing that Python does differently is that it *allows* you to change
what something references.  By being less restrictive than C++, you get
more power.  And more responsibility.

-- 
Signature file not found



More information about the Tutor mailing list