Differences between revisions 2 and 6 (spanning 4 versions)
Revision 2 as of 2023-04-11 16:44:59
Size: 1545
Comment:
Revision 6 as of 2023-06-15 20:44:18
Size: 3104
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
= Python DataClasses = ## page was renamed from Python/DataClass
= Python DataClass =
Line 3: Line 4:
'''`dataclasses`''' is a module that supports the creation of simple classes. '''`dataclass`''' is a module that supports the creation of simple classes.
Line 10: Line 11:
== Usage == == Decorators ==
Line 16: Line 17:
Decorate a class to generate [[Python/DunderMethod|additional methods]]. Use the '''`@dataclass`''' decorator on a class to automatically generate [[Python/DunderMethod|dunder methods]].
Line 33: Line 34:
=== AsDict ===

----



=== AsTuple ===

----
== Classes ==
Line 47: Line 40:
Create more complicated default behaviors for dataclass fields. A '''`Field`''' object represents a field in a dataclass. For complex logic, a dataclass can be defined in terms of `Field` objects.
Line 49: Line 42:
To create a field that defaults to an empty list, try: A `Field` object is instantiated with the `field()` function. This function takes the following optional named arguments:

 * `default`: default value
 * `default_factory`: callable that generates the default value as needed
 * `init`: boolean indicating that this field should be included in the generated [[Python/DunderMethod#__Init__|__init__]] method
 * `repr`: boolean indicating that this field should be included in the generated [[Python/DunderMethod#__Repr__|__repr__]] method
 * `hash`: boolean indicating that this field should be included in the generated [[Python/DunderMethod#__Hash__|__hash__]] method
 * `compare`: boolean indicating that this field should be included in the generated comparison methods (e.g. [[Python/DunderMethod#__Eq__|__eq__]] and so on)
 * `kw_only`: boolean indicating that this field is keyword-only

A `Field` object has `name` and `type `atributes, as well as attribute matching the names and meanings of the `field()` function's arguments.

To create a dataclass with a field that defaults to an empty list, try:
Line 66: Line 71:
== Functions ==



=== AsDict ===

{{{
import dataclass

@dataclass.dataclass
class Point:
     x: int
     y: int

p = Point(10, 20)
dataclass.asdict(p) # {'x': 10, 'y': 20}
}}}

----



=== AsTuple ===

{{{
import dataclass

@dataclass.dataclass
class Point:
     x: int
     y: int

p = Point(10, 20)
dataclass.astuple(p) # (10, 20)
}}}

----


Line 67: Line 112:

Extract the `Field` objects from a dataclass.
Line 78: Line 125:
=== KW_Only === === Make_DataClass ===
Line 80: Line 127:
A [[Python/TypeAnnotation|type annotation]] used for dataclasses. ----



=== Replace ===

----



== Constants ==

'''`KW_ONLY`''' is a
[[Python/TypeAnnotation|type annotation]] used for dataclasses.
Line 95: Line 154:
----



=== Make_DataClass ===

----



=== Missing ===

`dataclass.MISSING` is a sentinel value used internally.

----



=== Replace ===
'''`MISSING`''' is a sentinel value used internally.
Line 122: Line 163:


Python DataClass

dataclass is a module that supports the creation of simple classes.


Decorators

@DataClass

Use the @dataclass decorator on a class to automatically generate dunder methods.

import dataclass

@dataclass.dataclass
class User:
    name: str       # 'name' has no defualt value
    id: int = 1000  # 'id' defaults to 1000

A TypeError is raised if a field without a default value follows a field with a default value.


Classes

Field

A Field object represents a field in a dataclass. For complex logic, a dataclass can be defined in terms of Field objects.

A Field object is instantiated with the field() function. This function takes the following optional named arguments:

  • default: default value

  • default_factory: callable that generates the default value as needed

  • init: boolean indicating that this field should be included in the generated __init__ method

  • repr: boolean indicating that this field should be included in the generated __repr__ method

  • hash: boolean indicating that this field should be included in the generated __hash__ method

  • compare: boolean indicating that this field should be included in the generated comparison methods (e.g. __eq__ and so on)

  • kw_only: boolean indicating that this field is keyword-only

A Field object has name and type atributes, as well as attribute matching the names and meanings of the field() function's arguments.

To create a dataclass with a field that defaults to an empty list, try:

import dataclass

@dataclass.dataclass
class User:
    groups: list[int] = dataclass.field(default_factory=list)

u = User()
u.groups += [1, 2, 3]


Functions

AsDict

import dataclass

@dataclass.dataclass
class Point:
     x: int
     y: int

p = Point(10, 20)
dataclass.asdict(p)  # {'x': 10, 'y': 20}


AsTuple

import dataclass

@dataclass.dataclass
class Point:
     x: int
     y: int

p = Point(10, 20)
dataclass.astuple(p)  # (10, 20)


Fields

Extract the Field objects from a dataclass.


Is_DataClass


Make_DataClass


Replace


Constants

KW_ONLY is a type annotation used for dataclasses.

import dataclass

@dataclass.dataclass
class Point:
    x: float
    _: dataclass.KW_ONLY
    y: float
    z: float

p = Point(0, y=1.5, z=2.0)

MISSING is a sentinel value used internally.


See also

Python dataclasses module documentation


CategoryRicottone

Python/DataClasses (last edited 2023-06-15 20:49:37 by DominicRicottone)