[Fixed]-How come in the DRF source code for IsAuthenticated, it returns `request.user and request.user.is_authenticated()` when request.user is not a boolean?

1đź‘Ť

âś…

Python evaluates “boolean” expression starting by left to right, if any conditions fails and transform the whole expression in False or True, python stop the evaluation and returns the value.

So if request.user is None, the whole expression is False, then python returns False and skip request.user.is_authenticated() evaluation. So, you won’t get “attribute error” exception.

Note:
If request object has not user attribute, you will get an attribute error, but request object always on that step has an object or None. But, not always that object has is_authenticated() method.

This behaviour is called short-circuit-evaluation

Also, the method is named “has_permission”, so, is better to return a boolean saying if the current user if exists it has permission than raising an exception. Also, using try/except block, how are you sure that the raised exception is because request.user does not exists? even when you catch the correct exception, you needed at least 6 lines to representing 1.

Also in python

1 and 2 == True

Even when 1 and 2 are not "booleans". So, it does not matters if request.user is not a “boolean”, its about to check if request.user exists and is not None.

👤levi

Leave a comment