Opened 8 years ago

Closed 8 years ago

Last modified 7 years ago

#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 Tim Graham, 8 years ago

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.

comment:2 by Tim Graham, 8 years ago

Resolution: wontfix
Status: newclosed

django-developers discussion

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 Suresh V., 7 years ago

request.user.is_authenticated and request.user.is_anonymous

too verbose to check a boolean attribute. Totally "unpythonic".

Version 0, edited 7 years ago by Suresh V. (next)
Note: See TracTickets for help on using tickets.
Back to Top