+ 1

Decorators with multiple input arguments

I've been playing around with Python decorator functions to try and understand how to use them. I've modified the first code example in the course to take multple arguments as follows: def decorator(func, str): def modfunc(): print("============") func(str) print("============") return modfunc def print_text(str): print(str) decorated = decorator(print_text, "Hello World!") decorated() It appears that I can't do this using the @decorator short hand. Is this true or does anyone know how to use this syntax when the decorator takes more than just a single function as an argument?

16th Feb 2017, 3:58 PM
edd buggins
edd buggins - avatar
3 ответов
+ 3
That's not the right way to make/use decorators. Here is a great tutorial: https://youtu.be/FsAPt_9Bf3U
23rd Feb 2017, 3:54 AM
Jay
Jay - avatar
0
A decorator takes a function a returns a function. We typically want the function returned to have the same signature so here is how to do that: def decor(func): def wrap(x): print("#" * len(x) ) func(x) print("#" * len(x) ) return wrap decprint = decor(print) decprint("This is decorating with parameters") # Here is the second way of wrapping @decor def decprint2(x): print(x) decprint2("This is also decorating with parameters")
12th Jul 2017, 4:49 PM
Jasper Schellingerhout
7th Jun 2018, 2:00 AM
Denys Yeromenko
Denys Yeromenko - avatar