Decorators in python

Hi, I am a very newbie in this forum, being in this got a question to raise.
I keep getting errors while using the decorator function. Please assist me with your thoughts.
Here I have code for ‘decorator’ , the main program following the error.

‘decorator’ code is as follows:

def print_twice(func):
    def wrapper_print_twice(*args, **kwargs):
        func(*args, **kwargs)
        return func(*args, **kwargs)
    return wrapper_print_twice()

‘main’ code where I am trying to print fuction by passing parameters.

from decorate import print_twice

def say_hi(name):
    print('creating name')
    return f'Hello, {name}'


Receiving following error, unable to fix at my end.

Traceback (most recent call last):
  File "C:\Users\r58\PycharmProjects\Project_July_200_Target\", line 5, in <module>
    def say_hi(name):
  File "C:\Users\r58\PycharmProjects\Project_July_200_Target\", line 11, in print_twice
    return wrapper_print_twice()
  File "C:\Users\r58\PycharmProjects\Project_July_200_Target\", line 9, in wrapper_print_twice
    func(*args, **kwargs)
TypeError: say_hi() missing 1 required positional argument: 'name'

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Take a closer look at the print_twice function, specifically at what it returns. Keep in mind that decorator function should return wrapper function.

Dear Sanity, Thank you. I’ve had multiple trials to look forward to the return of wrapper function (the inner one), however, I don’t find any glitch over in the procedural functional.
Please help me.

print_twice function returns result of the executed wrapper function, instead of just the wrapper function.

Dear Sanity, You are obviously perfect. Yes, the called function in the inner method should be a First-class object and returned to the main program. The issue has been fixed with the following code.

def print_twice(func):
def wrapper_print_twice(*args, **kwargs):
value = func(*args, **kwargs)
return value
return wrapper_print_twice()

Dear Sanity, Understood, thank you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.