Decorate with a decorator

Decorator

Decorators are like adding some additional behavior to an existing function. For example, you can measure the execution time and output it, or add a message such as "~ ~ function was executed".

sample

This time, I made something to add a message to the output and execution time measurement Code created: https://github.com/KodairaTomonori/Qiita/tree/master/default_module/syntax

Add a message

decoration.py


deco =  '¡+゜+¡・゜・¡+*+¡・★・¡+*+¡・===[ '
deco_end = deco.replace('[', ']')[::-1]
deco_result = [' ∧____∧ Results', '( `Д´ )I will output', '(▄︻▇〓┳0035', '/   )', '( / ̄∪']

def deco_func(func):
    def decoration(*args, **kwargs):
        print(deco + 'start   ' + func.__name__ + deco_end)
        for i in range(len(deco_result) ):
            if i != 2: print(deco_result[i])
            else: print(deco_result[i], func(*args, **kwargs) )
        print(deco + 'end     ' + func.__name__ + deco_end)
    return decoration

@deco_func
def addition(a, b):
    return '{} + {} = {}'.format(a, b, a + b)

if __name__ == '__main__':
    addition(103842, 283746)

output

Screenshot 2015-10-27 2.02.23.png

The decorator is that the deco_func function returns the decoration function created within the function. decoration prints the beginning and end to decorate the output. You can get the function name with func.__name__. Also, by setting (* args, ** kwargs), it is possible to correspond to most functions.

To use it as a decorator, just add @deco_func in front of the function. By doing this, ʻaddition = deco_func (addition) (a, b) `.

measurement of time

timer.py


#usr/bin/python

import time

def timer(func):
    def print_time(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        print(func.__name__ + \
            'The time it took to execute{}Seconds'.format(time.time() - start) )
    return print_time

@timer
def roop_timer(a):
    return roop(a)

def roop(a):
    sum_ = 0
    for i in range(a):
        sum_ += i
    return sum_

if __name__ == '__main__':
    roop_timer(10000)
    timer(roop)(10000)

output

output.txt


roop_The time taken to execute the timer is 0.0008311271667480469 seconds
It took 0 time to execute roop.0008249282836914062 seconds

print_time measures the time and outputs the result. func.__name__ will fetch the function name. If you want to reflect @ timer only partially, you can do the same operation by settingtimer (roop) (10000). It is also possible to create a function dedicated to it, such as roop_timer (it is easier to create this when using two or more).

Summary

You can easily add other functions to a function by adding @decorate_function.

Recommended Posts

Decorate with a decorator
Easily cProfile with a decorator
A4 size with python-pptx
Make a function decorator
Use a Property Decorator?
Learn librosa with a tutorial 1
Draw a graph with NetworkX
Try programming with a shell!
Create a homepage with django
Using a printer with Debian 10
Make a fortune with Python
Create a heatmap with pyqtgraph
Create a directory with python
A little stuck with chainer
Draw a graph with networkx
Make a fire with kdeplot
Building a kubernetes environment with ansible 2
[Python] What is a with statement?
Solve ABC163 A ~ C with Python
Operate a receipt printer with python
A python graphing manual with Matplotlib.
Play with a turtle with turtle graphics (Part 1)
Draw a graph with Julia + PyQtGraph (2)
Decorator 1
Generate a normal distribution with SciPy
Creating a decision tree with scikit-learn
Let's make a GUI with python.
Make a sound with Jupyter notebook
Learn with FizzBuzz Iterator, Generator, Decorator
Enumerate files with a specific extension
Creating a Flask server with Docker
Build a deb file with Docker
Solve ABC166 A ~ D with Python
Draw a loose graph with matplotlib
Deploy a Django application with Docker
Let's make a breakout with wxPython
Create a virtual environment with Python!
I made a fortune with Python.
Draw a beautiful circle with numpy
Django Tips-Create a ranking site with Django-
Draw a graph with Julia + PyQtGraph (1)
Building a virtual environment with Python 3
Creating a simple app with flask
Draw a graph with Julia + PyQtGraph (3)
Solve ABC168 A ~ C with Python
Make a recommender system with python
Decorator 2
Build a web application with Django
Generate a Pre-Signed URL with golang
[Python] Generate a password with Slackbot
Solve ABC162 A ~ C with Python
Create a Python general-purpose decorator framework
Draw a graph with pandas + XlsxWriter
Make a filter with a django template
Solve ABC167 A ~ C with Python
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Create a poisson stepper with numpy.random
Make a nice graph with plotly
Building a kubernetes environment with ansible 1
Draw a graph with PySimple GUI