Reading Time: 1 minutes
Python Decorators
Decorators is a Python-exclusive feature, virtue of which you can define a function called a decorator function. This decorator function takes an object, manipulates it using its own object and returns this latter object. For example, in the event of decorating a function:
def decoratorFunction(inputFunction): def manipulateInputFunction(): capture return value of inputFunction return manipulatedReturnValueOfInputFunction return manipulateInputFunction @decoratorFunction def functionToBeDecorated(): # body of function returns an object, say a string
Significance of @ Notation
Any call to functionToBeDecorated() translates to decoratorFunction() with functionToBeDecorated as its argument i.e. functionToBeDecorated() becomes decoratorFunction(functionToBeDecorated)(). For example:
stringOne = functionToBeDecorated() BECOMES stringOne = decoratorFunction(functionToBeDecorated)()
Example
Let’s make the output of a function fancier by wrapping its return value with additional text. We will make use of the decorator annotation (@) provided by Python.
def decorateMyFunction(originalFunction): '''Decorates a function by wrapping its return value in a pair of HTML paragraph tags.''' def addAdditionalText(): # Obtain string returned by original function textFromOriginalFunction = originalFunction() # Adding new functionality to the function being decorated return "<p>" + textFromOriginalFunction + "</p>" return addAdditionalText @decorateMyFunction def functionToBeDecorated(): '''A simple function that returns a string.''' return "Hi there!" print( functionToBeDecorated() ) # OUTPUT: <p>Hi there!</p>