Re: Immutability and Python

Discussion in 'Python' started by Mark Lawrence, Oct 29, 2012.

  1. On 29/10/2012 15:20, andrea crotti wrote:
    > I have a philosofical doubt about immutability, that arised while doing
    > the SCALA functional programming course.
    >
    > Now suppose I have a simple NumWrapper class, that very stupidly does:
    >
    > class NumWrapper(object):
    > def __init__(self, number):
    > self.number = number
    >
    > and we want to change its state incrementing the number, normally I
    > would do this
    >
    > def increment(self):
    > self.number += 1
    >
    >
    > But the immutability purists would instead suggest to do this:
    >
    > def increment(self):
    > return NumWrapper(self.number + 1)
    >
    >
    > 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.
    >
    > My impression is that things get more clumsy in the immutable form, for
    > example in the mutable form I would do simply this:
    >
    > number = NumWrapper(1)
    > number.increment()
    >
    > while with immutability I have to do this instead:
    > new_number = number.increment()
    >
    > 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?
    >


    I prefer practicality beats purity.

    --
    Cheers.

    Mark Lawrence.
    Mark Lawrence, Oct 29, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. andrea crotti

    Immutability and Python

    andrea crotti, Oct 29, 2012, in forum: Python
    Replies:
    8
    Views:
    204
    Thomas Rachel
    Nov 8, 2012
  2. andrea crotti

    Re: Immutability and Python

    andrea crotti, Oct 29, 2012, in forum: Python
    Replies:
    0
    Views:
    161
    andrea crotti
    Oct 29, 2012
  3. andrea crotti

    Re: Immutability and Python

    andrea crotti, Oct 29, 2012, in forum: Python
    Replies:
    0
    Views:
    160
    andrea crotti
    Oct 29, 2012
  4. Paul Rubin

    Re: Immutability and Python

    Paul Rubin, Oct 29, 2012, in forum: Python
    Replies:
    7
    Views:
    143
    Steven D'Aprano
    Oct 29, 2012
  5. Terry Reedy

    Re: Immutability and Python

    Terry Reedy, Oct 29, 2012, in forum: Python
    Replies:
    0
    Views:
    162
    Terry Reedy
    Oct 29, 2012
Loading...

Share This Page