Say I have a function that takes some *args (or **kwargs??) for a http request and I want to input different arguments each time the function is called - something like:
def make_some_request(self, *args)
response = requests.get(*args)
return response
where *args
might be e.g. url, headers and parameters in one case and url and timeout in another case. How can this be formatted to get the request to look like
response = requests.get(url, headers=headers, params=parameters)
on the first function call and
response = requests.get(url, timeout=timeout)
on the second function call?
I wondered if this was possible using *args or **kwargs but the format doesn't seem quite right with either.
CodePudding user response:
You can do this with **kwargs
:
class Client:
def make_some_request(self, *args, **kwargs)
response = requests.get(*args, **kwargs)
return response
client = Client()
client.make_some_request("https://domain.tld/path?param=value", timeout=...)
client.make_some_request("https://domain.tld/path?param=value", headers=..., params=...)
*args
will take care of passing the positional argument (the URL), whereas the named arguments (timeout
, headers
, params
) will be passed to requests.get
by **kwargs
.