Functions as values: passing one to another
A function is a value like any other. You can store it, put it in a dictionary and hand it to another function, and agent frameworks rely on all three.
def shout(text):
return text.upper()
handler = shout
print(handler("refund please"))
print(shout)shout without brackets is the function itself; with brackets, it is a call. handler = shout stores the function, so calling handler runs shout. The last line prints the function, not its result.
Sorting by a field
tickets = [
{"id": 1, "priority": 2},
{"id": 2, "priority": 5},
{"id": 3, "priority": 3},
]
def by_priority(ticket):
return ticket["priority"]
urgent_first = sorted(tickets, key=by_priority, reverse=True)
print([ticket["id"] for ticket in urgent_first])sorted does not know how to order dictionaries. You pass it a function with key=, and it calls that function on each ticket and orders by what comes back. reverse=True puts the largest first.
lambda: a function without a name
urgent_first = sorted(tickets, key=lambda ticket: ticket["priority"], reverse=True)
print([ticket["id"] for ticket in urgent_first])lambda ticket: ticket["priority"] is the same function as by_priority, written in place. It can hold one expression and no more, which is why it suits a key=.
Calling a function by its name
A model that uses tools does not run them. It answers with the name of a tool and its arguments, and the program looks the function up and calls it.
def lookup_order(order_id):
return f"Order {order_id} shipped on 3 March."
def refund(order_id):
return f"Refund started for order {order_id}."
tools = {"lookup_order": lookup_order, "refund": refund}
chosen = "refund"
print(tools[chosen]("A17"))The dictionary maps names to functions. tools[chosen] is a function, and ("A17") calls it. Change chosen and a different function runs, with no if anywhere.
- Set
chosen = "lookup_order". - Set
chosen = "cancel"and read the error. How wouldgetfrom lesson 8 help? - Sort the tickets so the lowest priority comes first.
Slow is fine. Stopping is the only problem.