This example shows only a name, type and value, however, __dataclass_fields__ is a dict of Field objects, each containing information such as name, type, default value, etc.

Using dataclasses.fields()

Using dataclasses.fields() you can access fields you defined in your dataclass.

fields = dataclasses.fields(dataclass_instance)

Using inspect.getmembers()

Using inspect.getmembers() you can access all fields in your dataclass.

members = inspect.getmembers(type(dataclass_instance))
fields = list(dict(members)['__dataclass_fields__'].values())

Complete code solution

import dataclasses
import inspect


@dataclasses.dataclass
class Test:
    a: str = "a value"
    b: str = "b value"


def print_data_class(dataclass_instance):

    # option 1: fields
    fields = dataclasses.fields(dataclass_instance)

    # option 2: inspect
    members = inspect.getmembers(type(dataclass_instance))
    fields = list(dict(members)['__dataclass_fields__'].values())

    for v in fields:
        print(f'{v.name}: ({v.type.__name__}) = {getattr(dataclass_instance, v.name)}')


print_data_class(Test())
# a: (str) = a value
# b: (str) = b value

print_data_class(Test(a="1", b="2"))
# a: (str) = 1
# b: (str) = 2
Answer from K.Mat on Stack Overflow
Top answer
1 of 4
31

This example shows only a name, type and value, however, __dataclass_fields__ is a dict of Field objects, each containing information such as name, type, default value, etc.

Using dataclasses.fields()

Using dataclasses.fields() you can access fields you defined in your dataclass.

fields = dataclasses.fields(dataclass_instance)

Using inspect.getmembers()

Using inspect.getmembers() you can access all fields in your dataclass.

members = inspect.getmembers(type(dataclass_instance))
fields = list(dict(members)['__dataclass_fields__'].values())

Complete code solution

import dataclasses
import inspect


@dataclasses.dataclass
class Test:
    a: str = "a value"
    b: str = "b value"


def print_data_class(dataclass_instance):

    # option 1: fields
    fields = dataclasses.fields(dataclass_instance)

    # option 2: inspect
    members = inspect.getmembers(type(dataclass_instance))
    fields = list(dict(members)['__dataclass_fields__'].values())

    for v in fields:
        print(f'{v.name}: ({v.type.__name__}) = {getattr(dataclass_instance, v.name)}')


print_data_class(Test())
# a: (str) = a value
# b: (str) = b value

print_data_class(Test(a="1", b="2"))
# a: (str) = 1
# b: (str) = 2
2 of 4
9

Also, you can use __annotations__, well, because data fields are always annotated. This is the essense of dataclasses usage.

It works with classes

    fields = list(Test.__annotations__)

and with instances

    fields = list(test.__annotations__)

There should be noted that it doesn't work with dataclass subclasses. Obviously. However, simplicity gives you fields names directly, without extra code for extraction from Field objects.

🌐
Python
docs.python.org › 3 › library › dataclasses.html
dataclasses — Data Classes
February 23, 2026 - Changed in version 3.11: If a field ... them. Therefore, do not use __slots__ to retrieve the field names of a dataclass. Use fields() instead....
Discussions

How can I get Python 3.7 new dataclass field types? - Stack Overflow
Python 3.7 introduces new feature called data classes. from dataclasses import dataclass @dataclass class MyClass: id: int = 0 name: str = '' When using type hints (annotation) in function parameters, you can easily get annotated types using inspect module. How can I get dataclass field types? More on stackoverflow.com
🌐 stackoverflow.com
python - How do I pull out the attributes or field names from a dataclass? - Stack Overflow
Use dataclasses.fields to pull out the fields, from the class or an instance. Then use the .name attribute to get the field names. More on stackoverflow.com
🌐 stackoverflow.com
python - Extract all field names from nested dataclasses - Stack Overflow
I would like to create a list of all field names for attributes that aren't dataclasses, and if the attribute is a dataclass the to list the attributes of that class, so in this case the output would be ['var_3', 'var_1', 'var_2'] I know it's possible to use dataclasses.fields to get the fields ... More on stackoverflow.com
🌐 stackoverflow.com
Annotations using inner field names and values of TypedDicts/dataclass like objects - Ideas - Discussions on Python.org
Consider the following example: from typing import TypedDict, Literal, TypeAlias class Config(TypedDict): int_field: int str_field: str Environment: TypeAlias = Literal['production', 'development'] def _get_configuration(environment: Environment) -> Config: # Get the configuration fitting for ... More on discuss.python.org
🌐 discuss.python.org
1
May 5, 2023
🌐
GitHub
github.com › pydantic › pydantic › discussions › 8600
Is there any way to get the name of a field as a string? · pydantic/pydantic · Discussion #8600
from dataclasses import dataclass from functools import lru_cache from typing import TypeVar, cast, Any, reveal_type, TYPE_CHECKING from pydantic import BaseModel class Person(BaseModel): first_name: str @dataclass(frozen=True) class _GetFields: _model: type[BaseModel] def __getattr__(self, item: str) -> Any: if item in self._model.model_fields: return item return getattr(self._model, item) TModel = TypeVar("TModel", bound=type[BaseModel]) def fields(model: TModel, /) -> TModel: return cast(TModel, _GetFields(model)) if not TYPE_CHECKING: fields = lru_cache(maxsize=256)(fields) person_fields = fields(Person) reveal_type(person_fields) first_name = fields(Person).first_name reveal_type(first_name) print(first_name)
Author   pydantic
Top answer
1 of 3
127

