I have always wondered about the following code snippet:
import math
def func(n):
if not isinstance(n, int):
raise TypeError('input is not an integer')
return math.factorial(n)
print(func(True))
print(func(False))
I'm always surprised at the result because True and False actually work and are interpreted as the integers 1 and 0. Therefore the factorial function produces the expected results 1 and 1 when using True and False. The behavior of those booleans is clearly described in the python manual and for the most part I can live with the fact that a boolean is a subtype of integer.
However, I was wondering: is there any clever way to wash away something like True as an actual parameter for the factorial function (or any other context which requires integers) in a way that it'll throw some kind of exception which the programmer can handle?
Type bool is a subtype of int and isinstance can walk through inheritance to pass True as an int type.
Use the more stricter type:
if type(n) is not int:
raise TypeError('input is not an integer')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With