将**kwargs传递给内部函数

And*_*oll 8 python

我有一个功能

def wrapper_function(url, **kwargs)
   def foo():
      if kwargs:
          return do_something(url, kwargs)
      else:
          return do_something(url)
Run Code Online (Sandbox Code Playgroud)

do_something()函数可以有一个或多个参数.

当我打电话时wrapper_function(),想要把它称为

wrapper_function('www.bar.com')
Run Code Online (Sandbox Code Playgroud)

要么

wrapper_function('www.bar.com', selected_clients=clients)
Run Code Online (Sandbox Code Playgroud)

这样do_something('www.bar.com', selected_clients=clients).

但是,当我像这样接近它时,我收到一个错误 clients is not defined.

如何将params与关键字完全一样传递给内部函数?重要的是,该关键字也需要变量.

Cod*_*ing 10

当你的函数接受表单中的kwargs时foo(**kwargs),就像访问python dict一样访问keyworded参数.同样,要将dict以几个关键参数的形式传递给函数,只需**kwargs再次传递它即可.所以,在你的情况下,

do_something(url, **kwargs)
Run Code Online (Sandbox Code Playgroud)