Minseok Kim
Minseok Kim

Reputation: 83

Redefining a function by supplying some of its arguments

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!

Upvotes: 3

Views: 145

Answers (3)

MisterMiyagi
MisterMiyagi

Reputation: 52099

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:

  • If the initial function and its arguments can be pickled, the partial object can be pickled as well.
  • The repr/str of a partial object shows the initial function information.
  • Repeated application of partial is efficient, as it flattens the wrappers.
  • The function and its partially applied arguments can be inspected.

Note that if you want to partially apply arguments of a method, use functools.partialmethod instead.

Upvotes: 2

Minseok Kim
Minseok Kim

Reputation: 83

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

Upvotes: 2

Sven
Sven

Reputation: 1172

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

Upvotes: 5

Related Questions