__invert__ — Advanced Playground
Defines behavior for the ~ bitwise NOT operator
Python Playground
# __invert__ 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}")
Output
Click "Run" to execute your code
Understanding how __invert__ interacts with Python's descriptor protocol and method resolution order enables powerful patterns.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?