3

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.

Saba
  • 416
  • 3
  • 14

1 Answers1

2

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)
Rob Kwasowski
  • 2,690
  • 3
  • 13
  • 32
  • wow, very neat solution, I didn't know I could use functions like that. Thanks! – Saba Jul 19 '20 at 13:12
  • 1
    @Saba Yes, a function is just the same as any variable and so can be put inside a dictionary or list, and can be stored under a different name. – Rob Kwasowski Jul 19 '20 at 13:13