Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 23596

Python Morsels: dataclasses

$
0
0

Let's talk about dataclasses in Python.

A minimal boilerplate class

This Point class represents a 2-dimensional point:

classPoint:"""A two-dimensional point."""def__init__(self,x,y):self.x=xself.y=ydef__repr__(self):returnf"Point(x={self.x}, y={self.y})"

This class accepts arguments (thanks to the initializer method):

>>> frompointimportPoint>>> p=Point(1,2)

And it has a friendly string representation (thanks to the __repr__ method):

>>> pPoint(x=1, y=2)

Using the dataclass decorator

Instead of writing our __init__ and __repr__ method ourselves, we could use the dataclass decorator (from Python's dataclasses module) when defining our class.

The dataclass decorator requires us to define the attributes (and arguments) of our class with type hints:

fromdataclassesimportdataclass@dataclassclassPoint:"""A two-dimensional point."""x:floaty:float

The resulting class is essentially equivalent to this:

classPoint:"""A two-dimensional point."""def__init__(self,x:float,y:float)->None:self.x=xself.y=ydef__repr__(self):returnf"Point(x={self.x}, y={self.y})"def__eq__(self,other):"""Return True if our point is equal to the other point."""ifnotisinstance(other,Point):returnNotImplementedreturn(self.x,self.y)==(other.x,other.y)

It has an initializer and a nice string representation (just as before):

>>> frompointimportPoint>>> p=Point(1,2)>>> p>>> Point(x=1,y=2)

We can access x and y attributes (just as in our previous class):

>>> p.x1>>> p.y2

But we can also we can check equality between two Point objects:

>>> p==Point(1,2)True

We get all of that for free thanks to the dataclass decorator.

Making class objects immutable

To make our Point objects immutable, we could pass frozen=True to our dataclass decorator:

fromdataclassesimportdataclass@dataclass(frozen=True)classPoint:"""A two-dimensional point."""x:floaty:float

Now our Point objects are immutable which means we can't assign to their attributes:

>>> p=Point(1,2)>>> p.x=2Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4, in __setattr__dataclasses.FrozenInstanceError: cannot assign to field 'x'

When should you use dataclasses?

Whenever you'd like to quickly create a class with a friendly interface (with a nice string representation and sensible equality checking), consider reaching for the dataclass decorator from Python's dataclasses module.


Viewing all articles
Browse latest Browse all 23596

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>