Python 38 · Profile repeated route hints

Python lesson 38 of 50 · Advanced · About 45 minutes

Find out what a repeated map search actually does. Measure the route workload and reuse completed route results safely.

Pip follows a trail of orange lights past deep craters towards a radio tower.

Mission Use cProfile for a repeatable workload and an LRU cache for immutable routes on the fixed map.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Save the complete checkpoint below as moonbase_38.py in a project folder and run python moonbase_38.py from that folder. Use python3 on systems where that is the Python 3 command. Use Python 3.10 or newer.

Measure. Repeat a quiet, fixed workload.. → Reuse. Store completed routes by room pair.. → Compare. Check cache hits and correctness..
Measure → Reuse → Compare

Understand the Python in this lesson

Read the explanations, then follow the worked example before changing the code.

Put a memory in front of route

@lru_cache(maxsize=16) wraps the route function with a cache of up to sixteen argument and result pairs. The two room names are the key. A hit reuses the stored result, while a miss runs the search. LRU means the least recently used result is removed when the limit is exceeded.

Keep the measurement fair

route.cache_clear() removes entries and resets the counters. The loop for _ in range(40): runs the same query forty times, leaving the loop counter unused. Starting with an empty cache gives the first request the same work on each run.

Measure a specific block of code

with cProfile.Profile() as profiler: creates and starts a profiler for the indented block. Leaving the block ends the measurement. pstats.Stats(profiler) prepares a report. sort_stats("cumulative") sorts by time spent in a function together with functions it called, and print_stats(5) displays the first five entries.

Use counts to check the idea

route.cache_info() reports hits, misses, the size limit and how many results are stored. Room names can be used as keys and route tuples stay fixed. The search also reads WORLD. If that map is changed while the script runs, clear cached results before asking for routes again.

How the pieces fit The hint tells the player the same route as before. The profiler and cache counts show how the program can skip repeated searches while its map stays fixed.

Follow one run, step by step
  1. Run the checkpoint with --profile.
    The cache is empty before the loop starts. Why profile_routes clears it so earlier hints have no effect on the measurement.
  2. Look up Habitat to Beacon once.
    One miss and the tuple ('east', 'south'). Why The cache has no entry yet, so breadth-first search runs.
  3. Repeat the same lookup 39 times.
    hits=39, misses=1 and currsize=1. Why All repeats ask for the same ordered pair of rooms.

Predict before you run What if you swap the start and destination after that first lookup?

Reveal the explanation

It is a cache miss for a new key. Habitat to Beacon and Beacon to Habitat are different ordered pairs, and they can require different moves.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills cProfile, memoisation, lru_cache, cache invalidation.

1. Choose a small repeatable workload

A single route on our four-room base is fast, so guessing at performance does not teach much. Instead, call the same Habitat-to-Beacon route forty times so you can observe repeated work under a profiler. cProfile.Profile records function calls inside its context. pstats then presents an ordered summary. The exact time values can vary, so focus on the number of repeated requests and the cache report. Run your checkpoint from a terminal with --profile after the filename to view the report without playing a full game.

with cProfile.Profile() as profiler:
        for _ in range(40):
            route("Habitat", "Beacon")

2. Reuse a route when inputs match

The lru_cache decorator can store the result of route for a pair of room names. If the same two names are passed again, Python can return the previously calculated tuple. The limit of sixteen matches the number of possible ordered pairs among our four rooms. Since the results are tuples, a caller cannot change a route by accident after it has been cached. The world map used here stays fixed during a mission. If you edit WORLD while the program is running, clear the cache before using it again or stale routes could lead through a removed exit.

@lru_cache(maxsize=16)
def route(start, target):

3. Use hit and miss counts as evidence

The profile starts by clearing the cache. Calling the same pair forty times should produce one miss, when the program calculates the route, followed by thirty-nine hits. Compare those counts with your own output. Change the repeated call to use two alternate destinations and predict the result. This is a small example of measuring predictable work before changing an implementation. It also explains why reuse depends on correct assumptions: the same input must still mean the same route. Check that the interactive hint gives the same answer as the previous checkpoint.

