Читать книгу Professional Python - Luke Sneeringer - Страница 7
Part I
Functions
Chapter 1
Decorators
When You Should Write Decorators
ОглавлениеSeveral very good use cases exist for writing decorators in Python applications and modules.
Additional Functionality
Probably the most common reason to write a decorator is if you want to add additional functionality before or after the decorated method is executed. This could include use cases such as checking authentication or logging the result of a function to a consistent location.
Data Sanitization or Addition
A decorator could also sanitize the values of arguments being passed to the decorated function, to ensure consistency of argument type, or that a value conforms to a specific pattern. For example, a decorator could ensure that the values sent to a function conform to a specific type, or meet some other validation standard. (You will see an example of this shortly, a decorator called @requires_ints
.)
A decorator can also transform or sanitize data that is returned from a function. A valuable use case for this is if you want to have functions that return native Python objects (such as lists or dictionaries), but ultimately receive a serialized format (such as JSON or YAML) on the other end.
Some decorators actually provide additional data to a function, usually in the form of additional arguments. The @mock.patch
decorator is an example of this, because it (among other things) provides the mock object that it creates as an additional positional argument to the function.
Function Registration
Many times, it is useful to register a function elsewhere – for example, registering a task in a task runner, or a function with a signal handler. Any system in which some external input or routing mechanism decides what function runs is a candidate for function registration.