Python 3D Academyবাংলা

Functions are values too

🌍 In real life. A TV remote isn't the TV, but whoever holds it can work the TV. You can hand the remote to a friend, put it in a drawer, or keep a spare.

In Python, a function's name is like that remote: it points to the function. Without the brackets, greet is the function itself, a value like any other:

  • you can give it another name: hello = greet
  • you can pass it to another function, like sorted(names, key=len) (Chapter 16)
  • you can return a new function from a function

This is the key idea behind decorators, the topic of this chapter.

The idea in one sentence: a function is a value: you can name it, pass it, store it, and even return a new function from another function.

Its words:

  • first-class function: a function you can treat like any other value
  • inner function: a def inside another function
  • closure: an inner function that remembers values from the function that made it (Lesson 16.5)
def greet(name):
    return "Hi, " + name

hello = greet              # no brackets: the function itself
print(hello("Ana"))

def apply_twice(func, value):
    return func(func(value))

def add_three(n):
    return n + 3

print(apply_twice(add_three, 10))
greet() calls the function; greet without brackets hands the function over.

Functions that make functions, step by step. Think of a rubber-stamp maker: you tell it the text, and it gives you a new stamp that always prints that text.

  1. an outer function takes a setting, like make_stamp(word)
  2. inside it, a new function is defined that uses that setting
  3. the outer function returns the inner one (no brackets)
  4. the inner function remembers the setting even after the outer one has finished; this is called a closure
def make_stamp(word):
    def stamp(text):
        return f"[{word}] {text}"
    return stamp

paid = make_stamp("PAID")
urgent = make_stamp("URGENT")
print(paid("electricity bill"))
print(urgent("call the plumber"))

Why it matters here. This is the whole engine behind decorators (the next lesson): a decorator is just a function that takes a function and returns a new one. Once "a function is a value" feels natural, decorators are only a little extra syntax.

Mistakes and edge cases.

  • Returning the call instead of the function. return inner() returns inner's result; return inner returns the function.
  • Calling the maker's result too early. make_stamp("PAID") gives a stamp; make_stamp("PAID")() uses it.
  • Printing a function. print(stamp) shows <function make_stamp.<locals>.stamp at 0x...>; call it to see its output.

Quiz

  1. What does this print?

    def shout(text):
        return text.upper()
    
    say = shout
    print(say("hey"))
  2. What does this print?

    def make_adder(n):
        def add(x):
            return x + n
        return add
    
    plus5 = make_adder(5)
    print(plus5(10), plus5(1))
  3. What is the difference between greet and greet()?

    • greet is the function itself; greet() calls it and gives its result
    • There is no difference
    • greet() is the function; greet is an error
  4. What does this print?

    def double(n):
        return n * 2
    
    def square(n):
        return n * n
    
    for f in [double, square]:
        print(f(4))
  5. Which line has a mistake? (It should print 13.)

    def add_three(n):
        return n + 3
    
    def apply_twice(func, value):
        return func(func(value))
    
    print(apply_twice(add_three(), 7))

Coding tasks

  1. Write apply_twice(func, value) that calls func on value, then calls func again on that result.

  2. Write make_multiplier(n) that returns a new function, which multiplies its input by n.

  3. Write calculate(op, a, b) where op is "add", "sub" or "mul". Keep the three small functions in a dictionary and look the right one up.