Factory function with keyword arguments
Ron Adam
rrr at ronadam.com
Sun Sep 23 04:55:45 EDT 2007
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
More information about the Python-list
mailing list