Diego-MX
Diego-MX

Reputation: 2339

arguments in functions python

This is a subtle question about notation. I want to call a function with specific arguments, but without having to redefine it.

For example, min() with a key function on the second argument key = itemgetter(1) would look like:

min_arg2 = lambda p,q = min(p,q, key = itemgetter(1))

I'm hoping to just call it as something like min( *itemgetter(1) )...

Does anyone know how to do this? Thank you.

Upvotes: 1

Views: 171

Answers (2)

Zach Kelling
Zach Kelling

Reputation: 53819

Using functools (as in Duncan's answer) is a better approach, however you can use a lambda expression, you just didn't get the syntax correct:

min_arg2 = lambda p,q: min(p,q, key=itemgetter(1))

Upvotes: 2

Duncan
Duncan

Reputation: 95612

You want to use functools.partial():

min_arg2 = functools.partial(min, key=itemgetter(1))

See http://docs.python.org/library/functools.html for the docs.

Example:

>>> import functools
>>> from operator import itemgetter
>>> min_arg2 = functools.partial(min, key=itemgetter(1))
>>> min_arg2(vals)
('b', 0)

Upvotes: 10

Related Questions