Python:dataclasses
lastmod 2023-07-07created 2021-08-055 edits
This module provides a decorator and functions that automatically add generated special methods such as init() and repr() to user-defined classes. It was originally described in PEP 557.
How to use
from dataclasses import dataclass
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
An init() function like the one below is added automatically.
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
self.name = name
self.unit_price = unit_price
self.quantity_on_hand = quantity_on_hand
dataclass
For C, which inherits from Base, the following constructor is generated.
Customizing fields
To control characteristics such as initialization arguments and whether a field is included in __repr__, use the field function.
# -*- coding: utf-8 -*-
from typing import Optional, Any, List
from datetime import datetime
from dataclasses import dataclass, field
@dataclass
class Project:
uid: Optional[int] = None
group_uid: Optional[int] = None
slug: Optional[str] = None
name: Optional[str] = None
description: Optional[str] = None
features: Optional[List[str]] = None
extra: Optional[Any] = None
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
_group_slug: Optional[str] = field(default=None, init=False, repr=False)
def remove_sensitive(self) -> None:
self.uid = None
self.group_uid = None
@property
def group_slug(self) -> Optional[str]:
return self._group_slug
@group_slug.setter
def group_slug(self, value: Optional[str]):
self._group_slug = value
default_factory
If provided, it must be a zero-argument callable that is called when a default value is needed for this field.
Among other uses, this can be used to specify fields with mutable default values, as discussed below.
It is an error to specify both default and default_factory.