django - 使用'else:' - 有趣的案例

时间:2015-06-05 08:26:43

标签: python django

django的auth中间件有这段代码:

def get_user(request):
    """
    Returns the user model instance associated with the given request session.
    If no user is retrieved an instance of `AnonymousUser` is returned.
    """
    from .models import AnonymousUser
    user = None
    try:
        user_id = request.session[SESSION_KEY]
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else: # <------ this doesnot have if-part, but how is it meant to work? 
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            # more code... 

else部分很有意思,它没有if - 部分,这是什么?如果我不知道这个真的很酷

1 个答案:

答案 0 :(得分:6)

else构成try except

的其他部分
try:
    user_id = request.session[SESSION_KEY]
    backend_path = request.session[BACKEND_SESSION_KEY]
except KeyError:
    pass
else:  
    if backend_path in settings.AUTHENTICATION_BACKENDS:
        # more code... 

else子句,如果存在,则必须遵循除子句之外的所有子句。如果try子句不引发异常,则必须执行的代码很有用。

在这里,只有在代码没有引发任何KeyErrors

的情况下才会执行

示例

考虑我们有一本词典

>>> a_dict={"key" : "value"}

我们可以使用try except来处理KeyError

>>> try:
...     print a_dict["unknown"]
... except KeyError:
...     print "key error"
... 
key error

现在,我们需要检查是否发生了密钥错误,如果没有,则else子句执行为

>>> try:
...     print a_dict["key"]
... except KeyError:
...     print "key error"
... else:
...     print "no errors"
... 
value
no errors

如果提出任何except条款,那么它就不会被执行。

>>> try:
...     print a_dict["unkown"]
... except KeyError:
...     print "key error"
... else:
...     print "no errors"
... 
key error