Thursday, 21 November 2013

Python Decorators

A word about decorators in Python. A 'decorators' is a piece of code that modifies other code (often refered to as metaprogramming). There are two types of decorators: a function and a class decorators, modifying functions and classes respectively. Decorators take in a callable type and return a callable type. Lets restrict our attention to the following subset of callable types: user defined functions, builtin function and generator functions. Functions, like everything else in Python, is an object. The most simple decorator may take a user defined function as input and add an extra attribute to this function, returning this new version. In this case, the action of the underlying callable object does not change, we simply use the decorator to attach more information to it. A more complicated example of a decorator is one that changes the action of the 'decorated' callable, returning a new modified callable with different behaviour. An example of a decorator is the property builtin that was introduced in class. This function 'decorates' variables allowing to modify/restrict access, change doc strings etc. Note that variables are also objects, instances of more 'fundamental' classes such as int, float etc and these themselves are instances of a factory object 'type'. Factory as in a sense that this object assembles/creates 'fundamental' classes.

No comments:

Post a Comment