Factory function with keyword arguments

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 22 22:53:34 EDT 2007


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.



More information about the Python-list mailing list