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.

0

3 Answers 3

2

You are perhaps looking for operator.itemgetter:

from operator import itemgetter

get_zeroth = itemgetter(0)
assert get_zeroth(f()) == 'zero'
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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__

Comments

Your Answer

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.