Exercise 2: Reproducing and Fixing the Registration-Order Bug — Possible Solution ==================================================================== REPRODUCING IT (broken order, exactly as the chapter builds it) ------------------------------ routes = [ (compile_pattern('/users/'), 'user_detail'), # registered FIRST (compile_pattern('/users/new'), 'user_create_form'), # registered SECOND ] def resolve(path): for pattern, name in routes: if pattern.match(path): return name return '404' print(resolve('/users/new')) RESULT: 'user_detail' /users/'s own pattern matches [^/]+ (any non-slash characters at all), so it matches the literal string "new" just as happily as it would match "42" or any real user ID. Since it's checked first in the list, resolve() returns as soon as it matches - user_create_form's own pattern is never even reached, let alone checked. FIXING IT (swap the registration order) ------------------------------ routes = [ (compile_pattern('/users/new'), 'user_create_form'), # now FIRST (compile_pattern('/users/'), 'user_detail'), # now SECOND ] print(resolve('/users/new')) RESULT: 'user_create_form' With the specific, literal /users/new pattern checked before the general /users/ pattern, the literal match succeeds on the first comparison and resolve() returns immediately - the general pattern never gets a chance to intercept it, since the loop already stopped. CONFIRMING NOTHING ELSE BROKE ------------------------------ print(resolve('/users/42')) # still 'user_detail' "42" doesn't literally equal "new", so the first pattern (/users/new) fails to match it, and the loop correctly falls through to the second, general pattern, which does match. Reordering the two routes fixes the /users/new case without breaking real numeric IDs. WHY THIS WORKS AS AN ANSWER ---------------------------- It runs the exact broken configuration first and shows the real, concretely wrong output (not just describing that it would be wrong), then applies the fix, re-runs it, and confirms both the fixed case and a case that should remain unaffected (/users/42) still behave correctly - proving the fix is genuinely a reorder, not a rewrite.