473,241 Members | 1,807 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

Factory function with keyword arguments

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

def factory(flag):
def foo(obj, arg):
if flag:
# use the spam keyword to method()
return obj.method(spam=arg)
else:
# use the ham keyword
return obj.method(ham=arg)
return foo

Problem: the test of which keyword to use is done every time the produced
function is called, instead of once, in the factory.

I thought of doing this:

def factory(flag):
if flag: kw = 'spam'
else: kw = 'ham'
def foo(obj, arg):
kwargs = dict([(kw, arg)])
return obj.method(**kwargs)
return foo

Is this the best way of doing this? Are there any alternative methods
that aren't risky, slow or obfuscated?

Before anyone suggests changing the flag argument to the factory to the
name of the keyword, this is only a toy example, and doing so in my
actual code isn't practical.

--
Steven.
Sep 23 '07 #1
8 1708
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrites:
def factory(flag):
if flag: kw = 'spam'
else: kw = 'ham'
def foo(obj, arg):
kwargs = dict([(kw, arg)])
return obj.method(**kwargs)
return foo
Untested:

def factory(flag):
def foo(obj, arg):
p = 'spam' if flag else 'ham'
return obj.method(**{p:arg})
return foo

is the obvious way in that style.
Sep 23 '07 #2
On Sep 22, 10:53 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.auwrote:
I'm writing a factory function that needs to use keywords in the produced
function, not the factory. Here's a toy example:

def factory(flag):
def foo(obj, arg):
if flag:
# use the spam keyword to method()
return obj.method(spam=arg)
else:
# use the ham keyword
return obj.method(ham=arg)
return foo

Problem: the test of which keyword to use is done every time the produced
function is called, instead of once, in the factory.

I thought of doing this:

def factory(flag):
if flag: kw = 'spam'
else: kw = 'ham'
def foo(obj, arg):
kwargs = dict([(kw, arg)])
return obj.method(**kwargs)
return foo

Is this the best way of doing this? Are there any alternative methods
that aren't risky, slow or obfuscated?
Unless I'm missing something, the obvious way is to move the flag
check outside the function and have two definitions of foo:

def factory(flag):
if flag: # use the spam keyword to method()
def foo(obj, arg):
return obj.method(spam=arg)
else: # use the ham keyword
def foo(obj, arg):
return obj.method(ham=arg)
return foo

Now if foo is more than a line or two and the only difference the flag
makes is the keyword argument, you can either factor the common part
out in another function called by foo or (if performance is crucial)
create foo dynamically through exec:

def factory(flag):
kw = flag and 'spam' or 'ham'
exec '''def foo(obj, arg):
return obj.method(%s=arg)''' % kw
return foo
George

Sep 23 '07 #3


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:
I thought of doing this:

def factory(flag):
if flag: kw = 'spam'
else: kw = 'ham'
def foo(obj, arg):
kwargs = dict([(kw, arg)])
return obj.method(**kwargs)
return foo

Is this the best way of doing this? Are there any alternative methods
that aren't risky, slow or obfuscated?
Looks ok to me. It can be simplified a bit.

def factory(flag):
kw = 'spam' if flag else 'ham'
def foo(obj, arg):
return obj.method(**{kw:arg})
return foo
Cheers,
Ron
Sep 23 '07 #4


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:
I thought of doing this:

def factory(flag):
if flag: kw = 'spam'
else: kw = 'ham'
def foo(obj, arg):
kwargs = dict([(kw, arg)])
return obj.method(**kwargs)
return foo

Is this the best way of doing this? Are there any alternative methods
that aren't risky, slow or obfuscated?
Looks ok to me. It can be simplified a bit.

def factory(flag):
kw = 'spam' if flag else 'ham'
def foo(obj, arg):
return obj.method(**{kw:arg})
return foo
Cheers,
Ron

Sep 23 '07 #5
On 9/23/07, Ron Adam <rr*@ronadam.comwrote:
>

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:
http://docs.python.org/whatsnew/pep-309.html
Sep 23 '07 #6
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.
Sep 23 '07 #7
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrites:
A valuable lesson... always measure before guessing whether code
will be slow or not.
And after measuring, don't guess then either :-)

--
\ "Science doesn’t work by vote and it doesn’t work by |
`\ authority." —Richard Dawkins, Big Mistake (The Guardian) |
_o__) |
Ben Finney
Sep 23 '07 #8


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

Sep 23 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Stephen Boulet | last post by:
I've run across code like "myfunction(x, *someargs, **someotherargs)", but haven't seen documentation for this. Can someone fill me in on what the leading * and ** do? Thanks. Stephen
39
by: Marco Aschwanden | last post by:
Hi I don't have to talk about the beauty of Python and its clear and readable syntax... but there are a few things that striked me while learning Python. I have collected those thoughts. I am...
6
by: Boogie El Aceitoso | last post by:
Hi, I'd like to have a function factory that returns objects of a class hierarchy. What's the best way to deal with the fact that different subclasses will have different constructor arguments?...
3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
10
by: Chris Croughton | last post by:
What do people call their factory functions? 'new' is not an option (yes, it can be overloaded but has to return void*). The context is: class MyClass { public: // Factory functions...
21
by: Dmitry Anikin | last post by:
I mean, it's very convenient when default parameters can be in any position, like def a_func(x = 2, y = 1, z): ... (that defaults must go last is really a C++ quirk which is needed for overload...
5
by: ma740988 | last post by:
Consider: #include "handyfactory.h" #include <iostream> struct Shape { virtual void print() const=0; };
50
by: LaundroMat | last post by:
Suppose I have this function: def f(var=1): return var*2 What value do I have to pass to f() if I want it to evaluate var to 1? I know that f() will return 2, but what if I absolutely want to...
5
by: Agrona | last post by:
I found this thread: http://www.thescripts.com/forum/thread233505.html only marginally helpful. It seems that going through the callstack is the only way to determine which function may have...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, youll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.