Compiling URLResolver and path converters
How does path("stories/ 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 and ASGIHandler leave "desk.urls" untouched.
Verify that laziness in a fresh Python subprocess booting our newsroom project:
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() imports "desk.urls"! Calling get_resolver() hits the @functools.cache-wrapped _get_cached_resolver, which constructs a lightweight URLResolver shell holding nothing more than the root prefix pattern RegexPattern(r"^/ and the string "desk.urls". Only when the very first request calls URLResolver — touching the @cached_property URLResolver → URLResolver — does Python run importlib, importing every view module, form, and "admin tree!
Measure that cold first-request cost across five fresh subprocesses on our newsroom project:
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
Every entry returned by path() or re_path() is one of two tree nodes:
- A leaf
URLPatternwrapping a pattern object (RoutePatternorRegexPattern), a view callback, optional default kwargs, and aname. - A branch
URLResolver(created when the view argument is aninclude()tuple or a list of sub-patterns like"admin), wrapping a prefix pattern and a child URLconf tree..site .urls"
Inside path(), Django wraps the route string inside RoutePattern. Its __init__ immediately calls the @functools-memoized _route_to_regex(str(route), is_endpoint), which scans <converter: 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(), escapes all literal text via re.escape, substitutes (?P<parameter>{converter, and appends \Z when "is_endpoint" is True.
Django 6.1.3 registers five built-in converters in django/:
| Converter | Class | Regex | to_python |
to_url |
|---|---|---|---|---|
"str" (default) |
Class StringConverter |
Regex "[^/]+" |
to_python str |
to_url str |
"int" |
Class IntConverter |
Regex "[0-9]+" |
to_python int(value) |
to_url str(value) |
"slug" |
Class SlugConverter |
Regex "[-a-zA-Z0-9_]+" |
to_python str |
to_url str |
"uuid" |
Class UUIDConverter |
Regex "[0-9a-f]{8}-...-[0-9a-f]{12}" |
to_python uuid.UUID(value) |
to_url str(value) |
"path" |
Class PathConverter |
Regex ".+" |
to_python str |
to_url str |
Custom converters registered via register_converter store an instance in REGISTERED_CONVERTERS and explicitly clear the @functools.cache and @functools entries on get_converters and _route_to_regex — refusing duplicate names with ValueError. Notice one subtle detail in RoutePattern 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:
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). Four of our six routes have fast_str = True — and RoutePattern carries a crucial optimization comment on line 325: “Only use regex overhead if there are converters.”
- When
RoutePatternis non-empty (.converters "stories/),<slug: slug>/ " RoutePatternaccesses.match RoutePattern— triggering.regex LocaleRegexRouteDescriptor, which compiles.__get__ RoutePatternlazily via._regex re.compileand (for non-translated plainstrroutes) writes the compiledre.Patternstraight intoinstanceso the descriptor never runs again!.__dict__["regex"] - When
RoutePatternis empty (.converters "submit/","wire/status/","admin/"),RoutePatternnever touches.match RoutePatternat all! Endpoints execute plain Python string equality (.regex self); prefix includes execute._route == path str.startswithandstr.removeprefix.
That single if self 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: 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"survivesdjango.setup(). Because"ROOT_URLCONF"is imported lazily on the first request, a broken import inside a view module will not crashwsgi.pyat boot unless you runmanage.py check(which walksURLResolver) or warm a health-check route during deploy..check - Putting a leading slash on
path("/silently never matches. The rootstories/ ", ...) URLResolverconsumes the leading"/"withRegexPattern(r"^/before testing") url_patterns. Django’s system check"urls.W002"warns about leading slashes, except whenAPPEND_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 ofstr.startswithchecks — 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.