django – use of ‘else:’ – interesting case

django’s auth middleware has this code:

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... 

the else part is interesting, it doesnot have if-part, what is this? really cool thing if I dont know this yet

Answer

The else forms the else part of 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... 

The else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

That is here it would be executed only if the code doesn’t raise any KeyErrors

Example

Consider we have a dictionary as

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

We can use try except to handle a KeyError as

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

Now, we need to check if a key error occurs and if not, the else clause is executed as

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

Where as if any of the except clause is raised, then it won’t be executed.

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

Leave a Reply

Your email address will not be published. Required fields are marked *