I have some questions regarding what happens inside decorators in Python.
- Consider code, which saves sum in log file:
def logger(func):
def wrapped(*args, **kwargs):
result = func(*args, **kwargs)
with open('log.txt', 'w') as f:
f.write(str(result))
return result
return wrapped
@logger
def summator(numlist):
return sum(numlist)
print(f"Summator: {summator([1, 2, 3, 4, 5])}")
How does it work when I run summator([1, 2, 3, 4, 5, 6])? I suppose the logger to send the summator([1, 2, 3, 4, 5, 6]) function instance inside wrapped, where the summator function is executed and it's result is someway modified. But def logger(func) is strange for me: does it mean, that it takes func with func arguments attached? I see that logger itself doesn't take * args, ** kwargs, only wrapped does...
- Consider similar code:
def logger(filename):
def decorator(func):
def wrapped(*args, **kwargs):
result = func(*args, **kwargs)
with open(filename, 'w') as f:
f.write(str(result))
return result
return wrapped
return decorator
@logger('new_log.txt')
def summator(numlist):
return sum(numlist)
How does decorator get func? It is wrapped by logger, which accepts only a filename.