git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Property for dataclass field with default value


Ivan Ivanyuk wrote:

> On Thu, 18 Jun 2020 at 11:26, Peter Otten <__peter__ at web.de> wrote:
>>
>> Ivan Ivanyuk wrote:
>>
>> > Hello All,
>> >
>> > I have some trouble using @dataclass together with @property decorator
>> > or property() function.
>> >
>> > From the documentation and PEP is seems that the intended behaviour of
>> > @dataclass is to be the same as normal __init__() that sets instance
>> > variables.
>> >
>> > But it seems that when using @property decorator some parts work
>> > differently when relying on default values. I'm using Pyhton 3.8.3 for
>> > this.
>> >
>> > Using the code:
>> >
>> > from dataclasses import dataclass
>> >
>> > @dataclass
>> > class Container:
>> >     x: int = 30
>> >
>> >     @property
>> >     def x(self) -> int:
>> >         return self._x
>> >
>> >     @x.setter
>> >     def x(self, z: int):
>> >         if z > 1:
>> >             self._x = z
>> >         else:
>> >             raise ValueError

[...]

>> Your class definition is basically
>>
>> class Container:
>>     x = default_value
>>     x = property_x
>>
>> i. e. you use the same name twice. A possible workaround might be to
>> define the property in a subclass. That way you get distinct namespaces
>> for the default value and the property:

[...]

> Didn't think about it in such a way! But now that it was pointed, I
> see no obvious way to resolve this in dataclass decorator given the
> way it's implemented now. And while adding another class looks easy it
> somewhat detracts from the dataclasses' purpose of removing
> boilerplate.
> 
> Does it seems like a good idea to ask for documenting that behaviour
> in dataclasses documentation or it's not popular enough use case?

I don't know. From what I've seen runtime value checking has not even been 
considered even though it is part of attrs which seems to be a source of 
inspiration for dataclasses.

https://www.attrs.org/en/stable/examples.html#validators

If you make a feature request on python-ideas or the bugtracker you may at 
least find out why this part was not copied.