print(route.cache_info())
    pstats.Stats(profiler).sort_stats("cumulative").print_stats(5)
Complete Python checkpoint · moonbase_38.py
from dataclasses import dataclass, replace
from collections import deque
import json
import sys
import cProfile
import pstats
from functools import lru_cache

WORLD = {
    "Habitat": {"east": "Workshop", "south": "Greenhouse"},
    "Workshop": {"west": "Habitat", "south": "Beacon"},
    "Greenhouse": {"north": "Habitat", "east": "Beacon"},
    "Beacon": {"north": "Workshop", "west": "Greenhouse"},
}
PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"}
REQUIRED = {"Coil", "Cell"}


MAX_ENERGY = 8


@dataclass(frozen=True)
class State:
    room: str = "Habitat"
    parts: tuple = ()
    rescued: bool = False
    energy: int = MAX_ENERGY
    turns: int = 0

def spend(state, **changes):
    return replace(state, energy=state.energy - 1,
                   turns=state.turns + 1, **changes)

def step(state, command):
    if state.rescued:
        return state, "Beacon already online."
    if command == "charge":
        if state.energy == MAX_ENERGY:
            return state, "The battery is already full."
        return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
    if state.energy == 0:
        return state, "Battery empty. Use charge to continue."
    if command.startswith("go "):
        direction = command[3:]
        target = WORLD[state.room].get(direction)
        if target is None:
            return state, "No exit that way."
        return spend(state, room=target), f"Arrived at {target}."
    if command == "take":
        part = PART_AT.get(state.room)
        if part is None:
            return state, "There is no part here."
        if part in state.parts:
            return state, "You already have that part."
        return spend(state, parts=(*state.parts, part)), f"Packed {part}."
    if command == "repair":
        if state.room != "Beacon":
            return state, "Repair at the Beacon."
        if not REQUIRED.issubset(state.parts):
            return state, "Find both the Coil and the Cell."
        return spend(state, rescued=True), "Beacon online!"
    return state, "Unknown command."

def render_map(state):
    rooms = []
    for room, exits in WORLD.items():
        current = " [Pip is here]" if room == state.room else ""
        links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())
        rooms.append(f"{room}{current}: {links}.")
    return "\n".join(rooms)

@lru_cache(maxsize=16)
def route(start, target):
    queue = deque([(start, ())])
    seen = {start}
    while queue:
        room, moves = queue.popleft()
        if room == target:
            return moves
        for direction, neighbour in WORLD[room].items():
            if neighbour not in seen:
                seen.add(neighbour)
                queue.append((neighbour, (*moves, direction)))
    return None

DEMO = ('go east', 'take', 'go west', 'go south', 'take', 'go east', 'repair')


def replay(commands):
    state = State()
    for command in commands:
        state, _ = step(state, command)
    return state


def run_demo():
    copied_log = json.dumps(DEMO)
    print(copied_log)
    state = replay(json.loads(copied_log))
    print(f"Replay: room={state.room}, turns={state.turns}, rescued={state.rescued}.")

def profile_routes():
    route.cache_clear()
    with cProfile.Profile() as profiler:
        for _ in range(40):
            route("Habitat", "Beacon")
    print("Profiled 40 route queries.")
    print(route.cache_info())
    pstats.Stats(profiler).sort_stats("cumulative").print_stats(5)

def describe(state):
    pack = ", ".join(state.parts) or "empty"
    restored = "online" if state.rescued else "offline"
    message = f"{state.room} | pack: {pack} | Beacon: {restored}"
    return f"{message} | energy: {state.energy} | turns: {state.turns}"

def normalise(text):
    return " ".join(text.lower().split())

