Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redefining a function by supplying some of its arguments

Tags:

python

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!

like image 684
Minseok Kim Avatar asked Jan 29 '26 10:01

Minseok Kim


2 Answers

You can use lambda in python

Original function

def func(arg1, arg2):

Then you get the value you want as default for arg2 and define simple_func

simple_func = lambda arg1 : func(arg1, arg2=new_default)

Now you can run simple_func

simple_func("abc") #"abc" = value for arg1

Hope I could help you

like image 53
Sven Avatar answered Feb 01 '26 00:02

Sven


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
like image 33
Minseok Kim Avatar answered Jan 31 '26 23:01

Minseok Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!