2

I have a class like:

class TestClass(object):
    def __init__(self, *args):
        try:
            ##  check some condition
        except:
            return
            ## Should exit class

    def do_something_else(self):
        ...

    def return_something(self):
        ##  return something

Now I am trying to call the class like:

TestClass(arg1, arg2, ..).do_something_else()
somthing = TestClass(arg1, arg2, ..).return_something()

When I execute the first command, my conditions fails and raise an exception. What I want is that if some exception occurs in __init__ function then do_something_method should not be called and control flow should go to the second command.

In the second command, all conditions are met and the return_something function should be called.

How can I achieve this?

Manish Gupta
  • 4,438
  • 18
  • 57
  • 104
  • 1
    This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You don't "exit" a class – what are you actually trying to do? – Will Vousden May 05 '17 at 10:22
  • I have a distributed task queue (celery) in which this function is called. I want to minimize the error logs in celery and store the error in the database logs instead. That's why While Initializing the class if the conditions are not met I want to store the error details in my database log and exit from the class. There are some methods which return data while others just process some other data. Otherwise, I would have called the functions from `__init__` function. – Manish Gupta May 05 '17 at 10:28

3 Answers3

5

Maybe I'm wrong, but I'd keep it simple, using a flag variable and doing this way:

class TestClass(object):
    def __init__(self, *args):
        self.flag=False
        try:
            ##  check some condition
        except:
            self.flag=True

    def do_something_else(self):
        if self.flag:
            #do what you want, e.g. call a second command
            return
        ...

    def return_something(self):
        ##  return something
decadenza
  • 2,380
  • 3
  • 18
  • 31
1

I would suggest you to handle the exceptional condition in a separate function rather than inside the constructor

Instead of

TestClass(arg1, arg2, ..).do_something_else()

do

try:
    obj = TestClass(arg1,arg2)
except:
     pass
else:
     obj.do_something_else()

And remove the try/except statement from the init method.
You shouldn't return anything from __init__ method.

Shiva
  • 2,627
  • 21
  • 33
-1

You can just create an Object of the class TestClass and return "True" from try block and "False" from except block. Check if the value is True or Flase and execute the the required function. Creating an object will automatically triiger the init method and return true or false based on your condition. Check that returned value to decide whether to execute required method or not.

Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22