在Python 2.7中使用以参数命名的关键字参数进行闭包

时间:2016-08-19 14:40:41

标签: python-2.7 dynamic lambda closures named-parameters

我需要在运行时动态声明一个具有任意数量的命名参数(关键字)的funktion,以便不同的库可以使用字典作为参数调用此函数。以下是我需要的一个例子:

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)

这在python 2.7中是否可行? f1和f2的参数实际上将作为dict传递。如果lambda对此更好,那也没关系。

谢谢!

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

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

您甚至可以实际删除*names