Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"or die()" in Python

Tags:

python

Is anyone using anything like this in Python:

def die(error_message):     raise Exception(error_message)  ...  check_something() or die('Incorrect data') 

I think this kind of style is used in PHP and Perl.

Do you find any (dis)advantages in this [style]?

like image 547
warvariuc Avatar asked Jul 17 '11 06:07

warvariuc


People also ask

What is die command in Python?

For what it's worth calling '''die''' is the standard way to raise an exception in Perl 5. The '''... or die ...''' expression in Perl is turning the non-fatal returning of an error into a catchable exception. In general you don't write this in Python as Python defaults to raising exceptions everywhere.

How do you stop a Python execution?

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program from running. It is the most reliable, cross-platform way of stopping code execution.

How do you raise an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


1 Answers

Well, first, sys.exit([arg]) is more common, and if you really wanted something equivalent to die in PHP, you should use that, raise a SystemExit error, or call os._exit.

The major use of the die method in PHP is, "The script has reached some impasse cannot recover from it". It is rarely, if ever, used on production code. You are better off raising an exception in a called function, catching it in the parent, and finding a graceful exit point -- that is the best way in both languages.

like image 120
cwallenpoole Avatar answered Sep 22 '22 05:09

cwallenpoole