1

I need to declare a funktion dynamically at runtime that has an arbitrary number of named arguments (keywords), so that a different library can call this function with a dictionary as arguments. Here is an example of what I need:

def generateFunction(*kwrds):
  #kwrds are a bunch of strings
  def functionTheLibraryCalls('''an argument for every string in kwrds '''):
    #Get all arguments in a tuple in the order as listed above
    result = tuple(args)
    #Code that needs to be executed inside the library,
    #it can handle a variable number of arguments
    return result
  return functionTheLibraryCalls


f1 = generateFunction('x', 'y','z')
print f1(x = 3,y = 2, z = 1)
#>> (3,2,1)
f2 = generateFunction('a', 'b')
print f2(a = 10, b = 0)
#>> (10,0)

Is this possible in python 2.7? The parameters to f1 and f2 will actually be passed as a dict. If a lambda is better for this that is fine too.

Thank you!

RunOrVeith
  • 4,487
  • 4
  • 32
  • 50

1 Answers1

0

It is what you want ?

def generateFunction(*names):
    #kwrds are a bunch of strings
    def functionTheLibraryCalls(**kwrds):
        #Code that needs to be executed inside the library,
        #it can handle a variable number of arguments
        print names, kwrds
        return 42
    return functionTheLibraryCalls

You can even remove *names actually.

romain-aga
  • 1,441
  • 9
  • 14