Python Forum
Returning True or False vs. True or None
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Returning True or False vs. True or None
#7
In some cases, not always, functions return something and if an error happens or there was no match, they return None explicit or implicit.

Explicit None
def foo():
    return None
Implicit None
def foo():
    pass
The implicit None returns always, if no other return-statement was executed.


If you get from a function some type back and you have to check for None, just recognize that True, False, None are singletons and they're unique. If a bad function, not your code, returns sometimes a list with strings, sometimes None and sometimes an empty list, then you have to do two checks.

First you check, if the return type is a None.
If this check passes, you check if the list is not empty.

import random


def silly_function():
    return_vals = (None, [], ['Hello', 'World'])
    return random.choice(return_vals)

# now the tests are more complex, if you
# want to handle the None explicit

return_value = silly_function()
if return_value is None:
    print('None')
elif return_value:
    print('The list is not empty')
else:
    # no None, but a empty list
    print('The list is empty')
Sometimes we have to handle this.
A better approach is this:

def find(pattern):
    words = ('foo', 'bar', 'baz', 'fizz', 'fuzz')
    results = []
    for word in words:
        if word.startswith(pattern):
            results.append(word)
            # MATCH
    return results

# the return type of results is always a list
# which is good, because lesser cases to check

return_value = find('f')
if return_value:
    print(return_value)
else:
    print('Sorry, I did not find any matches. The list is empty')
The line if return_value: does an implicit bool(return_value).
If the list is empty, bool(your_list) returns False.

So in general the boolean of sequences and containers is False, if the container or sequence is empty.
Otherwise it's True.

True and False are subtypes of int.
This expression is True: (0.0 == 0 == False)
This expression is True: (1.0 == 1 == True)
Other funny stuff: (True + True == 2)

Counting True in a list, where only True and False are inside.

true_false_list = [True, False, True, True, False, True]
# sum True
trues = sum(true_false_list)
print('True is', trues, 'times in the list')

# of course you can use also
# true_false_list.count(True)
All values of integers and floats are evaluated as boolean to True, if the value is not zero.

values = (True, False, None, 0, -1, 1, 10, 0.0, 5.5, -5.5, [], (1,2,3), [1])
# a tuple with some values
for value in values:
    print(f'The boolean of the value {value!s:<10} is {bool(value)}')
Output:
The boolean of the value True is True The boolean of the value False is False The boolean of the value None is False The boolean of the value 0 is False The boolean of the value -1 is True The boolean of the value 1 is True The boolean of the value 10 is True The boolean of the value 0.0 is False The boolean of the value 5.5 is True The boolean of the value -5.5 is True The boolean of the value [] is False The boolean of the value (1, 2, 3) is True The boolean of the value [1] is True
With this knowledge you can simplify your code and write it more pythonic.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Returning True or False vs. True or None - by DeaD_EyE - Apr-04-2019, 08:42 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Boolean: Anybody know why is this True? LilD 8 1,922 Feb-06-2022, 09:15 AM
Last Post: LilD
  Need to parse a list of boolean columns inside a list and return true values Python84 4 2,144 Jan-09-2022, 02:39 AM
Last Post: Python84
  Question on True expressions mgreen2251660 2 1,955 Jun-25-2021, 04:49 PM
Last Post: Yoriz
  pathlib destpath.exists() true even file does not exist NaN 9 4,742 Dec-01-2020, 12:43 PM
Last Post: NaN
  While True loop help Nickd12 2 2,010 Oct-17-2020, 08:12 AM
Last Post: Nickd12
  path.exists returning True when it shouldn't natha18 0 1,518 Sep-21-2020, 01:04 PM
Last Post: natha18
  while True error Nickd12 2 2,093 Sep-13-2020, 06:29 AM
Last Post: Nickd12
  Recursive function returns None, when True is expected akar 0 3,412 Sep-07-2020, 07:58 PM
Last Post: akar
  isinstance() always return true for object type check Yoki91 2 2,597 Jul-22-2020, 06:52 PM
Last Post: Yoki91
  Is using while True loop good? escape_freedom13 5 3,595 Jul-03-2020, 08:27 PM
Last Post: escape_freedom13

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020