Complex function composition in 1 line | Python 3.7

44 Views Asked by At

function composition of single argument functions is a simple 1 liner.

how would I (if it's possible) write the following composition in 1 line?

    def fn(x: int) -> str:
        def inner(a, b):
            return strjoin(a, g(b))
        return inner(*f(x))
1

There are 1 best solutions below

0
Silvio Mayolo On

You can convert any one-line function whose only statement is a return to a lambda trivially. So you can write it this way.

def fn(x: int) -> str:
  return (lambda a, b: strjoin(a, g(b)))(*f(x))

Now, as for why you would do that, I'm not sure, unless you're getting paid by the line of code and abhor the idea of making money.

Most people would write the more approachable

def fn(x: int) -> str:
  a, b = f(x)
  return strjoin(a, g(b))