4

I have a boolean variable named mapped_filter. If I am not wrong, this variable can hold 3 values, either True, False or None.

I want to differentiate each of the 3 possible values in an if statement. Is there a better way to achieve that than doing the following?

if mapped_filter:
    print("True")
elif mapped_filter == False:
    print("False")
else:
    print("None")
Dalvtor
  • 3,160
  • 3
  • 21
  • 36
  • 4
    `if mapped_filter is None` unmistakably compares with `None`... – hiro protagonist Mar 12 '18 at 12:49
  • if you're looking for a `case` statement, I'm sorry, but no, there's not a better way. You still can do crazy things like having a dictionary like `crazy_dict = {True: ..., False:..., None: ...}` and then `crazy_dict[mapped_filter]()`. – Marco Lavagnino Mar 12 '18 at 12:52
  • 4
    Your assumption is wrong. If `mapped_filter` is a boolean, it can only have two different values: `True` or `False`. – mkrieger1 Mar 12 '18 at 12:52

1 Answers1

8

In your code anything that's not truthy or False prints "None", even if it's something else. So [] would go print None. If no object other than True, False and None can get there your code is fine.

But in python we generally allow any object to be truthy or not. If you want to do this, a better way would be to do:

if mapped_filter is None:
    # None stuff
elif mapped_filter:
    # truthy stuff
else:
    # falsey stuff

if you explicitly want to disallow any value that's not a bool or None, then instead do:

if isinstance(mapped_filter, bool):
    if mapped_filter:
        # true stuff
    else:
        # false stuff
elif mapped_filter is None:
    # None stuff
else:
    raise TypeError(f'mapped_filter should be None or a bool, not {mapped_filter.__class__.__name__}')
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47