An error in one address candidate should not prevent inspection of the remaining candidates, but an item that stays unresolved must not vanish from failure reporting. This small synthetic function and its execution records separate those decisions without returning the original addresses.
The caller supplies the base and candidate order
This helper discovers no sites or image attributes. It accepts an absolute HTTP-family base from trusted configuration and an already ordered list of strings. The list is limited to thirty-two candidates; each string, including the base, is limited to 4,096 Python characters. The full contract is checked before iteration, so an invalid later type is rejected even when the first candidate looks usable.
An invalid base is shared configuration failure and stops the call with ValueError. A ValueError raised while resolving and parsing an individual candidate instead becomes that candidate’s parse_error. Configuration defects and local candidate errors deliberately have different continuation policies. These limits belong to this independent example, not to a newly imposed input policy across the native collector.
Inspect only through the first interpretable candidate
Empty strings are excluded as empty; parsed but unsupported schemes are excluded as unsupported_scheme. When resolution and parsing produce an HTTP-family scheme, the helper chooses that candidate’s zero-based index and stops. Candidates after that point were not attempted, so their possible errors are not diagnosed. attempted counts only the entries actually inspected.
The result contains no base, selected address or raw exception message that might contain input text. Fixed reasons and indices provide the diagnostic structure instead. This is not proof that every sensitive input has been anonymized: candidate count and ordering can themselves be sensitive in a particular business. Review those structural details before sharing operational records.
Complete code for isolating candidate parsing failures
The implementation below uses only Python’s standard library. It resolves with urljoin, inspects with urlsplit and handles only ValueError within that boundary. A test injects an unexpected RuntimeError and checks that it reaches the caller. The helper is intentionally not a mechanism for continuing after every possible defect.
A selected_index lets the caller locate the same original input. Before actual access, the host must apply its own policy and resolve the address for that operation. The helper creates neither an approved host nor a safe storage path. Understanding exactly what the result establishes matters more than merely copying the function into a larger program.
Explore the implementation
Complete independent synthetic implementation
"""Ordered syntax selection; this module never fetches a resource."""
from urllib.parse import urljoin, urlsplit
MAX_CANDIDATES = 32
MAX_CHARACTERS = 4096
def select_candidate(base, candidates):
"""Return an index and bounded diagnostics, never the input addresses."""
if type(base) is not str or not base or len(base) > MAX_CHARACTERS:
raise ValueError("invalid base contract")
parsed_base = urlsplit(base)
if parsed_base.scheme not in ("http", "https") or not parsed_base.hostname:
raise ValueError("base must be an absolute HTTP(S) address")
if type(candidates) is not list or len(candidates) > MAX_CANDIDATES:
raise ValueError("expected at most 32 ordered candidates")
if any(type(value) is not str or len(value) > MAX_CHARACTERS
for value in candidates):
raise ValueError("candidate must be a string of at most 4096 characters")
errors, skipped = [], []
chosen = None
attempted = 0
for index, raw in enumerate(candidates):
attempted += 1
value = raw.strip()
if not value:
skipped.append({"index": index, "reason": "empty"})
continue
try:
parsed = urlsplit(urljoin(base, value))
except ValueError:
errors.append({"index": index, "reason": "parse_error"})
continue
if parsed.scheme not in ("http", "https"):
skipped.append({"index": index, "reason": "unsupported_scheme"})
continue
chosen = index
break
return {
"selected_index": chosen,
"attempted": attempted,
"parse_errors": errors,
"skipped": skipped,
"unresolved_parse_failure": chosen is None and bool(errors),
"performs_fetch": False,
"security_approval": False,
}
Do not mark a resolved item failed because an earlier candidate broke
When an early candidate fails to parse but a later candidate is selected, parse_errors remains populated while unresolved_parse_failure is false. The signal becomes true only when parsing errors occurred and no candidate was ultimately selected. An image-level counter can treat true as one unresolved image; the error-array length is not a failed-image count.
If the list contains only unsupported data or blob forms, selected_index is None and this parsing-failure signal is false. No selection means neither complete acquisition nor necessarily a parsing failure. A host should report the reason for nonselection separately from transfer outcomes. There is no code here that turns selection success into download success.
Six records are not six web-collection results
Six generated results cover malformed-then-valid, all malformed, unsupported-only, relative selection, valid IPv6 and stopping at the first selected candidate. The selector below reads that JSON. It runs no Python, contacts no network and accepts no visitor file upload. Its purpose is to make changing selection and error indices inspectable.
The actual bilingual inline scripts are connected to DOM stubs for two initial displays and twelve scenario selections. That differs from rendered-browser, keyboard-focus, mobile-layout or image-display verification. The Python function is tested separately through twenty checks in the source and extracted package, rather than combined with the native product’s previous forty-one checks into one misleading total.
Parsing success is not permission to access
security_approval and performs_fetch are always false. A parsable address may still refer to a prohibited network location or contain credentials, an inappropriate port or redirects. This example implements no DNS checks, access control, SSRF protection, response limits or image decoding. It neither repeats requests nor automatically selects another candidate after a download fails.
HTML attribute extraction and interpretation of srcset or JSON attributes also belong to the caller. The public function receives an already ordered list. The native collector has its own candidate-building rules and download path; replacing them wholesale with this example would be inappropriate. Align the inputs and results between parsing, access policy, transfer, storage and reporting before integrating it.
Ship execution instructions with the scope of reuse
The ZIP includes selector.py, twenty tests, examples.py, six records in records.json, a README and the MIT license. Run python -B -m unittest -v for the function tests and python -B examples.py to regenerate the synthetic records. Only the example runner writes records.json in its working directory; the selector writes no files. No external package installation or live site connection is needed.
The tests also cover input preservation, independent result objects, count and character limits, invalid base configuration, supported relative references, IPv6, query brackets and propagation of unexpected errors. Modification, redistribution and commercial reuse are permitted under the license. This is a starting point for reviewing failure boundaries and accounting units, not a replacement for verifying a customer collection or recovering historical failures.