__sizeof__ — Advanced Examples
Returns the memory size of the object in bytes
__sizeof__ with descriptors
Advanced usage of __sizeof__ with descriptors and MRO.
python
# __sizeof__ with descriptors class ValidatedAttribute: def __init__(self, validator): self.validator = validator self.name = None def __set_name__(self, owner, name): self.name = name def __get__(self, obj, objtype=None): if obj is None: return self return getattr(obj, f"_{self.name}", None) def __set__(self, obj, value): if not self.validator(value): raise ValueError(f"Invalid value for {self.name}: {value}") setattr(obj, f"_{self.name}", value) class User: name = ValidatedAttribute(lambda v: isinstance(v, str) and len(v) > 0) age = ValidatedAttribute(lambda v: isinstance(v, int) and 0 <= v <= 150) u = User() u.name = "Alice" u.age = 30 print(f"{u.name}, age {u.age}") try: u.age = -1 except ValueError as e: print(f"Validation error: {e}")
Understanding how __sizeof__ interacts with Python's descriptor protocol and method resolution order enables powerful patterns.
Want to try these examples interactively?
Open Advanced Playground