Codementor Events

Creating a Simple Python Decorator

Published Aug 14, 2017
Creating a Simple Python Decorator

One of the amazing things about the Python language is the use of decorators to alter functionality. Decorators are used to extend functions without actually modifying them directly.

What is a function? What are decorators?

What is a function?

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

What is a decorator?

A decorator is similar to a wrapper, modifying the behavior of the code before and after a target function execution, without the need to modify the function itself. Source: TheCodeShip

A decorator is a callable function or method that accepts a callable as input and returns a callable as output. You apply the decorator by using the @ syntax.

@json
def add(x,y):
    return x + y

In the example above, we've applied the json decorator on the add function.
Writing your own decorators gives you a lot of control and enables many capabilities.

Writing your own decorator

A decorator is a function, only difference is that it is poweful enough to modify another function. To define a decorator, we use the def keyword.
Here's a simple decorator:

def print_method_type(f):
    def decorated(*args, **kwargs):
        print f, type(f)
        return f(*args, **kwargs)
    return decorated

All this decorator does is to print the input callable and type before invoking it.

Here's the decorator in action:
Screen Shot 2017-08-14 at 4.17.27 AM.png

You can check out the code here.

Passing arguments to decorators

Another powerful capability of decorators is the ability to pass arguents to them like normal functions, after all they're functions too.

A Simple decorator to return noun in a format

First, let's write the decorator function before testing it out:

def noun(i):
  def tag(func):
    def wrapper(name):
      return "My {0} is {1}".format(i, func(name))
    return wrapper
  return tag
    

@noun("name")
def say_something(something):
    return something
    
print say_something('Bolaji')

@noun("age")
def say_something(something):
    return something
    
print say_something(24)

The code is available here.

Discover and read more posts from Bolaji Olajide
get started
post commentsBe the first to share your opinion
Aderonmu Abosede Oyindamola
6 years ago

How can i be a computer programmer? Please help me

Show more replies