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
?
sweeneyde
(Dennis Sweeney)
November 2, 2021, 9:38pm
2
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?
sweeneyde
(Dennis Sweeney)
November 2, 2021, 11:04pm
4
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.
zware
(Zachary Ware)
November 3, 2021, 12:30am
6
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.
J-M0
(J-M0)
November 3, 2021, 1:56pm
8
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.
layday
(layday)
November 6, 2021, 1:15pm
10
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