Immutability and Python

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Nov 8 08:38:42 CET 2012


Am 29.10.2012 16:20 schrieb andrea crotti:

> Now on one hand I would love to use only immutable data in my code, but
> on the other hand I wonder if it makes so much sense in Python.

You can have both. Many mutable types distinguish between them with 
their operators.

To pick up your example,


class NumWrapper(object):
     def __init__(self, number):
         self.number = number
     def __iadd__(self, x):
         self.number += x
         return self
     def __add__(self, x):
         return NumWrapper(self.number + x)

So with

     number += 1

you keep the same object and modify it, while with

     number = number + 1

or

     new_number = number + 1

you create a new object.


> But more importantly normally classes are way more complicated than my
> stupid example, so recreating a new object with the modified state might
> be quite complex.
>
> Any comments about this? What do you prefer and why?

That's why I generally prefer mutable objects, but it can depend.


Thomas



More information about the Python-list mailing list