1. Technology

Python Decorators, Methods, and Functions


1 of 7

Python's Function Decorators: An Introduction

Decorators were introduced to the Python world as part of the 2.4 release. They have since become increasingly importantin, especially for maintaining and extending Python programs. In order to best grasp the purpose and beneficiality of Python's decorators, it is important to understand what happens when one imports modules.

When a module is imported, the content of that module is inserted into your code at the point it is imported. So, when you import the re module or the sys module, Python stops reading your code when it hits "import <module name>", reads the given module from the code library, and then returns to your code. The module becomes part of the Python bytecode which is then converted to machine readable code for execution.

In this way, the Python library allows the programmer to nuance the pre-written code to a desired specification. Similarly, a decorator allows one to customise the use of a function, adding to it as desired without changing the original function. This discussion will rely on your having a good working knowledge of Python functions and classes. If you need to refresh yourself on functions, see my discussions of the syntax and purpose of Python functions and classes.

  1. About.com
  2. Technology
  3. Python
  4. Beginning Python
  5. Programming Python Functions - Decorating Python Functions

©2014 About.com. All rights reserved.