is there any overheard with try/except statements?

Delaney, Timothy (Tim) tdelaney at avaya.com
Thu Mar 9 02:03:07 CET 2006


Steven D'Aprano wrote:

> The classic example of the "look before you leap" and
> "just do it" idioms involves looking up a key in a
> dictionary:
> 
> # method one
> if some_dict.has_key(key):
>      do_something_with(some_dict[key])
> else:
>      do_something_else()

FWIW, in recent Python versions the version:

    if key in some_dict:
        do_something_with(some_dict[key])
    else:
        do_something_else()

will always be faster than the above.

> # method two
> try:
>      do_something_with(some_dict[key])
> except KeyError:
>      do_something_else()
> 
> 
> If you expect lots of missing keys, the first method
> will be quicker; if only a few, the second.

This is still correct in general.

Generally, you should always go for whatever is clearest/most easily
read (not just in Python, but in all languages). Only after profiling
should you then optimise. But it's definitely important to understand
the general performance of various constructs.

Tim Delaney



More information about the Python-list mailing list