To confirm, yes, raising an Exception is the canonical Python way to return errors from any function, including constructors (aka __init__). This behavior is found throughout Python libraries including the standard library:
>>> from datetime import datetime >>> d = datetime(-1,12,1,23,59,59) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: year is out of range >>> Leo On Apr 28, 5:37 am, Xavier Ho <[email protected]> wrote: > For some reason my message via email doesn't display on Google Groups. > I apologise if you have received this again, but please let me know if > you actually got my first email. > > --- Begin previous email paste --- > > Something like this? > > >>> class Test(object): > > ... def __init__(self, arg): > ... if not isinstance(arg, int): > ... raise TypeError('arg {0} must be an > integer.'.format(arg)) > ... self.arg = arg > ...>>> Test(1) > > <__main__.Test object at 0x02F72490>>>> Test('a') > > Traceback (most recent call last): > File "<input>", line 1, in <module> > File "<input>", line 4, in __init__ > TypeError: arg a must be an integer. > > On Apr 28, 6:18 am, shawnpatapoff <[email protected]> wrote: > > > This may be a more basic question. > > > I have a class being created and I'm testing the arguments when the > > class is called. Within the class can I error out if the types are > > wrong and prevent the class from returning? How do you guys handle > > this? > > > Cheers, > > Shawn > > > --http://groups.google.com/group/python_inside_maya > > --http://groups.google.com/group/python_inside_maya -- http://groups.google.com/group/python_inside_maya
