0

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

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • The first result for googling `python try except else` is the official python documentation. Its excerpt on google starts with "The try ... except statement has an optional else clause, which, when present, must follow all except clauses". Please attempt to google things like this before asking on SO. – l4mpi Jun 05 '15 at 08:40
  • @l4mpi thanks, I just posted the question to make it more googlable for others who dont know it yet. just knowing and not sharing is cruel! – doniyor Jun 05 '15 at 08:46

1 Answers1

6

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
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52