6q9nqBjo
6q9nqBjo

Reputation: 191

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?

Upvotes: 3

Views: 553

Answers (2)

tfv
tfv

Reputation: 6259

This piece of code seems to distinguish between boolean and integer parameters in functions. What am I missing?

import math
def func(n):
    if type(n) == type(True):
        print "This is a boolean parameter"
    else:
        print "This is not a boolean parameter"
    if not isinstance(n, int):
        raise TypeError('input is not an integer')
    return math.factorial(n)

print(func(True))
print(func(False))
print(func(1))

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78554

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

Upvotes: 4

Related Questions