Q:

Optional argument in lambda function

I have a function:
cost(X, model, reg = 1e-3, sparse)

And I need to pass this function to another one under the form:
f(X, model)
f(X, model, reg = reg)

I am using lambda to do this:
f = lambda X, model: cost(X, model, sparse = np.random.rand(10,10))

And python complains that lambda got an unexpected argument reg. How do I do this correctly?
If I do the other way:
f = lambda X, model, reg: cost(X, model, reg = reg, sparse = np.random.rand(10,10))

Then it's not working in the first case.

A:

Lambda's take the same signature as regular functions, and you can give reg a default:
f = lambda X, model, reg=1e3: cost(X, model, reg=reg, sparse=np.random.rand(10,10))

What default you give it depends on what default the cost function has assigned to that same parameter. These defaults are stored on that function in the cost.__defaults__ structure, matching the argument names. It is perhaps easiest to use the inspect.getargspec() function to introspect that info:
from inspect import getargspec

spec = getargspec(cost)
cost_defaults = dict(zip(spec.args[-len(defaults:], spec.defaults))
f = lambda X, model, reg=cost_defaults['reg']: cost(X, model, reg=reg, sparse=np.random.rand(10,10))

Alternatively, you could just pass on any extra keyword argument:
f = lambda X, model, **kw: cost(X, model, sparse=np.random.rand(10,10), **kw)

A:

have you tried something like
f = lambda X, model, **kw: cost(X, model, sparse = np.random.rand(10,10), **kw)
then reg (and any other named argument you want to pass through (other than sparse)) should work fine.

