try vs. has_key()

Andrew Dalke dalke at bioreason.com
Thu Apr 22 21:15:19 EDT 1999


Aahz Maruch <aahz at netcom.com> asked:
> Can people explain their preferences [for try/except over has_key]?

As I recall, has_key is a relatively new addition to Python
so older code (and people who learned from older code) will
use try/except.

I usually use has_key because coming from a shop where most
people have C experience, it's easier to explain that than using
what it in essense the side effect of exceptions.

Also, I believe Barry Warsaw did a benchmark on the tradeoffs of
when you do one over the other.  The exception case of a try/except
has some pretty high overhead, while the has_key call is slightly
worse than the non-exception case of the try/except.  Barry's
results showed that if 5% of the cases or less were "exceptional"
then try/except is faster, otherwise, use has_key.  Alas, I cannot
find the URL for that paper.

						Andrew
						dalke at acm.org




More information about the Python-list mailing list