Using the decorators module

With all the functionality that decorators provide, and their common use among Python packages, it's inevitable that someone would create a package just for decorators. https://pypi.python.org/pypi/decorator provides a pip installable package to help when working with decorators.

The decorator module is a very stable (more than 10 years old) tool that provides the ability to preserve decorated functions across different Python versions. The aim of the module is to simplify decorator usage, reduce boilerplate code, and enhance program readability and maintainability. 

Decorators can be broken down into two main types: signature-preserving and signature-changing. The preserving decorators take a function call and return a function as the output, without changing anything about the function call's signature. These decorators are the most common type.

Signature-changing decorators accept a function call, but change the signature when output, or simply return non-callable objects. @staticmethod and @classmethod, discussed previously, are examples of signature-changing decorators.

Identifying a function's signature is provided by Python's introspection capabilities. In essence, a signature provides all necessary information about a function, that is, input and output parameters, default arguments, and so on, so that a developer, or the program, knows how to use a function.

This module is designed to provide generic factory of generators to hide the complexity of making signature-preserving decorators. Preserving decorators, while more common, are not necessarily easy to code from scratch, especially if the decorator needs to accept all functions with any signature.

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

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