Content · Programming · Python

Python dataclasses.fields() Function: Usage and Examples

Inspect declared dataclass fields using dataclasses.fields().

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

Inspect declared dataclass fields using dataclasses.fields().

What You Will Learn


fields(class_or_instance) returns Field objects describing real dataclass fields, including their names and types. It excludes ClassVar and InitVar pseudo-fields and raises TypeError for unrelated objects.

Avoid relying on private implementation attributes of Field objects.

Step-by-Step Example


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

from dataclasses import dataclass, fields

@dataclass
class NetworkConfig:
    hostname: str
    port: int = 443

field_names = [field_info.name for field_info in fields(NetworkConfig)]
print(field_names)

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: dataclasses.
  • The class NetworkConfig groups data and behavior; its methods run when called on an instance.
  • The variable field_names holds the result of [field_info.name for field_info in fields(NetworkConfig)]. 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 field_names prints ['hostname', 'port']. Compare that result with the rule above before you change the argument.

Expected output from the example:

['hostname', 'port']

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


Display each field name and its default for a simple dataclass.

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


  • Calling fields() on a normal class without the dataclass decorator.
  • Assuming ClassVar and InitVar annotations are included among actual instance fields.

Key Takeaways


  • Inspect declared dataclass fields using dataclasses.fields().
  • fields(class_or_instance) returns Field objects describing real dataclass fields, including their names and types.
  • Avoid relying on private implementation attributes of Field objects.
Share this resourceSend this page to someone who may find it useful.