简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM