Python › Descriptors & Properties
How do properties and descriptors interact with __slots__, and what special consideration is needed?
AdvancedAnswer
A descriptor (including @property) works fine as a CLASS attribute alongside __slots__, since the descriptor ITSELF lives on the class, not the instance — but a custom descriptor's __get__/__set__ implementation CAN'T use a plain instance.__dict__ for storage (since __slots__ removes __dict__ entirely) and must instead store data in a DEDICATED slot or a WeakKeyDictionary keyed by instance.
class Point:
__slots__ = ("_x",) # explicit slot for internal storage
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value # stored in the '_x' slot, not a __dict__ (which doesn't exist)
p = Point()
p.x = 5
print(p.x) # 5Real-world example Combining @property-based validation with __slots__-based memory optimization for a class expected to have millions of instances.