6q9nqBjo 6q9nqBjo - 2 months ago 17
Python Question

Filter out boolean as non-integer?

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?

Answer

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')
Comments