raise TypeError exception for incorrect input value in a class
11,837
Its a bit different between 2.x and 3.x, but use isinstance to figure out type and then raise the exception if you are not satisfied.
class calibration(object):
def __init__(self, inputs, outputs, calibration_info, interpolations=2):
if not isinstance(inputs, basestring):
raise TypeError("input must be a string")
Python2 differentiates between ascii and unicode strings - "basestring" convers them both. In python3, there are only unicode strings and you use 'str' instead.
Author by
Dalek
Updated on June 17, 2022Comments
-
Dalek almost 2 years
I am trying to write a
class
and I want that if the initial input values for the class don't obey specific types, it would raise an exception. For instance I would useexcept TypeError
to return an error. I don't know how it should be done though. My first attempt to write theclass
is as following:class calibration(object): def __init__(self, inputs, outputs, calibration_info, interpolations=2): try: self.inputs=inputs except TypeError self.outputs=outputs self.cal_info=calibration_info self.interpol=interpolations
I would like that if
inputs
value is not a string then it raises an error message. I would appreciate for any help.