1

In python, is there a way to exit a class after testing a condition, without exiting out of python?

Say I have the class

class test():
     def __init__(self):
         self.a = 2

     def create_b(self):
         self.b = 3

     def does_b_exist(self):
         if <self.b doesnt exist>:
             #terminate

         self.b += 1

try/except` doesn't work since the rest of the program doesn't terminate after failing. I'm basically trying to catch an error, and do what python does when it shows you errors, but i cant figure out how to do it

joaquin
  • 82,968
  • 29
  • 138
  • 152
apple pie
  • 11
  • 1
  • So you want the whole program to end on the "#terminate" line? That'd be a job for sys.exit(), but see my answer if that's not exactly what you want. A better description would help ;) – TryPyPy Jan 07 '11 at 05:52
  • You can exit from the `does_b_exist()` method by using `return`. – martineau Jan 07 '11 at 05:56
  • The concept of "exit a class" doesn't really make any sense. First off, you aren't "in" the class; you're running a method of an object. – Karl Knechtel Jan 07 '11 at 08:36
  • I think what you want to do is `raise` an exception that will either pass control to a `try/except` handler the caller has set up (that, say, prints an error message), or terminates the program if there's no handler for it. – martineau Jan 07 '11 at 12:05

2 Answers2

2

You might want to run "python -i", which takes you to an interactive console after program execution, to run sys.exit(), which terminates the program, or you (probably) want to customize sys.excepthook. Describe the behavior you want in a little more detail and we can give you some code to try.

TryPyPy
  • 6,214
  • 5
  • 35
  • 63
0

quit() is a decent option. It will quit the process, but make sure to clean up before you do. You could consider throwing an uncaught exception and using finally statements as your script aborts cleanly.

motoku
  • 1,571
  • 1
  • 21
  • 49