Menu Close

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 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.

Posted in Python, Python Answers