关于python:为不同的函数分离** kwargs

Separating **kwargs for different functions

给定一个更高阶函数,它将多个函数作为参数,该函数如何将关键字参数传递给函数参数?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def eat(food='eggs', how_much=1):
    print(food * how_much)


def parrot_is(state='dead'):
    print("This parrot is %s." % state)


def skit(*lines, **kwargs):
    for line in lines:
        line(**kwargs)

skit(eat, parrot_is)  # eggs
 This parrot is dead.
skit(eat, parrot_is, food='spam', how_much=50, state='an ex-parrot') # error

state不是eat的关键字arg所以skit如何才能传递与其调用的函数相关的关键字args?


您可以根据函数的func_code.co_varnames过滤kwargs字典:

1
2
3
4
def skit(*lines, **kwargs):
    for line in lines:
        line(**{key: value for key, value in kwargs.iteritems()
                if key in line.func_code.co_varnames})

另请参阅:您是否可以列出Python函数接收的关键字参数?


如果将**kwargs添加到所有定义中,则可以传递整个批次:

1
2
3
4
5
6
7
8
9
10
11
def eat(food='eggs', how_much=1, **kwargs):
    print(food * how_much)


def parrot_is(state='dead', **kwargs):
    print("This parrot is %s." % state)


def skit(*lines, **kwargs):
    for line in lines:
        line(**kwargs)

**kwargs中任何不是显式关键字参数的东西都会在kwargs中保留,并被例如忽略。eat

例:

1
2
3
>>> skit(eat, parrot_is, food='spam', how_much=50, state='an ex-parrot')
spamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspam
This parrot is an ex-parrot.