Inspecting __annotations__ gives you the raw annotations, but those don't necessarily correspond to a dataclass's field types. Things like ClassVar and InitVar show up in __annotations__, even though they're not fields, and inherited fields don't show up.

Instead, call dataclasses.fields on the dataclass, and inspect the field objects:

field_types = {field.name: field.type for field in fields(MyClass)}

Neither __annotations__ nor fields will resolve string annotations. If you want to resolve string annotations, the best way is probably typing.get_type_hints. get_type_hints will include ClassVars and InitVars, so we use fields to filter those out:

resolved_hints = typing.get_type_hints(MyClass)
field_names = [field.name for field in fields(MyClass)]
resolved_field_types = {name: resolved_hints[name] for name in field_names}
2 of 3
58
from dataclasses import dataclass

@dataclass
class MyClass:
    id: int = 0
    name: str = '' 

myclass = MyClass()

myclass.__annotations__
>> {'id': int, 'name': str}
myclass.__dataclass_fields__
>> {'id': Field(name='id',type=<class 'int'>,default=0,default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),
 'name': Field(name='name',type=<class 'str'>,default='',default_factory=<dataclasses._MISSING_TYPE object at 0x0000000004EED668>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)}

on a side note there is also:

myclass.__dataclass_params__
>>_DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=False)
🌐
Snyk
snyk.io › advisor › dataclasses › functions › dataclasses.fields
https://snyk.io/advisor/python/dataclasses/functio...
def from_pyvalue(cls, data, *, allow_missing=False): if not isinstance(data, dict): raise cls._err(f'expected a dict value, got {type(data)!r}') spec = config.get_settings() data = dict(data) tname = data.pop('_tname', None) if tname is not None: if '::' in tname: tname = s_name.Name(tname).name cls = spec.get_type_by_name(tname) fields = {f.name: f for f in dataclasses.fields(cls)} items = {} inv_keys = [] for fieldname, value in data.items(): field = fields.get(fieldname) if field is None: if value is None: # This may happen when data is produced by # a polymorphic config query. pass else: inv_keys.append(fieldname) continue f_type = field.type · danielgtaylor / python-betterproto / src / betterproto / __init__.py View on Github ·
🌐
DEV Community
dev.to › divshekhar › python-data-class-field-2e51
Python Data Class Field - DEV Community
September 28, 2020 - #python · There is an in-built function called _dataclass_fields that is called on the class object and it returns all the field the class contains. Example: Data class Fields · @dataclass() class Student(): name: str clss: int stu_id: int ...
Find elsewhere
🌐
YouTube
youtube.com › codekick
python dataclass get field names - YouTube
Instantly Download or Run the code at https://codegive.com sure! here's a tutorial on how to use python's dataclass to get field names:python's dataclass mo...
Published   March 30, 2024
Views   28
🌐
ProgramCreek
programcreek.com › python › example › 110835 › dataclasses.fields
Python Examples of dataclasses.fields
def to_json(dataclass_instance: Dataclass) -> str: data = {} for field in dataclasses.fields(type(dataclass_instance)): field_type, _ = _extract_type_if_optional(field.type) if field_type not in serializers: if issubclass(field_type, Enum): serializers[field_type] = lambda field: field.value else: raise Exception(f"Type {field_type} not supported") if getattr(dataclass_instance, field.name): data[field.name] = serializers[field_type](getattr(dataclass_instance, field.name)) # type: ignore else: data[field.name] = None return json.dumps(data)
🌐
Python.org
discuss.python.org › ideas
Annotations using inner field names and values of TypedDicts/dataclass like objects - Ideas - Discussions on Python.org
May 5, 2023 - Consider the following example: from typing import TypedDict, Literal, TypeAlias class Config(TypedDict): int_field: int str_field: str Environment: TypeAlias = Literal['production', 'development'] def _get_configuration(environment: Environment) -> Config: # Get the configuration fitting for the given environment pass def _infer_environment() -> Environment: # Read environment variables to infer if we are running in development or production pass def get_confi...
🌐
GitHub
github.com › ijl › orjson › issues › 45
Alias dataclass field name · Issue #45 · ijl/orjson
January 6, 2020 - When parsing JSON, sometimes the fields need/have horrible names so I think it'd be neat to add an option to specify the JSON field name for encoding/decoding. ... @dataclass class A: b: int = field(metadata={"name": 'anothername'}) orjson.dumps(A(1)) # will print b'{"anothername": 1}'
Author   aviramha
🌐
Real Python
realpython.com › python-data-classes
Data Classes in Python (Guide) – Real Python
March 8, 2024 - As an example, we will create a ... decorator just above the class definition. Beneath the class Position: line, you simply list the fields you want in your data class....
🌐
Ritviknag
dcw.ritviknag.com › en › latest › using_field_properties.html
Using Field Properties — Dataclass Wizard 0.39.1 documentation
However, suppose you want the ability ... then that’s where it starts to get a little tricky. But first, let’s start out by defining what I mean by a field property. Here is how I’d define the use of a field property in Python dataclasses:...
Top answer
1 of 2
31

