1

I have the following situation: I have a single master_function that I wish to pass a sub_function into. The function that I wish to pass into this changes (for example 1 and 2). The arguments of each function also vary in their number and type.

def sub_function_1( x, y, z):
   return x + y + z

def sub_function_2( x, y ):
   return x + y 

def master_function( x, y, z, F ): 
   return x*y + F()

Quick fix

The simple fix to this would be to write the function callback with all possible arguments, whether they are used or not:

   def master_function( x, y, z, F ): 
       return x*y + F(x,y,z)

Then we can call master_function( x, y, z, sub_function_1) or master_function( x, y, z, sub_function_2) as desired.

Unfortunately, I have many functions that I wish to pass into the master function; so this approach is not suitable!

Is there a way to write F in master_function without reference to the arguments required? How can I generalise this?

AngusTheMan
  • 564
  • 1
  • 6
  • 15
  • @Prune I am still not certain about the answer to my question, despite having a good look at the linked answers, would it be possible to unmark this ? Many thanks :) – AngusTheMan Apr 27 '18 at 16:26

2 Answers2

1

The best way would be to just make the calls constant

def sub_function_1( x, y, z):
    return x + y + z

def sub_function_2( x, y, z ):
    return x + y 

def master_function( x, y, z, F ): 
    return x * y + F(x,y,z) 

But you can have it be more dynamic if you like:

def sub_function_1( x, y, z, **kwargs):
    return x + y + z

def sub_function_2( x, y, **kwargs ):
    return x + y 

def master_function( x, y, z, F ): 
    return x * y + F(**locals())

This works better in Python 3 potential as:

def sub_function_1(*args):
    return args[0] + args[1] + args[2]

def sub_function_2(*args):
    return args[0] + args[1] 

def master_function(*args, F): 
    return args[0] * args[1] + F(*args) 
.
.
.
>>> master_function(1,2,3,F=sub_function_1)
8
>>> master_function(1,2,3,F=sub_function_2)
5
>>> master_function(1,2,F=sub_function_2)
5
>>> master_function(1,2,F=sub_function_1)
IndexError: tuple index out of range
Chris Hagmann
  • 1,086
  • 8
  • 14
1

Here is your code, updated per the duplicate I mentioned.

def sub_function_1( x, y, z):
   return x + y + z

def sub_function_2( x, y ):
   return x + y 

def master_function(*args):
   F = args[-1]
   F_args = args[:-1]
   x = args[0]
   y = args[1]

   return x*y + F(*F_args)

print(master_function(1, 2, 3, sub_function_1))
print(master_function(-10, -20, sub_function_2))

Output:

8
170
Prune
  • 76,765
  • 14
  • 60
  • 81