0

I have a very generic function call that looks like

result = getattr(class_name, func_name)(result)

This function call updates result. This function call is very generic such that it can invoke many functions from different classes. Currently, all these functions only take one argument result. However, it doesn't scale to the cases that some functions need to pass more than just result but more arguments (say, args).

Is there a way in Python (2.7) that allows this generic function call to pass args but still invoke the functions that don't have the extra arguments? If not, what would be a better approach to solve this problem?

EDIT: I cannot change the existing function definitions, including those that only take only the argument result. I can only change this line:

result = getattr(class_name, func_name)(result)
return 0
  • 4,226
  • 6
  • 47
  • 72
  • def myfunc(*args) #passes list of arguments **args passes dictionary of all the supplied arguments. See http://stackoverflow.com/questions/3394835/args-and-kwargs – Ron Sep 22 '16 at 17:45

2 Answers2

1

You can add a * within the function call. This will pass result as multiple arguments. Lets say you have two functions:

class YourClass:
   def my_first_def(one_arg):
      return (1, 2)

   def my_second_def(one_arg, second_arg):
      return (1, 2, 3)


if not instanceof(result, tuple):
  result = (result,)

result = getattr(YourClass, 'my_first_def')(*result)
result = getattr(YourClass, 'my_second_def')(*result)

Do note that result must be a tuple

  • It looks like a good solution, the only thing that doesn't fit into my project is that `my_first_def` and `my_second_def` return `result` only unfortunately. Any way around that? – return 0 Sep 22 '16 at 18:05
  • You could add a check if the result is tuple. For instance: `if not instanceof(result, tuple): result = (result, )` – Wouter Klein Heerenbrink Sep 22 '16 at 18:09
0

The general solution for this is that when we want to provide a common function name such as this, that it is the responsibility of each class to implement its local definition of that function. This is why you see, for example, a method __init__ in many different classes. The system standardizes the name, placing the requirement on the classes.

The other common way is borrowed from C: you pass a list of arguments, the canonical *args solution. This allows one generic, flexible function to interpret the arglist as appropriate.

Prune
  • 76,765
  • 14
  • 60
  • 81