简体   繁体   中英

Assert using Python- How do I check if the input is Integer or not?

I wrote a function, which gets a number as an input. For example:

def return_it_back(n):
    return n

I simply need to check if the input is integer or not with assert . So, I wrote a test function:

def test():
    assert return_it_back("k"), "incorrect input"
test()

Python doesn't show "incorrect input". Doesn't the assert return_it_back("k"), "incorrect input" need to print the "incorrect input"?

assert condition, message is just syntactic sugar for:

if not condition:
    raise AssertionError(message)

In your code, return_it_back() just returns it's argument, so

assert return_it_back(n), message

is equivalent to

assert n, message

which is equivalent to

if not n:
    raise AssertionError(message)

so what's get tested is the truth value of n , whatever it is.

In Python, all objects have a boolean value - empty collections (builtin ones at least), the empty string, numerical zeros and None having a false value and most other objects having by default a true value.

IOW, unless n is an empty collection, empty string, numerical zero or None it will eval to True and the assertion will succeed.

If you want to test whether an object is of a given class (or list of classes), you can use isinstance(obj, cls) (or isinstance(obj, cls, othercls, etc) ). Typechecking arguments is usually considered unpythonic (as long as the object acts as expected, who cares what type it is, AKA duck typing ), but there are a couple places where it makes sense - when sanitizing user inputs, at subsystems boundary, and eventually when it's garanteed that any other type will break the function one way or another.

Also, assert is a coder tool, not something to use for arguments validation - if your code is compiled with the --optimize flag for example assert statements will be ignored. IOW it's fine for unittesting (but there are more advanced tools in the unittest package) or debugging but not for production code. If you really want to prevent your function from accepting anything but ints you should raise a TypeError (or a ValueError if for example you expect a positive integer and get a negative one) instead.

There are several ways, one might be

def return_it_back(n):
    assert type(n) == int, "Incorrect input"
    return n

return_it_back(123)
return_it_back('123')

This will obviously break on the second attempt.


You can also check the return value as in your attempt with

 def return_it_back(n): return n assert type(return_it_back(123)) == int, "Incorrect input" assert type(return_it_back('123')) == int, "Incorrect input" 

but this is redundant and therefore not considered "pythonic". Take the first alternative.

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