Читать книгу Professional Python - Luke Sneeringer - Страница 5

Part I
Functions
Chapter 1
Decorators
Where Decorators Are Used

Оглавление

The standard library includes many modules that incorporate decorators, and many common tools and frameworks make use of them for common functionality.

For example, if you want to make a method on a class not require an instance of the class, you use the @classmethod or @staticmethod decorator, which is part of the standard library. The mock module (which is used for unit testing, and which was added to the standard library in Python 3.3) allows the use of @mock.patch or @mock.patch.object as a decorator.

Common tools also use decorators. Django (which is a common web framework for Python) uses @login_required as a decorator to allow developers to specify that a user must be logged in to view a particular page, and uses @permission_required for applying more specific permissions. Flask (another common web framework) uses @app.route to serve as a registry between specific URIs and the functions that run when the browser hits those URIs.

Celery (a common Python task runner) uses a complex @task decorator to identify a function as an asynchronous task. This decorator actually returns an instance of a Task class, which illustrates how decorators can be used to make a very convenient API.

Professional Python

Подняться наверх