Reputation: 449
Is there a more Pythonic way to implement this logic:
res = func()
if res is not None: # res is either True, False, something else
if res is True:
#do something # res is True
elif res is False:
#do something else # res is False
else:
#do something else2 # res is not in [True,False]
else:
#failed # res is None
Upvotes: 2
Views: 242
Reputation: 48077
You may create a function to map the values to corresponding functions. Something like:
# Function to map values
def do_something(res):
return {
None: func_1, # Each `res` mapped to corresponding function
True: func_2,
False: func_3,
}.get(res, func_4)
do_something(res)()
# ^ call the function returned by `do_something()`
The equivalent of the above code can be written based on your logic mentioned in question as:
if res is not None:
if res is True:
func_2()
elif res is False:
func_3()
else:
func_4()
else:
func_1()
Upvotes: 1
Reputation: 83
if res is None:
#do something
elif res:
#do something else
elif not res:
#do something else 2
Upvotes: 0
Reputation: 1121924
No, you already have it covered.
Generally, don't use is True
or is False
, if you must have tri-state boolean, use:
if res is None:
# handle None case
elif res:
# handle true case
else:
# handle false case
e.g. put the burden on the developer to use the tri-state correctly.
If the function needs to communicate more states, you should not use a boolean; in that case switch to using an enum value.
Upvotes: 6