Annotating a boolean as a function return value

Consider this function

def is_bigger_than_one(number):
    if number > 1:
        return True
    else:
        return False

I wanna know what’s the most Pythonic way to annotate it.

Is it

def is_bigger_than_one(number: int) -> bool:
    if number > 1:
        return True
    else:
        return False

or is it

def is_bigger_than_one(number: int) -> True | False:
    if number > 1:
        return True
    else:
        return False

?

Typeshed (where some annotations for the standard library live) seems to consistently use bool:

class str:
    ...
    def isdigit(self) -> bool: ...
    ...

It’s also shorter!

Yes, I understand that the annotation is shorter by using bool, but being more expressive is sometimes better than being shorter. What do you think about that? :thinking:

Worse for the True | False option is that bool.__or__ has a definition different from type.__or__:

>>> True | False
True
>>> def f() -> bool:
...     pass
... 
>>> f.__annotations__
{'return': <class 'bool'>}
>>> def g() -> True | False:
...     pass
... 
>>> g.__annotations__
{'return': True}

Thanks, I didn’t know that. I’ll use bool.

The final nail in the coffin of True | False is that True and False are instances, not types.

@zware, yes, you are right. True and False are instances of the bool type, and the bool type is a subclass of the int type.

Just for giggles, if you did want write out the return the long way, this should be the same as def f() -> bool

def f() -> Literal[True] | Literal[False]:
    ...

but I find that quite ugly.

3 Likes

Thanks, @J-M0, this answers my question completely. I also find

def f() -> Literal[True] | Literal[False]:
    ...

quite ugly.

Now I’m convinced that

def is_bigger_than_one(number: int) -> bool:
    if number > 1:
        return True
    else:
        return False

is the best option.

Also note that literal has a short form Literal[True, False] which is equivalent to Literal[True] | Literal[False] (not that you should use it instead of bool).

1 Like