C-style static variables in Python?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Apr 2 19:57:02 EDT 2010

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.  ;)
>> ~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 

>>> from timeit import Timer
>>> t1 = Timer("pass", "")
>>> t2 = Timer("try:\n    pass\nexcept Exception:\n    pass", "")
>>> min(t2.repeat())/min(t1.repeat())

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())

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.


More information about the Python-list mailing list