How slow are Python / django exceptions?

python exception slow? I am kind using python exceptions for the structural program that follow in my web application and I am wondering how throwing exceptions will affect the performance of my application. What do you think?

Which of the following statements is less costly in terms of memory and processor?

try: artist = Artist.objects.get(id=id) except: raise Http404 artist = Artist.objects.filter(id=id) if not artist: return HttpResponse('404') 
+6
python django exception
source share
3 answers

Exception handling will be the least of your performance concerns. I would suggest, however, that you are using the shortcut provided by Django for you:

 from django.shortcuts import get_object_or_404 artist = get_object_or_404(Artist, id=id) 

Either assigns an artist object or returns a value of 404. This is a win-win!

In addition, you should check out the django-debug-toolbar , which provides rendering time / cpu, context switches and all sorts of other useful tidbits for developers, and may just be the tool you need.

+15
source share

To really understand the performance of your system, you will need to profile it. But Python is a language that encourages the use of such exceptions, so they have no unusual overhead, as in some other languages.

For example, sometimes people discuss this choice:

 if hasattr(obj, "attr"): use(obj.attr) else: some_other(obj) 

or

 try: use(obj.attr) except AttributeError: some_other(obj) 

People who say that you should use the first to avoid an exception should understand that internally, hasattr is implemented by accessing the attribute and returning False if an AttributeError occurs. Thus, in fact, both code fragments use exceptions.

+10
source share

This guy made a nice little try / except speed with dicts test record, I'm sure you will have an analog in your case. In any case, making a good profile will give you better information.

+8
source share