#28259 closed New feature (wontfix)
Make bool(AnonymousUser) evaluate to false
Reported by: | Linus Lewandowski | Owned by: | nobody |
---|---|---|---|
Component: | contrib.auth | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I suggest adding __bool__() method returning False to the AnonymousUser.
This way it'll be possible to check if the user is authenticated by simply writing
if request.user:
It's a frequent source of bugs (at least for me, but probably I'm not alone) that right now this code returns True for anonymous users.
Change History (3)
comment:1 by , 7 years ago
comment:2 by , 7 years ago
Resolution: | → wontfix |
---|---|
Status: | new → closed |
Closing for now as Adam's reply on the mailing list confirms my intuition: "We already have if request.user.is_authenticated
and request.user.is_anonymous
which are both more explicit and pythonic. Additionally all python classes, and thus instances of User atm, are by default truthy, so implementing this custom __bool__
introduces space for more subtle bugs, e.g. the result of filter([request.user])
would change."
comment:3 by , 7 years ago
request.user.is_authenticated and request.user.is_anonymous
too verbose to check a boolean attribute. Totally "unpythonic".
The Django test suite passes with the change but I feel like that could have some backwards compatibility concerns. Also "explicit is better than implicit"? You could write to the DevelopersMailingList to get other opinions.