What are Data Classes in Python?

Data classes is a new feature introduced in Python 3.7. This feature aims to reduce boilerplate code sucs as __init__() and __eq()__ methods in user-defined Python classes. By using the dataclasses module’s decorators and functions, one can create conc…

Data classes is a new feature introduced in Python 3.7. This feature aims to reduce boilerplate code sucs as __init__() and __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', 'john.doe@example.com', 10000, ['Fishing', 'Soccer'])
print(emp1)    #Employee(id=1, first_name='John', last_name='Doe', email='john.doe@example.com', base_pay=10000, tax_rate=0.01, hobbies=['Fishing', 'Soccer']) 
print(emp1.calculate_pay())  #9900.0
  • @dataclass decorator above generates init, repr and eq methods by default. @dataclass generator 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)
  • If order parameter is set to true, it will generate boilerplate methods lt, gt, le, and ge. Also, true value supplied to the unsafe_hash parameter would generate hash method.
  • Dataclasses use the typing module 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.Any for 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_rate field in the example is excluded from the init method.
tax_rate: float = field(default=0.01, init=False)
  • Also, we can use the default_factory parameter to initialize complex data types such as list.
  • Dataclasses module has several convenience functions. For example, dataclasses.fields function provides a list of fields in the form of tuple. Also, dataclasses.asdict returns 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.


Print Share Comment Cite Upload Translate
APA
dev0928 | Sciencx (2024-03-28T09:40:14+00:00) » What are Data Classes in Python?. Retrieved from https://www.scien.cx/2021/04/12/what-are-data-classes-in-python/.
MLA
" » What are Data Classes in Python?." dev0928 | Sciencx - Monday April 12, 2021, https://www.scien.cx/2021/04/12/what-are-data-classes-in-python/
HARVARD
dev0928 | Sciencx Monday April 12, 2021 » What are Data Classes in Python?., viewed 2024-03-28T09:40:14+00:00,<https://www.scien.cx/2021/04/12/what-are-data-classes-in-python/>
VANCOUVER
dev0928 | Sciencx - » What are Data Classes in Python?. [Internet]. [Accessed 2024-03-28T09:40:14+00:00]. Available from: https://www.scien.cx/2021/04/12/what-are-data-classes-in-python/
CHICAGO
" » What are Data Classes in Python?." dev0928 | Sciencx - Accessed 2024-03-28T09:40:14+00:00. https://www.scien.cx/2021/04/12/what-are-data-classes-in-python/
IEEE
" » What are Data Classes in Python?." dev0928 | Sciencx [Online]. Available: https://www.scien.cx/2021/04/12/what-are-data-classes-in-python/. [Accessed: 2024-03-28T09:40:14+00:00]
rf:citation
» What are Data Classes in Python? | dev0928 | Sciencx | https://www.scien.cx/2021/04/12/what-are-data-classes-in-python/ | 2024-03-28T09:40:14+00:00
https://github.com/addpipe/simple-recorderjs-demo