DEV Community

Cover image for Reconciling Dataclasses And Properties In Python

Reconciling Dataclasses And Properties In Python

Florimond Manca on October 08, 2018

Originally published at blog.florimondmanca.com on Oct 6, 2018. If you can't wait for the TL;DR, jump to Lessons Learned at the end of this articl...
Collapse
 
rhymes profile image
rhymes

Thanks Florimond, this is very interesting!

I'm not sure if I'll need data classes in future projects but I'll definitely come back to this post if I do :)

I'm also pratically sold on the idea of type annotations in Python

ps. Raymond Hettinger is one of the coolest Python developers in the business :-D

Collapse
 
florimondmanca profile image
Florimond Manca

Sweet! I didn’t think data classes would be useful to me before I began using them... ;) Also glad to hear you’re adopting type annotations! I enjoy the extra safety and readability they provide, especially when working with other developers.

Collapse
 
rhymes profile image
rhymes

Yeah, they also help tooling/IDEs a lot.

Collapse
 
paddyroddy profile image
Patrick Roddy

do you how to combine this with abstract classes? If I do the following:

from dataclasses import dataclass, field
from abc import abstractmethod

@dataclass # type: ignore
class Vehicle:

    wheels: int
    _wheels: int = field(init=False, repr=False)

    @property
    def wheels(self) -> int:
        print('getting wheels')
        return self._wheels

    @wheels.setter
    def wheels(self, wheels: int):
        print('setting wheels to', wheels)
        self._wheels = wheels

    @abstractmethod
    def sound_horn(self):
        raise NotImplementedError

then I get the warning test.py:10: error: Name 'wheels' already defined on line 7

Collapse
 
sandordargo profile image
Sandor Dargo

So do you think it's worth using dataclasses with properties? To me, it seems less readable. On the other hand, you have repr...

Collapse
 
florimondmanca profile image
Florimond Manca

Hi! I do agree with you — it is probably less readable, and not very obvious. The reason being that there are many little details whose interplay allow this "trick" to even work.

So my answer would be: it depends on your priorities. Is it okay for you to sacrifice some readability over the advantages of dataclasses?

For example, it might not be okay because other people working on the project may not be familiar with dataclasses; they'd probably end up clueless about how it can even work.

Also, remember the Zen of Python: "there should be one — and preferably only one — way to do it." Consider alternatives; if they look more obvious, use them. Otherwise, go for @property. :-)