콘텐츠로 건너뛰기

파이썬 데이터 클래스의 frozen 속성 사용하기

[

Python Dataclasses Frozen

Python dataclasses are a useful feature introduced in Python 3.7 that allows for the creation of classes with less boilerplate code. They automatically generate special methods like __init__, __repr__, and __eq__, saving us from writing them manually. The dataclass decorator from the dataclasses module is used to define dataclasses.

In this tutorial, you will learn about creating frozen dataclasses in Python. A frozen dataclass is one where the instances are immutable, meaning their attributes cannot be changed once initialized. This is useful when you want to ensure that an object’s state remains constant throughout its lifetime.

Creating a Dataclass

Before diving into frozen dataclasses, let’s first understand how to create a regular dataclass.

To create a dataclass, we need to import the dataclass decorator from the dataclasses module and apply it above our class definition. We also need to define the attributes inside the class.

from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
occupation: str

In the above example, we created a dataclass named Person with three attributes: name, age, and occupation. Notice that we didn’t have to write the __init__, __repr__, and __eq__ methods - they were automatically generated for us.

We can now create instances of the Person class and access their attributes easily:

person1 = Person("John", 25, "Engineer")
person2 = Person("Alice", 30, "Teacher")
print(person1.name) # Output: John
print(person2.age) # Output: 30

Creating a Frozen Dataclass

To create a frozen dataclass, we need to set the frozen parameter of the dataclass decorator to True.

from dataclasses import dataclass
@dataclass(frozen=True)
class Person:
name: str
age: int
occupation: str

By setting frozen=True, we ensure that the instances of the Person class become immutable. Once the attributes are assigned, they cannot be modified.

Now, let’s try to modify the attribute of a frozen dataclass and see what happens:

person = Person("John", 25, "Engineer")
person.age = 30 # Error: dataclass is immutable

When we try to modify the attribute age, a dataclasses.FrozenInstanceError is raised, indicating that the instance is immutable.

Benefits of Frozen Dataclasses

Using frozen dataclasses provides several benefits:

  1. Immutability: By making instances of a dataclass immutable, we ensure that their state cannot be changed accidentally, leading to more predictable and reliable code.

  2. Hashability: Frozen dataclasses are hashable, meaning they can be used as keys in dictionaries and elements in sets. This is useful when you need to store instances in data structures that require hashable objects.

  3. Thread Safety: Since frozen dataclasses are immutable, they can be shared among multiple threads without the need for synchronization mechanisms. This simplifies concurrent programming and reduces the risk of race conditions.

Conclusion

In this tutorial, you learned about creating frozen dataclasses in Python. We explored how to define a dataclass using the @dataclass decorator and how to set the frozen parameter to make instances immutable. We also discussed the benefits of using frozen dataclasses, such as immutability, hashability, and thread safety.

Dataclasses are a powerful tool for working with structured data in Python, and frozen dataclasses enhance their usage by ensuring immutability. By leveraging the features of dataclasses, you can write cleaner and more concise code while maintaining the integrity of your data.