def play():
    state = State()
    history = []
    print('Moonbase Rescue. Type go east, take, repair, status or quit.')
    while True:
        try:
            command = normalise(input("> "))
        except EOFError:
            break
        if command == "quit":
            break
        if command == "status":
            print(describe(state))
            continue
        if command == "map":
            print(render_map(state))
            continue
        if command == "history":
            print("History:", " > ".join(history) or "no moves yet")
            continue
        if command.startswith("hint "):
            target = command[5:].title()
            if target not in WORLD:
                print("Unknown destination.")
            else:
                moves = route(state.room, target)
                print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable")
            continue
        if command == "log":
            print(json.dumps(history))
            continue
        next_state, message = step(state, command)
        if next_state != state:
            history.append(command)
        state = next_state
        print(message)
    print("Mission ended.")

if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else ""
    if mode == "--demo":
        run_demo()
    elif mode == "--profile":
        profile_routes()
    else:
        play()

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–23
Line 1 from dataclasses import dataclass, replace
Bring dataclass, replace into this file from dataclasses. These names can now be used directly.
Line 2 from collections import deque
Bring deque into this file from collections. These names can now be used directly.
Line 3 import json
Bring in json. Its module name gives you access to the tools it contains.
Line 4 import sys
Bring in sys. Its module name gives you access to the tools it contains.
Line 5 import cProfile
Bring in cProfile. Its module name gives you access to the tools it contains.
Line 6 import pstats
Bring in pstats. Its module name gives you access to the tools it contains.
Line 7 from functools import lru_cache
Bring lru_cache into this file from functools. These names can now be used directly.
Lines 9–14 WORLD = { "Habitat": {"east": "Workshop", "south": "Greenhouse"}, "Workshop": {"west": "Habitat", "south": "Beacon"}, "Greenhouse": {"north": "Habitat", "east": "Beacon"}, "Beacon": {"north": "Workshop", "west": "Greenhouse"}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Line 15 PART_AT = {"Workshop": "Coil", "Greenhouse": "Cell"}
Work out the value on the right, then store it in PART_AT. Each colon pairs a key with its value.
Line 16 REQUIRED = {"Coil", "Cell"}
Work out the value on the right, then store it in REQUIRED.
Line 19 MAX_ENERGY = 8
Work out the value on the right, then store it in MAX_ENERGY.
Line 22 @dataclass(frozen=True)
Ask Python to create the usual data-handling methods from the listed fields.
Line 23 class State:
Define State, a class that groups related data or behaviour.
Lines 24–39
Line 24 room: str = "Habitat"
Describe the expected type of room as str and provide its starting value.
Line 25 parts: tuple = ()
Describe the expected type of parts as tuple and provide its starting value. Commas group these values into an ordered tuple.
Line 26 rescued: bool = False
Describe the expected type of rescued as bool and provide its starting value.
Line 27 energy: int = MAX_ENERGY
Describe the expected type of energy as int and provide its starting value.
Line 28 turns: int = 0
Describe the expected type of turns as int and provide its starting value.
Line 30 def spend(state, **changes):
Define spend, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Lines 31–32 return replace(state, energy=state.energy - 1, turns=state.turns + 1, **changes)
Leave this function now and hand the result back to the line that called it. Make a new state with the named changes. The old state stays available.
Line 34 def step(state, command):
Define step, a reusable piece of the program. Its input names are state, command. The indented body runs when something calls it.
Line 35 if state.rescued:
Run the indented block only if this check is true.
Line 36 return state, "Beacon already online."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 37 if command == "charge":
Run the indented block only if this check is true.
Line 38 if state.energy == MAX_ENERGY:
Run the indented block only if this check is true.
Line 39 return state, "The battery is already full."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Lines 40–52
Line 40 return replace(state, energy=MAX_ENERGY, turns=state.turns + 1), "Charged to 8."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Make a new state with the named changes. The old state stays available.
Line 41 if state.energy == 0:
Run the indented block only if this check is true.
Line 42 return state, "Battery empty. Use charge to continue."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 43 if command.startswith("go "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 44 direction = command[3:]
Work out the value on the right, then store it in direction. The slice copies a portion, stopping before the end index if one is given.
Line 45 target = WORLD[state.room].get(direction)
Work out the value on the right, then store it in target. Look up a key. Use the given fallback, or None, if the key is missing.
Line 46 if target is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 47 return state, "No exit that way."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 48 return spend(state, room=target), f"Arrived at {target}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
Line 49 if command == "take":
Run the indented block only if this check is true.
Line 50 part = PART_AT.get(state.room)
Work out the value on the right, then store it in part. Look up a key. Use the given fallback, or None, if the key is missing.
Line 51 if part is None:
Run the indented block only if this check is true. The is comparison checks identity, such as whether a result is exactly None.
Line 52 return state, "There is no part here."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Lines 53–66
Line 53 if part in state.parts:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 54 return state, "You already have that part."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 55 return spend(state, parts=(*state.parts, part)), f"Packed {part}."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns. Python fills the braces with values before it uses the text.
Line 56 if command == "repair":
Run the indented block only if this check is true.
Line 57 if state.room != "Beacon":
Run the indented block only if this check is true.
Line 58 return state, "Repair at the Beacon."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 59 if not REQUIRED.issubset(state.parts):
Run the indented block only if this check is true. The word not reverses which result counts as true. Check whether every item in this set appears in the other collection.
Line 60 return state, "Find both the Coil and the Cell."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 61 return spend(state, rescued=True), "Beacon online!"
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple. Run spend with the supplied inputs and come back here when it returns.
Line 62 return state, "Unknown command."
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 64 def render_map(state):
Define render_map, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 65 rooms = []
Work out the value on the right, then store it in rooms.
Line 66 for room, exits in WORLD.items():
Take one item at a time and give it to room, exits, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Lines 67–80
Line 67 current = " [Pip is here]" if room == state.room else ""
Work out the value on the right, then store it in current. Choose the first value if the condition is true, otherwise choose the value after else.
Line 68 links = ", ".join(f"{direction} to {end}" for direction, end in exits.items())
Work out the value on the right, then store it in links. Put strings together with the text before .join separating them. The expression supplies matching values one at a time to the operation using it. Python fills the braces with values before it uses the text.
Line 69 rooms.append(f"{room}{current}: {links}.")
Add the value to the end without replacing the earlier entries. Python fills the braces with values before it uses the text.
Line 70 return "\n".join(rooms)
Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them.
Line 72 @lru_cache(maxsize=16)
Reuse earlier results for matching inputs instead of doing the same work again.
Line 73 def route(start, target):
Define route, a reusable piece of the program. Its input names are start, target. The indented body runs when something calls it.
Line 74 queue = deque([(start, ())])
Work out the value on the right, then store it in queue. Create a queue that can efficiently take items from either end. Commas group these values into an ordered tuple.
Line 75 seen = {start}
Work out the value on the right, then store it in seen.
Line 76 while queue:
Check queue before each pass. Repeat the indented work while it is true.
Line 77 room, moves = queue.popleft()
Give each returned value to the matching name, from left to right. Remove and return the oldest entry at the front of the queue.
Line 78 if room == target:
Run the indented block only if this check is true.
Line 79 return moves
Leave this function now and hand the result back to the line that called it.
Line 80 for direction, neighbour in WORLD[room].items():
Take one item at a time and give it to direction, neighbour, then run the indented block. Make the dictionary's key and value pairs available to loop over.
Lines 81–98
Line 81 if neighbour not in seen:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 82 seen.add(neighbour)
Add the value to the set. A set keeps at most one copy.
Line 83 queue.append((neighbour, (*moves, direction)))
Add the value to the end without replacing the earlier entries. Commas group these values into an ordered tuple.
Line 84 return None
Leave this function now and hand the result back to the line that called it.
Line 86 DEMO = ('go east', 'take', 'go west', 'go south', 'take', 'go east', 'repair')
Work out the value on the right, then store it in DEMO. Commas group these values into an ordered tuple.
Line 89 def replay(commands):
Define replay, a reusable piece of the program. Its input names are commands. The indented body runs when something calls it.
Line 90 state = State()
Work out the value on the right, then store it in state. Create a mission state using the supplied field values and any defaults.
Line 91 for command in commands:
Take one item at a time and give it to command, then run the indented block.
Line 92 state, _ = step(state, command)
Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
Line 93 return state
Leave this function now and hand the result back to the line that called it.
Line 96 def run_demo():
Define run_demo, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 97 copied_log = json.dumps(DEMO)
Work out the value on the right, then store it in copied_log. Turn Python data into JSON text. This step does not write a file.
Line 98 print(copied_log)
Show the message or value in the output.
Lines 99–113
Line 99 state = replay(json.loads(copied_log))
Work out the value on the right, then store it in state. Run replay with the supplied inputs and come back here when it returns. Read JSON text or bytes and turn it back into Python data.
Line 100 print(f"Replay: room={state.room}, turns={state.turns}, rescued={state.rescued}.")
Show the message or value in the output. Python fills the braces with values before it uses the text.
Line 102 def profile_routes():
Define profile_routes, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 103 route.cache_clear()
Empty the saved results so this measurement starts fresh.
Line 104 with cProfile.Profile() as profiler:
Use the file or helper inside this indented block. Python closes it or finishes that context when the block ends.
Line 105 for _ in range(40):
Take one item at a time and give it to _, then run the indented block. Generate a sequence of integers that stops before the final limit.
Line 106 route("Habitat", "Beacon")
Run route with the supplied inputs and come back here when it returns.
Line 107 print("Profiled 40 route queries.")
Show the message or value in the output.
Line 108 print(route.cache_info())
Show the message or value in the output. Read statistics on results already saved and requests that needed fresh work.
Line 109 pstats.Stats(profiler).sort_stats("cumulative").print_stats(5)
Prepare the profiler’s recorded measurements for display. Choose the order in which measurements will be shown. Print the measured counts and timings for the selected functions.
Line 111 def describe(state):
Define describe, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 112 pack = ", ".join(state.parts) or "empty"
Work out the value on the right, then store it in pack. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Line 113 restored = "online" if state.rescued else "offline"
Work out the value on the right, then store it in restored. Choose the first value if the condition is true, otherwise choose the value after else.
Lines 114–128
Line 114 message = f"{state.room} | pack: {pack} | Beacon: {restored}"
Work out the value on the right, then store it in message. Python fills the braces with values before it uses the text.
Line 115 return f"{message} | energy: {state.energy} | turns: {state.turns}"
Leave this function now and hand the result back to the line that called it. Python fills the braces with values before it uses the text.
Line 117 def normalise(text):
Define normalise, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 118 return " ".join(text.lower().split())
Leave this function now and hand the result back to the line that called it. Put strings together with the text before .join separating them. Separate the string into a list of pieces. Return a lowercase copy so capital letters do not change a command.
Line 120 def play():
Define play, a reusable piece of the program. It needs no positional inputs. The indented body runs when something calls it.
Line 121 state = State()
Work out the value on the right, then store it in state. Create a mission state using the supplied field values and any defaults.
Line 122 history = []
Work out the value on the right, then store it in history.
Line 123 print('Moonbase Rescue. Type go east, take, repair, status or quit.')
Show the message or value in the output.
Line 124 while True:
Repeat the indented work until a break, return or error ends this path.
Line 125 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 126 command = normalise(input("> "))
Work out the value on the right, then store it in command. Run normalise with the supplied inputs and come back here when it returns. Show the prompt and wait for the player to type a line. The answer starts as text.
Line 127 except EOFError:
Run this part only when the try block raises EOFError.
Line 128 break
Leave the nearest loop immediately and continue after it.
Lines 129–141
Line 129 if command == "quit":
Run the indented block only if this check is true.
Line 130 break
Leave the nearest loop immediately and continue after it.
Line 131 if command == "status":
Run the indented block only if this check is true.
Line 132 print(describe(state))
Show the message or value in the output. Run describe with the supplied inputs and come back here when it returns.
Line 133 continue
Skip the rest of this pass and start the next loop check.
Line 134 if command == "map":
Run the indented block only if this check is true.
Line 135 print(render_map(state))
Show the message or value in the output. Run render_map with the supplied inputs and come back here when it returns.
Line 136 continue
Skip the rest of this pass and start the next loop check.
Line 137 if command == "history":
Run the indented block only if this check is true.
Line 138 print("History:", " > ".join(history) or "no moves yet")
Show the message or value in the output. With or, the first true result can settle the check. Put strings together with the text before .join separating them.
Line 139 continue
Skip the rest of this pass and start the next loop check.
Line 140 if command.startswith("hint "):
Run the indented block only if this check is true. Check whether this text begins with the given prefix.
Line 141 target = command[5:].title()
Work out the value on the right, then store it in target. Return words with title-style capital letters for display.
Lines 142–154
Line 142 if target not in WORLD:
Run the indented block only if this check is true. Membership checks ask whether an item or key is in a collection.
Line 143 print("Unknown destination.")
Show the message or value in the output.
Line 144 else:
Take this branch if the earlier checks for this decision were false.
Line 145 moves = route(state.room, target)
Work out the value on the right, then store it in moves. Run route with the supplied inputs and come back here when it returns.
Line 146 print("Route:", " then ".join(moves) if moves else "already there" if moves == () else "unreachable")
Show the message or value in the output. Choose the first value if the condition is true, otherwise choose the value after else. Put strings together with the text before .join separating them.
Line 147 continue
Skip the rest of this pass and start the next loop check.
Line 148 if command == "log":
Run the indented block only if this check is true.
Line 149 print(json.dumps(history))
Show the message or value in the output. Turn Python data into JSON text. This step does not write a file.
Line 150 continue
Skip the rest of this pass and start the next loop check.
Line 151 next_state, message = step(state, command)
Give each returned value to the matching name, from left to right. Run step with the supplied inputs and come back here when it returns.
Line 152 if next_state != state:
Run the indented block only if this check is true.
Line 153 history.append(command)
Add the value to the end without replacing the earlier entries.
Line 154 state = next_state
Work out the value on the right, then store it in state.
Lines 155–165
Line 155 print(message)
Show the message or value in the output.
Line 156 print("Mission ended.")
Show the message or value in the output.
Line 158 if __name__ == "__main__":
Start the mission when this file is run as the program. Importing it for a test leaves the mission stopped.
Line 159 mode = sys.argv[1] if len(sys.argv) > 1 else ""
Work out the value on the right, then store it in mode. Choose the first value if the condition is true, otherwise choose the value after else. Count the characters or items. The brackets look up a dictionary key or a position that starts at zero.
Line 160 if mode == "--demo":
Run the indented block only if this check is true.
Line 161 run_demo()
Run run_demo with the supplied inputs and come back here when it returns.
Line 162 elif mode == "--profile":
Run the indented block only if this check is true.
Line 163 profile_routes()
Run profile_routes with the supplied inputs and come back here when it returns.
Line 164 else:
Take this branch if the earlier checks for this decision were false.
Line 165 play()
Run play with the supplied inputs and come back here when it returns.

Test the mission

  • Run --profile and explain the first miss in your own words.
  • Clear the cache and query two different destinations once each. Predict the miss count.
  • Run the normal game and compare a hint with the result in lesson 35.

If something goes wrong

The profile starts with forty hits.
Call route.cache_clear before measuring so the first request has to calculate the result.
A path still uses a changed exit.
Clear cached routes whenever the world map changes.

Mission extension

Use the profile to compare forty requests for one route with forty requests spread over four routes. Record cache hits and misses for both.