Search code examples
pythonkeyword-argument

What is the efficient way to check if kwargs are valid then pass them accordingly?


I have the following code and what I need to do is to check if either status, issue, owner and mantis_id are valid (not empty). According to the validity result I pass all those that are valid as kwargs to a function called upsert().

form=ticket_form()
status=request.form['status']
issue=request.form['ticket_issue']
owner=request.form['owner']
mantis_id=request.form['mantis_id']

Here is the second part where I pass those arguments that are valid as kwargs:

cur.execute(upsert('tbl_tickets', status=status, issue=issue, owner=owner))
connect.commit()

I can check each of them individually but I was wondering if there is a more efficient/compact way that I can use. Thanks.


Solution

  • You can do something like this:

    all_args = dict(
        form=ticket_form()
        status=request.form['status']
        issue=request.form['ticket_issue']
        owner=request.form['owner']
        mantis_id=request.form['mantis_id']
    )
    valid_args = {k: v for k, v in all_args.items() if v}
    cur.execute(upsert('tbl_tickets', **valid_args))