C-style static variables in Python?
ethan at stoneleaf.us
Sat Apr 3 04:48:59 CEST 2010
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... at 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. ;)
>>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
> The cost of a try...except is *very* low -- about the same as a pass
>>>>from timeit import Timer
>>>>t1 = Timer("pass", "")
>>>>t2 = Timer("try:\n pass\nexcept Exception:\n pass", "")
> Actually catching the exception, on the other hand, is quite expensive:
>>>>t1 = Timer("len('')", "")
>>>>t2 = Timer("try:\n len(0)\nexcept Exception:\n pass", "")
> 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.
More information about the Python-list