473,387 Members | 1,791 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,387 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 1712
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.