Immutability and Python

andrea crotti andrea.crotti.0 at gmail.com
Mon Oct 29 12:33:03 EDT 2012


2012/10/29 Chris Angelico <rosuav at gmail.com>:
> On Tue, Oct 30, 2012 at 2:55 AM, Paul Rubin <no.email at nospam.invalid> wrote:
>> andrea crotti <andrea.crotti.0 at gmail.com> writes:
>>> and we want to change its state incrementing the number ...
>>>  the immutability purists would instead suggest to do this:
>>>     def increment(self):
>>>         return NumWrapper(self.number + 1)
>>
>> Immutability purists would say that numbers don't have "state" and if
>> you're trying to change a number's state by incrementing it, that's not
>> immutability.  You end up with a rather different programming style than
>> imperative programming, for example using tail recursion (maybe wrapped
>> in an itertools-like higher-order function) instead of indexed loops to
>> iterate over a structure.
>
> In that case, rename increment to next_integer and TYAOOYDAO. [1]
> You're not changing the state of this number, you're locating the
> number which has a particular relationship to this one (in the same
> way that GUI systems generally let you locate the next and previous
> siblings of any given object).
>
> ChrisA
> [1] "there you are, out of your difficulty at once" - cf WS Gilbert's "Iolanthe"
> --
> http://mail.python.org/mailman/listinfo/python-list


Yes the name should be changed, but the point is that they are both
ways to implement the same thing.

For example suppose I want to have 10 objects (for some silly reason)
that represent the next number, in the first case I would do:

numbers = [NumWrapper(orig.number)] * 10
for num in numbers:
    num.increment()

while in the second is as simple as:
numbers = [orig.next_number()] * 10

composing things become much easier, but as a downside it's not always
so easy and convienient to write code in this way, it probably depends
on the use case..



More information about the Python-list mailing list