1

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.

Stedy
7,47715 gold badges60 silver badges79 bronze badges
asked Sep 23, 2011 at 17:17
1
  • 1
    "but without having to redefine it." How can this possibly be avoided? What are you trying to do? If min() doesn't mean __builtins__.min() people will hate you. Commented Sep 23, 2011 at 17:34

2 Answers 2

10

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)
answered Sep 23, 2011 at 17:20
Sign up to request clarification or add additional context in comments.

1 Comment

Where do you define vals?
2

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))
answered Sep 23, 2011 at 17:34

1 Comment

thanks, that mistake wasa typo, although functools.partial was what I wanted.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.