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

# Compiling URLResolver and path converters

How does `path("stories/<slug:slug>/", ...)` turn into a compiled regular expression, and when is the URLconf tree actually imported and populated?

Chapter 2 showed that `django.setup` imports `django.urls` on line 16 — spending `124.78 ms` loading Django's URL machinery — yet never imports your project's own `"ROOT_URLCONF"` module at startup. Even `WSGIHandler.__init__` and `ASGIHandler.__init__` leave `"desk.urls"` untouched.

Verify that laziness in a fresh Python subprocess booting our newsroom project:

```text recording=ch04-routing
URLResolver lazy ROOT_URLCONF import, RoutePattern regexes, resolve(), and reverse()
  cold subprocess: after django.setup() desk.urls imported=False; after get_resolver()=False; after first resolve()=True (matched 'wire-status')
```

Not even `get_resolver()` (`django/urls/resolvers.py:get_resolver`) imports `"desk.urls"`! Calling `get_resolver()` hits the `@functools.cache`-wrapped `_get_cached_resolver` (`django/urls/resolvers.py:_get_cached_resolver`), which constructs a lightweight **`URLResolver`** shell (`django/urls/resolvers.py:URLResolver`) holding nothing more than the root prefix pattern `RegexPattern(r"^/")` and the string `"desk.urls"`. Only when the **very first request** calls `URLResolver.resolve` — touching the `@cached_property` `URLResolver.url_patterns` → `URLResolver.urlconf_module` (`django/urls/resolvers.py:URLResolver.urlconf_module`) — does Python run `importlib.import_module("desk.urls")`, importing every view module, form, and `"admin.site.urls"` tree!

Measure that cold first-request cost across five fresh subprocesses on our newsroom project:

```text recording=ch04-bench
Cold first-request URLconf load on desk/ (5 fresh subprocesses, milliseconds)
  stage                                  median_ms   least_ms
  import desk.urls (+ admin.site.urls)        6.22       6.13
  URLResolver._populate() (10 keys)         3.50       3.49
  Total first-request URL setup               9.72       9.65
```

On a six-route newsroom app, that first request absorbs **`9.72 ms`** of one-time URL setup (`6.22 ms` importing `"desk.urls"` and the admin URL tree, `3.50 ms` building the reverse lookup table). On a large production monolith with hundreds of views and admin models, that lazy first-request spike routinely reaches hundreds of milliseconds — which is why health-check warm-up probes hit a real URL after worker boot before load balancers send live traffic.

## From `path()` to `RoutePattern` and `URLPattern`

> **History.** Until Django 2.0, every route in Django was written as a raw regular expression via `url(r"^articles/(?P<year>[0-9]{4})/$", ...)` — verbose for beginners and unable to coerce captured strings into integers or UUIDs. In October 2016, Tom Christie, Sjoerd Job Postmus, and Aymeric Augustin authored DEP 0201 (`deps:final/0201-simplified-routing-syntax.rst`), modelled on Flask's typed route syntax: *"the underlying implementation for the typed URL syntax would actually be to expand the typed URLs out into the existing regex style... Hopefully many projects will migrate to `django.urls.path` (the carrot) before being forced to migrate to `django.urls.re_path` (the stick)."*

Every entry returned by `path()` (`django/urls/conf.py:path`) or `re_path()` (`django/urls/conf.py:re_path`) is one of two tree nodes:

- A leaf **`URLPattern`** (`django/urls/resolvers.py:URLPattern`) wrapping a pattern object (`RoutePattern` or `RegexPattern`), a view callback, optional default kwargs, and a `name`.
- A branch **`URLResolver`** (created when the view argument is an `include()` tuple or a list of sub-patterns like `"admin.site.urls"`), wrapping a prefix pattern and a child URLconf tree.

Inside `path()`, Django wraps the route string inside **`RoutePattern`** (`django/urls/resolvers.py:RoutePattern`). Its `__init__` immediately calls the `@functools.lru_cache`-memoized `_route_to_regex(str(route), is_endpoint)` (`django/urls/resolvers.py:_route_to_regex`), which scans `<converter:parameter>` placeholders with a regex, validates that every parameter name is a valid Python identifier with no whitespace inside `<...>`, looks up the **path converter** in `get_converters()` (`django/urls/converters.py:get_converters`), escapes all literal text via `re.escape`, substitutes `(?P<parameter>{converter.regex})`, and appends `\Z` when `"is_endpoint"` is `True`.

Django `6.1.3` registers five built-in converters in `django/urls/converters.py`:

