Understanding Python Descriptors and Decorators: Concepts, Differences, and Practical Applications
This article explains Python descriptors and decorators, detailing their protocols, differences, and use cases such as attribute validation, logging, permission control, caching, and parameter validation with illustrative code examples in real-world scenarios.
Python descriptors are classes implementing the descriptor protocol (__get__, __set__, __delete__) to manage attribute access, enabling features like validation, computed properties, and caching. Built‑in examples include property, classmethod, and staticmethod.
Example descriptor:
class Descriptor:
def __init__(self):
self._value = 0
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
if value < 0:
raise ValueError("Value must be non-negative.")
self._value = value
class MyClass:
attr = Descriptor()
obj = MyClass()
obj.attr = 10
print(obj.attr) # 10
obj.attr = -1 # raises ValueErrorDecorators are higher‑order functions that take a function (or class) and return a new function, adding behavior such as logging, timing, or access control without modifying the original definition.
Example decorator:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()Key differences: descriptors focus on attribute access control and are integrated via special methods; decorators wrap functions or classes to extend functionality. Descriptors are used at the class design level for fine‑grained attribute logic, while decorators are applied to functions, methods, or classes for cross‑cutting concerns like logging, permission checks, and performance optimization.
Practical scenarios:
Attribute validation descriptor – ensures a value meets a condition (e.g., status code must be 200‑299).
Logging decorator – automatically logs function calls and results.
Permission‑control decorator – restricts execution to admin users.
Cached property descriptor – stores expensive computation results for reuse.
Parameter‑validation decorator – validates incoming arguments against a schema before calling the function.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.