Download tasks/data/forward/adaptedas__url_parser.2635bab/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 64.3 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adaptedas__url_parser.2635bab/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adaptedas__url_parser.2635bab/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adaptedas__url_parser.2635bab/instruction.md
adaptedas/url_parser
Project Overview
The adaptedas/url_parser repository hosts url-parser, a lightweight Python package for parsing URLs of all types in vanilla Python, returning the parsed URL in convenient grouped form. Its purpose is to take any URL string and break it into its constituent parts without requiring external dependencies.
The package exposes three primary functions. parse_url accepts a URL and returns its sections as a dictionary; get_url performs the same parsing but returns the parts as an object with attribute access; and get_base_url reduces a URL to its main base address. Together they decompose URLs into well-defined fields - protocol, www prefix, sub_domain, domain, top_domain, dir, file, path, fragment, and query - each yielding None when absent from the URL, with domain and top_domain always present. Backwards compatibility is an explicit design concern: the dict-based parse_url API was preserved when the object-returning get_url was introduced, and version 2.1 added get_base_url for extracting the main URL from a string.
Architecturally the project is a compact, single-package library. The url_parser module contains the parsing logic in its __init__.py, supported by a bundled public suffix list (public_suffix_list.dat with a public_suffix_list.py helper) that enables accurate separation of registrable domains from their top-level suffixes. Unit tests reside under url_parser/tests and run via Python's unittest runner. The project is distributed on PyPI as url-parser for pip installation, with usage documented in README.md, release history in CHANGELOG.md, and continuous integration configuration under .github supporting ongoing maintenance.
Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.
Submission Constraints (read carefully — the evaluation depends on these)
This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.py/conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.
Install / Reconstruction Contract
Follow this contract before implementing the documented APIs:
- Project root:
/workspace/repoat runtime; the submitted repository root is.. - Package/distribution name:
url_parser - Package roots:
. - Install strategy:
editable-install - Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- Provision commands:
python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } export -f programgen_pip_install programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel programgen_pip_install python3 -m pip install 'setuptools>=61,<82' wheel ( programgen_install_report="$(mktemp)" trap 'rm -f "$programgen_install_report"' EXIT SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" ) - Runtime setup:
{ [ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; }; SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; } - Project root for installation:
. - Build-version environment:
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0,PDM_BUILD_SCM_VERSION=0.0.0,POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0,UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 - Test directory:
url_parser/tests - Test command:
bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= url_parser/tests/test_url_parser.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= url_parser/tests/test_url_parser.py); fi collect=(python3 -m pytest -q -o addopts= url_parser/tests/test_url_parser.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?' - Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.
Environment & Project Structure
- Language: python
- Build system: python
- Test command:
bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= url_parser/tests/test_url_parser.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= url_parser/tests/test_url_parser.py); fi collect=(python3 -m pytest -q -o addopts= url_parser/tests/test_url_parser.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?
Project Directory Structure
.github/workflows/pythonpublish.yml
.gitignore
CHANGELOG.md
LICENSE
MANIFEST.in
README.md
setup.py
url_parser/__init__.py
url_parser/public_suffix_list.dat
url_parser/public_suffix_list.py
API Usage Guide
Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.
Capability: Public suffix list loading and caching
Capability: Public suffix list loading and caching
Purpose
PublicSuffixList.get_list() turns the bundled Mozilla Public Suffix List data
file into a plain Python list of suffix strings, ready for exact-match lookups
when the parser must decide where a hostname's registrable domain ends and its
top-level suffix begins. The parse result is cached after the first successful
load: the finished list is stored as class state and every later call returns
that stored object directly. Failed loads and concurrent cold starts may parse
the file more than once, and a manual reset forces a re-parse, so the disk read
is not guaranteed to happen at most once per process — only each successful
load's result is cached and reused until the next reset. Callers never see
comment headers, blank separators, or line terminators — only bare suffix
strings such as com, co.uk, or virtualserver.io in their original file
order.
Single entry point, no instances required
get_list() is a @staticmethod, so the class itself is the interface: both
PublicSuffixList.get_list() and PublicSuffixList().get_list() work and have
identical effect. There is no constructor logic, no per-instance state, and no
configuration. The first successful invocation performs the load: the
class-level _public_suffix_list attribute flips from None to the parsed
list, and all subsequent invocations short-circuit straight to that stored
reference.
Load-and-filter pipeline (cold-cache loads)
Whenever the cache is cold — the first call, a retry after a failed load, or the call following a manual reset — the data file is resolved relative to the module's own real path, so the list is found regardless of the caller's working directory. The file is opened with UTF-8 encoding and read line by line, then filtered in this exact order:
- Comment skip. Any line whose first two characters are
//is dropped. This removes the license header, section markers such as// ===BEGIN ICANN DOMAINS===, and per-TLD annotations. The check runs on the raw line, before newline removal. - Terminator stripping. Remaining lines have every
\nand every\rcharacter removed (two separatestr.replacepasses, so both Windows CRLF endings and any stray carriage returns anywhere in the line disappear). - Blank skip. A line that is now exactly
''is dropped. These are the visual separators between TLD blocks in the source file. - Append. Everything else is appended verbatim — no lowercasing, no
trimming of spaces or unicode punctuation, no deduplication, no wildcard
or exception-line (
*,!) preprocessing.
After the loop, the finished list is assigned to the class attribute and
returned. For the shipped data file this yields 8,912 entries, from ac
(first data line) through the PRIVATE-DOMAIN section's newer additions at the
end.
Caching semantics that tests can observe
- Identity stability.
PublicSuffixList.get_list() is PublicSuffixList.get_list()isTrueafter the first successful call: the exact samelistobject is handed back, not a copy or a rebuild. This holds only between resets — each successful reload installs a brand-new list object, so the guarantee is per cached generation, not for the life of the process. - Shared mutability. Between resets, because no copy is made, mutating the returned list (appending, sorting, clearing) mutates the cache and is visible to every later caller — including the URL parser itself. Tests should treat the return value as read-only unless they intentionally want to patch the effective suffix set; a reset replaces the cached object and ends that patch's effect.
- Cache key is the class, not the module. The state lives on
PublicSuffixListas a class attribute, so it survives across importers that share the class object and resets naturally in a fresh process or interpreter. - Manual reset. Setting
PublicSuffixList._public_suffix_list = Nonemakes the next call re-read and re-parse the file from disk. The reload does not reuse or mutate the old list: it builds and caches a brand-new list object, so references returned before the reset become detached snapshots of the old suffix set — mutating them no longer affects later callers or URL parsing, and entries appended to them are lost on reload. This is the only sanctioned way to force a reload; there is noreload()orclear()API. - Failure does not cache. The attribute is assigned only after the entire
file has been consumed. If the open/read raises (file missing, decode
error), the cache stays
Noneand a retry attempt re-runs the whole load. - No locking. There is no synchronization. Two threads racing on a cold cache could both parse the file; both would end up with valid, equal lists and the last assignment wins, so results stay correct even if the work is duplicated.
Filtering edge cases
- Only
//at position 0 starts a comment. A line like// note(leading whitespace) orx // noteis not treated as a comment and would be appended with its whitespace intact. The shipped file never triggers this, but synthetic data files in tests could. - Indentation is not stripped: a data line
comwould be cached as" com"and then fail an exact==comparison against a parsed hostname label. - Whitespace-only lines (spaces/tabs, no newline left after stripping) are not blank and would be cached as-is for the same reason.
- Empty file → empty list, still cached as
[](a non-Nonecache), so the disk is never read again. - The
\n/\rremoval is global to the line, not just trailing; embedded control characters of those two kinds cannot survive into a cached entry.
Role in the URL-parsing workflow
parse_url, get_url, and get_base_url all depend on this list to
guarantee the documented invariant that domain and top_domain are always
present while everything else may be None. Conceptually the flow is:
- Hostname extracted from the URL (credentials, port, path, query, fragment
removed;
wwwhandled separately as its own flag/field). - Hostname labels split on
.. - The longest trailing sequence of labels matching an entry in
PublicSuffixList.get_list()becomestop_domain; everything before it becomesdomain(plussub_domainin between).
Because the suffix list is cached, the per-URL cost of that lookup is just a list scan — the disk I/O and parsing overhead is paid once per cached generation (the first successful load, and again only when a reset forces a re-parse), which is what keeps the zero-dependency parser fast when parsing many URLs. Any test that stubs or extends the returned list therefore directly changes how every subsequent URL in the same process is split.
Exact API Reference
url_parser.public_suffix_list.PublicSuffixList
- Import Path:
from url_parser.public_suffix_list import PublicSuffixList - Signature:
class PublicSuffixList:
def get_list()
Capability: Effective top-domain detection via public suffix matching
Effective top-domain detection via public suffix matching
Purpose
This capability decides which dot-suffix of a URL's host is the true public suffix (the top_domain), so that domain becomes the single label immediately left of it and everything further left lands in sub_domain. It is the step that makes www.example.co.uk parse as domain example / top_domain co.uk rather than co / uk.
Two-stage pipeline
get_url and parse_url route every input through _parse_url_with_public_suffix, which always runs the same sequence:
- Host token extraction. A
re.searchanchored at start-of-string or a/captures the first run of characters containing none of:,/,#,?, terminated by/,#,?or end-of-string. The(?:^|/)anchor makes token extraction itself tolerate a missing scheme, but that tolerance is extraction-only: stage 2's master regex is^-anchored (used withre.search, so it can only match at string start) and its sub_domain/domain character classes admit no/, so a leading//can never be consumed and the end-to-end parse of//host/...still fails —get_url('//example.com/x')raisesAttributeError. The token class does exclude:, so a port (host:8080) or colon-bearing userinfo (user:pass@host) makes the search returnNone, and the immediatematch.group('domain')raisesAttributeError. - Tail-gram scan. The host token is split on
.; foriascending, the dot-join ofparts[i:]is tested for exact membership in the public suffix list obtained fromPublicSuffixList.get_list()and sorted in place on every call. The first hit wins andbreaks, so scanning longest-tail-first selects the longest literal suffix present: forwww.example.co.uk,co.ukbeatsuk. Ordering of entries in the list is irrelevant; the scan direction alone supplies precedence. - Suffix-anchored full parse. The winner is interpolated through
re.escapeinto the master regex in_parse_url_with_top_domain; thetop_domaingroup can then only match that exact string, guarded by the lookahead(?![^/?#])— the suffix must end at end-of-string or immediately before/,#,?. This guard keeps the anchor aligned to the host's true end and forces the suffix anchor to the last occurrence of the suffix, not the first: insub.co.uk.co.ukthe earlierco.ukoccurrence is rejected because a.follows it, so the parse is sub_domainsub.co, domainuk, top_domainco.uk.
Stage 2 is strictly stricter than stage 1: a URL that survives stage 1 can still fail stage 2, never the reverse for the suffix itself.
State and cost
- The only persistent state is the class-level cache inside
PublicSuffixList; this capability'ssort()mutates it in place on the first parse and is idempotent afterwards. - No per-URL memoization: each call re-runs the sort (O(n log n) over the whole cached list) plus a linear
inscan of roughly ten thousand strings per tail-gram. Matching is plain string equality — no set, no trie.
Matching semantics
- Literal entries only. Wildcard (
*.ck) and exception (!www.ck) rows sit in the bundled list as literal strings and are inert only for hosts whose labels contain no*/!. The stage-1 token class[^:/#?]+admits both characters, so a host that literally contains them matches the row by exact equality:http://www.*.ckyields tail-gram*.ck, which equals the wildcard entry, and the URL parses with top_domain*.ck(domain*);!www.ckbehaves the same for hosts containing!. Multi-part suffixes otherwise resolve only where the list enumerates them literally (co.uk,uk.com,com.br, ...);foo.bar.cktherefore resolves top_domainck, notbar.ck. - Case-sensitive. The list is lowercase and comparison is exact, so
Example.COMfinds no suffix and yields top_domainNone. - No normalization. No lowercasing, percent-decoding or IDNA mapping precedes matching; a Unicode host parses only when its exact lowercase suffix is a literal entry (e.g.
.рф). - By construction
top_domainis always a dot-suffix of the extracted host token, and the result stores the stage-1 variable directly, so the reported value and the regex anchor cannot diverge.
Result contract
On success, domain is the single label directly before top_domain. sub_domain is www. — trailing dot included — when the www group matched and nothing else precedes domain; when www is absent it is the labels left of domain dot-joined with no trailing separator dot (e.g. a.b for a.b.example.co.uk); with a www prefix plus further labels both parts land inside it (www.a.b.example for www.a.b.example.co.uk); when empty it is stored as None. The literal www is additionally captured into www. domain and top_domain are always populated — but only for URLs that survive both regexes; failures raise rather than return partial data. Sample outcomes: https://www.example.co.uk/a/b?q=1 prints www. | example | co.uk; http://shop.uk.com prints | shop | uk.com (sub_domain None — the lazy sub-remainder prefers empty, so domain shop binds directly against uk.com).
Test-sensitive edge cases
- Unknown TLD (
example.invalidtld): no tail-gram matches, top_domain isNone, andre.escape(None)coerces to the literal regex textNone. Stage 2 then demands a.Nonesegment and fails →AttributeError: 'NoneType' object has no attribute 'group'. - Bare public suffix or single-label host (
co.uk,com,localhost): stage 1 may resolve a suffix, but stage 2 requires a label before it →AttributeError. top_domainNonereaches the output only if the URL literally contains.None. - Ports and colon-bearing userinfo (
example.com:8080,user:pass@host) abort in stage 1: the token class excludes:, so the search returnsNone→AttributeErrorthere. - Colon-less userinfo is not an error:
@passes through the token class, sohttp://user@example.comextracts tokenuser@example.com, resolves top_domainexample.com, and parses with@absorbed into the domain label (domainuser@example, sub_domainNone). - Trailing dot (
example.com.) does not abort stage 1:[^:/#?]+includes., so the token is extracted with its empty final label; no tail-gram (com., the bare dot) matches, top_domain becomesNone, and theAttributeError('NoneType' object has no attribute 'group') is raised in stage 2 when the regex demanding a literal.Nonesegment finds no match. - Uppercase in the suffix region → same unknown-suffix failure.
- Empty labels (
example..com): stage 1 can pickcom, but the label structure of stage 2 cannot align across the double dot →AttributeError. - Query/fragment safety: the host token stops at
?/#, so slashes inside a query (example.com?q=a/b) do not disturb extraction.
Re-implementation rule of thumb: extract the host token → pick the longest literal dot-suffix present in the lowercase list → re-parse the entire URL anchored on that suffix; any mismatch raises AttributeError rather than yielding a degraded result.
Exact API Reference
url_parser
- Import Path:
url_parser - Required Test Import Paths:
- url_parser
- Exact Test Import Statements:
- import url_parser
- Kind: module
- Behavior: Module required during hidden-test collection.
Capability: Structured URL object API (get_url)
Purpose
get_url is the object-shaped front door of the parser: one call turns a raw URL string into a UrlObject namedtuple whose ten fields are read as typed attributes (result.domain, result.top_domain, ...) instead of dictionary keys. It exists so callers get fixed-order, tuple-grade results, while the older dict API stays compatible for existing users. The other entry points funnel through it: parse_url delegates to it and converts the result with _asdict(), and get_base_url consumes it to rebuild a bare origin string. Re-implementers should treat get_url as the single parsing engine; the object wrapper is a thin, deterministic layer over the parse dictionary.
Shape of the result
UrlObject fields, in order: protocol, www, sub_domain, domain, top_domain, path, dir, file, fragment, query. Because it is a namedtuple, the object also behaves as a plain 10-tuple: positional indexing (result[3] is domain), iteration and unpacking in exactly that field order, len() == 10, equality with an equivalent 10-tuple, and a UrlObject(protocol=..., ...) repr. _asdict() returns a regular dict whose keys are exactly the historical parse keys, which is the sanctioned bridge between the object API and the dict API. _replace() builds a modified copy; the copy is shallow, so a present query dict is shared with the original.
Field types: every field is str or None, except query, which is dict or None.
Defaults and what is always present
domainandtop_domainare the only fields guaranteed non-Nonewhen aUrlObjectcomes back; every other field yieldsNonewhen the part is absent from the input.protocolis the text before://(http, https, ftp, ...); scheme-less input is accepted and leaves itNone.wwwis the literalwwworNone. Its capture group can never contain a dot:http://www..example.comstill yieldswww == 'www', with the doubled dot absorbed by the sub-domain part.sub_domainholds the labels between the front of the host and the registrable domain, internal dots included (my.subdomain). Non-obvious: for a host that is onlywww.<domain>.<tld>,sub_domainis the stringwww.with a trailing dot, notNone. That exact literal is whyget_base_urlspecial-casessub_domain != 'www.'when rebuilding a base URL; dropping or keeping that dot is a regression a test suite will catch.pathstarts with/and runs to the#or?boundary.diris the slash-terminated directory prefix (/multiple/folders/);fileis the final segment (sample.mp4). The identitypath == dir + fileholds only when the path has no empty (//) segments: with double slashes the optional separator between thedirandfilegroups absorbs the extra/, so/a//bparses asdir == '/a/',file == 'b', yetpath == '/a//b'; and for a path starting with//there is nodir, with the leading slash retained insidefile(//bgivesdir is None,file == '/b'). A path ending without a slash puts its last segment infile, neverdir(/folder/testgivesdir == '/folder/',file == 'test'), and a lone segment like/file.jsleavesdirasNonewhilepathandfileare set.fragmentis the text after#, cut at the first?(so#frag?args=1storesfrag). An empty#yieldsNone, never an empty string.queryis a dict built from the raw query string: split on&; a bare key (?flag) maps toNone; a value is only the text between the first and second=, soa=b=cstoresband the trailing=cis discarded; duplicate keys are overwritten by the later occurrence; nothing is percent-decoded and casing is preserved. The query capture extends to the end of the string: when#appears after?(http://example.com?a=1#frag), the#and everything after it stay inside the raw query value (query == {'a': '1#frag'}) andfragmentstaysNone; the text-after-#rule applies only when#occurs before any?. A missing?, or a trailing bare?, yieldsquery is None.
How a call proceeds (ordering)
- A host candidate is located as the run of characters after
^or/up to the next:,/,#,?, or end of string. The scan excludes only those four characters (plus the boundaries), so@is a legal candidate character: userinfo is captured into the candidate rather than rejected and typically ends up folded intodomain(http://user@example.comreturnsdomain == 'user@example',sub_domain is None,top_domain == 'com', with no exception). Only:-bearing hosts are disqualified by the scan — which is why ports (example.com:8080) are outside the supported grammar: the colon terminates the candidate. - The longest dot-separated tail of the host that appears in the bundled public suffix list becomes
top_domain; the match is anchored so the suffix must be followed by/,?,#, or end of string (a.nocannot swallow a.noo). - One anchored regex splits the remainder into the remaining eight fields, and every empty capture is normalized to
None.
The function is pure from the caller's perspective: arguments are not mutated, no parse state accumulates between calls, and each call returns a fresh object. The only indirect state is the public suffix list, which is loaded on first use and cached; re-sorting it per call is idempotent.
Edge cases the tests pin down
- Scheme-less and www-less inputs both parse:
example.comandwww.example.comboth givedomain == 'example',top_domain == 'com'. Both inputs are scheme-less, soprotocolisNonefor each; the fields that differ arewww(Nonevs'www') andsub_domain(Nonevs'www.'), notprotocolandwww. - www/sub-domain interplay:
www.example.comgiveswww == 'www',sub_domain == 'www.';my.subdomain.example.comgiveswww is None,sub_domain == 'my.subdomain'. - Multi-label suffixes win over their shorter tails (
example.co.ukresolvestop_domain == 'co.uk'), a label that merely contains a suffix string is not split (nogo.nokeepsdomain == 'nogo'), and a suffix occurring mid-host (test.com.hello.nogo.no) is ignored in favor of the final suffix, leavingsub_domain == 'test.com.hello'. - Long hyphenated/underscored subdomains (
very_long-and-complixated_subdomaind-for-page.mywebpageishere.com) parse without pathological backtracking; the sub-domain pattern is deliberately lazy and anchored. - Query text is never re-examined for suffixes:
http://test.com.hello.nogo.no?my_query_domain=www.test.comstill resolvestop_domain == 'no'and stores the full value under its key. - There is no error contract for unparseable hosts, and the failure mode depends on where the parse breaks. A colon-bearing host with nothing usable after the colon (
http://example.com:8080) yields no candidate at all; the internal match is consumed unchecked, so this surfaces anAttributeErrorrather than aUrlObjectfull ofNonefields. A candidate that is located but bears no known public suffix fails earlier and differently: the missing suffix is interpolated into the anchored pattern and raises aTypeErrorbefore any regex matching — a colon-bearing host with a trailing path segment (http://example.com:8080/x) lands in this class too, since the scan skips the disqualified candidate and the trailing segment carries no suffix.@-bearing hosts are in neither class: they parse, with the userinfo folded intodomain. - Hashability: when
queryis a dict the object is unhashable, so instances carrying a query cannot be used in sets or as dict keys; instances without a query hash and compare like tuples. Equality always compares all ten fields.
Working with the sibling APIs
- The dict API emits a
DeprecationWarningand returnsget_url(url)._asdict(): identical data, key access. Tests assert the same values through both surfaces, so any behavioral fix must land in the shared engine, not in one wrapper. get_base_urlcallsget_urlinternally and reassemblesprotocol://[www.][sub_domain.]domain.top_domain, defaulting the scheme tohttp://when the input had none, omittingwww.when absent, and suppressing the sub-domain when it is thewww.literal.
Exact API Reference
url_parser.get_url
- Import Path:
from url_parser import get_url - Required Test Import Paths:
- url_parser.get_url
- Exact Test Import Statements:
- import url_parser
- Signature:
def get_url(url: str) -> UrlObject
Capability: Dictionary parse API with deprecation handling (parse_url)
parse_url — legacy dictionary API with deprecation handling
Purpose and contract
parse_url exists to keep the package's original dict-based contract alive after the object-returning get_url API became the recommended entry point. It is deliberately a thin compatibility shim: announce deprecation, delegate to the shared parsing pipeline, and flatten the resulting UrlObject into a plain dict via _asdict(). A re-implementation must reproduce exactly three behaviors: the warning, the delegation, and the mapping shape. Everything about the parsed values is inherited from get_url; the dict-specific facts are the key set, the key order, and mapping-style access.
Execution order and state
- The
DeprecationWarningis emitted first, before any parsing work. A call whose URL later fails to parse has already warned. - Parsing proceeds exactly as in
get_url: the host's listed public suffix is located, then an anchored regular expression decomposes the URL against that suffix. - The namedtuple is converted with
_asdict(), producing a fresh dict on every call. There is no result caching and no shared mutable state in this path; mutating the returned dict (including the nestedquerydict) never affects later calls.
Return shape
The return value is always a dict containing all ten keys, in this insertion order (the UrlObject field order): protocol, www, sub_domain, domain, top_domain, path, dir, file, fragment, query. Keys are never omitted, so result[key] is safe for every key.
Values are str or None, with one exception: query is either None or a nested dict mapping parameter names to values.
protocol—Noneunless the URL starts<scheme>://withschemematching[\w\d]+. The scheme is captured verbatim (any case, e.g.HTTP);http,https, andftpare ordinary cases.www— the string'www'only when the host literally begins with lowercasewww; otherwiseNone. UppercaseWWWdoes not match.sub_domain— the raw host text preceding the registrable domain. Non-obvious: for awww-only host such aswww.example.com,sub_domainis the string'www.'(thewwwtoken plus its trailing dot), notNoneand not'www'; with an additional label it becomes'www.sub'. For ordinary subdomains the value is the bare dotted labels with no trailing dot ('mysubdomain','a.b').Noneoccurs only when nothing precedes the domain (example.com); a non-lowercaseWWWprefix lands here verbatim ('WWW') whilewwwstaysNone.domain,top_domain— always non-Nonefor any URL that parses at all.domainnever contains a dot;top_domainmay be multi-label (co.uk).path,dir,file— see the split rules below.fragment— text after#up to?or end; an empty fragment (#) normalizes toNone.
Query value semantics
The raw query string is split on &, then each token is split on every = and the stored value is only the second piece — the text between the first and second =; any further =-separated pieces are silently discarded:
a=1&b=2&flag→{'a': '1', 'b': '2', 'flag': None}— valueless parameters map toNone.k=a=b→{'k': 'a'}— only the text between the first and second=survives; the trailing=bis dropped.a=→{'a': ''}— a token ending in=maps to the empty string, notNone.- Duplicate keys: the last occurrence wins (plain dict overwrite in split order).
- No percent-decoding, no type coercion; values remain raw strings.
Path / dir / file split
diris the leading, slash-terminated directory prefix:/multiple/folders/for.../multiple/folders/with_a_file.js. It requires at least one completesegment/pair, so a single segment with no trailing slash (.../path) givesdir=Noneandfile='path'.fileis the final path segment when the path does not end in/; it isNonefor directory-style URLs.pathis the full concatenation (/path/with/file.js). For a bare trailing slash after the host (http://example.com/),pathis the single string'/'whiledirandfileare bothNone.- A
#appearing after?is swallowed into the query value:?a=1#secparses to{'a': '1#sec'}withfragment=None, because the query expression consumes to end-of-string. A?after#behaves normally (#frag?a=1→ fragmentfrag, query parsed).
The deprecation warning
The message is exactly parse_url is deprecated, use get_url instead with category DeprecationWarning, emitted via warnings.warn with the default stacklevel — so it is attributed to this module's line, not the caller's. Because CPython's default filters show a DeprecationWarning once per (message, module, lineno) and only in __main__, repeated calls in one process typically warn a single time, and under some runners not at all. Tests asserting on the warning must run inside warnings.catch_warnings() with simplefilter('always') (as assertWarns and pytest.warns do internally) or the warning can be filtered out before the assertion sees it.
Failure modes
Failures split into three classes, distinguished by exception type:
- No host token / no anchored match →
AttributeError, neverTypeError. Empty strings and:portURLs such ashttp://example.com:8080/leave the host-token regex(?:^|/)(?P<domain>[^:/#?]+)(?:[/#?]|$)with no match; a whitespace prefix (https://example.com) still locates the suffix normally, but the anchored match then comes backNone. In all these cases the error is raised bymatch.groupon thatNonematch. - Host token found, suffix miss →
TypeError. A single-label host likelocalhost, an unknown TLD, or an uppercase host likeEXAMPLE.COM(list membership is case-sensitive) leaves the located suffix asNone, and the regex built from it fails immediately withTypeError(escapingNone). - Userinfo is not a failure case.
user@example.comparses successfully:@is accepted inside the domain token, the tail gramcomresolves against the bundled list, and the result issub_domain=None,domain='user@example',top_domain='com'.
The parse is regex-anchored at the start of the string, so a whitespace prefix fails as above — but word-character garbage before the scheme does not break the match: it is absorbed into the scheme, and xxhttps://example.com parses with protocol='xxhttps'.
Relation to the sibling APIs
get_url(url)._asdict() == parse_url(url)holds exactly, including the nestedquerydict.get_base_urlcallsget_urlinternally, so deriving base URLs never triggers the deprecation warning.- Migration is mechanical: replace
result['field']withresult.field; key order in the dict matches the namedtuple field order, though dict equality ignores order.
Exact API Reference
url_parser.parse_url
- Import Path:
from url_parser import parse_url - Required Test Import Paths:
- url_parser.parse_url
- Exact Test Import Statements:
- import url_parser
- Signature:
def parse_url(url: str) -> dict
Capability: Base URL reconstruction (get_base_url)
Base URL reconstruction with get_base_url
Purpose
get_base_url is the reduction step of the library: it takes any URL string and returns only its addressing origin - scheme, www prefix, sub-domain, and registrable domain (domain plus top-level suffix) - as a plain str. Everything that lives "after the host" (directories, file name, fragment, query string) is parsed internally and then deliberately discarded. Typical uses: collapsing crawled links that differ only in fragment or query, deduplicating URL lists by host, and checking a link against an allow-listed origin without re-implementing public-suffix logic.
How it relates to the rest of the package
get_base_url is a thin consumer of the object API, not an independent parser:
- It delegates the entire parse to
get_url, so it inherits the whole public-suffix pipeline: the suffix list load/sort, the tail-gram scan that fixestop_domain, and the anchored structural regex that splits protocol,www,sub_domain,domain, and the rest. Every quirk of that parse is visible in the rebuilt string. - It does not route through
parse_url, so using it never triggers the deprecation warning that the dict API emits. - The function is pure with respect to its inputs: no mutation of the URL, no options, no output state. There is no parse-result caching: every call to
get_base_url- and equally every call toget_url- re-runs the complete parse from scratch (host-token scan, suffix-tail scan, anchored structural regex), so repeated calls repeat that work in full. The only work shared between calls is the public-suffix list load/cache, which the first call warms exactly asget_url/parse_urldo; results are deterministic because the parse is a pure function of the input and the bundled suffix list.
Reconstruction rules (fixed order)
The returned string is always assembled in this exact order:
<protocol> + "://" + <"www." if www else ""> + <sub_domain + "." unless sub_domain == "www."> + <domain> + "." + <top_domain>
- Protocol - the parsed scheme is echoed verbatim with
://appended. If the input carried no scheme, the literal defaulthttp://is used;httpsis never inferred from context. Schemes are recognized as a[\w\d]+run followed by://, so schemes containing-,+, or.are not seen as protocols. - www -
www.is re-attached only when the parse actually found awwwprefix (the detection is case-sensitive:WWW.example.comparses as a sub-domain, not a www host). - sub-domain - the parsed sub-domain is re-attached with one trailing
., but skipped entirely when its value is exactly the string'www.'. The guard exists because of how the parser stores hosts: for a plainwww.host such aswww.example.com, the dot afterwwwlands insidesub_domain(parsed value'www.'), and re-appending it would yieldwww.www.. - domain + top_domain - both are always present by the parser's contract, joined with a single
..top_domainis whatever the bundled suffix list identified (com,co.uk, ...).
Edge cases and test-sensitive behavior
- Scheme-less input gets
http://.get_base_url('example.com')returns'http://example.com'. This unconditional default is the most commonly asserted behavior. - Full stripping. Paths, file names,
#fragment, and?queryall vanish, and a lone trailing slash is stripped too:https://example.com/a/b.html?x=1#topandhttps://example.com/both reduce to'https://example.com'. A?or#terminates host detection cleanly, so query-only and fragment-only suffixes do not disturb the origin. - Round-trip correctness holds for three host shapes: bare (
example.com), www-only (www.example.com), and sub-domain-only (blog.example.com). The rule-3 guard exactly cancels the parser's dot placement in these cases. wwwcombined with an extra sub-domain does not round-trip. Forwww.blog.example.comthe parse yieldswww='www'andsub_domain='www.blog'; the rebuild re-emits both prefixes, producing...://www.www.blog.example.com. The guard only matches the exact value'www.', so the combined case slips through. If the true origin of such hosts matters, read theprotocol...top_domainfields fromget_urldirectly instead.- Sub-domain shape asymmetry. When the sub-domain has extra labels (
blog.example.com) the parsedsub_domaincarries no trailing dot ('blog'); only the www-only case stores the dot. Reconstruction normalizes both, which is why the guard compares against'www.'with the dot included. - Case is preserved. Scheme and host text are echoed exactly as parsed; no lowercasing happens anywhere in reconstruction.
- Ports, credentials, and suffix-less hosts are outside the model. Host detection stops at
:,/,#,?, and suffix detection needs a known public-suffix tail; an input the underlying parse cannot represent fails in the parse stage before any reconstruction runs, so failure modes are inherited fromget_urlrather than introduced here. - Return type is always
str- never aUrlObjector dict - even though a full structured parse runs internally on every call.
Minimal workflow
import url_parser
raw = 'https://www.example.com/docs/page.html?ref=x#install'
origin = url_parser.get_base_url(raw) # 'https://www.example.com'
parts = url_parser.get_url(raw) # same parse, full field access
assert origin.endswith(parts.domain + '.' + parts.top_domain)
Use get_url when callers need the discarded parts, and get_base_url when only the canonical origin matters; both perform the identical complete parse from scratch on every call with no parse-result caching, so calling one after the other repeats the full parse rather than reusing it - the only work shared between calls is the public-suffix list load/cache.
Exact API Reference
url_parser.get_base_url
- Import Path:
from url_parser import get_base_url - Required Test Import Paths:
- url_parser.get_base_url
- Exact Test Import Statements:
- import url_parser
- Signature:
def get_base_url(url: str) -> str
Detailed Implementation Nodes
Node: Public suffix list loading and caching
Implementation nodes
Functional constraints
get_list()is a@staticmethod; callable asPublicSuffixList.get_list()or via an instance. No arguments, no configuration, no instance state.- Data file is located relative to
os.path.realpath(__file__)of the module itself — never the CWD — and opened withencoding='utf-8'. - Filter order is fixed: drop lines whose first two chars are
//(checked before newline stripping) → remove all\n→ remove all\r→ drop lines equal to''→ append the rest verbatim. - No lowercasing, no whitespace stripping, no deduplication, no wildcard (
*) or exception (!) handling; file order is preserved exactly. - Cache is the class attribute
_public_suffix_list, initialized toNoneand assigned only after the full file is parsed; on error it staysNoneso the next call retries the load from disk (failed and concurrent cold loads can parse the file more than once per process). - After the first success — and until the next reset — every call returns the
same list object (
get_list() is get_list()→True); mutations of the returned list leak into the shared cache. Each successful reload installs a brand-new list object, so identity stability and shared mutability hold only between resets. - Reset/refresh = assign
Noneback to_public_suffix_listmanually; the next call re-parses the file and caches a brand-new list object, leaving pre-reset references as detached snapshots of the old suffix set (mutations to them no longer affect the cache or URL parsing). An empty data file still caches an empty list and prevents re-reads. - Not thread-safe for concurrent cold loads (possible duplicate parse), but the final cached value is always a complete, valid list.
- Shipped file yields 8,912 entries; consumers use it for longest-suffix
matching to split hostnames into
domain/sub_domain/top_domain.
Usage example
from url_parser.public_suffix_list import PublicSuffixList
suffixes = PublicSuffixList.get_list() # first call: parse the .dat file
assert PublicSuffixList.get_list() is suffixes # later calls return the same object
assert suffixes[0] == "ac" # file order kept, comments/blanks removed
assert "\n" not in suffixes[0] # entries are bare suffix strings
suffixes.append("example.internal") # mutates the shared cache
assert "example.internal" in PublicSuffixList.get_list()
PublicSuffixList._public_suffix_list = None # force a re-read; reload caches a NEW object
fresh = PublicSuffixList.get_list()
assert fresh is not suffixes # pre-reset references are detached snapshots
assert "example.internal" not in fresh # appends to the old reference are lost on reload
Node: Effective top-domain detection via public suffix matching
Functional constraints
- Pipeline order is fixed and load-bearing: host-token extraction → longest-first tail-gram membership scan (break on first hit) → full regex re-parse anchored on
re.escape(top_domain). - Suffix membership is exact, case-sensitive, literal equality against the loaded list; wildcard (
*) and exception (!) rows are inert only for hosts whose labels contain neither character —*/!are admitted inside host tokens ([^:/#?]+), so a host that literally contains those characters matches the row by exact equality (top_domain*.ckfor hostwww.*.ck;!www.ckbehaves the same). - The scan is longest-tail-first, so the longest literal matching suffix wins (
uk.combeatscom); entry order and the in-placesort()affect no precedence. top_domainis always a dot-suffix of the host token and is copied from the scan result into the output; stage 2 enforces the(?![^/?#])end guard so the anchor sits at the host's end — the last occurrence of the suffix when it appears more than once (earlier occurrences followed by more host text are rejected by the guard, e.g.sub.co.uk.co.ukanchors on the trailingco.uk, giving sub_domainsub.co, domainuk).- Missing suffix ⇒
top_domain = None⇒ the regex embeds literal textNone⇒match.groupraisesAttributeError; bare-suffix or single-label hosts fail the same way because a label must precede the suffix. - Host tokens exclude only
:(besides the//#/?terminators): ports and colon-bearing userinfo (user:pass@host) abort in stage 1.@passes through the token class, so colon-less userinfo is a test-sensitive non-error outcome:http://user@example.comparses with tokenuser@example.com, top_domainexample.com, and@absorbed into the domain label (domainuser@example, sub_domainNone). A trailing dot does not abort stage 1: the token is extracted with its empty final label, no tail-gram matches, top_domain becomesNone, and theAttributeErroris raised by the stage-2 match beingNone(the literal.Noneanchor finds nothing). - On success:
domain= label immediately beforetop_domain;sub_domain=www.(with dot) when the www group matched with nothing else before domain, otherwise the dot-joined labels left of domain with no trailing dot (a.bfora.b.example.co.uk), elseNone; the first parse also sorts the cached suffix list in place.
Usage
from url_parser import get_url
for url in ('https://www.example.co.uk/a/b?q=1', 'http://shop.uk.com', 'example.com:8080'):
try:
o = get_url(url)
print(o.sub_domain, '|', o.domain, '|', o.top_domain)
except AttributeError as err:
print('unparseable:', err)
# www. | example | co.uk
# | shop | uk.com (longest literal suffix wins over com)
# unparseable: 'NoneType' object has no attribute 'group'
Node: Structured URL object API (get_url)
Functional constraints
- Input is one
urlstring, consumed as-is: no validation, normalization, or percent-decoding. - Output is a
UrlObjectnamedtuple with fixed field orderprotocol, www, sub_domain, domain, top_domain, path, dir, file, fragment, query; indexing, iteration,len() == 10, tuple equality,_asdict(), and_replace()all work as for any namedtuple. - Every absent part is
None; onlydomainandtop_domainare guaranteed non-Noneon success. queryisdictorNone, never a string:&-separated groups, bare keys map toNone, a value is the text between the first and second=only, duplicate keys last-wins, keys/values keep raw casing and order. The capture runs to end of string, so a#following?remains part of the query value andfragmentstaysNone.wwwiswwworNoneand can never contain a dot; a www-only host yields the literalsub_domain == 'www.'(trailing dot included).path == dir + fileonly when the path has no empty (//) segments;diralways ends with/or isNone; the final segment isfile, which stops at?or#. With double slashes the extra separator is consumed betweendirandfile, and for a path starting with//the leading slash is retained insidefile, sofilecan contain a slash and is not always slash-less.fragmentis the text after#truncated at the first?; the text-after-#rule applies only when#occurs before any?. Empty#or?sections produceNone, not empty strings.top_domainis the longest dot-tail of the host present in the bundled suffix list, anchored so it must be followed by/,?,#, or end of string.- The host-candidate scan excludes only
:,/,#,?(plus boundaries). Hosts containing:(ports) are unsupported — the colon terminates the candidate — but@(userinfo) is a legal candidate character and is not rejected: userinfo is captured into the candidate and typically folded intodomain(http://user@example.comreturnsdomain == 'user@example', no exception). Failure modes split in two: (a) no host candidate found — e.g. a port-bearing host with nothing usable after the colon — consumes aNonematch and raisesAttributeError; (b) a located candidate with no known public suffix raisesTypeErrorwhile building the anchored pattern (re.escapeon the missing suffix), before any regex matching. A colon-bearing host with a trailing path segment (http://example.com:8080/x) skips the disqualified candidate and ends up suffix-less, so it raisesTypeError, notAttributeError. There is no documented exception contract. - The call is pure per invocation; the first call may additionally load and cache the public suffix list.
Usage
import url_parser
r = url_parser.get_url('https://api.example.co.uk/v2/files/report.pdf?year=2024&draft')
r.protocol # 'https'
r.www # None
r.sub_domain # 'api'
r.domain # 'example'
r.top_domain # 'co.uk'
r.path # '/v2/files/report.pdf'
r.dir # '/v2/files/'
r.file # 'report.pdf'
r.fragment # None
r.query # {'year': '2024', 'draft': None}
Node: Dictionary parse API with deprecation handling (parse_url)
Functional constraints
- Return a plain
dictwith all ten keys, in orderprotocol, www, sub_domain, domain, top_domain, path, dir, file, fragment, query; absent parts areNone;queryis a nested dict orNone. - Emit
DeprecationWarning(exact upstream message) before parsing, with defaultstacklevelso it is attributed to the module. - Delegation contract: result must equal
get_url(url)._asdict()— one shared parse pipeline, no caching, fresh dict per call. domain(dot-free) andtop_domain(possibly multi-label, e.g.co.uk) are always set when a URL parses; every other field may beNone.wwwmatches only the lowercase literal token;sub_domainkeeps thewwwtoken and trailing dot forwww.-prefixed hosts ('www.'when no other subdomain exists), while ordinary subdomains carry no trailing dot.- Path split:
dir= leading slash-terminated prefix (needs at leastsegment/);file= final segment only when the path does not end in/;path= concatenation; trailing-slash-only host yieldspath='/'withdir=None,file=None. - Query: split on
&, then on every=; the stored value is only the second segment (text between the first and second=), any further=-separated parts are discarded (k=a=b→{'k': 'a'});a=yields''rather thanNone; valueless params map toNone; last duplicate wins; no URL-decoding;?a=1#x→{'a': '1#x'}withfragment=None. - No-host-token inputs (empty string,
:portURLs, whitespace prefixes) fail withAttributeErrorfrommatch.groupon aNonematch, neverTypeError. - Suffix-miss inputs (single-label hosts like
localhost, unknown or uppercase TLDs — case-sensitive list membership) leave the suffixNoneand fail withTypeErrorfromre.escape(None); no exception translation in either class. - Userinfo is not a failure:
user@example.comparses with the userinfo folded intodomain(sub_domain=None,domain='user@example',top_domain='com'). - Test-sensitive: default warning filters deduplicate per call site — assert with
catch_warnings+simplefilter('always').
Example
import warnings
import url_parser
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
data = url_parser.parse_url("https://sub.example.co.uk/dir/file.js?a=1&flag")
assert caught and caught[0].category is DeprecationWarning
assert data["top_domain"] == "co.uk" and data["domain"] == "example"
assert data["sub_domain"] == "sub"
assert data["path"] == "/dir/file.js" and data["file"] == "file.js"
assert data["query"] == {"a": "1", "flag": None}
Node: Base URL reconstruction (get_base_url)
Functional constraints
- Input is a single
strURL; output is astrcontaining only the origin: protocol +www+ sub-domain + registrable domain. No options, no extra parameters. - Delegates to
get_url, so the URL must be representable by the parser: the host token must end in a public suffix known to the bundled list and match the structural regex. Unrepresentable inputs fail in the parse stage before reconstruction; this function adds no failure modes of its own. - Assembly order is fixed: parsed protocol verbatim +
://(literalhttp://when the input had no scheme) ->www.only if a www prefix was parsed ->sub_domain+.unless the value is exactly'www.'->domain+.+top_domain. - Everything after the top-level suffix is parsed then dropped: path, dir, file, fragment, query, and a lone trailing slash never reach the result. Case is preserved verbatim.
- Pure function: mutates nothing, emits no warnings (the deprecated
parse_urlpath is untouched), and shares only the public-suffix cache with the rest of the package. - Known asymmetry: hosts with both
wwwand an additional sub-domain (www.blog.example.com) rebuild with both prefixes re-attached (www.www.blog...), because the skip guard only matches the exact value'www.'.
Example
import url_parser
url_parser.get_base_url('https://www.example.com/a/b.html?x=1#top')
# 'https://www.example.com'
url_parser.get_base_url('example.com')
# 'http://example.com'
url_parser.get_base_url('ftp://files.example.com')
# 'ftp://files.example.com'