0

Say I have a function that returns a tuple of outputs:

def f():
    return 'zero', 1

But I have to supply in-line a new anonymous function that returns only e.g. the zeroth element of that returned tuple. This is an easy one-liner with a lambda:

lambda : f()[0]  # returns 'zero'

Is there a way to do the same thing using functools or similar?

Given that lambda was allegedly 'planned to [be removed] from Python 3, as one of "Python's glitches"', I'm assuming there's a way to do this without lambda, but I haven't been able to figure it out.

I know that functools.partial can pretty much be a substitute for lambda when managing a function's input arguments. But managing a function's outputs? Haven't figured it out.

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188

3 Answers3

2

You are perhaps looking for operator.itemgetter:

from operator import itemgetter

get_zeroth = itemgetter(0)
assert get_zeroth(f()) == 'zero'
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can try behaviour to produce a poor-man's conditional expression

print(f()[f()[0]==' '])

Since [f()[0]!=' '] produces a boolean , As you said it produce a tuple so [f()[0]==' '] will always be wrong so it will give 0 which is index no which you want.

0

The current answers appear to be producing the value itself -- which you seem to be content with achieving through f()[0] -- as opposed to a callable producing the value. Is lazy evaluation (as you have with your lambda example) a requirement? If not, the problem is no longer that of post-composing f with a projection but rather that of defining a constant function, and I'll nominate

itertools.repeat(f()[0]).__next__
fuglede
  • 17,388
  • 2
  • 54
  • 99