---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Matching paths and reversing names

How does `URLResolver.resolve` walk nested includes in order, and how does `reverse` invert regex patterns back into concrete URL strings?

Forward URL matching and backward URL generation look like mirror images of one another, yet Django implements them with two completely different data structures. Forward resolution walks the live `URLResolver` tree depth-first until a pattern matches; backward reversal builds a pre-inverted lookup table once in `URLResolver._populate` and then re-validates every generated string against the forward regex before returning it.

```text figure=url-compile-reverse
Two-way URL pipeline on desk/'s stories/<slug:slug>/ route (ch04-routing)

forward path (compile & resolve):
  1. path('stories/<slug:slug>/', name='story-detail')
  2. _route_to_regex() [lru_cache] -> ^stories/(?P<slug>[-a-zA-Z0-9_]+)/\Z  +  {'slug': SlugConverter}
  3. URLResolver.resolve('/stories/bridge-bond-passes/') [4 patterns tried]
     -> ResolverMatch(view_name='story-detail', kwargs={'slug': 'bridge-bond-passes'})

RoutePattern fast path: static routes with converters == {} (admin/, submit/, wire/status/) skip regex and run str == or startswith().

reverse path (populate, normalize & re-validate):
  1. URLResolver._populate() [walks reversed(url_patterns)]
     -> normalize() emits [('stories/%(slug)s/', ['slug'])] in reverse_dict
  2. _reverse_with_prefix() calls SlugConverter.to_url(val), substitutes, and runs re.search(forward_regex, candidate)
     - PASS (slug='bridge-bond-passes'): quote() -> '/stories/bridge-bond-passes/'
     - REJECT (slug='bad/slug'): fails forward regex -> NoReverseMatch
```

*Every compiled regex, normalized template, and result is parsed from `ch04-routing`. Notice that `reverse()` never trusts string formatting alone: it runs the forward regular expression back over the candidate URL before quoting and returning it.*

## Depth-first `resolve()` and `ResolverMatch`

When `BaseHandler.resolve_request` calls `URLResolver.resolve` (`django/urls/resolvers.py:URLResolver.resolve`), Django first runs `RegexPattern.match` on the root resolver (`RegexPattern(r"^/")`), stripping the leading `"/"` and producing `new_path`. It then loops sequentially through `URLResolver.url_patterns`:

- If the child is a leaf `URLPattern` (`django/urls/resolvers.py:URLPattern.resolve`), it tests `URLPattern.pattern` against `new_path`. On a hit, it merges captured kwargs with any `default_args` passed to `path()` and returns a **`ResolverMatch`** (`django/urls/resolvers.py:ResolverMatch`) carrying `func`, `args`, `kwargs`, `url_name`, `app_names`, `namespaces`, `route`, `captured_kwargs`, `extra_kwargs`, and `tried`.
- If the child is a nested `URLResolver` (an `include()`), it recurses. On a miss, the child raises `Resolver404` (`django/urls/exceptions.py:Resolver404`) carrying every pattern it attempted; the parent merges those paths into `tried` via `URLResolver._extend_tried` so the debug `404` page can print the complete tree of tried routes.
- Look closely at lines 688–693 of `django/urls/resolvers.py`: **if any named capture group matched, Django discards all unnamed positional groups** (`if not sub_match_dict: sub_match_args = args + sub_match.args`). Mixing named and unnamed groups in one `re_path` silently drops the unnamed captures.

Because `ResolverMatch` implements `__getitem__` over `(self.func, self.args, self.kwargs)`, `BaseHandler._get_response` can unpack `callback, callback_args, callback_kwargs = self.resolve_request(request)` while simultaneously exposing `resolver_match` on `HttpRequest`. And because `ResolverMatch.__reduce_ex__` explicitly raises `pickle.PicklingError`, a request carrying `resolver_match` can never be pickled accidentally into a cache or session.

## Inverting regexes in `_populate()` and `reverse()`

Calling **`reverse`** (`django/urls/base.py:reverse`) triggers `URLResolver._populate` (`django/urls/resolvers.py:URLResolver._populate`) the first time a language's lookup table is needed. Inside a thread-local recursion guard on `URLResolver._local` (`"populating"`), `_populate()` walks **`reversed(self.url_patterns)`** and builds three per-language dictionaries:

1. `reverse_dict` (a `MultiValueDict` keyed by *both* `URLPattern.name` and `URLPattern.callback`): for each leaf, Django feeds the compiled regex pattern string through `django.utils.regex_helper.normalize` (`django/utils/regex_helper.py:normalize`), a lightweight regex parser that expands alternations and named groups into a list of `(format_string, param_names)` pairs — turning `"^stories/(?P<slug>[-a-zA-Z0-9_]+)/\\Z"` into `[("stories/%(slug)s/", ["slug"])]`.
2. `namespace_dict`: maps each instance namespace name (`"metro"`, `"sports"`, `"admin"`) to `(prefix_pattern, sub_resolver)`.
3. `app_dict`: maps each application namespace (`"section"`, `"admin"`) to the list of instance namespaces mounted for that app.

Then `URLResolver._reverse_with_prefix` (`django/urls/resolvers.py:URLResolver._reverse_with_prefix`) walks the candidate tuples for the requested view name or callable:

