Search code examples
pythonoopfunctional-programmingimperative-programming

Mutable and Immutable objects are implemented the same in all programming languages?


The main ideas of immutability are kept the same throughout the scope of OOP and functional programming or do, for example, Java and Python have their own versions of immutability. More specifically do the following hold in all languages?

  • Mutable Objects: Set, Dict, List
  • Immutable Objects: Bool, Int, Float, String, Tuple
  • In python two immutable objects with the same value also have the same id, two references one value.
  • In python again two mutable objects with the same value don't share the same id, two references two values.
  • Does this idea of two references binding together in mutable objects hold in all languages? And the reverse as well, that is, bindings cannot be changed, meaning that references can only change the value they are pointing to.

    i = {1,2,3} # Set, a mutable object
    j = {1,2,3}
    i is j
    False
    i = j
    j.remove(3)
    i is j
    True
    

I'm asking because for example in scripting languages objects are passed by references (in other languages passed by value or in C where we have both) so doesn't this change the whole notion of immutability?


Solution

  • If you have any object, even literal ones, it needs to use some space in memory.

    This memory needs to be mutated by the language runtime and it is the same if it's immutable or not. Thus mutable objects mutate memory when object gets created.

    Thus an immutable object is one that either is ensured not to be changed at compile time or protected by the runtime when the program runs.

    In python two immutable objects with the same value also have the same id, two references one value.

    I don't think this is guaranteed at all. Eg.

    x = (1,2,3)
    y = (1,2,3)
    x is y
    // => False
    

    When I run it in my repl. If it's anything like Common Lisp and Java it might happen that implementations are free to reuse memory locations of the same literals and thus any boolean result would be acceptable.