Search code examples
pythonpython-dataclassesslots

Define __dict__ in slotted dataclass


Consider the following example:

from dataclasses import dataclass

@dataclass(slots=True)
class Circle:
    radius:int = 2

    @property
    def myslots(self):
        return self.__slots__

    @property
    def __dict__(self):
        return self.__slots__

c = Circle()
print(c.myslots)
print(c.__dict__)

which results in:

❯ python test.py 
('radius',)
Traceback (most recent call last):
  File "/home/raffaele/Downloads/test.py", line 21, in <module>
    print(c.__dict__)
          ^^^^^^^^^^
AttributeError: 'Circle' object has no attribute '__dict__'. Did you mean: '__dir__'?

How can I define a dict property in a dataclass with slots=True?


Solution

  • Given that, as @Anentropic said, the whole poiunt of slots=True is to not create a __dict__ attribute, you can obtain a dictionary of the instance attribute like the following:

    from dataclasses import dataclass
    
    @dataclass(slots=True)
    class User:
        name:str
        age:int
    
        def to_dict(self):
            d = dict()
            for var in self.__slots__:
                d[var] = self.__getattribute__(var)
            return d
    
    u = User("Mark", 23)
    print(u.to_dict())
    
    {'name': 'Mark', 'age': 23}