The answer depends on whether or not you have access to an object of the class.

Just using the class

If you only have access to the class, then you can use dataclasses.fields(C) which returns a list of field objects (each of which has a .name property):

[field.name for field in dataclasses.fields(C)]

From an existing object

If you have a constructed object of the class, then you have two additional options:

  1. Use dataclasses.fields on the object:
[field.name for field in dataclasses.fields(obj)]
  1. Use dataclasses.asdict(obj) (as pointed out by this answer) which returns a dictionary from field name to field value. It sounds like you are only interested in the .keys() of the dictionary:
dataclasses.asdict(obj).keys()       # gives a dict_keys object
list(dataclasses.asdict(obj).keys()) # gives a list
list(dataclasses.asdict(obj))        # same 

Full example

Here are all of the options using your example:

from dataclasses import dataclass, fields, asdict


@dataclass
class C:
    x: int
    y: int
    z: int
    t: int

# from the class
print([field.name for field in fields(C)])

# using an object
obj = C(1, 2, 3, 4)

print([field.name for field in fields(obj)])
print(asdict(obj).keys())
print(list(asdict(obj).keys()))
print(list(asdict(obj)))

Output:

['x', 'y', 'z', 't']
['x', 'y', 'z', 't']
dict_keys(['x', 'y', 'z', 't'])
['x', 'y', 'z', 't']
['x', 'y', 'z', 't']
2 of 2
14

You can use the asdict method of the dataclasses module. For example:

from dataclasses import dataclass, asdict


@dataclass
class Person:
    age: int
    name: str


adam = Person(25, 'Adam')

# if you want the keys

print(asdict(adam).keys()) # dict_keys(['age', 'name'])

# if you want the values

print(asdict(adam).values()) # dict_values([25, 'Adam'])

Both methods above return a View object which you can iterate on, or you can convert it to list using list(...).

🌐
Ivergara
ivergara.github.io › deeper-dataclasses.html
Deeper into dataclasses - On data, programming, and technology
August 5, 2019 - Thus, instead of having to name each coordinate of the point in the different operation methods, we can iterate over them. # Introspection based solution from dataclasses import astuple, dataclass, fields @dataclass class Point: x: float y: float z: float def __add__(self, other): return Point(*(getattr(self, dim.name)+getattr(other, dim.name) for dim in fields(self))) def __sub__(self, other): return Point(*(getattr(self, dim.name)-getattr(other, dim.name) for dim in fields(self))) def __mul__(self, other): return Point(*(getattr(self, dim.name)*other for dim in fields(self))) def __rmul__(self, other): return self.__mul__(other) def __iter__(self): return iter(astuple(self))
🌐
Python.org
discuss.python.org › ideas
Dataclasses - make use of Annotated - Ideas - Discussions on Python.org
July 21, 2023 - dataclasses are great and I make extensive use of them but there is something which I always find non-matching. Example: from dataclasses import dataclass, field @dataclass class Dummy: a: int = field(init=False, default=5) Having declared a to be of type int the assignment is the result of a callable field which (as an end-user) I am not sure it is returning an int Given that Annotated can convey metainformation, would it not be really appropriate to use it for dataclasses, as in: from...
🌐
Python Morsels
pythonmorsels.com › customizing-dataclass-fields
Customizing dataclass fields - Python Morsels
October 23, 2024 - This is a tool that the dataclasses module provides for defining fields while customizing their behavior. Now when we make new instances of this class, we'll see that each one called Python's list function to get an independent empty list:
🌐
CodeRivers
coderivers.org › blog › python-get-all-keys-from-dataclass
Python: Getting All Keys from a Dataclass - CodeRivers
January 23, 2025 - Then, we use the keys() method of the dictionary to get the keys (field names) and convert the result to a list for easier manipulation. The output will be ['title', 'author', 'year']. The built-in vars() function returns a dictionary representing the object's attributes.
🌐
DataCamp
datacamp.com › tutorial › python-data-classes
Python Data Classes: A Comprehensive Tutorial | DataCamp
March 15, 2024 - In practice, you will rarely define defaults with name: type = value syntax. Instead, you will use the field function, which allows more control of each field definition: from dataclasses import field @dataclass class Exercise: name: str = field(default="Push-up") reps: int = field(default=10) sets: int = field(default=3) weight: float = field(default=0) # Now, all fields have defaults ex5 = Exercise() ex5 Exercise(name='Push-up', reps=10, sets=3, weight=0)