28

In python, I am currently doing this:

if user_can_read(request.user, b) == False:

Is there any other way of checking if the function returns False?

3
  • 15
    if not function_return_boolean(): Commented Aug 23, 2012 at 18:31
  • 3
    if user_can_read(request.user,b) is False: Commented Aug 23, 2012 at 18:34
  • The BDFL suggests explicitly checking if the return value is an instance of bool and nhahtdh's method if you specifically want to compare with False and not just any falsy value, since is False is nearly always a bug. Commented Aug 23, 2012 at 18:42

1 Answer 1

48

You could just use

if user_can_read(request.user, b):
    ## do stuff

If user_can_read returns anything (except 0, False, etc), it will be considered True, and do stuff.

And the negation: if not user_can_read(request.user, b)

Sign up to request clarification or add additional context in comments.

3 Comments

@iyrag: As a side note, a common mistake is to assume that negative numbers evaluate to False. This is wrong, bool(-1) evaluates to True.
@Joel: People really believe that negative numbers evaluate to False? That surprises me.
@AdamRosenfield: I've come across this a few times. It probably stems from the fact that traditionally, a search with no result should return -1 (since 0 is taken up by the first index).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.