Why does the decorator return the type None?
Question:
Help me understand why this decorator does not add a value to the end of the list that is formed in the do_list () function.
I get the result of the function working with the decorator None
def dec_do_list(func):
def wrapper(arg: int):
result = func(arg).append(4)
return result
return wrapper
@dec_do_list
def do_list(arg: int):
import random
result = []
for i in range(arg):
result.append(random.random())
return result
print(do_list(4))
Thank you in advance!
P.S.
I do this for educational purposes, in order to better understand the Decorator pattern
Answers:
result = func(arg).append(4)
append
doesn’t return a new list. It modifies the list in-place. You are getting the result
as the return value of append
and then returning it so at the end the returned value is None
.
You can change it to:
result = func(arg)
result.append(4)
return result
or, in one line:
return func(arg) + [4]
Help me understand why this decorator does not add a value to the end of the list that is formed in the do_list () function.
I get the result of the function working with the decorator None
def dec_do_list(func):
def wrapper(arg: int):
result = func(arg).append(4)
return result
return wrapper
@dec_do_list
def do_list(arg: int):
import random
result = []
for i in range(arg):
result.append(random.random())
return result
print(do_list(4))
Thank you in advance!
P.S.
I do this for educational purposes, in order to better understand the Decorator pattern
result = func(arg).append(4)
append
doesn’t return a new list. It modifies the list in-place. You are getting the result
as the return value of append
and then returning it so at the end the returned value is None
.
You can change it to:
result = func(arg)
result.append(4)
return result
or, in one line:
return func(arg) + [4]