What is the difference between None and boolean (True, False) in python's default argument values?

Viewed 5701

In function definitions, one can define a boolean default argument's values as argument=None or argument=False.

An example from pandas concat:

def concat(
    objs,
    axis=0,
    join="outer",
    join_axes=None,
    ignore_index=False,
    keys=None,
    levels=None,
    names=None,
    verify_integrity=False,
    sort=None,
    copy=True,
):

While both usages can be found, why would one be using one over the other?

Is there any PEP on this?

4 Answers

True and False are specific bool values. Use default False when you have a bool field and you want the default to be False.Don't use False as a value for a non-bool field.

None is used as a generic placeholder when the value will be set later. It can be typed as Optional[T], which is equivalent to Union[T, None].

You might be thinking of None and False as similar because they're both "falsy" (bool(x) returns False), but the same is true of several other values, [] () {} 0 0.0, etc and we don't use them like None either.

In your example, True/False are used where the field takes a boolean value. None is used where the field takes an Optional[List]. (The exception is sort: Optional[bool], which is being used temporarily as an ad-hoc compatibility tool for a deprecated behavior.)

True and False are boolean values, so in this context None can make sense if you have a boolean variable that can be in an 'unknown' state. Strictly spoken, such a variable would not be boolean, but in reality, this can be quite handy.

For example:

# In the beginning, we simply don't know if it's true or not
is_cat_alive = None

# But later we will determine the status
is_cat_alive = check_cat_in(box)

Note that if you are using a boolean like this, then if is_cat_alive will be false when is_cat_alive is either False or None which makes sense but might not be what you want to know. So to explicitly check for a dead cat, you would have to use if is_cat_alive == False.

None is similar to a null value if you know anything about those. Someone might say it's equal to 0, but None means that it is nothing. Say age = None for example. age is a variable, but it is equal to nothing. False is an actual value. True and False can be used as an indicator such as

def name_check(name)
    if name == "Brittany":
        return True
    else:
        return False

Calling that function with "Brittany" as the name parameter would return True which could be used in other conditions as well. Hope this helped! Good luck!

Look at the following code:

my_string = ''
my_other_string = None
my_final_string = 'I am a string'

If you were using these within python in something like an if statement they would actually equal the following:

my_string = False
my_other_string = None
my_final_string = True

Hope that helps

Related