Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataclasses and property decorator

I've been reading up on Python 3.7's dataclass as an alternative to namedtuples (what I typically use when having to group data in a structure). I was wondering if dataclass is compatible with the property decorator to define getter and setter functions for the data elements of the dataclass. If so, is this described somewhere? Or are there examples available?

like image 909
GertVdE Avatar asked Jun 28 '18 09:06

GertVdE


People also ask

What are DataClasses used for?

Dataclasses provides many features that allow you to easily work with classes that act as data containers. In particular, this module helps to: write less boilerplate code. represent objects in a readable format.

What is Python property decorator?

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

How does DataClass work in Python?

DataClass in Python DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented. Parameters: init: If true __init__() method will be generated. repr: If true __repr__() method will be generated.

What is Python @property?

The @property Decorator In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None)


1 Answers

It sure does work:

from dataclasses import dataclass  @dataclass class Test:     _name: str="schbell"      @property     def name(self) -> str:         return self._name      @name.setter     def name(self, v: str) -> None:         self._name = v  t = Test() print(t.name) # schbell t.name = "flirp" print(t.name) # flirp print(t) # Test(_name='flirp') 

In fact, why should it not? In the end, what you get is just a good old class, derived from type:

print(type(t)) # <class '__main__.Test'> print(type(Test)) # <class 'type'> 

Maybe that's why properties are nowhere mentioned specifically. However, the PEP-557's Abstract mentions the general usability of well-known Python class features:

Because Data Classes use normal class definition syntax, you are free to use inheritance, metaclasses, docstrings, user-defined methods, class factories, and other Python class features.

like image 135
shmee Avatar answered Sep 20 '22 07:09

shmee