I am defining a function which needs to take a user defined function user_function(a,b,possibly_lots_more_arguments)
. The problem is possibly_lots_more_arguments
may be empty. I see two ways to handle this, and I'm wondering if one is "better" than the other.
Here's a fairly simple example. f
handles this by defining a function that tests whether there are extra arguments. g
handles this by creating a longer list. The func1
and func2
functions are obviously toy examples of a user-defined function.
def f(user_function, parameters = None):
def my_user_function(alpha, beta, my_parameters):
if my_parameters == None:
return user_function(alpha, beta)
else:
return user_function(alpha, beta, *my_parameters)
for a in range(4):
for b in range(3):
if my_user_function(a,b,parameters):
print "it's True"
else:
print "it's False"
def g(user_function, parameters = []):
for a in range(4):
for b in range(3):
L=[a,b]+list(parameters) #parameters could be a tuple
if (user_function(*L)):
print "it's True"
else:
print "it's False"
def func1(a,b,c):
return a+b<c
def func2(a,b):
return a+b<4
print 'f(func1)'
f(func1,[4])
print 'g(func1)'
g(func1,[4])
print 'f(func2)'
f(func2)
print 'g(func2)'
g(func2)
I feel like g
is better, but I may need to call the user function several times and this could get ugly.
I've never had to write transparent code except for making sure I can understand it a year later. The code I'm doing here is likely to be used by others. Is one of these inherently better either for performance or readability reasons, or is another option even better?