Data classes is a new feature introduced in Python 3.7. This feature aims to reduce boilerplate code sucs as
__eq()__ methods in user-defined Python classes. By using the
dataclasses module’s decorators and functions, one can create concise Python classes. Let’s review the use of the data classes feature with an example.
Employee class could be declared concisely like shown below with the data classes decorator.
from dataclasses import dataclass, field @dataclass class Employee: id: int first_name: str last_name: str email: str base_pay: float tax_rate: float = field(default=0.01, init=False) hobbies: list = field(default_factory=list()) def calculate_pay(self): net_pay = self.base_pay - (self.base_pay * self.tax_rate) return net_pay emp1 = Employee(1, 'John', 'Doe', 'firstname.lastname@example.org', 10000, ['Fishing', 'Soccer']) print(emp1) #Employee(id=1, first_name='John', last_name='Doe', email@example.com', base_pay=10000, tax_rate=0.01, hobbies=['Fishing', 'Soccer']) print(emp1.calculate_pay()) #9900.0
@dataclassdecorator above generates
eqmethods by default.
@dataclassgenerator without any parameters like declared above is equivalent to the below declaration:
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
orderparameter is set to true, it will generate boilerplate methods
ge. Also, true value supplied to the
unsafe_hashparameter would generate
- Dataclasses use the
typingmodule to define the data type of the declared class fields. However, if one wishes to not specify the field data types, they can use
typing.Anyfor all of their fields in the class.
- By default, all fields of the class are included in the generated methods. But this can be customizable using field declaration. For example,
tax_ratefield in the example is excluded from the
tax_rate: float = field(default=0.01, init=False)
- Also, we can use the
default_factoryparameter to initialize complex data types such as list.
- Dataclasses module has several convenience functions. For example,
dataclasses.fieldsfunction provides a list of fields in the form of tuple. Also,
dataclasses.asdictreturns a dictionary representation of the supplied object.
Dataclasses is one of the powerful features introduced in the recent versions of Python. Here is the link for learning more about it's capabilities so you can start using this feature in your projects.