dataclasses --- Data Classes

原始碼:Lib/dataclasses.py


This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.

The member variables to use in these generated methods are defined using PEP 526 type annotations. For example, this code:

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

will add, among other things, a __init__() that looks like:

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

Note that this method is automatically added to the class: it is not directly specified in the InventoryItem definition shown above.

在 3.7 版被加入.

模組內容

@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)

This function is a decorator that is used to add generated special methods to classes, as described below.

The @dataclass decorator examines the class to find fields. A field is defined as a class variable that has a type annotation. With two exceptions described below, nothing in @dataclass examines the type specified in the variable annotation.

The order of the fields in all of the generated methods is the order in which they appear in the class definition.

如下所述,@dataclass 裝飾器會向類別新增各種 "dunder" 方法。如果類別中已存在任何新增的方法,則行為會取決於參數,如下方文件所述。裝飾器會回傳呼叫它的同一個類別;不會建立新類別。

If @dataclass is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of @dataclass are equivalent:

@dataclass
class C:
    ...

@dataclass()
class C:
    ...

@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False,
           match_args=True, kw_only=False, slots=False, weakref_slot=False)
class C:
    ...

@dataclass 的參數是:

  • init:如果為真(預設值),將生成一個 __init__() 方法。

    如果該類別已經定義了 __init__(),則此參數會被忽略。

  • repr: If true (the default), a __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10).

    如果該類別已經定義了 __repr__(),則此參數會被忽略。

  • eq: If true (the default), an __eq__() method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type.

    如果該類別已經定義了 __eq__(),則此參數會被忽略。

  • order: If true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, a ValueError is raised.

    如果該類別已經定義了 __lt__()__le__()__gt__()__ge__() 中的任何一個,則引發 TypeError

  • unsafe_hash: If true, force dataclasses to create a __hash__() method, even though it may not be safe to do so. Otherwise, generate a __hash__() method according to how eq and frozen are set. The default value is False.

    __hash__() is used by built-in hash(), and when objects are added to hashed collections such as dictionaries and sets. Having a __hash__() implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer's intent, the existence and behavior of __eq__(), and the values of the eq and frozen flags in the @dataclass decorator.

    By default, @dataclass will not implicitly add a __hash__() method unless it is safe to do so. Neither will it add or change an existing explicitly defined __hash__() method. Setting the class attribute __hash__ = None has a specific meaning to Python, as described in the __hash__() documentation.

    If __hash__() is not explicitly defined, or if it is set to None, then @dataclass may add an implicit __hash__() method. Although not recommended, you can force @dataclass to create a __hash__() method with unsafe_hash=True. This might be the case if your class is logically immutable but can still be mutated. This is a specialized use case and should be considered carefully.

    Here are the rules governing implicit creation of a __hash__() method. Note that you cannot both have an explicit __hash__() method in your dataclass and set unsafe_hash=True; this will result in a TypeError.

    如果 eqfrozen 都為真,預設情況下 @dataclass 會為你生成一個 __hash__() 方法。如果 eq 為真且 frozen 為假,__hash__() 將被設定為 None,並將其標記為不可雜湊(因為它是可變的)。如果 eq 為假,__hash__() 將保持不變,這意味著將使用超類別的 __hash__() 方法(如果超類別是 object,這意味著它將回退到基於 id 的雜湊)。

  • frozen: If true (the default is False), assigning to fields will generate an exception. This emulates read-only frozen instances. See the discussion below.

    如果類別中定義了 __setattr__()__delattr__()frozen 為真,則會引發 TypeError

  • match_args: If true (the default is True), the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method (even if __init__() is not generated, see above). If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.

在 3.10 版被加入.

  • kw_only: If true (the default value is False), then all fields will be marked as keyword-only. If a field is marked as keyword-only, then the only effect is that the __init__() parameter generated from a keyword-only field must be specified with a keyword when __init__() is called. See the parameter glossary entry for details. Also see the KW_ONLY section.

    Keyword-only fields are not included in __match_args__.

