let's suppose there is a function like below:
def func(arg1, args2):
# do sth using arg1 and arg2
In the runtime, I would like to keep use some value for args2
which we can't know when defining the func
.
So what I would like to do is:
func_simpler = func(, args2=some_value_for_arg2)
func_simpler(some_value_for_arg1) # actual usage
Any idea on it? I know that there is a walk-around such as defining func
better, but I seek for a solution more like func_simpler
thing. Thanks in advance!
You can use lambda
in python
def func(arg1, arg2):
simple_func = lambda arg1 : func(arg1, arg2=new_default)
simple_func("abc") #"abc" = value for arg1
Hope I could help you
I was trying to solve this myself and I found a not-bad solution:
def func(a, b):
print(a, ": variable given everytime the model is used")
print(b, ": variable given when the model is defined")
enter code here
def model(b):
def model_deliver(a):
func(a, b)
return model_deliver
s = model(20)
s(12) #prints result as below
# 12 : variable given everytime the model is used
# 20 : variable given when the model is defined
Use functools.partial
:
from functools import partial
def func(arg1, arg2):
print(f'got {arg1!r} and {arg2!r}')
simple_func = partial(func, arg2='something')
simple_func("value of arg1")
# got 'value of arg1' and 'something'
Using partial
produces an object which has various advantages over using a wrapper function:
pickle
d, the partial
object can be pickle
d as well.repr
/ str
of a partial
object shows the initial function information. partial
is efficient, as it flattens the wrappers. Note that if you want to partially apply arguments of a method, use functools.partialmethod
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.