Content · Programming · Python

Python dataclasses.astuple() Function: Usage and Examples

Convert the fields of a dataclass into an ordered tuple.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Convert the fields of a dataclass into an ordered tuple.

What You Will Learn


dataclasses.astuple(instance) produces a tuple in field definition order. Nested dataclasses and supported containers are converted recursively; it is not necessarily a shallow or allocation-free transformation.

Use tuple_factory= when a different tuple-like output container is needed.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from dataclasses import dataclass, astuple

@dataclass
class Coordinate:
    latitude: float
    longitude: float

location = Coordinate(32.0, 34.9)
print(astuple(location))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: dataclasses.
  • The class Coordinate groups data and behavior; its methods run when called on an instance.
  • The variable location holds the result of Coordinate(32.0, 34.9). Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression astuple(location) prints (32.0, 34.9). Compare that result with the rule above before you change the argument.

Expected output from the example:

(32.0, 34.9)

When You Would Use This


These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.

Practice: Modify the Code


Convert a three-field dataclass into a tuple and unpack it.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Expecting astuple() to use alphabetical field order instead of declaration order.
  • Assuming conversion is always shallow and preserves every nested object reference.

Key Takeaways


  • Convert the fields of a dataclass into an ordered tuple.
  • dataclasses.astuple(instance) produces a tuple in field definition order.
  • Use tuple_factory= when a different tuple-like output container is needed.
Share this resourceSend this page to someone who may find it useful.