0

I'm trying to use dataclass field as a property to allow custom setter/getter logic, but the metadata information seems to be getting lost when I do so.

Consider the below simple example highlighting this issue:

from dataclasses import dataclass, field, fields

@dataclass
class Test:
    name:str = field(metadata={'persistence': 'DB'})
    _name:str = field(init=False, default='name', repr=False)
    
    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, value):
        self._name = value
        
print(fields(Test))

The output shows empty metadata for the field name:

(Field(name='name',type=<class 'str'>,default=<property object at 0x7f15d103d590>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f1617c4dbe0>,init=True,repr=True,hash=None,compare=True,
metadata=mappingproxy({}),_field_type=_FIELD),
Field(name='_name',type=<class 'str'>,default='name',default_factory=<dataclasses._MISSING_TYPE object at 0x7f1617c4dbe0>,init=False,repr=False,hash=None,compare=True,
metadata=mappingproxy({}),_field_type=_FIELD))

How can I avoid this issue?

  • Yes, because you are overwriting it will h the property. Maybe just don't use a dataclass – juanpa.arrivillaga Jun 19 '22 at 18:25
  • I need to use a dataclass because the actual code class is a derived dataclass and is relying on couple of dataclass features such as fields to work correctly. – Dishank Agrawal Jun 19 '22 at 18:28
  • I found this related question about dataclasses and properties. There's no specific discussion on the metadata flag for the public attribute, but maybe there's some useful info there or in any of the other answers or articles linked off of it. https://stackoverflow.com/questions/51079503/dataclasses-and-property-decorator – nigh_anxiety Jun 19 '22 at 19:42
  • what are you trying to do i.e. whats the `metadata` field used for? I feel like there imght be a way to set a default value for a field property if it's not specified in the constructor, but some more info on what you plan to do with the metadata might be helpful. – rv.kvetch Jun 19 '22 at 23:37

0 Answers0