Easyread
Published in

Easyread

Python decorator

How to make a decorator with or without parameters in python

Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it. Decorators also can help you to reduce duplication on code.

In this article i’ll give some example how to write decorator with parameter or without parameter in python, learning this tool will help you so much in real project when you working in large code base that need some additional functionality without change it. It will like box inside the box.

I will use python native module from functools for wrapping my main function.

Decorator Without Parameter

This example will print double message “hello world” in given function.

simple decorator to print double message

In this decorator code i will run this function twice, and this is my main function.

main function to print some message

Here you can see how to call the decorator using just “@function_name”, put it above the function and this decorator will execute right before the main function is executed and this is the result. This function will be executed twice. How easy is it ?? 😀

result decorator without parameters

Decorator with parameters

Then we may think, what about we want to print this message based on the parameters, we can determine how much this message will be printed.

From earlier example, it just need to change little bit our decorator to support that feature.

decorator with parameter

In this change I just wrapped the previous decorator with one outline function to support the parameters, I will set the default loop as 1. So with this little change I can specify the number of times this main function will run with respect to the given parameter.

my main function is still the same as before but changed the decorator and added a new parameter called “repeat” as we defined earlier.

main function

So when I run this code, it will execute as many parameters as given. This is the result.

result decorator with parameters

See we can change or manipulate the result of the function without changing the main code by using decorators. Cool isn’t it ?😎 this can be implemented in any function that requires this same functionality without duplicating our code.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store