Steven D'Aprano wrote:
On Fri, 02 Apr 2010 12:39:16 -0700, Patrick Maupin wrote:
On Apr 2, 2:38 pm, Ethan Furman <et...@stoneleaf.us> wrote:
[...]
Sounds like a personal preference issue, rather than a necessary /
unnecessary issue -- after all, if you call that function a thousand
times, only once is mongo not defined... clearly the exception. ;)
~Ethan~
Well, I think the whole discussion has basically been about personal
preference. OTOH, but if you call the function a few million times, you
might find the cost of try/except to be something that you would rather
not incur -- it might become a performance issue rather than a personal
choice issue.
The cost of a try...except is *very* low -- about the same as a pass
statement:
from timeit import Timer
t1 = Timer("pass", "")
t2 = Timer("try:\n pass\nexcept Exception:\n pass", "")
min(t2.repeat())/min(t1.repeat())
1.9227982449955801
Actually catching the exception, on the other hand, is quite expensive:
t1 = Timer("len('')", "")
t2 = Timer("try:\n len(0)\nexcept Exception:\n pass", "")
min(t2.repeat())/min(t1.repeat())
10.598482743564809
The heuristic I use is, if I expect the try block to raise an exception
more than about one time in ten, I change to an explicit test. In this
case, since the exception should only be raised once, and then never
again, I would use a try...except block.
That was my reasoning as well, but when I timed it for one million runs
(so 1 instantiation, 999,999 simple calls), the __getattr__ time was .5
seconds, the try...execpt block was .6; at ten million it was 5 and 6.
At those rates, personal preference takes over, at least for me.
~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list