Skip to content

Dataclasses

Quality Score

Overall Score: 8.7/10 ✅ Excellent

  • Technical Accuracy: 28/35
  • Code Quality: 23/25
  • Educational Value: 22/25
  • Documentation: 14/15

Last reviewed: June 22, 2026

Dataclasses are a new feature in Python 3.7. They are a convenient way to create classes which are mainly used to store data. By default, dataclasses provide a __repr__ and __init__ method, so we don't have to write them ourselves.

src.beginner.dataclass

Module to create a dataclass Circle, with properties and methods.

This module contains a class to explain dataclass, properties and methods with args and *kwargs.

src.beginner.dataclass.Circle dataclass

Circle class demonstrating dataclass features with calculated properties.

This class uses the @dataclass decorator to automatically generate init, repr, and other special methods. It includes properties for calculating geometric measurements (diameter, area, perimeter) with configurable decimal precision.

Attributes:

Name Type Description
radius float

The radius of the circle in any unit (e.g., meters, inches).

decimal_precision int

Number of decimal places to round calculations to.

Source code in src/beginner/dataclass/dataclasses.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@dataclass
class Circle:
    """Circle class demonstrating dataclass features with calculated properties.

    This class uses the @dataclass decorator to automatically generate
    __init__, __repr__, and other special methods. It includes properties
    for calculating geometric measurements (diameter, area, perimeter) with
    configurable decimal precision.

    Attributes:
        radius: The radius of the circle in any unit (e.g., meters, inches).
        decimal_precision: Number of decimal places to round calculations to.
    """

    radius: float
    decimal_precision: int

    @property
    def diameter(self) -> float:
        """Calculate and return the diameter of the circle.

        The diameter is twice the radius. The result is rounded to the
        configured decimal precision.

        Returns:
            The diameter of the circle, rounded to decimal_precision places.
        """
        diameter = 2 * self.radius
        return round(diameter, self.decimal_precision)

    @property
    def area(self) -> float:
        """Calculate and return the area of the circle.

        Uses the formula A = πr² where r is the radius. The result is
        rounded to the configured decimal precision.

        Returns:
            The area of the circle, rounded to decimal_precision places.
        """
        area: float = (self.radius**2) * pi
        return round(area, self.decimal_precision)

    @property
    def perimeter(self) -> float:
        """Calculate and return the perimeter of the circle.

        Uses the formula C = 2πr where r is the radius. The result is
        rounded to the configured decimal precision.

        Returns:
            The perimeter of the circle, rounded to decimal_precision places.
        """
        perimeter: float = 2 * self.radius * pi
        return round(perimeter, self.decimal_precision)

    @classmethod
    def set_circle_args(cls, *args: Any) -> "Circle":
        """Create a Circle instance from positional arguments.

        Demonstrates how to use *args to unpack positional arguments
        when creating a dataclass instance. The arguments are passed
        in order: radius, then decimal_precision.

        Args:
            *args: Variable length argument list. Expected arguments:
                - args[0] (float): The radius of the circle
                - args[1] (int): The decimal precision for calculations

        Returns:
            A new Circle instance created with the provided arguments.
        """
        circle: Circle = cls(*args)
        return circle

    @classmethod
    def set_circle_kwargs(cls, **kwargs: Any) -> "Circle":
        """Create a Circle instance from keyword arguments.

        Demonstrates how to use **kwargs to unpack keyword arguments
        when creating a dataclass instance. The arguments must match
        the attribute names defined in the dataclass.

        Args:
            **kwargs: Variable keyword arguments. Expected arguments:
                - radius (float): The radius of the circle
                - decimal_precision (int): The decimal precision for
                  calculations

        Returns:
            A new Circle instance created with the provided keyword
            arguments.
        """
        circle_kwargs: Circle = cls(**kwargs)
        return circle_kwargs
area property

Calculate and return the area of the circle.

Uses the formula A = πr² where r is the radius. The result is rounded to the configured decimal precision.

Returns:

Type Description
float

The area of the circle, rounded to decimal_precision places.

diameter property

Calculate and return the diameter of the circle.

The diameter is twice the radius. The result is rounded to the configured decimal precision.

Returns:

Type Description
float

The diameter of the circle, rounded to decimal_precision places.

perimeter property

Calculate and return the perimeter of the circle.

Uses the formula C = 2πr where r is the radius. The result is rounded to the configured decimal precision.

Returns:

Type Description
float

The perimeter of the circle, rounded to decimal_precision places.

set_circle_args(*args) classmethod

Create a Circle instance from positional arguments.

Demonstrates how to use *args to unpack positional arguments when creating a dataclass instance. The arguments are passed in order: radius, then decimal_precision.

Parameters:

Name Type Description Default
*args Any

Variable length argument list. Expected arguments: - args[0] (float): The radius of the circle - args[1] (int): The decimal precision for calculations

()

Returns:

Type Description
Circle

A new Circle instance created with the provided arguments.

Source code in src/beginner/dataclass/dataclasses.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@classmethod
def set_circle_args(cls, *args: Any) -> "Circle":
    """Create a Circle instance from positional arguments.

    Demonstrates how to use *args to unpack positional arguments
    when creating a dataclass instance. The arguments are passed
    in order: radius, then decimal_precision.

    Args:
        *args: Variable length argument list. Expected arguments:
            - args[0] (float): The radius of the circle
            - args[1] (int): The decimal precision for calculations

    Returns:
        A new Circle instance created with the provided arguments.
    """
    circle: Circle = cls(*args)
    return circle
set_circle_kwargs(**kwargs) classmethod

Create a Circle instance from keyword arguments.

Demonstrates how to use **kwargs to unpack keyword arguments when creating a dataclass instance. The arguments must match the attribute names defined in the dataclass.

Parameters:

Name Type Description Default
**kwargs Any

Variable keyword arguments. Expected arguments: - radius (float): The radius of the circle - decimal_precision (int): The decimal precision for calculations

{}

Returns:

Type Description
Circle

A new Circle instance created with the provided keyword

Circle

arguments.

Source code in src/beginner/dataclass/dataclasses.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@classmethod
def set_circle_kwargs(cls, **kwargs: Any) -> "Circle":
    """Create a Circle instance from keyword arguments.

    Demonstrates how to use **kwargs to unpack keyword arguments
    when creating a dataclass instance. The arguments must match
    the attribute names defined in the dataclass.

    Args:
        **kwargs: Variable keyword arguments. Expected arguments:
            - radius (float): The radius of the circle
            - decimal_precision (int): The decimal precision for
              calculations

    Returns:
        A new Circle instance created with the provided keyword
        arguments.
    """
    circle_kwargs: Circle = cls(**kwargs)
    return circle_kwargs

Properties

Dataclasses can have properties, which are computed attributes. They are defined by using the @property decorator. And they can be used like normal attributes, without parentheses.

*args and **kwargs

Methods can be called with *args and **kwargs. *args represents a tuple of positional arguments, and **kwargs represents a dict of keyword arguments. This is useful when we want to pass a variable number of arguments to a method, or when we want to capture arguments that we don't know about.

Common pitfalls

Remember to avoid using mutable default values for dataclass fields. They are shared across all instances of the dataclass, which can lead to unexpected behavior.

# bad example
@dataclass
class Team:
    name: str
    members: list = []

# correct example
from dataclasses import dataclass, field

@dataclass
class Team:
    name: str
    members: list = field(default_factory=list)

References