user2015487
user2015487

Reputation: 2185

Function with fewer arguments and optional arguments

I often write code that looks like this and am looking for a better suggestion. Basically, I usually create some general function myfuc_general that handles all the cases I need with parameters, usually with optional parameters. However, often I usually run 2 (possibly more) specific functions. Everything is the same except one of the arguments is different, in this case a. I run them so often that I actually prefer to just have two additional functions so I don't have to remember what the optional parameter needs to be.

So for myfunct_specific1, I am running a=10 and for myfunct_specific2, a=20. Is there something better to do than this? This seems pretty sloppy and it has the disadvantage in the event that I need to change the myfuct_general call, then I have to change all the other functions.

def myfunc_general(constant, a=1,b=2):
    return constant+a+b

def myfunct_specific1(constant,b=2):
    a=10
    return myfunc_general(constant,a,b=2)

def myfunct_specific2(constant,b=2):
    a=20
    return myfunc_general(constant,a,b=2)

print myfunct_specific1(3) #15
print myfunct_specific2(3) #25

edit (addition):

iCodez thank you for suggestion. I have this particular situation and it is throwing me an error. Help? Thanks again

def myfunc_general(constant, constant2, a=0,b=2):
    return constant+constant2+b+a

import functools
myfunct_specific=functools.partial(myfunc_general,constant2=30)

print myfunct_specific
print myfunct_specific(3,5,b=3)


Traceback (most recent call last):
  File "C:/Python27/test", line 8, in <module>
    print myfunct_specific(3,5,b=3)
TypeError: myfunc_general() got multiple values for keyword argument 'constant2'

Upvotes: 4

Views: 2380

Answers (1)

user2555451
user2555451

Reputation:

You can use functools.partial to make this a lot easier:

from functools import partial

def myfunc_general(constant, a=1, b=2):
    return constant+a+b

myfunct_specific1 = partial(myfunc_general, a=10)
myfunct_specific2 = partial(myfunc_general, a=20)

Below is a demonstration:

>>> from functools import partial
>>>
>>> def myfunc_general(constant, a=1, b=2):
...     return constant+a+b
...
>>> myfunct_specific1 = partial(myfunc_general, a=10)
>>> myfunct_specific2 = partial(myfunc_general, a=20)
>>>
>>> print myfunct_specific1(3)
15
>>> print myfunct_specific2(3)
25
>>>

Upvotes: 7

Related Questions