So you just want to do something like:

try:
    foo = MyClass(args, which, may, be, bad)
except TypeError:
    print "Bad args, bad!"

?


If so, just raise an exception in your class's init:

class MyClass(object):
    def __init__(self, *args):
        if badArgs(args):
            raise TypeError
        # do other stuff...

On Wed, Apr 28, 2010 at 11:10 AM, shawnpatapoff <[email protected]> wrote:
> What I mean by 'when a class is called' is when a class is being
> instanced, or created.
>
> On Apr 27, 11:49 pm, Viktoras <[email protected]> wrote:
>> > 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?
>>
>> what do you mean by "class is called" ? __init__() ? __call__() ? custom
>> methods?
>>
>> like already said, exceptions are the right way to handle execution flow
>> when errors occur.
>>
>> usually if you need to do some error checking for argument, you got to
>> make sure there's only one
>> way for data to enter, e.g.  this is two ways for data to enter, you'd
>> have to check at two places:
>>
>> class Person:
>>      def __init__(self,name):
>>          # name comes unchecked here
>>          self.name = name
>>
>>      def setName(self,name)
>>          if name is None:
>>              raise BadNameException,'name cannot be empty'
>>          if len(name)<2:
>>              raise BadNameException,'name is too short'
>>          self.name = name
>>
>> to fix that, you'd need to go with a lightweight constructor (with no
>> arguments), or use setName() in costructor to
>> initialize data.
>>
>> notice there's no problem with inheriting classes:
>>
>> class PersonInDatabase(Person)
>>      def __init__(self,id):
>>          # constructor will fail if setting invalid name from database
>>          self.setName(Database.loadPersonName(id))
>>
>> --http://groups.google.com/group/python_inside_maya
>
> --
> http://groups.google.com/group/python_inside_maya

-- 
http://groups.google.com/group/python_inside_maya

Reply via email to