Do you guys make decorators
? Embarrassingly, I learned the details ** today **. Even if I noticed the existence, I ignored it until today, but since I studied, I am writing with the intention of outputting something.
Immediately, I tried to make something like this.
deco_test.py
def decof(Func,*_args,**_kwargs):
def _deco(func):
def wrapper(*args,**kwargs):
return Func(func(*args,**kwargs),*_args,**_kwargs)
return wrapper
return _deco
def decob(Func,*_args,**_kwargs):
def _deco(func):
def wrapper(*args,**kwargs):
return Func(*_args,func(*args,**kwargs),**_kwargs)
return wrapper
return _deco
Roughly speaking, you can create a function ** that allows the specified function to receive the return value of the function to be wrapped.
There are two because it is used properly depending on whether the return value is received as the first argument (decof ()
) or the last argument (decob ()
).
It's hard to understand in words, so when I demonstrate it,
deco_test.py
import numpy as np
from functools import reduce
from operator import sub
@decob(reduce,sub)
@decof(np.array,dtype=int)
@decof(list)
@decof(str)
@decob(pow,2)
@decof(pow,2)
def add(a,b):return a+b
print(add(3,4))
output
-55
#3+4 -> 7**2 -> 2**49 -> '562949953421312' -> ['5', '6', '2', '9', '4', '9', '9', '5', '3', '4', '2', '1', '3', '1', '2']
# -> array([5, 6, 2, 9, 4, 9, 9, 5, 3, 4, 2, 1, 3, 1, 2]) -> 5-6-2-9-4-9-9-5-3-4-2-1-3-1-2 -> -55
You can clearly express (?) A function relay like this. that's all.
I've avoided it until now, but it seems to be quite convenient depending on how it is used, so if you come up with something again, I'd like to introduce it here. Thank you for reading to the end.