Python Data Class Field With Example
September 18, 2020 / By HTD / Python / Data Classes, fields
Advertisement
In the previous blog, we learned the python data class parameters or the parameterized data class in python. This time we will learn about Field in python data class, which helps us to customize our python class.
Let’s start learning about the 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 fields the class contains.
Example:
@dataclass()
class Student():
name: str
clss: int
stu_id: int
student = Student('HTD', 10, 17)
>>> print(student.__dataclass_fields__)
{
'name': Field(name='name',type=<class 'str'>,default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),
'clss': Field(name='clss',type=<class 'int'>,default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),
'stu_id': Field(name='stu_id',type=<class 'int'>,default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)
}
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.
>>> print(student.__dataclass_fields__['name'])
Field(name='name',type=<class 'str'>,default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD)
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 fields from the data classes module.
from dataclasses import dataclass, field
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
Customize Field in Python Data Class
Let’s take a look at each parameter.
Default parameter
This is used to set the default value of the field.
Example:
@dataclass()
class Student():
name: str
stu_id: int
clss: int = field(default=10)
student = Student('HTD', 17)
>>> print(student)
Student(name='HTD', stu_id=17, clss=10)
The default value of a field can also be set normally like this.
clss: int = 10
One thing to keep in mind while declaring the default value is that the default value should always be declared at the last. Else you will get an error.
Example:
@dataclass()
class Student():
name: str
clss: int = field(default=10)
stu_id: int
>>> student = Student('HTD', 17)
Traceback (most recent call last):
class Student():
TypeError: non-default argument 'stu_id' follows default argument
This error occurs because the positional arguments are not placed properly.
Default Factory Parameter in Python Data Class Fields
This parameter also takes a function, that returns a value and the returned value is taken as the default value.
Example:
def calc_id():
return 'HTD' + '123'
@dataclass()
class Student():
name: str
clss: int
stu_id: int = field(default_factory=calc_id)
student = Student('HTD', 10)
>>> print(student)
Student(name='HTD', clss=10, stu_id='HTD123')
The default_factory parameter takes only functions without parameters, as there is no way you can pass the arguments.
repr Parameter
By default, the repr parameter is set to True and it provides the representation of the field when the class object is printed.
If set to False, the field will not be displayed in the class object representation.
Example:
@dataclass()
class Student():
name: str
clss: int
stu_id: int = field(repr=False)
student = Student('HTD', 10, 17)
>>> print(student)
Student(name='HTD', clss=10)
hash Parameter in Field
When the python data class parameter unsafe_hash or the frozen is set to True, we can create the hash value for the class object.
For creating the hash value all the fields are taken into consideration. If we set the hash parameter in the field parameter to False, that field will not be considered for the hash.
Example:
@dataclass(unsafe_hash=True)
class Student():
name: str
clss: int
stu_id: int = field(hash=False)
student = Student('HTD', 10, 17)
>>> print(hash(student))
-5158773297166144479
Let’s see if the hash is the same after we consider the stu_id field.
@dataclass(unsafe_hash=True)
class Student():
name: str
clss: int
stu_id: int = field(hash=True)
student = Student('HTD', 10, 17)
>>> print(hash(student))
-1079423850397226099
init Parameter in Python Data Class Field
This parameter is responsible for creating the fields the class attributes. If set to false, the field will no longer be the class attribute.
Example:
@dataclass()
class Student():
name: str
clss: int
stu_id: int = field(init=False, default=123)
student = Student('HTD', 10)
>>> print(student)
Student(name='HTD', clss=10, stu_id=123)
As you can see, we had to provide the default value for the field whose init parameter is set to False.
compare parameter
The compare parameter is used to compare the fields of two objects. If set to False the field will no longer be compared in an object.
Example:
@dataclass()
class Student():
name: str
clss: int
stu_id: int = field(compare=False)
student1 = Student('HTD', 10, 17)
student2 = Student('HTD', 10, 18)
>>> print(student1 == student2)
True
Metadata Parameter
This parameter provides extra information in the __dataclass_fields_ method.
Example:
@dataclass()
class Student():
name: str
clss: int
stu_id: int = field(metadata={'UID': '123'})
student = Student('HTD', 10, 17)
>>> print(student.__dataclass_fields__['stu_id'])
Field(name='stu_id',type=<class 'int'>,default=,default_factory=,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({'UID': '123'}),_field_type=_FIELD)
Hope you like it!
Learn more about the python data class field from the official documentation.