1. Rejects mixed positional and keyword arguments (`ValueError`).
2. Checks that the supplied `args` count or `kwargs` keys match `params` (accounting for any `default_args`).
3. Converts every value to text via the converter's `StringConverter.to_url` (`django/urls/converters.py:StringConverter.to_url`, treating `ValueError` as a non-match so overloaded patterns with the same name can fall through cleanly).
4. Substitutes into the decoded `format_string` and **re-runs `re.search("^%s%s" % (re.escape(_prefix), pattern), candidate)`** against the decoded string! That re-validation is why `reverse("story-detail", kwargs={"slug": "bad/slug"})` raises `NoReverseMatch` instead of emitting a broken link containing a slash.
5. Percent-encodes the validated path with `urllib.parse.quote` (keeping RFC 3986 sub-delims) and passes it through `escape_leading_slashes` (`django/utils/http.py:escape_leading_slashes`) so a reversed path can never start with `"//"` and turn into a scheme-relative open redirect.

## Recording resolve, reverse, and namespaces live

Watch all four mechanics — `normalize`, `resolve`, `reverse` validation, and **URL namespaces** — run on Django `6.1.3`:

```text recording=ch04-routing
  normalize('^stories/(?P<slug>[-a-zA-Z0-9_]+)/\\Z') -> [('stories/%(slug)s/', ['slug'])]
  resolve('/stories/bridge-bond-passes/') -> view_name='story-detail' route='stories/<slug:slug>/' kwargs={'slug': 'bridge-bond-passes'} tried_patterns=4
  reverse('story-detail', kwargs={'slug': 'bridge-bond-passes'}) -> '/stories/bridge-bond-passes/'
  reverse('story-detail', slug='bad/slug') -> NoReverseMatch: Reverse for 'story-detail' with keyword arguments '{'slug': 'bad/slug'}' not found. 1 pattern(s) tried: ['stories/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
  namespaces (app_name='section'): reverse('section:front')='/sports/' reverse('metro:front')='/metro/' reverse('section:front', current_app='sports')='/sports/'
  resolve('/sports/') -> app_name='section' namespace='sports' view_name='sports:front'
```

STOP AND LOOK AT LINE 5 OF THAT TRACE!

We mounted the same reusable app (`app_name = "section"`) under two instance **URL namespaces** in order: `"metro/"` first (`namespace="metro"`), then `"sports/"` second (`namespace="sports"`). When we called `reverse("section:front")` *without* specifying `"current_app"`, Django returned **`"/sports/"`** — the **second** mount, not the first!

Why? Look back at line 558 of `django/urls/resolvers.py` and lines 64–73 of `django/urls/base.py`:
- `URLResolver._populate` walks `reversed(self.url_patterns)`, so it visits `"sports/"` *before* `"metro/"` and builds `app_dict["section"] = ["sports", "metro"]`.
- When `reverse("section:front")` sees that `"section"` is an application namespace not shared by any instance namespace name, and no `"current_app"` was passed, line 73 picks `app_list[0]` — which is `"sports"`, the **last** declaration in `"urls.py"`!
- Pass `current_app="metro"` (or reverse directly by instance namespace `"metro:front"`), and Django picks `"metro"` deterministically.

## Linear `resolve()` vs. constant-time `reverse()`

Compare the measured scaling of forward resolution and backward reversal across `10`, `50`, `200`, and `500` routes (`2,000` calls × `5` trials):

```text recording=ch04-bench
URL resolution O(N) scaling matching last route (2,000 calls x 5 trials, microseconds)
  routes  static_path_us  slug_path_us  re_path_us  slug/static  warm_reverse_us  populate_ms
  10                6.05         13.34       13.57         2.2x             5.58         0.11
  50               13.15         44.11       47.15         3.4x             5.59         0.48
  200              40.36        164.08      177.32         4.1x             5.64         1.90
  500              93.52        402.60      432.19         4.3x             5.70         4.78
```

Every `50x` jump in route count increases `resolve()` cost almost linearly — `6.05 -> 93.52 us` for static `path()`, `13.34 -> 402.60 us` for parameterized `path()`, `13.57 -> 432.19 us` for `re_path()` — while warm `reverse()` stays glued to **`5.6 us`** across all four sizes because `reverse_dict` is a hash table built once during `_populate()` (`0.11 -> 4.78 ms`).

## Where resolving and reversing leak

- **Calling `reverse()` at module import time crashes or deadlocks.** Importing a model or view that calls `reverse()` at class-definition time (for example, `success_url = reverse("edition-front")`) triggers `URLResolver._populate` while `"urls.py"` is still half-imported — causing circular-import `ImproperlyConfigured` errors! Use `reverse_lazy` (`django/urls/base.py:reverse_lazy`), which wraps `reverse` inside `django.utils.functional.lazy` so evaluation waits until runtime.
- **Duplicate names and double-mounted apps pick the LAST declaration.** Because `_populate()` iterates `reversed(self.url_patterns)`, both duplicate URL names and un-qualified `app_name` reversals prefer the last entry in `"urls.py"`, while forward `resolve()` prefers the first!
- **Named regexes with lookarounds or backreferences can break `normalize()`.** `django.utils.regex_helper.normalize` handles standard groups and alternations; exotic regex syntax in `re_path` may fail to reverse cleanly even when forward `resolve()` matches.

Once `resolve()` hands back a `ResolverMatch`, Django calls the view callback — which is rarely a raw function once decorators get involved. Let's unwrap view decorators next in [Function views and decorator wrappers](views-and-decorators.md).
