{:check ["true"], :rank ["functions_as_values"]}

Index

Functional Programming in Python

  • Python supports functional programming, a programming paradigm in which functions can be values to be passed between functions.

  • Having functions as values create new patterns in programming.

Functions As Values

Functions as values

  • When a function is declared, the function name is actually a variable that refers to the function object.

    # Define a function
    def hello():
        print("Hello world.")
    
    # The function can be treated as a data value
    x = hello
    y = x
    
    # Variables assigned to functions can
    # be used as functions themselves
    x() # -> Hello world.
    y() # -> Hello world.
    
  • Functions can be the return values of functions.

    # This main function returns a function.  
    # The returned function is constructed based
    # on the argument(s) of the main function.
    def make_adder_fn(increment):
        def f(x):
            return x + increment
        return f
    
  • Functions can be parameters of functions.

    # This function expects a function as its first
    # argument, and a number as a second argument.
    # The main function applies the argument function
    # twice to the second argument.
    def apply_twice(f, x):
        return f(f(x))
    
    box

    Definition:

    A higher order function is a function that accepts another function as an input.

  • Anonymous functions.

    add = lambda x,y: x + y