-1

So I've come across the code below here, and I can't wrap my head around how the return statements work. operation is an argument in the functions seven and five but it's used as a function call in the return statements. What's happening here?

The code is :

def seven(operation = None):
    if operation == None:
        return 7
    else:
        return operation(7)


def five(operation = None):
    if operation == None:
        return 5
    else:
        return operation(5)


def times(number):
   return lambda y: y * number

Edit: following @chepner comment this is how they are called, for example this:

print(seven(times(five())))
ehsan0x
  • 660
  • 5
  • 10
  • 24
  • In python functions can be passed to other functions as argument as they are so called **first-class citizens**. See here: [What is first class function in Python](https://stackoverflow.com/questions/27392402/what-is-first-class-function-in-python) – czeni Jul 27 '21 at 12:26
  • You are missing how `seven` and `five` get *called*. For example, you might write `seven(times)`, which would return a function that multiplies *its* argument by `7`. Then `seven(times)(3) == 21`. – chepner Jul 27 '21 at 12:28
  • You see this a lot in functional programming: `times` is a function that partially applies the `*` operator to its argument. `times(3) == lambda y: y * 3`. You can also write `times(3)(7) == 21`. `five` and `seven` are functions that apply their arguments to `5` and `7`, respectively. – chepner Jul 27 '21 at 12:31
  • The default argument `None` in both is standing in for the identity function, `lambda x : x`. It would be very nice if this were built-in to Python under the name `id`, but (alas) that name is already taken. – chepner Jul 27 '21 at 12:32

2 Answers2

1

Those methods are basically allowing you to pass function objects which will be called. See this example

def square(x):
    return x*x

def five(operation=None):
    if operation is None:
        return 5
    else:
        return operation(5)

I can now call five and pass square as the operation

>>> five(square)
25
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

What's happening here?

This code utilize that functions are first-class citizens in python, therefore functions might be passed as functions arguments. This ability is not unique to python language, but might be initally mind-boggling if you are accustomed to language without that feature.

Daweo
  • 31,313
  • 3
  • 12
  • 25