2

Is it a bad coding practice to call the exit() function in Python repeatedly?

I'm working on a command-line tool, so there are multiple function definitions... Basically:

def usage()
def error(arg1)
def find(arg1, arg2)

In the end of usage() I call exit(), which I assume it's OK, but it's also called in the success of find(), and in error() (which is called in the failure of find().

As you can see, exit() is being called many times in my code, and I wasn't sure if this is actually a bad coding practice.

3 Answers 3

4

It does work to call exit() on multiple locations and if it's simple program with only you using it it's no problem. But in my opinion it always makes inspecting/debugging code more complex if there are multiple exit points. Especially if you think other developers will at some point be modifying your code or you will offer part of your code as a library to other developers.

Other option is to raise exceptions and catch them on the outer function. This way you also have chance to do some additional tasks before exiting (release some resources for example).

Sign up to request clarification or add additional context in comments.

2 Comments

exit() actually raises an exception, so finally blocks get to run. +1 for raising exceptions more specific than SystemExit, though.
That's a great point, but it's just a tiny program where when something is passed to def error(), it's not actually an error, but a sign that the program couldn't find a specified entry in a file
1

Not really bad practice IMO - just make sure you return an exit code reflecting the different exit points whenever that might be useful to the calling process...

Comments

1

I do that all the time in my scripts. In general, you need not worry about that, since python takes care of cleaning the system before program termination. I also used to do

signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))

To force system cleaning up in case I need to kill a stalled script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.