Factory function with keyword arguments

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Sep 23 06:55:46 EDT 2007


On Sun, 23 Sep 2007 03:55:45 -0500, Ron Adam wrote:

> Steven D'Aprano wrote:
>> I'm writing a factory function that needs to use keywords in the
>> produced function, not the factory. Here's a toy example:

[snip]

Thanks everyone who answered, you've given me a lot of good ideas.

I've run some tests with timeit, and most of the variants given were very 
close in speed. The one exception was (not surprisingly) my version that 
builds a tuple, puts it in a list, then converts it to a dict, *before* 
doing anything useful with it. It was 3-4 times slower than the others.

George's version, with two definitions of foo(), was the fastest. The 
second fastest was the variant using exec, which surprised me a lot. I 
expected exec to be the slowest of the lot. Unfortunately, I doubt that 
these would scale well as the factory becomes more complicated.

Excluding those two, the next fastest was the original code snippet, the 
one I rejected as clearly too slow! It's apparently faster to check a 
flag than it is build and then expand a dict for keyword arguments.

A valuable lesson... always measure before guessing whether code will be 
slow or not.



-- 
Steven.



More information about the Python-list mailing list