testing - How can I best assert a value can be converted to int in Python? -
i'm writing tests in python , 1 of tests need verify value either int or can converted int cleanly.
should pass:
0 1 "0" "123456"
should fail:
"" "x" "1.23" 3.14
how can best write assertion?
so, 100% sure, must like:
def is_integery(val): if isinstance(val, (int, long)): # integer values return true elif isinstance(val, float): # floats can converted without loss return int(val) == float(val) elif not isinstance(val, basestring): # can't convert non-string return false else: try: # try/except better isdigit, because "-1".isdigit() - false int(val) except valueerror: return false # someting non-convertible return true
in answers below thre check, using type conversions , equality checking, think not work correctly huge integers.
maybe there shorter way
Comments
Post a Comment