0

My application is this:

  • I have an executor function that needs to execute some code based on a switch that is sent as an argument. It retains references to multiple functions and selects the needed function based on the switch. The thing is that these functions have different no. of params.

e.g.

class Execute:

  def func1(self, f1_arg):
      print("f1_arg", f1_arg)

  def func2(self, f2_arg1, f2_arg2):
      print("arguments: %s and %s" % (f2_arg1, f2_arg2))

  def executor(self, sw):
      available_functions = {
                        "sw1": self.func1,
                        "sw2": self.func2
                        }
      predefined_arguments = {
                        "sw1": "f1_argument",
                        "sw2": ("f2_argument1", "f2_argument2")
                        }
      # this is pseudo code, I have no idea how to do it
      available_functions[sw](predefined_arguments[sw])
CostinC
  • 21
  • 1
  • 4
  • Are the arguments always static inside `executer`? – Tomerikoo Jun 09 '21 at 18:14
  • The reason `eval` is considered dangerous is because it has this ability. – Mark Ransom Jun 09 '21 at 18:14
  • In case of `sw2` you are simply passing a single tuple as an argument. Instead, make the argument of `sw1` a tuple as well (`("f1_argument",)`) and then unpack the tuples in the function call `available_functions[sw](*predefined_arguments[sw])` – Tomerikoo Jun 09 '21 at 18:17
  • 1
    This is basically what `functools.partial` does. `p = partial(func1, arg1); p()` is the same as `func1(arg1)`. – chepner Jun 09 '21 at 18:23
  • Thanks guys. The thing is that this is an over simplified example. The functions I have to call are from a module that I cannot modify. Moreover, the functions have static arguments ... so no *args – CostinC Jun 09 '21 at 18:25
  • Thanks chepner, your comment saved me ! – CostinC Jun 09 '21 at 18:28

0 Answers0