How to make an immutable object in Python?

Sometimes, we want to make an immutable object in Python.

In this article, we’ll look at how to make an immutable object in Python.

How to make an immutable object in Python?

To make an immutable object in Python, we can create a named tuple.

For instance, we write:

import collections

Immutable = collections.namedtuple("Immutable", ["a", "b"])
i = Immutable(a=1, b=2)
print(i)

to call collections.namedtuple to create the Immutable class with a constructor that has a and b as parameters.

Then we use the Immutable constructor by calling it with a and b.

Therefore, i is Immutable(a=1, b=2) according to print.

Conclusion

To make an immutable object in Python, we can create a named tuple.