Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32383

Immutability and Python

Date 2012-10-29 15:20 +0000
Subject Immutability and Python
From andrea crotti <andrea.crotti.0@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3018.1351524004.27098.python-list@python.org> (permalink)

Show all headers | View raw


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?

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Immutability and Python andrea crotti <andrea.crotti.0@gmail.com> - 2012-10-29 15:20 +0000
  Re: Immutability and Python Paul Rubin <no.email@nospam.invalid> - 2012-10-29 08:55 -0700
    Re: Immutability and Python Chris Angelico <rosuav@gmail.com> - 2012-10-30 03:08 +1100
    Re: Immutability and Python andrea crotti <andrea.crotti.0@gmail.com> - 2012-10-29 16:33 +0000
  Re: Immutability and Python Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-10-29 23:02 +0000
  Re: Immutability and Python rusi <rustompmody@gmail.com> - 2012-10-30 09:22 -0700
    Re: Immutability and Python Neal Becker <ndbecker2@gmail.com> - 2012-10-30 16:45 -0400
      Re: Immutability and Python rusi <rustompmody@gmail.com> - 2012-10-30 20:21 -0700
  Re: Immutability and Python Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2012-11-08 08:38 +0100

csiph-web