Reputation: 1259
Good day everyone,
I am new to python and I was suggested to make use of the function dictionary as below:
def func1(var1,var2,var3):
return var1+var2+var3
def func2(var1,var2,var3,var4):
return var1+var2+var3+var4
def func3(var1,var2):
return var1 + ' ' + var2
functs_to_execute = {
'func1': func1,
'func2': func2,
'func3': func3
}
var1 = 1
var2 = 2
var3 = 3
var4 = 4
for f in fs:
current_funct = functs_to_execute.get(f)
#trying to pass in diff arguments for different functions called
current_funct(--variables--)
is that possible to pass in the right parameters to current_funct()
without using any if-else?
Upvotes: 1
Views: 75
Reputation: 2645
Given the nature of your functions, which all take a sequence of arguments of the same type, you can make it so all the functions accept the same format for arguments, in a way that will work regardless of how many there are:
from functools import reduce
def func1(*args):
return reduce(lambda x, y: x + y, args)
# Func2 is now effectively the same as func1,
# unless you want to restrict the number of arguments to
# exactly 3 and 4 respectively. You can do that with args[:3]
# and args[:4] in place of just args, and the rest, if there
# are any, will be ignored:
def func2(*args):
return reduce(lambda x, y: x + y, args[4])
def func3(*args):
return args[0] + ' ' + args[1]
reduce
works by calling a function (the lambda
in this case) on all elements of a list (args
) until it accumulates into a single result. In this case it sums up everything in args
until there is just a string left, but it would also work with numbers if you fed numbers into func1
.
Using *
before a parameter, like in *args
above, tells Python to collect all parameters (given without an explicit name) into a list, so args
is a list of what you feed into func1
and you can give it however many arguments you want, you don't need to know the number in advance. These are called variadic arguments, because how many there are of them varies.
Upvotes: 1
Reputation: 120391
Change function signatures to be the same for each function by setting useless arguments to None:
def func1(var1, var2, var3, var4=None): # <- HERE
return var1 + var2 + var3
def func2(var1, var2, var3, var4):
return var1 + var2 + var3 + var4
def func3(var1, var2, var3=None, var4=None): # <- HERE
return str(var1) + ' ' + str(var2) # <- Avoid exception
functs_to_execute = {
'func1': func1,
'func2': func2,
'func3': func3
}
var1 = 1
var2 = 2
var3 = 3
var4 = 4
for f in functs_to_execute.values(): # <- Loop on function pointer
print(f(var1, var2, var3, var4))
Output:
6
10
1 2
Upvotes: 0