What are python decorators? How can you create your own function decorator? Check out!

What are python decorators

Python decorators are a wrappers around the function/method/class that can do actions before/after some function/method/class is invoked.

To make that happen, you re-use function as a parameter. Basically you create a private function that contains other function as a parameter. Sounds like not a trivial thing? Don't be scared, it's pretty simple.

As a reference think about a profiler that can measure how much time your function took. With wrapper it's easy-peasy.

To The Point

To create your first decorator, first you create a function wrapper:

def wrapper(*args, **kwargs):
    return function_that_you_take_as_argument()

But wait, what is the function_that_you_take_as_argument ? It's exactly what it says - a function that is taken with decorator as argument.

To make a working decorator you also need to make an outer-function around it:

def decorator_name(function_that_you_take_as_argument):
    def wrapper(*args, **kwargs):
        return function_that_you_take_as_argument()
    return wrapper

@decorator_name
def function_that_you_take_as_argument()
    print("test")

This decorator does nothing at this time. But if you add output to variable and make statements before and after like that:

def decorator_name(function_that_you_take_as_argument):
    def wrapper(*args, **kwargs):
        print("before:")
        output =function_that_you_take_as_argument()
        print("after:")
        return output
    return wrapper

@decorator_name
def your_function_this_name_is_different_then_in_wrapper_argument()
    print("test")

Then your function call with decorator will:

  • first print before:
  • make function - print test
  • print after -when function has done it's executement.

Snippets

def decorator_name(function_wrapped):
    def wrapper(*args, **kwargs):
        output = function_wrapped(*args, **kwargs)
        return output
    return wrapper

Asciinema

Example from asciinema

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 [Anselmos](github.com/anselmos) <anselmos@users.noreply.github.com>
#
# Distributed under terms of the MIT license.

"""
Decorators example
"""

def decorator_name(function_name):
    """ Here you put your function """
    def wrapper(*args, **kwargs):

        print("before invoking function")
        output_of_function = function_name(*args, **kwargs)
        print("after invoking function")
        return output_of_function
    return wrapper

@decorator_name
def your_function_that_will_use_decorator():
    """TODO: Docstring for your_function_that_will_use_decorator.
    :returns: TODO

    """
    print("Test")

your_function_that_will_use_decorator()

Acknowledgements

Autopromotion:

Found while research of the topic

Thanks!

That's it :) Comment, share or don't :)

If you have any suggestions what I should blog about in the next articles - please give me a hint :)

See you in the next episode! Cheers!



Comments

comments powered by Disqus