将if-elseif语句转换为字典

时间:2014-01-10 14:37:33

标签: python design-patterns dictionary 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

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

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

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

谢谢!

1 个答案:

答案 0 :(得分:8)

使用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
                 ...}

现在你可以使用

func, args, kwargs = function_dict[request]
result = func(*args, **kwargs)

另外,请注意使用is比较字符串是一个坏主意(尽管它sometimes works);最好使用==

if request == 'get_id':