Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Returning True or False vs. True or None
#1
Hello,

I was just wondering if there is any reason that I should explicitly return False from a function instead of just letting it return None?

Example:

def function():
    if condition:
        return True
    else:
        return False
versus

def function():
    if condition:
        return True
Quote
#2
Quote:I was just wondering if there is any reason that I should explicitly return False from a function instead of just letting it return None?
In almost all cases, None can be treated the same as a Boolean. The one exception I can think of is in embedded code where the Boolean value is setting a register or toggling a GPIO port. There are certainly other instances.
You need to decide if it's needed or not for the application you are running. My guess is not.
trevorkavanaugh likes this post
Quote
#3
I think it's generally best to use the first version and explicitly return False. It's often useful to return True, False, or None, with None representing a situation where the truth value could not be determined for some reason. Explicitly return False makes your True/False functions consistent with that usage.

However, I often use a third case: just return condition. If the condition has a boolean operator, just return it:

def five_or_less(x):
     return x <= 5
But perhaps you were only concerned with conditions without a boolean operator.
buran and trevorkavanaugh like this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#4
(Apr-04-2019, 02:13 AM)ichabod801 Wrote: ...

Thanks! As a new python programmer I am just trying to make sure that I am developing good coding practices, and you're argument for explicitly returning False does make sense. Appreciate both of your responses.
Quote
#5
+1 to just returning the condition, I see the first form as something only newb programmers do. (It's fine that you're a new programmer, you just presumably don't want to be one forever :) )
trevorkavanaugh and buran like this post
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.

Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)
Quote
#6
If the condition is not explicitly boolean, you can
    return bool(condition)
which always returns True or False.
ichabod801 likes this post
Quote
#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.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Do break operators turn while loop conditions from True to False? Drone4four 3 121 Oct-20-2019, 05:28 AM
Last Post: buran
  How to use while true/while loop on python christing 4 190 Oct-08-2019, 08:02 AM
Last Post: perfringo
  while True: error 2wheelz4me 8 224 Oct-04-2019, 08:58 PM
Last Post: newbieAuggie2019
  What condition caused this True? majorjohnusa 14 506 Sep-03-2019, 01:01 PM
Last Post: venquessa
  Trouble Setting a Variable True basing on an Imput VictorVictus 5 192 Aug-02-2019, 08:14 PM
Last Post: VictorVictus
  While True is a syntax error? Piethon 8 424 Jul-21-2019, 12:40 PM
Last Post: metulburr
  if cond1 or cond2 or ...condN is not True asheru93 4 307 Jun-03-2019, 04:24 PM
Last Post: buran
  str in str == True speedskis777 7 504 Mar-27-2019, 12:15 PM
Last Post: snippsat
  file.write stops while true loop from executing in python3 boonr 3 348 Mar-25-2019, 12:50 PM
Last Post: ichabod801
  'True' if 'string' has at least one uppercase letter ClassicalSoul 1 282 Feb-28-2019, 12:08 PM
Last Post: buran

Forum Jump:


Users browsing this thread: 1 Guest(s)