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.

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) 
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)) 

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.