Search code examples
pythonfunctionpartial

Using partial() to fix terms out of order


Let's say I have a function:

def my_function(a, b, c):
    # Some Code

I can use:

functools.partial(my_function, "hello")

To get a callable of my_function where a="hello". But suppose I want to set the value of parameter b. How could I set the value of parameter b without doing something like:

functools.partial(my_function, "hello", "bob")

which would also (undesirably) set the value of parameter a?


Solution

  • You can do;

    functools.partial(my_function, b='hello')
    

    However you are going to have to specify your arguments with your parameter names coming after b:

    >>> partial_function = functools.partial(my_function, b='hello')
    >>> partial_function('a', c='c')