jcp
jcp

Reputation: 851

Define a python function based on previously defined function specifying argument

I have one defined function and I would like to define another one which is exactly the same as the first, but specifying one parameter.

One possible way of doing that is

def my_function(arg1, arg2):
    print(arg1, arg2)

def my_function_foo(arg1):
    return(my_function(arg1, 'bar'))


>>> my_function_foo('foo')
foo bar

But I suppose there is a cleaner way, closer to:

my_function_foo = my_function(arg2 = 'foo')

Upvotes: 0

Views: 740

Answers (4)

SalvadorViramontes
SalvadorViramontes

Reputation: 580

You could use the multiple dispatch library to do a method override like in C:

from multipledispatch import dispatch

@dispatch(object, object)
def my_function(arg1, arg2):
    print(arg1, arg2)

@dispatch(object)
def my_function(arg1):
    return(my_function(arg1, 'bar'))

my_function('foo')
my_function('foo', 'foo')

Upvotes: 0

Kian
Kian

Reputation: 1350

You might solve your problem with an inner function as follows:

def my_function(arg1, arg2='bar'):
    def my_function_foo(arg1):
        print(arg1, arg2)
    return my_function_foo(arg1)

my_function(arg1 = 'foo')

Upvotes: 0

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15588

You can create a decorator that will pass the parameter for you.

from functools import wraps

def give_param(param='bar'):
    def inner_function(func):
        @wraps(func)
        def wrapper(*args, **kwargs):

            return func(*args, arg2=param)

        return wrapper

    return inner_function

@give_param('bar')
def my_function(arg1,arg2):
    # do some stuff
    print(arg1,arg2)

So if you want arg2 = 3,

@give_param(3)
def my_function(arg1,arg2):
    # do some stuff
    print(arg1,arg2)

Upvotes: 1

chepner
chepner

Reputation: 532238

Use functools.partial:

>>> from functools import partial
>>> my_function_foo = partial(my_function, arg2='bar')
>>> my_function_foo('foo')
foo bar

Note that my_function_foo is not technically a function, but an instance of partial. Calling the instance calls the underlying function using the previously given and current arguments merged in the expected way.

Upvotes: 2

Related Questions