Home > OS >  How expensive is raise in Python?
How expensive is raise in Python?

Time:08-17

During development using drf, an efficient method for error handling was needed.

I found two methods, one using ErrorResponse created by inheriting Response, and one using APIException provided by drf.

The first method is done through return, and the second method uses the raise command.

I wonder which one is more efficient and why!

I apologize in advance for the question may be too vague.

CodePudding user response:

raise produces an error in the current level of the call stack. You can catch a raised error by covering the area where the error might be raised in a try and handling that error in an except.

return on the other hand, returns a value to where the function was called from, so returning an exception usually is not the functionality you are looking for in a situation like this, since the exception itself is not the thing triggering the except it is instead the raising of the exception that triggers it.

https://docs.python.org/3/reference/simple_stmts.html#raise

https://docs.python.org/3/reference/simple_stmts.html#return

So to answer your question I would raise because it is built for errors compared to return. Also, they are the same in speed/efficiency.

CodePudding user response:

Not sure if efficiency and CPU time is most important thing.

You have to understand Django request-response cycle first. The next step after return Response (or raise Exception) is not a client side browser but number of Middlewares that you imported in your application. And these Middlewares may be different depends on what happens inside View.

When you raising something you break this cycle flow.
Django handling raised exception, writing extra error logs, returning specified error response to client side. You don't have to care that all conditions of correct responses will be satisfied, because error already happens, it is already not correct. In other way returned Response will be delivered to client side by normal way. Django will care that all validations and steps will be passed before response reach a client.

If you need to economy milliseconds by choosing between return / raise and deeply thinking about efficiency, at first stop using Django. Seriously. It is slowest framework even for python.

  • Related