2

If I were to set a variable as False, it is read as being equal to zero. Is there any way I can carry out a check to see if the variable if actually False or if it's the number 0.

Something like:

Spam = False if Spam == False and not Spam == 0: do something 

I'm getting the feeling this isn't possible; but I wanted to double check.

Side note: In the future would it be better to assign "None" rather than "False" when a variable could be zero? For the current code I don't want to have to rework the whole script with try and excepts, so I'll change False to -1 (not a viable value for the situation). But for future reference, I assume the None method is more Pythonic?

Help as always is appreciated and if any more details are needed, just ask.

1
  • 1
    What is the purpose of Spam, that it could take either a Boolean or an integer value? Commented Dec 4, 2014 at 14:05

1 Answer 1

7

You can test if the object is the False singleton value, by testing for identity:

if Spam is False: 

You should really refactor your code to not have to rely on the type here; None is a better false-y sentinel value to use, yes.

In general, use None as a sentinel meaning 'no value set', or if you should support None as well, use a unique object as a sentinel:

_sentinel = object() # ... if option is _sentinel: # no value set 
Sign up to request clarification or add additional context in comments.

5 Comments

Or even, if you feel like getting adventurous, if not Spam.
@killermonkey50 That's the opposite of what the OP is trying to do, which is distinguish between False and 0.
@killermonkey50: No, because that'd be true for 0 too.
@killermonkey50: empty containers and numeric 0 are false in a boolean context, see truth value testing.
This is brilliant. Will change the way I code in future, but this will save me having to completely rework the code (for now at least!). Thank you very much for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.