| Converter | Class | Regex | `to_python` | `to_url` |
| --- | --- | --- | --- | --- |
| `"str"` *(default)* | `StringConverter` | `"[^/]+"` | `str` | `str` |
| `"int"` | `IntConverter` | `"[0-9]+"` | `int(value)` | `str(value)` |
| `"slug"` | `SlugConverter` | `"[-a-zA-Z0-9_]+"` | `str` | `str` |
| `"uuid"` | `UUIDConverter` | `"[0-9a-f]{8}-...-[0-9a-f]{12}"` | `uuid.UUID(value)` | `str(value)` |
| `"path"` | `PathConverter` | `".+"` | `str` | `str` |

Custom converters registered via `register_converter` (`django/urls/converters.py:register_converter`) store an instance in `REGISTERED_CONVERTERS` and explicitly clear the `@functools.cache` and `@functools.lru_cache` entries on `get_converters` and `_route_to_regex` — refusing duplicate names with `ValueError`. Notice one subtle detail in `RoutePattern.match` lines 333–336: if a custom converter's `to_python` raises `ValueError` (for example, rejecting month `"13"` after `"[0-9]{2}"` matched), Django treats it cleanly as a **non-match** (`return None`) and keeps scanning later patterns rather than raising a `500`!

## The compiled table — and `RoutePattern`'s zero-regex fast path

Inspect all six top-level routes compiled on our newsroom project:

```text recording=ch04-routing
  desk.urls compiled patterns:
    route                        kind          fast_str  converters  compiled_regex
    admin/                       RoutePattern  True      none        ^admin/
    <empty>                      RoutePattern  True      none        ^\Z
    editions/<slug:issue_date>/  RoutePattern  False     issue_date:SlugConverter  ^editions/(?P<issue_date>[-a-zA-Z0-9_]+)/\Z
    stories/<slug:slug>/         RoutePattern  False     slug:SlugConverter  ^stories/(?P<slug>[-a-zA-Z0-9_]+)/\Z
    submit/                      RoutePattern  True      none        ^submit/\Z
    wire/status/                 RoutePattern  True      none        ^wire/status/\Z
```

Look closely at the `"fast_str"` column (`not bool(pat.converters)`). Four of our six routes have `fast_str = True` — and `RoutePattern.match` (`django/urls/resolvers.py:RoutePattern.match`) carries a crucial optimization comment on line 325: *"Only use regex overhead if there are converters."*

- When `RoutePattern.converters` is non-empty (`"stories/<slug:slug>/"`), `RoutePattern.match` accesses `RoutePattern.regex` — triggering `LocaleRegexRouteDescriptor.__get__` (`django/urls/resolvers.py:LocaleRegexRouteDescriptor`), which compiles `RoutePattern._regex` lazily via `re.compile` and (for non-translated plain `str` routes) writes the compiled `re.Pattern` straight into `instance.__dict__["regex"]` so the descriptor never runs again!
- When `RoutePattern.converters` is **empty** (`"submit/"`, `"wire/status/"`, `"admin/"`), `RoutePattern.match` **never touches `RoutePattern.regex` at all**! Endpoints execute plain Python string equality (`self._route == path`); prefix includes execute `str.startswith` and `str.removeprefix`.

That single `if self.converters:` branch is what produced the **`4.3x` speedup** in our chapter-opening benchmark: at `500` routes, scanning static `path()` entries takes **`93.52 us`**, whereas scanning `500` `path("<slug:slug>/")` entries takes **`402.60 us`** and `500` `re_path()` entries takes **`432.19 us`**.

## Where URL compilation leaks

- **A syntax or import error in `"urls.py"` survives `django.setup()`.** Because `"ROOT_URLCONF"` is imported lazily on the first request, a broken import inside a view module will not crash `wsgi.py` at boot unless you run `manage.py check` (which walks `URLResolver.check`) or warm a health-check route during deploy.
- **Putting a leading slash on `path("/stories/", ...)` silently never matches.** The root `URLResolver` consumes the leading `"/"` with `RegexPattern(r"^/")` before testing `url_patterns`. Django's system check `"urls.W002"` warns about leading slashes, except when `APPEND_SLASH = False`.
- **Flat lists of hundreds of regex routes scale linearly.** Grouping routes under static prefix `include("api/", ...)` or `include("admin/", ...)` turns a `500`-pattern scan into a handful of `str.startswith` checks — skipping entire subtrees in fractions of a microsecond.

Now that the `URLResolver` tree is compiled, let's watch it run in both directions — resolving paths into `ResolverMatch` and inverting regexes back into validated URL strings — in [Matching paths and reversing names](resolving-and-reversing.md).
