Categories
Python Answers

How to make an immutable object in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *