Index Ai Academy
Phase 0 · ToolsPython core

Functions as values

About 35 minLooking ahead: some prerequisites aren't done yet

Why this matters

When a language model uses a tool, your code receives the tool's name as text, like "get_weather", and must run the matching function. The standard way to do that is a dictionary from names to functions. The same idea sorts a catalog by price, registers web routes and answers button clicks. It all rests on one fact: in Python, a function is a value you can store and pass around, like a number or a list.

  • Store functions in variables and dictionaries, and call the one you need by name
  • Sort and pick items with key=, using a named function or a lambda
  • Write functions that accept any number of arguments with *args and **kwargs
  • Pass a list or a dictionary into a call with * and **

A function is a value

You've called functions by writing their name followed by parentheses. Leave the parentheses off, and you get the function itself, not its result. You can store it under another name and call it through that name:

def shout(text):
    return text.upper() + "!"

speak = shout
print(speak("tents on sale"))
print(shout)

speak = shout doesn't run anything. It gives the same function a second name. The last line shows what a function looks like when printed: Python's description of it, with its name.

Because functions are values, they can go anywhere a value can: in a list, in a dictionary, into another function as an argument.