1

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')
3
  • Won’t def my_function(arg1, arg2='bar'):... do? Commented Dec 6, 2018 at 16:13
  • 2
    @PraysonW.Daniel You might want several functions, one that assumes a value of bar for arg2, one that assumes a value of 3, etc. Commented Dec 6, 2018 at 16:14
  • 1
    Ah! This calls for decorators;) Commented Dec 6, 2018 at 16:20

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Learned something today ;)
2

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)

Comments

1

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')

Comments

0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.