r/pythonhelp • u/a_idanwalton • Jun 01 '22
Using a dictionary to specify which parameter to be sent to a function
I have a function which has three arguments that do different things but take the same input. They change the way that the parameter is dealt with.
Easy way of explaining is a function like this
def Func(arg1=None, arg2=None, arg3=None):
chosen = [arg for arg in [arg1, arg2, arg3] if arg is not None]
print(chosen)It's a *VERY* simplified version of what the function does but that's not what is important (I think)
What I'm trying to do is, in a class, have an attribute that specifies which argument to be given the input.
class Class:
def __init__(self, whichArg="arg1"):
self.whichArg = whichArgThen, later on in the class, when the function is called, only pass that specific argument.
I know that it's possible to do this using an if statement, but I'm really into branchless programming and efficiency so I was wondering if there was a way I could use a dictionary to specify it.
For example:
arguments = {"arg1": arg1,
"arg2": arg2,
"arg3": arg3
}Hopefully that makes sense?
2
u/kaleidist Jun 02 '22
You can specify keyword arguments to pass in a function call with double star notation. For example:
kwargs = {"arg1": 1, "arg2": 2}
Func(**kwargs)That function call is the same as writing:
Func(arg1=1, arg2=2)I don't know if that helps you though, because I'm not sure exactly what you want to do. I have an intuition that what you want to do is indeed possible, but I would need to work it out some clarification with you to know for sure.
2
u/Zeroflops Jun 02 '22
The way you have it written only one argument is actually passed. Why not just pass that one argument rather than making it convoluted, then take action based on what is passed into the function.
function (arg):If you need to take different actions based on the type of argument, pass two arguments. One with the value and the second with the action to take place.
Function(arg, action=process1) But a more reasonable approach would be to write three functions that each do a specific task and not muddle a function by doing multiple tasks in one function.
1
u/Goobyalus Jun 02 '22
Agree with u/Zeroflops and u/kaleidist . Is this what you're going for?
If so, there's probably a cleaner way to accomplish what you want.