简体   繁体   中英

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.

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.

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') .

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.

fn()

KeyError: 'client'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM