Search code examples
pythonfunctionpython-3.xdefault-arguments

Parsing default arguments in functions without executing the them


I need to pass a function (without calling it) to another function, but I need to specify a different value for a default argument.

For example:

def func_a(input, default_arg=True):
    pass

def func_b(function):
    pass

func_b(func_a(default_arg=False))

This, however, calls func_a() and passes the result to func_b().

How do I set default_arg=False without executing func_a?


Solution

  • Use a lambda function. Like this:

    func_b(lambda input: func_a(input, default_arg=False))
    

    In func_b you will have a callable function which accepts argument input and executes func_a with previously specified default_arg argument.


    Thanks to cdarke for suggest this way:

    from functools import partial, wraps
    
    def func_wrapper(f, **kwargs):
        @wraps(f)
        def wrapper(input):
            return f(input, **kwargs)
        return wrapper
    
    func_b(func_wrapper(func_a, default_arg=False))