了解python的参数收集蛮久了,但一直不理解很多第三方库源码中的使用,今天在读flask源码的时候突然明白了。比如:
def run(self, host='localhost', port=5000, **options):
from werkzeug.serving import run_simple
if 'debug' in options:
self.debug = options.pop('debug')
options.setdefault('use_reloader', self.debug)
options.setdefault('use_debugger', self.debug)
return run_simple(host, port, self, **options)
在上面这段函数中,将**options收进来后最后又把 **options传给了另外一个函数。其实 **options作为形参是把关键字参数打包成一个字典, 而作为实参传给另外一个函数时是把字典里的键值对又拆成了一个个关键字参数。例如:
def f(**context):
return context.pop('a'),context.pop('b')
def render_template(template_name, **context):
print('template_name: {}'.format(template_name))
print('arguments: ', *(f(**context)))
# 运行示例:
>>> render_template('index', a=2, b=3)
template_name: index
arguments: 2 3