Data classes

Data classes

Explore the power of functions and object-oriented programming in Python. This section delves into function definitions, class structures, and advanced topics such as properties and descriptors, ensuring you understand how to create robust and reusable code.

5 audio · 1:21

Nortren·

What is a data class?

0:17
A data class is a class created using the dataclass decorator from the dataclasses module, introduced in Python 3.7. It automatically generates dunder init, dunder repr, and dunder eq methods based on the class's annotated attributes. Data classes reduce boilerplate for classes that primarily hold data.

How do you make a data class immutable?

0:14
Pass frozen equals True to the dataclass decorator. The generated class will raise FrozenInstanceError if you try to assign to its attributes after creation. Frozen data classes are also hashable by default, so they can be used as dictionary keys or set elements.

What is the difference between a data class and a named tuple?

0:18
A named tuple is an immutable subclass of tuple with named fields, defined with collections.namedtuple or typing.NamedTuple. A data class is a regular class generated by the dataclass decorator, mutable by default. Data classes support inheritance, default factories, and custom methods more naturally.

What is the field function in dataclasses?

0:18
The field function customizes individual fields in a data class. It can specify a default value, a default factory for mutable defaults, whether the field is included in init or repr, and metadata. Default factories are essential for mutable defaults like lists, since data classes forbid mutable defaults directly.

What is a kw-only data class?

0:14
Setting kw_only equals True on a data class makes all fields keyword-only in the generated init. This was added in Python 3.10. Individual fields can also be marked keyword-only with field. This avoids ambiguity when a class has many fields and improves API stability. ---