[Python-ideas] True and False are singletons

Steven D'Aprano steve at pearwood.info
Mon Mar 18 18:15:04 EDT 2019


On Tue, Mar 19, 2019 at 09:58:55AM +1300, Greg Ewing wrote:
> Oleg Broytman wrote:
> >   Three-way (tri state) checkbox. You have to distinguish False and
> >None if the possible valuse are None, False and True.
> 
> In that case the conventional way to write it would be
> 
>     if settings[MY_KEY] == True:
>         ...

For a tri-state setting, I would always check for None (or 
whatever third state was used) first:

    setting = settings[MY_KEY]
    if setting is None:
        # handle third state
    elif setting:
        # handle true state
    else:
        # handle false state


If for some strange reason I required the flags to be precisely True or 
False rather than arbitrary truthy values, that's a *four* state flag 
where the fourth state is an error condition.

    setting = settings[MY_KEY]
    if setting is None:
        # handle third state
    if not isinstance(setting, bool):
        raise TypeError("not a bool! (but why do I care???)")
    if setting:
        # handle true state
    else:
        # handle false state



 
> It's not a major issue, but I get nervous when I see code
> that assumes True and False are unique, because things
> weren't always that way.

Do you also guard against True and False not being defined at all?

As long as True and False have been builtins, it has been a language 
guarantee that they will be unique.


-- 
Steven


More information about the Python-ideas mailing list