Function to apply superset of arguments to a function

Carl Banks pavlovevidence at gmail.com
Wed Sep 9 17:58:22 EDT 2009


On Sep 9, 10:40 am, David Stanek <dsta... at dstanek.com> wrote:
> On Wed, Sep 9, 2009 at 12:45 PM, Andrey Fedorov<anfedo... at gmail.com> wrote:
> > Hi all,
>
> > I've written a function [1] called apply_some which takes a set of
> > keywords arguments, filters only those a function is expecting, and
> > calls the function with only those arguments. This is meant to
> > suppress TypeErrors - a way to abstract the logic which checks what
> > arguments a passed-in function accepts.
>
> > For example:
>
> >> def foo(x=1, y=2):
> >>    return (x,y)
>
> >> apply_some(foo, y=0, z="hi") // calls foo(y=0)
> >> -> (1,0)
>
> > I'd like to expand this to fill undefined arguments with None, but
> > before I do, does anyone know of any packages/libraries which either
> > do something similar or would make this code cleaner?
>
> What is your use-case for using this? It seems really odd to me.

Use case seems perfectly obvious to me.  You have a set of functions
that use different strategies to accomplish a task, and there is a lot
of overlap in the arguments used but no consistency.  You want to be
able to swap in different functions so as to try different strategies
(either while editing, or programmatically).  Instead of dealing with
arguments that change everytime you want to swap in a different
function, you can use this filter and work with a single argument set.

The example that pops to my mind is numerical optimization.  Many
numerical optimizers have similar overall strategies but differ in
underlying details, so they will tend to take different options.  An
argument filter like the OP wrote would be quite handy here.


Carl Banks



More information about the Python-list mailing list