将if-elseif语句转换为字典

Tom*_*eck 2 python dictionary design-patterns switch-statement

我有以下代码用于对服务器进行RESTful调用:

def request(self, request, account_id, user):

    if request is 'get_id':
        #Get user from id
        result = requests.get(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)

    elif request is 'get_username':
        #Get user from username
        result = requests.get(api_root + "/accounts/" + account_id + "/users?username=" + user, headers=self.headers)

    elif request is 'get_email':
        #Get user from username
        result = requests.get(api_root + "/accounts/" + account_id + "/users?email=" + user, headers=self.headers)

    elif request is 'post':
        #Add user to new account
        result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)

    elif request is 'delete':
        #Delete user from account
        result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)

    #Throw exception if non-200 response
    result.raise_for_status()

    #Print request result / status
    print "\nRequest " + request + " Result: " + result.text + "\nStatus: " + str(result.status_code)

    return result
Run Code Online (Sandbox Code Playgroud)

我知道这很难看,我想把它改成字典,比如:

def request(self, request, account_id, user):
    url = api_root + "/accounts/" + account_id

    function_dictionary = {}
    function_dictionary['get_id']       = requests.get(url + "/users/" + user, headers=self.headers)
    function_dictionary['get_username'] = requests.get(api_root + "/accounts/" + account_id + "/users?username=" + user, headers=self.headers)
    function_dictionary['get_email']    = requests.get(api_root + "/accounts/" + account_id + "/users?email=" + user, headers=self.headers)
    function_dictionary['delete']       = requests.delete(url + "/users/" + user, headers=self.headers)
    function_dictionary['post']         = requests.post(url + '/users', data=json.dumps(user), headers=self.headers)  

    result = function_dictionary.get(request)

    #Throw exception if non-200 response
    result.raise_for_status()
    return result
Run Code Online (Sandbox Code Playgroud)

我仍然有一种感觉,我会以错误的方式去做.任何人都可以告诉我,如果Python中的/ elseif语句是正确的方法吗?

谢谢!

jon*_*rpe 8

使用a dict替换if: elif:循环肯定是Pythonic,但请注意,在您的示例中,您为字典中存储的每个案例调用 requests.get等,即字典值是这些调用的结果.

另一种方法是在字典中单独存储函数和参数:

function_dict = {'get_id': (requests.get, # function
                            (url + "/users/" + user,), # tuple of arguments  
                            {'headers': self.headers}), # dict of keyword args
                 ...}
Run Code Online (Sandbox Code Playgroud)

现在你可以使用了

func, args, kwargs = function_dict[request]
result = func(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

另外,请注意比较字符串使用is是一个坏主意(虽然它有时有效); 最好使用==:

if request == 'get_id':
Run Code Online (Sandbox Code Playgroud)

  • 在这里检查元组:headers = self.headers ...语法无效 (2认同)