I have an endpoint with some required and optional parameters:
Required: ID [str]
Optional: name_1 [str], regex [boolean], ignore_case [boolean]
I want to build a function to use this endpoint:
import requests
def get_function(ID, name_1=None, regex=None, ignore_case=None):
url= 'heretheurl/{ID}'.format(ID)
params = {}
if name_1 is not None:
params.update({'name_1':name_1})
if regex is not None:
params.update({'regex':regex})
if ignore_case is not None:
params.update({'ignore_case':ignore_case})
response = requests.get(url, params=params)
Is it a better way to do this avoiding all these IF s?
You could use **kwargs
for the convenience of having the params in a dictionary rather than a bunch of local variables that are then harder to deal with, but then enforce that only certain keyward arguments are acceptable, and for anything else, raise a TypeError
. (You could instead have an explicit argument list and then use locals()
, but it will include other local variables, so it could get messy.)
import requests
def get_function(ID, **kwargs):
supported_args = {'name_1', 'regex', 'ignore_case'}
for key in kwargs:
if key not in supported_args:
raise TypeError(f"{key} not supported")
url = 'heretheurl/{ID}'.format(ID=ID)
params = dict((k, v) for k, v in kwargs.items() if v is not None)
response = requests.get(url, params=params)
get_function("blah", name_1="stuff", ignore_case=True)
BTW, your format
usage is wrong in the line starting url =
(you are mixing the usage for keyword and positional parameters), so I've corrected this.
The first version of this answer said raise a ValueError
if the argument is not supported, but I have changed it to TypeError
in order to match what is raised when an unexpected keyword argument is passed while using an explicit argument list.
import requests
def get_function(ID, **kwargs):
url= 'heretheurl/{ID}'.format(ID)
response = requests.get(url, params=kwargs)
I guess you could say:
for local, value in locals().items():
if value is not None:
params[local] = value
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.