Python Immutable

In Python there is no simple way to create an immutable class directly. You could create a class that uses __slots__ and then use__setattr__ to prevent changes to the variables but there is a trivially simple way to create an immutable class which effectively can act as a struct in Python this is by using a namedtuple. This is nice because a tuple is by its nature an immutable. Let us take a simple 2d point which has an X and a Y

You could do this code:


import collections

Point
= collections.namedtuple('Point', 'x y')

p
=Point(1,1)

print("x={} y={}".format( p.x, p.y))

p
.x=7


Now this code will work to a point. The code will print this



x=1 y=1

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in
7 print("x={} y={}".format( p.x, p.y))
8
----> 9 p.x=7

AttributeError: can't set attribute





Note how we have our Point(…) object but we can not change it we must create a new Object hence why the p.x=7 causes the stack trace,. Yes you may have noticed I do use Jupyter to test my code for these blogs.


People who enjoyed this article also enjoyed the following:


Python Decorator Semantics
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial


And the following Trails:

C++
Java
python
Scala
Investment Banking tutorials



HOME
homeicon




By clicking Dismiss you accept that you may get a cookie that is used to improve your user experience and for analytics.
All data is anonymised. Our privacy page is here =>
Privacy Policy
This message is required under GDPR (General Data Protection Rules ) and the ICO (Information Commissioners Office).