I am trying to print the pattern as follows:
******
20
******
I used decorator function to print the pattern before and after main function. But my code is not printing the pattern only main function is getting executed. Please suggest how I can write the function in a better format.
Following is my code:
def banner(str1, len1):
def decorator(func):
def wrapper(*args1):
new_line = '\n'
str2 = str1 * len1
return f'{str2}{new_line}{func(*args1)}{new_line}{str2}'
return wrapper
return decorator
@banner('*', 6)
def func1(a, b):
print(a*b)
func1(5,4)
CodePudding user response:
You need to return a * b
, not print it:
@banner('*', 6)
def func1(a, b):
return a * b
Output:
>>> func1(5, 4)
'******\n20\n******'
>>> print(func1(5, 4))
******
20
******
The reason you need to return is because your wrapped function is called in the middle of that f-string, with func(*args1)
. With only a print
statement in the function originally, your function defaulted to the implicit return None
that all functions in Python default to if a return
is not explicitly provided.