Opened 8 years ago
Closed 8 years ago
#28420 closed Cleanup/optimization (fixed)
Document CallableBool comparison restriction for User.is_authenticated / is_anonymous
| Reported by: | Tobi | Owned by: | Tobi | 
|---|---|---|---|
| Component: | Documentation | Version: | 1.11 | 
| Severity: | Normal | Keywords: | documentation | 
| Cc: | Triage Stage: | Accepted | |
| Has patch: | yes | Needs documentation: | no | 
| Needs tests: | no | Patch needs improvement: | no | 
| Easy pickings: | no | UI/UX: | no | 
Description
I have just run into the issue described in https://code.djangoproject.com/ticket/26988, trying to check identity rather then equality on User.is_authenticated.
The documentation for this attribute is misleading. It implies that that is_authenticated is True for authenticated users, while in reality the attribute has to be called or checked for equality (==) :
Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False).
I suggest to add a notice/warning to the documentation, that use of *is* / identity checking is not yet supported. There's a similar warning in the deprecation notice for User.is_authenticated() here, but neither the warning nor the deprecation notice can be found in the documentation for contrib.auth.models.User.is_authenticated
Change History (6)
comment:1 by , 8 years ago
| Component: | contrib.auth → Documentation | 
|---|
follow-up: 3 comment:2 by , 8 years ago
| Summary: | Document CallableBool behaviour → Document CallableBool comparison restriction for User.is_authenticated / is_anonymous | 
|---|---|
| Triage Stage: | Unreviewed → Accepted | 
| Type: | Uncategorized → Cleanup/optimization | 
comment:3 by , 8 years ago
Replying to Tim Graham:
It's more Python to write
if request.user.is_authenticated:orif not request.user.is_authenticated:rather than== Truebut a note wouldn't hurt.
True, == True: is less Python, but this one does actually work. The problem is that if request.user.is_authenticated is True: and if request.user.is_authenticated: yield different results: 
>>> AnonymousUser().is_authenticated is True
False
>>> AnonymousUser().is_authenticated is False
False
>>> if AnonymousUser().is_authenticated:
...    print('Authed')
...
>>>
So different to the documentation is_authenticated is not an attribute which *is* always True (or False for AnonymousUser), but its return type has to be called when used with is, which would be the pythonic way to check here (as if not is_authenticated would also catch None, 0, '' [] etc). 
comment:4 by , 8 years ago
| Owner: | changed from to | 
|---|---|
| Status: | new → assigned | 
It's more Python to write
if request.user.is_authenticated:orif not request.user.is_authenticated:rather than== Truebut a note wouldn't hurt.