Reputation: 51
I frequently write more advanced wrapper functions that call primitive functions I wrote earlier in a module. The point is to re-use code from the primitive function and do something extra but optional. The pain point is whenever I update the primitive function's parameters, I have to adjust for that in the advanced function. Is there a way to make this dynamic through the way the advanced function is written (something like below)? Or is there a better solution in general?
I could just write an all-encompassing general function, but I think it would be a waste of code.
It's usually like the example below but with deeper and deeper nested functions in additional wrappers to add additional optional parameters.
advanced/wrapper function
def pb_jam_sandwich(sandwich, pb, jam=None):
if jam is None:
pb_sandwich(sandwich, pb)
else:
pb_sandwich(sandwich, pb)
add_jam(jam)
I was thinking something like this for the advanced function, if it worked:
def pb_jam_sandwich(*args, jam=None):
if jam is None:
pb_sandwich(*args)
else:
pb_sandwich(*args)
add_jam(jam)
Upvotes: 0
Views: 119
Reputation: 532208
I think your design is backwards. More specific functions should be defined in terms of more general ones.
# Note: no default values
def pbandjsandwich(pb, sandwich, jam):
return pb + sandwich + jam
def pbsandwich(pb, sandwich):
return pbandjsandwich(pb, sandwich, 0)
Now you can ask the question of whether or not you need a separate function pbsandwich
at all, or if a default value for jam
is sufficient:
def pbandjsandwich(pb, sandwich, jam=0):
return pb + sandwich + jam
Avoiding a second function call would be more efficient, at least.
Upvotes: 1