July 27, 2018

Python Dataclasses

Python 3 brought a whole slew of features. Although only available in python 3.7, a new feature that excites me is the concept of “DataClasses“.  

So what are data-classes?

Transferring knowledge from other programming languages, you can consider data-classes as Models. It really that simple.  

But that’s not a new concept.

True. The concept of data-classes is not a new one. What this does however is save you a lot of boilerplate code. Check this (Without data-classes)
class Phone(object):
    battery_value: int
    volume_value: int

def __init__(self,battery,volume):
    self.battery_value = battery
    self.volume_value = volume
With Data-classes all we need isa @dataclass decorator and we can simply do this:
from dataclasses import dataclass

class Phone(object):
    battery_value: int
    volume_value: int
  and you can access both classes the same way.
def use_phone_class():
    phone = Phone(battery,volume)
  PS: Did i mention @dataclasses also generates __repr__ methods and more? If you;d like to know more you can read up on PEP-557 here
Scroll UpScroll Up