how to save mutliple function arguments into one variable

Viewed 49

I want to save multiple function arguments into one variable so that when I want to change something I will have to change it once and not four times.

this is my code

def request_function(self):
    if self.request_type == "get":
        return requests.get(url=self.main_url + self.api_url, json=self.json_file, headers=self.headers)
    elif self.request_type == "post":
        return requests.post(url=self.main_url + self.api_url, json=self.json_file, headers=self.headers)
    elif self.request_type == "delete":
        return requests.delete(url=self.main_url + self.api_url, json=self.json_file, headers=self.headers)
    elif self.request_type == "put":
        return requests.put(url=self.main_url + self.api_url, json=self.json_file, headers=self.headers)

I want to declare one variable containing all the parameter info at the beginning of the function and then pass this variable to request function.

1 Answers

This is how I would do it:

from requests import get, post, delete, put

def request_function(self):
    fn = {
        'get' : get,
        'post' : post,
        'delete' : delete,
        'put' : put,
    }[self.request_type]
    return fn(url=self.main_url + self.api_url, json=self.json_file, headers=self.headers)
Related