DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on

Python Data Class Field

Get All Fields From Data Class

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


student = Student('HTD', 10, 17)

>>> print(student.__dataclass_fields__)

Enter fullscreen mode Exit fullscreen mode
{
'name': Field(name='name',type=<class 'str'>,default=<dataclasses._MISSING_TYPE object at 0x00000217EBF3F460>,default_factory=<dataclasses._MISSING_TYPE object at 0x00000217EBF3F460>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD), 

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

'stu_id': Field(name='stu_id',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x00000217EBF3F460>,default_factory=<dataclasses._MISSING_TYPE object at 0x00000217EBF3F460>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)
}
Enter fullscreen mode Exit fullscreen mode

This method returns a dictionary of all the field information of the object. The field name is the key of the dictionary and the value is the Field class containing the field information.

Access Specific Field

In the previous code, we accessed all the field properties. Let’s now try to access a specific field.

Access Specific Field

>>> print(student.__dataclass_fields__['name'])


Field(name='name',type=<class 'str'>,default=<dataclasses._MISSING_TYPE object at 0x0000022C8E26F460>,default_factory=<dataclasses._MISSING_TYPE object at 0x0000022C8E26F460>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)
Enter fullscreen mode Exit fullscreen mode

Let’s now learn how we can change some of the field values.

Import Field

To customize the fields in the python data class, we will have to import field from the dataclasses module.

import field
from dataclasses import dataclass, field
Enter fullscreen mode Exit fullscreen mode

Now we can customize the fields.

Python Data Class Field
field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)

There are six optional parameters that can be set to customize the field properties.

  • default
  • default_factory
  • repr
  • hash
  • init
  • compare
  • metadata

Learn about each parameter of Python Data Class Fields in detail from the original Post.

Top comments (0)