Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

dataclasses.astuple

Recursively converts data-class fields to positional tuples in field declaration order.

Version: Python 3.14; repository image, production runtime not attested

Syntax

dataclasses.astuple(obj, *, tuple_factory=tuple)

Recursively converts data-class fields to positional tuples in field declaration order.

Unlike a dictionary conversion, the resulting tuple contains values without field names, including in nested data classes.

Export field values in declaration order, with no field names. tuple_factory constructs the representation for each visited dataclass. Lists, dictionaries and tuples are visited recursively, and other objects are deep-copied. An argument other than a dataclass instance raises TypeError. The outer Row contributes one field, giving ((3, 8),).

from dataclasses import astuple, dataclass
@dataclass
class Pair:
    x: int
    data: list
p = Pair(4, [7])
vals = astuple(p)
vals[1].append(8)
assert vals == (4, [7, 8]) and p.data == [7]
assert astuple(p, tuple_factory=list) == [4, [7]]

Examples

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

@dataclasses.dataclass
class Row:
    p: Point

print(dataclasses.astuple(Row(Point(3, 8))))

Result

((3, 8),)

Export field values in declaration order, with no field names. tuple_factory constructs the representation for each visited dataclass. Lists, dictionaries and tuples are visited recursively, and other objects are deep-copied. An argument other than a dataclass instance raises TypeError. The outer Row contributes one field, giving ((3, 8),).

Sources