[英]Passing default values to **kwargs
I have a function that returns some data, what I need to do in order to get the data is to pass an SQL-like query to the build_query
variable.我有一个返回一些数据的 function,为了获取数据我需要做的是将类似 SQL 的查询传递给
build_query
变量。
def foo(client):
"""
API service that returns JSON data and accepts arguments
"""
report_query = (client.buildQuery()
.Select('Date','SearchEngine')
.From('Report_10')
.During('Yesterday')
get_report.downloadReport(
skip_header=True,
include_names=False,
get_summary=True,
get_totals=False)
What I am trying to do is make this function in to one that accepts **kwargs
but has default arguments for the selected fields.我想要做的是将这个 function 变成一个接受
**kwargs
但默认为所选字段的 arguments 。
The idea is that I would be able to pass an argument to .During()
and if I don't it defaults to Yesterday
, I would be able to pass arguments to .Select()
, for example .Select()
would be .Select('Date','Device','StrategyType')
.我的想法是,我可以将参数传递给
.During()
,如果我不这样做,它默认为Yesterday
,我可以将 arguments 传递给.Select()
,例如.Select()
将是.Select('Date','Device','StrategyType')
。
What I've tried and trying to understand:我尝试并试图理解的内容:
def fn(**kwargs):
print(f"""
({kwargs['client']}.buildQuery()
.Select({kwargs['select']}))
.From({kwargs['report_type']})
.During({kwargs['during']})
get_report.downloadReport(
skip_header={kwargs['skip_header']},
include_names={kwargs['include_names']},
get_summary={kwargs['get_summary']},
get_totals={kwargs['get_totals']})""")
fn(client='10',select=['Date', 'SearchEngine'],report_type='new',during='Yesterday',skip_header=True)
Returns:退货:
(10.buildQuery()
.Select(['Date', 'SearchEngine']))
.From(new)
.During(Yesterday)
get_report.downloadReport(
skip_header=True,
include_names=False,
get_summary=True,
get_totals=False)
Where I get stuck is trying to call fn()
without any keyword arguments and wishing that the function would have default arguments for each field, such that it would look like the first code snippet in my question.我遇到困难的地方是尝试在没有任何关键字 arguments 的情况下调用
fn()
并希望 function 对每个字段都有默认值 arguments,这样它看起来就像我问题中的第一个代码片段。
fn()
KeyError: 'client'
KeyError: '客户端'
Is it possible to achieve something like this?有可能实现这样的目标吗?
You can use the spread operator on dictionaries:您可以在字典上使用展开运算符:
def func(**kwargs):
kwargs = {"printer": None, **kwargs}
This will set the value printer
to none if it is not given.如果未给出,这会将值
printer
设置为 none。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.