Immutability and Python
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
To pick up your example,
def __init__(self, number):
self.number = number
def __iadd__(self, x):
self.number += x
def __add__(self, x):
return NumWrapper(self.number + x)
number += 1
you keep the same object and modify it, while with
number = number + 1
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.
More information about the Python-list