在 3.10 版被加入.

  • slots: If true (the default is False), __slots__ attribute will be generated and new class will be returned instead of the original one. If __slots__ is already defined in the class, then TypeError is raised.

警告

Passing parameters to a base class __init_subclass__() when using slots=True will result in a TypeError. Either use __init_subclass__ with no parameters or use default values as a workaround. See gh-91126 for full details.

在 3.10 版被加入.

在 3.11 版的變更: If a field name is already included in the __slots__ of a base class, it will not be included in the generated __slots__ to prevent overriding them. Therefore, do not use __slots__ to retrieve the field names of a dataclass. Use fields() instead. To be able to determine inherited slots, base class __slots__ may be any iterable, but not an iterator.

  • weakref_slot: If true (the default is False), add a slot named "__weakref__", which is required to make an instance weakref-able. It is an error to specify weakref_slot=True without also specifying slots=True.

在 3.11 版被加入.

fields may optionally specify a default value, using normal Python syntax:

@dataclass
class C:
    a: int       # 'a' has no default value
    b: int = 0   # assign a default value for 'b'

In this example, both a and b will be included in the added __init__() method, which will be defined as:

def __init__(self, a: int, b: int = 0):

TypeError will be raised if a field without a default value follows a field with a default value. This is true whether this occurs in a single class, or as a result of class inheritance.

dataclasses.field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING, doc=None)

For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided field() function. For example:

@dataclass
class C:
    mylist: list[int] = field(default_factory=list)

c = C()
c.mylist += [1, 2, 3]

As shown above, the MISSING value is a sentinel object used to detect if some parameters are provided by the user. This sentinel is used because None is a valid value for some parameters with a distinct meaning. No code should directly use the MISSING value.

field() 的參數是:

  • default:如果有提供,這將是該欄位的預設值。這是必需的,因為 field() 呼叫本身會替換預設值的正常位置。

  • default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, 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.

  • init: If true (the default), this field is included as a parameter to the generated __init__() method.

  • repr: If true (the default), this field is included in the string returned by the generated __repr__() method.

  • hash: This can be a bool or None. If true, this field is included in the generated __hash__() method. If false, this field is excluded from the generated __hash__(). If None (the default), use the value of compare: this would normally be the expected behavior, since a field should be included in the hash if it's used for comparisons. Setting this value to anything other than None is discouraged.

    One possible reason to set hash=False but compare=True would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type's hash value. Even if a field is excluded from the hash, it will still be used for comparisons.

  • compare: If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.).

  • metadata: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType() to make it read-only, and exposed on the Field object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.

  • kw_only: If true, this field will be marked as keyword-only. This is used when the generated __init__() method's parameters are computed.

    Keyword-only fields are also not included in __match_args__.

在 3.10 版被加入.

  • doc: optional docstring for this field.

在 3.14 版被加入.

If the default value of a field is specified by a call to field(), then the class attribute for this field will be replaced by the specified default value. If default is not provided, then the class attribute will be deleted. The intent is that after the @dataclass decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after:

@dataclass
class C:
    x: int
    y: int = field(repr=False)
    z: int = field(repr=False, default=10)
    t: int = 20

The class attribute C.z will be 10, the class attribute C.t will be 20, and the class attributes C.x and C.y will not be set.

class dataclasses.Field

Field objects describe each defined field. These objects are created internally, and are returned by the fields() module-level method (see below). Users should never instantiate a Field object directly. Its documented attributes are:

  • name:欄位的名稱。

  • type:欄位的型別。

  • default, default_factory, init, repr, hash, compare, metadata, and kw_only have the identical meaning and values as they do in the field() function.

Other attributes may exist, but they are private and must not be inspected or relied on.

class dataclasses.InitVar

InitVar[T] type annotations describe variables that are init-only. Fields annotated with InitVar are considered pseudo-fields, and thus are neither returned by the fields() function nor used in any way except adding them as parameters to __init__() and an optional __post_init__().

dataclasses.fields(class_or_instance)

Returns a tuple of Field objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises