3

Let's say I have a function like this:

def func_1(a, b=1, c=None):
     code here

Now I want to make another function that has the same internals but different keyword arguments.

def func_2(a, b=2, c='asdf'):
    code here

One option would be a closure like this:

 def make_func(b, c):
     def func(a, b=b, c=c):
         code here
     return func

 func_1 = make_func(1, None)
 func_2 = make_func(2, 'asdf')

Is there a more concise/Pythonic way to go about this?

5
  • Why use a closure? Just call one from the other: def func_2(a, b=2, c='asdf'): func_1(a, b, c) Commented Mar 15, 2016 at 22:43
  • @jonrsharpe: the closure acts as a factory to produce more such functions. I had made the same comment, then deleted it again once I realised that. Commented Mar 15, 2016 at 22:45
  • @MartijnPieters true, but generating the functions dynamically seems unnecessary for a small number (not to mention likely makes life harder for IDEs). Commented Mar 15, 2016 at 22:47
  • Or does the OP actually mean changing, i.e. altering the defaults in an existing function object, which isn't what the example does. Commented Mar 15, 2016 at 22:48
  • @jonrsharpe I meant making another function with same behavior, different keywords - sorry for ambiguous wording. Commented Mar 16, 2016 at 0:04

1 Answer 1

3

Use a functools.partial() object:

from functools import partial

func_2 = partial(func_1, b=2, c='asdf')

The defaults supplied to the partial can be overridden again when calling it:

>>> from functools import partial
>>> def func_1(a, b=1, c=None):
...     return a, b, c
...
>>> func_2 = partial(func_1, b=2, c='asdf')
>>> func_2(42)
(42, 2, 'asdf')
>>> func_2(42, b=5, c='spam')
(42, 5, 'spam')
Sign up to request clarification or add additional context in comments.

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.