Factory function with keyword arguments

Ron Adam rrr at ronadam.com
Sun Sep 23 12:35:59 EDT 2007



Steven D'Aprano wrote:
> 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.

The one with exec (the others less so) will depend on the ratio of how 
often the factory is called vs how often the foo is called.  If the factory 
is called only once, then exec only runs once.  If the factory is called 
every time foo is needed, then it will be much slower.  So  your test needs 
to take into account how the factory function will be used in your program 
also.

Ron




More information about the Python-list mailing list