1

Given a function fxn1()

def fxn1(a,b=1):
    return a*b

I would like to do something like:

fxn2=fxn1(.,b=2)

In words, I would like to make a new function fxn2() which is identical to fxn1() but with different default values of optional arguments. I have not been able to find an answer/direction on web.

2
  • 1
    You may want to read about functools.partial Commented May 27, 2019 at 19:55
  • It's called early binding. Use partial from functools. Commented May 27, 2019 at 19:55

4 Answers 4

2

You can use functools.partial (official doc):

from functools import partial

def fxn1(a,b=1):
    return a*b

fxn2 = partial(fxn1, b=2)

print(fxn2(4))

Prints:

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

Comments

2

You can use partial function:

from functools import partial
fxn2 = partial(fxn1, b=2)

fxn2(1)

Comments

1
def fxn1(a,b=1):
    return a*b

def fxn2(a,b=2):
    return fxn1(a,b)

Comments

0

The easiest way will be

def fxn2(a, b=2):
    return fxn1(a, b)

4 Comments

It should be return fxn1(a, b)
You are of course right, thanks for catching it :-)
Actually, the easiest way will be functools.partial
Partial is arguably more elegant. I figured that for a beginner, the other option would be easier.

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.