File size: 64,265 Bytes
d086025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 | # 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:
1. **Do NOT create or modify any files under the test directories** (e.g.
`tests/`, `test/`, `testing/`, or files named `test_*.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.
2. **Your package MUST be importable by the name the tests use.** The hidden
tests `import` your package by its documented top-level name (see the
Project Directory Structure and API Usage Guide below). Provide a valid
`pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that
`pip install -e .` succeeds and the package imports cleanly. If your package
is not installable/importable, every test errors out and the reward is 0.
3. **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/repo` at 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**:
```bash
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**:
```bash
{
[ -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:
1. **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.
2. **Terminator stripping.** Remaining lines have every `\n` and every `\r`
character removed (two separate `str.replace` passes, so both Windows CRLF
endings and any stray carriage returns anywhere in the line disappear).
3. **Blank skip.** A line that is now exactly `''` is dropped. These are the
visual separators between TLD blocks in the source file.
4. **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()` is `True` after the first successful call: the
exact same `list` object 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
`PublicSuffixList` as 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 = None`
makes 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 no `reload()` or
`clear()` 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 `None` and 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) or `x // note` is *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 ` com` would 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-`None` cache), so the
disk is never read again.
- The `\n`/`\r` removal 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:
1. Hostname extracted from the URL (credentials, port, path, query, fragment
removed; `www` handled separately as its own flag/field).
2. Hostname labels split on `.`.
3. The longest trailing sequence of labels matching an entry in
`PublicSuffixList.get_list()` becomes `top_domain`; everything before it
becomes `domain` (plus `sub_domain` in 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**:
```python
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:
1. **Host token extraction.** A `re.search` anchored 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 with `re.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')` raises `AttributeError`. The token class does exclude `:`, so a port (`host:8080`) or colon-bearing userinfo (`user:pass@host`) makes the search return `None`, and the immediate `match.group('domain')` raises `AttributeError`.
2. **Tail-gram scan.** The host token is split on `.`; for `i` ascending, the dot-join of `parts[i:]` is tested for exact membership in the public suffix list obtained from `PublicSuffixList.get_list()` and sorted in place on every call. The first hit wins and `break`s, so scanning longest-tail-first selects the longest literal suffix present: for `www.example.co.uk`, `co.uk` beats `uk`. Ordering of entries in the list is irrelevant; the scan direction alone supplies precedence.
3. **Suffix-anchored full parse.** The winner is interpolated through `re.escape` into the master regex in `_parse_url_with_top_domain`; the `top_domain` group 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: in `sub.co.uk.co.uk` the earlier `co.uk` occurrence is rejected because a `.` follows it, so the parse is sub_domain `sub.co`, domain `uk`, top_domain `co.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's `sort()` 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 `in` scan 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.*.ck` yields tail-gram `*.ck`, which equals the wildcard entry, and the URL parses with top_domain `*.ck` (domain `*`); `!www.ck` behaves 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.ck` therefore resolves top_domain `ck`, not `bar.ck`.
- **Case-sensitive.** The list is lowercase and comparison is exact, so `Example.COM` finds no suffix and yields top_domain `None`.
- **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_domain` is 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 is `None`, and `re.escape(None)` coerces to the literal regex text `None`. Stage 2 then demands a `.None` segment 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_domain `None` reaches 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 returns `None` → `AttributeError` there.
- **Colon-less userinfo is not an error:** `@` passes through the token class, so `http://user@example.com` extracts token `user@example.com`, resolves top_domain `example.com`, and parses with `@` absorbed into the domain label (domain `user@example`, sub_domain `None`).
- **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 becomes `None`, and the `AttributeError` (`'NoneType' object has no attribute 'group'`) is raised in stage 2 when the regex demanding a literal `.None` segment finds no match.
- **Uppercase in the suffix region** → same unknown-suffix failure.
- **Empty labels** (`example..com`): stage 1 can pick `com`, 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
- `domain` and `top_domain` are the only fields guaranteed non-`None` when a `UrlObject` comes back; every other field yields `None` when the part is absent from the input.
- `protocol` is the text before `://` (http, https, ftp, ...); scheme-less input is accepted and leaves it `None`.
- `www` is the literal `www` or `None`. Its capture group can never contain a dot: `http://www..example.com` still yields `www == 'www'`, with the doubled dot absorbed by the sub-domain part.
- `sub_domain` holds the labels between the front of the host and the registrable domain, internal dots included (`my.subdomain`). Non-obvious: for a host that is only `www.<domain>.<tld>`, `sub_domain` is the string `www.` with a trailing dot, not `None`. That exact literal is why `get_base_url` special-cases `sub_domain != 'www.'` when rebuilding a base URL; dropping or keeping that dot is a regression a test suite will catch.
- `path` starts with `/` and runs to the `#` or `?` boundary. `dir` is the slash-terminated directory prefix (`/multiple/folders/`); `file` is the final segment (`sample.mp4`). The identity `path == dir + file` holds only when the path has no empty (`//`) segments: with double slashes the optional separator between the `dir` and `file` groups absorbs the extra `/`, so `/a//b` parses as `dir == '/a/'`, `file == 'b'`, yet `path == '/a//b'`; and for a path starting with `//` there is no `dir`, with the leading slash retained inside `file` (`//b` gives `dir is None`, `file == '/b'`). A path ending without a slash puts its last segment in `file`, never `dir` (`/folder/test` gives `dir == '/folder/'`, `file == 'test'`), and a lone segment like `/file.js` leaves `dir` as `None` while `path` and `file` are set.
- `fragment` is the text after `#`, cut at the first `?` (so `#frag?args=1` stores `frag`). An empty `#` yields `None`, never an empty string.
- `query` is a dict built from the raw query string: split on `&`; a bare key (`?flag`) maps to `None`; a value is only the text between the first and second `=`, so `a=b=c` stores `b` and the trailing `=c` is 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'}`) and `fragment` stays `None`; the text-after-`#` rule applies only when `#` occurs before any `?`. A missing `?`, or a trailing bare `?`, yields `query is None`.
## How a call proceeds (ordering)
1. 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 into `domain` (`http://user@example.com` returns `domain == '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.
2. 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 `.no` cannot swallow a `.noo`).
3. 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.com` and `www.example.com` both give `domain == 'example'`, `top_domain == 'com'`. Both inputs are scheme-less, so `protocol` is `None` for each; the fields that differ are `www` (`None` vs `'www'`) and `sub_domain` (`None` vs `'www.'`), not `protocol` and `www`.
- www/sub-domain interplay: `www.example.com` gives `www == 'www'`, `sub_domain == 'www.'`; `my.subdomain.example.com` gives `www is None`, `sub_domain == 'my.subdomain'`.
- Multi-label suffixes win over their shorter tails (`example.co.uk` resolves `top_domain == 'co.uk'`), a label that merely contains a suffix string is not split (`nogo.no` keeps `domain == 'nogo'`), and a suffix occurring mid-host (`test.com.hello.nogo.no`) is ignored in favor of the final suffix, leaving `sub_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.com` still resolves `top_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 an `AttributeError` rather than a `UrlObject` full of `None` fields. 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 a `TypeError` before 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 into `domain`.
- Hashability: when `query` is 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 `DeprecationWarning` and returns `get_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_url` calls `get_url` internally and reassembles `protocol://[www.][sub_domain.]domain.top_domain`, defaulting the scheme to `http://` when the input had none, omitting `www.` when absent, and suppressing the sub-domain when it is the `www.` 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**:
```python
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
1. The `DeprecationWarning` is emitted **first**, before any parsing work. A call whose URL later fails to parse has already warned.
2. 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.
3. 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 nested `query` dict) 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` — `None` unless the URL starts `<scheme>://` with `scheme` matching `[\w\d]+`. The scheme is captured verbatim (any case, e.g. `HTTP`); `http`, `https`, and `ftp` are ordinary cases.
- `www` — the string `'www'` only when the host literally begins with lowercase `www`; otherwise `None`. Uppercase `WWW` does not match.
- `sub_domain` — the raw host text preceding the registrable domain. Non-obvious: for a `www`-only host such as `www.example.com`, `sub_domain` is the string `'www.'` (the `www` token **plus its trailing dot**), not `None` and 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'`). `None` occurs only when nothing precedes the domain (`example.com`); a non-lowercase `WWW` prefix lands here verbatim (`'WWW'`) while `www` stays `None`.
- `domain`, `top_domain` — always non-`None` for any URL that parses at all. `domain` never contains a dot; `top_domain` may be multi-label (`co.uk`).
- `path`, `dir`, `file` — see the split rules below.
- `fragment` — text after `#` up to `?` or end; an empty fragment (`#`) normalizes to `None`.
## 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 to `None`.
- `k=a=b` → `{'k': 'a'}` — only the text between the first and second `=` survives; the trailing `=b` is dropped.
- `a=` → `{'a': ''}` — a token ending in `=` maps to the **empty string**, not `None`.
- 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
- `dir` is the leading, slash-terminated directory prefix: `/multiple/folders/` for `.../multiple/folders/with_a_file.js`. It requires at least one complete `segment/` pair, so a single segment with no trailing slash (`.../path`) gives `dir=None` and `file='path'`.
- `file` is the final path segment when the path does **not** end in `/`; it is `None` for directory-style URLs.
- `path` is the full concatenation (`/path/with/file.js`). For a bare trailing slash after the host (`http://example.com/`), `path` is the single string `'/'` while `dir` and `file` are both `None`.
- A `#` appearing **after** `?` is swallowed into the query value: `?a=1#sec` parses to `{'a': '1#sec'}` with `fragment=None`, because the query expression consumes to end-of-string. A `?` after `#` behaves normally (`#frag?a=1` → fragment `frag`, 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`, never `TypeError`.** Empty strings and `:port` URLs such as `http://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 back `None`. In all these cases the error is raised by `match.group` on that `None` match.
- **Host token found, suffix miss → `TypeError`.** A single-label host like `localhost`, an unknown TLD, or an uppercase host like `EXAMPLE.COM` (list membership is case-sensitive) leaves the located suffix as `None`, and the regex built from it fails immediately with `TypeError` (escaping `None`).
- **Userinfo is not a failure case.** `user@example.com` parses successfully: `@` is accepted inside the domain token, the tail gram `com` resolves against the bundled list, and the result is `sub_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 nested `query` dict.
- `get_base_url` calls `get_url` internally, so deriving base URLs never triggers the deprecation warning.
- Migration is mechanical: replace `result['field']` with `result.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**:
```python
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 fixes `top_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 to `get_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 as `get_url`/`parse_url` do; 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>
```
1. **Protocol** - the parsed scheme is echoed verbatim with `://` appended. If the input carried no scheme, the literal default `http://` is used; `https` is never inferred from context. Schemes are recognized as a `[\w\d]+` run followed by `://`, so schemes containing `-`, `+`, or `.` are not seen as protocols.
2. **www** - `www.` is re-attached only when the parse actually found a `www` prefix (the detection is case-sensitive: `WWW.example.com` parses as a sub-domain, not a www host).
3. **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 plain `www.` host such as `www.example.com`, the dot after `www` lands inside `sub_domain` (parsed value `'www.'`), and re-appending it would yield `www.www.`.
4. **domain + top_domain** - both are always present by the parser's contract, joined with a single `.`. `top_domain` is 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 `?query` all vanish, and a lone trailing slash is stripped too: `https://example.com/a/b.html?x=1#top` and `https://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.
- **`www` combined with an extra sub-domain does not round-trip.** For `www.blog.example.com` the parse yields `www='www'` and `sub_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 the `protocol`...`top_domain` fields from `get_url` directly instead.
- **Sub-domain shape asymmetry.** When the sub-domain has extra labels (`blog.example.com`) the parsed `sub_domain` carries 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 from `get_url` rather than introduced here.
- **Return type is always `str`** - never a `UrlObject` or dict - even though a full structured parse runs internally on every call.
## Minimal workflow
```python
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**:
```python
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 as `PublicSuffixList.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 with `encoding='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 to `None`
and assigned only after the full file is parsed; on error it stays `None`
so 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 `None` back to `_public_suffix_list` manually; 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
```python
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 `*.ck` for host `www.*.ck`; `!www.ck` behaves the same).
- The scan is longest-tail-first, so the longest literal matching suffix wins (`uk.com` beats `com`); entry order and the in-place `sort()` affect no precedence.
- `top_domain` is 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.uk` anchors on the trailing `co.uk`, giving sub_domain `sub.co`, domain `uk`).
- Missing suffix ⇒ `top_domain = None` ⇒ the regex embeds literal text `None` ⇒ `match.group` raises `AttributeError`; 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.com` parses with token `user@example.com`, top_domain `example.com`, and `@` absorbed into the domain label (domain `user@example`, sub_domain `None`). A trailing dot does not abort stage 1: the token is extracted with its empty final label, no tail-gram matches, top_domain becomes `None`, and the `AttributeError` is raised by the stage-2 match being `None` (the literal `.None` anchor finds nothing).
- On success: `domain` = label immediately before `top_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.b` for `a.b.example.co.uk`), else `None`; the first parse also sorts the cached suffix list in place.
## Usage
```python
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 `url` string, consumed as-is: no validation, normalization, or percent-decoding.
- Output is a `UrlObject` namedtuple with fixed field order `protocol, 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`; only `domain` and `top_domain` are guaranteed non-`None` on success.
- `query` is `dict` or `None`, never a string: `&`-separated groups, bare keys map to `None`, 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 and `fragment` stays `None`.
- `www` is `www` or `None` and can never contain a dot; a www-only host yields the literal `sub_domain == 'www.'` (trailing dot included).
- `path == dir + file` only when the path has no empty (`//`) segments; `dir` always ends with `/` or is `None`; the final segment is `file`, which stops at `?` or `#`. With double slashes the extra separator is consumed between `dir` and `file`, and for a path starting with `//` the leading slash is retained inside `file`, so `file` can contain a slash and is not always slash-less.
- `fragment` is the text after `#` truncated at the first `?`; the text-after-`#` rule applies only when `#` occurs before any `?`. Empty `#` or `?` sections produce `None`, not empty strings.
- `top_domain` is 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 into `domain` (`http://user@example.com` returns `domain == '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 a `None` match and raises `AttributeError`; (b) a located candidate with no known public suffix raises `TypeError` while building the anchored pattern (`re.escape` on 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 raises `TypeError`, not `AttributeError`. 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
```python
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 `dict` with all ten keys, in order `protocol, www, sub_domain, domain, top_domain, path, dir, file, fragment, query`; absent parts are `None`; `query` is a nested dict or `None`.
- Emit `DeprecationWarning` (exact upstream message) **before** parsing, with default `stacklevel` so 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) and `top_domain` (possibly multi-label, e.g. `co.uk`) are always set when a URL parses; every other field may be `None`.
- `www` matches only the lowercase literal token; `sub_domain` keeps the `www` token and trailing dot for `www.`-prefixed hosts (`'www.'` when no other subdomain exists), while ordinary subdomains carry no trailing dot.
- Path split: `dir` = leading slash-terminated prefix (needs at least `segment/`); `file` = final segment only when the path does not end in `/`; `path` = concatenation; trailing-slash-only host yields `path='/'` with `dir=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 than `None`; valueless params map to `None`; last duplicate wins; no URL-decoding; `?a=1#x` → `{'a': '1#x'}` with `fragment=None`.
- No-host-token inputs (empty string, `:port` URLs, whitespace prefixes) fail with `AttributeError` from `match.group` on a `None` match, never `TypeError`.
- Suffix-miss inputs (single-label hosts like `localhost`, unknown or uppercase TLDs — case-sensitive list membership) leave the suffix `None` and fail with `TypeError` from `re.escape(None)`; no exception translation in either class.
- Userinfo is not a failure: `user@example.com` parses with the userinfo folded into `domain` (`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
```python
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 `str` URL; output is a `str` containing 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 + `://` (literal `http://` 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_url` path is untouched), and shares only the public-suffix cache with the rest of the package.
- Known asymmetry: hosts with both `www` and 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
```python
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'
```
|