Question

I was playing around with the python3k interpreter and came across the Decimal class in the decimal.py module. Documentation on the class indicates that objects created from the class are immutable. I tried to look into the python library code to see exactly how the programmers coded the class to make it immutable. Unfortunately, I was unable to discover exactly what they had done (mainly due to the fact that the class itself is quite large).

I am curious to know if anyone understands how this class achieves its immutable state. I am thinking it may have something to do with overriding the getattr() and setattr() methods within the class, but I could not find any evidence of this.

I also noticed that this class is able to hide the attributes it defines in its slots variable somehow. Perhaps the class uses some type of metaclass technique to achieve this as well as its immutability.

If anyone has any ideas I would appreciate your feedback. Thanks

Was it helpful?

Solution

Good question. Doesn't seem invincibly immutable to me. Python 2.7.2:

>>> from decimal import Decimal
>>> d = Decimal('1.23')
>>> d
Decimal('1.23')
>>> f = d
>>> f
Decimal('1.23')
>>> d._exp = 1
>>> f
Decimal('1.23E+3')

I do see that the documentation says it's immutable. I guess they mean if you use the documented interface, it's immutable. E.g.

>>> d += 100
>>> f
Decimal('1.23E+3')
>>> d
Decimal('1330')

The way this works is simply that Decimal does not define operator overloads for ?= operators: functions like __i[op]__. In that case, d += 100 translates to d = d.__add__(100), which returns a new object and changes the identity of d while not affecting the original object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top