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 use the dataclass decorator.

For instance, we write

from dataclasses import dataclass
from typing import Any

@dataclass(frozen=True)
class Immutable:
    a: Any
    b: Any

to create the Immutable class.

We decorate it with the dataclass decorator with frozen set to True to make the class create immutable objects when we instantiate the class.

Conclusion

To make an immutable object in Python, we can use the dataclass decorator.

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 *