Decorate functions

Functions are probably the simplest representation of a Python object that can be decorated. We can use decorators on functions to apply all sorts of logic to them—we can validate parameters, check preconditions, change the behavior entirely, modify its signature, cache results (create a memorized version of the original function), and more.

As an example, we will create a basic decorator that implements a retry mechanism, controlling a particular domain-level exception and retrying a certain number of times:

# decorator_function_1.py
class ControlledException(Exception): """A generic exception on the program's domain.""" def retry(operation): @wraps(operation) def wrapped(*args, **kwargs): last_raised = None RETRIES_LIMIT = 3 for _ in range(RETRIES_LIMIT): try: return operation(*args, **kwargs) except ControlledException as e: logger.info("retrying %s", operation.__qualname__) last_raised = e raise last_raised return wrapped

The use of @wraps can be ignored for now, as it will be covered in the section named Effective decorators - avoiding common mistakes. The use of _ in the for loop, means that the number is assigned to a variable we are not interested in at the moment, because it's not used inside the for loop (it's a common idiom in Python to name _ values that are ignored).

The retry decorator doesn't take any parameters, so it can be easily applied to any function, as follows:

@retry
def run_operation(task):
    """Run a particular task, simulating some failures on its execution."""
    return task.run()

As explained at the beginning, the definition of @retry on top of run_operation is just syntactic sugar that Python provides to actually execute run_operation = retry(run_operation).

In this limited example, we can see how decorators can be used to create a generic retry operation that, under certain conditions (in this case, represented as exceptions that could be related to timeouts, for example), will allow calling the decorated code multiple times.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.112.210