Reputation: 11
I'm trying to make an error message appear when the wrong type of data is entered into a function. In this instance, I am only trying to accept an int
or float
when the function is called. Entering a str
in the function should return an error message
def isPrime(i):
if not (type(i)==float or type(i)==int):
print("Input wrong type")
return None
i = abs(int(i))
if i == 2 or i == 1:
return True
if not i & 1:
return False
for x in range(3, int(i**0.5) + 1, 2):
if i % x == 0:
return False
return True
# Wanting the code to return an error
isPrime(bob)
Upvotes: 1
Views: 2529
Reputation: 106768
If you're using Python 3.5+, you can use type hint with the following decorator (which I adapted from @MartijnPieters's typeconversion decorator) to enforce the type hints:
import functools
import inspect
def enforce_types(f):
sig = inspect.signature(f)
@functools.wraps(f)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
bound.apply_defaults()
args = bound.arguments
for param in sig.parameters.values():
if param.annotation is not param.empty and not isinstance(args[param.name], param.annotation):
raise TypeError("Parameter '%s' must be an instance of %s" % (param.name, param.annotation))
result = f(*bound.args, **bound.kwargs)
if sig.return_annotation is not sig.empty and not isinstance(result, sig.return_annotation):
raise TypeError("Returning value of function '%s' must be an instance of %s" % (f.__name__, sig.return_annotation))
return result
return wrapper
@enforce_types
def isPrime(i: float) -> bool:
i = abs(int(i))
if i == 2 or i == 1:
return True
if not i & 1:
return False
for x in range(3, int(i**0.5) + 1, 2):
if i % x == 0:
return False
return True
so that:
print(isPrime(1))
print(isPrime(1.0))
would both output True
, but:
print(isPrime('one'))
would raise the following exception:
TypeError: Parameter 'i' must be an instance of <class 'float'>
Upvotes: 2
Reputation: 71580
So:
if not (type(i)==float or type(i)==int):
print("Input wrong type")
return None
Could be simplified to:
if not isinstance(i,(float,int)):
print("Input wrong type")
return None
Then do error message:
if not isinstance(i,(float,int)):
raise TypeError('Your Text here') #You can do any error i do `TypeError` just for now.
Then to create own Error message:
class MyError(Exception):
pass
Then here:
if not isinstance(i,(float,int)):
raise MyError('Your Text here')
But I'll prefer to use TypeError
, for doing errror
Upvotes: 0