Skip to content

URLSearchParams

The URLSearchParams class provides utilities for working with URL query strings according to the WHATWG URL Standard.

Overview

URLSearchParams implements Python's MutableMapping interface, enabling dictionary-style access alongside WHATWG-compliant methods.

from pywhatwgurl import URLSearchParams

params = URLSearchParams("foo=1&bar=2")
print(params["foo"])      # "1" (Pythonic)
print("bar" in params)    # True (Pythonic)
params["baz"] = "3"       # Pythonic assignment
del params["bar"]         # Pythonic deletion

Pythonic vs WHATWG Methods

Operation Pythonic (Preferred) WHATWG Method
Get value params["key"] params.get("key")
Set value params["key"] = "value" params.set("key", "value")
Delete del params["key"] params.delete("key")
Check exists "key" in params params.has("key")
Get length len(params) params.size
Iterate params.items() params.entries()
To string str(params) params.to_string()

Constructor

Initialize the URLSearchParams object.

Parameters:

Name Type Description Default
init Optional[Union[str, Iterable[Sequence[str]], Mapping[str, Union[str, Sequence[str]]], 'URLSearchParams']]

Initializing object. Can be a query string, iterable of pairs, mapping (dict), or valid URLSearchParams object.

None
Source code in pywhatwgurl/search_params.py
def __init__(
    self,
    init: Optional[
        Union[
            str,
            Iterable[Sequence[str]],
            Mapping[str, Union[str, Sequence[str]]],
            "URLSearchParamsImpl",
        ]
    ] = None,
) -> None:
    self._list: List[Tuple[str, str]] = []
    self._url: Optional["URLImpl"] = None

    if init is None:
        return

    if isinstance(init, str):
        if init.startswith("?"):
            init = init[1:]
        self._list = _parse_urlencoded_string(init)
    elif isinstance(init, URLSearchParamsImpl):
        self._list = list(init._list)
    elif isinstance(init, Mapping):
        for key, val in init.items():
            if isinstance(val, str):
                self._list.append((key, val))
            else:
                for item in val:
                    self._list.append((key, item))
    else:
        for pair in init:
            seq = list(pair)
            if len(seq) != 2:
                raise TypeError(
                    "Failed to construct 'URLSearchParams': "
                    "parameter 1 sequence's element does not contain exactly two elements."
                )
            self._list.append((str(seq[0]), str(seq[1])))

Reading Parameters

get

Return the first value associated with the given search parameter.

Note

params[name] or params.get(name) is preferred. This method is primarily for WHATWG Spec compliance.

Parameters:

Name Type Description Default
name str

The name of the parameter to retrieve.

required

Returns:

Type Description
Optional[str]

The first value associated with name, or None if not found.

Source code in pywhatwgurl/search_params.py
def get(self, name: str) -> Optional[str]:  # type: ignore[override]
    for n, v in self._list:
        if n == name:
            return v
    return None

get_all

Use this method when a parameter may have multiple values.

Return all values associated with the given search parameter.

Parameters:

Name Type Description Default
name str

The name of the parameter to retrieve.

required

Returns:

Type Description
Tuple[str, ...]

A tuple containing all values associated with name.

Source code in pywhatwgurl/search_params.py
def get_all(self, name: str) -> Tuple[str, ...]:
    return tuple(v for n, v in self._list if n == name)

has

Return True if name exists.

If value is provided, return True only if a pair with name and value exists.

Note

name in params is preferred for checking existence of a key. This method is primarily for WHATWG Spec compliance.

Parameters:

Name Type Description Default
name str

The name of the parameter to check.

required
value Optional[str]

The specific value to check for.

None

Returns:

Type Description
bool

True if the parameter exists (matching value if provided), False otherwise.

Source code in pywhatwgurl/search_params.py
def has(self, name: str, value: Optional[str] = None) -> bool:
    for n, v in self._list:
        if n == name and (value is None or v == value):
            return True
    return False

Modifying Parameters

set

Set the value associated with a given search parameter to the given value.

If there were several values, delete the others.

Note

params[name] = value is preferred. This method is primarily for WHATWG Spec compliance.

Parameters:

Name Type Description Default
name str

The name of the parameter to set.

required
value str

The value to set.

required
Source code in pywhatwgurl/search_params.py
def set(self, name: str, value: str) -> None:
    found = False
    i = 0
    while i < len(self._list):
        if self._list[i][0] == name:
            if found:
                self._list.pop(i)
            else:
                self._list[i] = (name, value)
                found = True
                i += 1
        else:
            i += 1
    if not found:
        self._list.append((name, value))
    self._update_steps()

append

Use this method to add multiple values for the same key.

Append a new name-value pair to the query string.

Parameters:

Name Type Description Default
name str

The name of the parameter.

required
value str

The value of the parameter.

required
Source code in pywhatwgurl/search_params.py
def append(self, name: str, value: str) -> None:
    self._list.append((name, value))
    self._update_steps()

delete

Remove all name-value pairs where name is name.

If value is provided, only remove pairs where both name and value match.

Note

For deleting by name, del params[name] is preferred. This method is primarily for WHATWG Spec compliance.

Parameters:

Name Type Description Default
name str

The name of the parameter(s) to remove.

required
value Optional[str]

The specific value to match. If None, removes all pairs with name.

None
Source code in pywhatwgurl/search_params.py
def delete(self, name: str, value: Optional[str] = None) -> None:
    i = 0
    while i < len(self._list):
        if self._list[i][0] == name and (
            value is None or self._list[i][1] == value
        ):
            self._list.pop(i)
        else:
            i += 1
    self._update_steps()

sort

Sort all name-value pairs by name.

Note

This method is primarily for WHATWG Spec compliance. Valid URLs do not require sorted parameters.

Source code in pywhatwgurl/search_params.py
def sort(self) -> None:
    # Sort by name using UTF-16 code unit ordering per WHATWG spec
    def utf16_sort_key(item: Tuple[str, str]) -> List[int]:
        encoded = item[0].encode("utf-16-be")
        return [
            int.from_bytes(encoded[i : i + 2], "big")
            for i in range(0, len(encoded), 2)
        ]

    self._list.sort(key=utf16_sort_key)
    self._update_steps()

Iteration

entries

Return an iterator over all name-value pairs.

Note

params.items() is preferred. This method is primarily for WHATWG Spec compliance.

Returns:

Type Description
Iterator[Tuple[str, str]]

An iterator yielding (name, value) tuples.

Source code in pywhatwgurl/search_params.py
def entries(self) -> Iterator[Tuple[str, str]]:
    return iter(self._list)

keys

Return an iterator over all parameter names.

Source code in pywhatwgurl/interfaces.py
def keys(self) -> Iterator[str]:  # type: ignore[override]
    """Return an iterator over all parameter names."""
    for key, _ in self.entries():
        yield key

values

Return an iterator over all parameter values.

Source code in pywhatwgurl/interfaces.py
def values(self) -> Iterator[str]:  # type: ignore[override]
    """Return an iterator over all parameter values."""
    for _, value in self.entries():
        yield value

items

Pythonic method equivalent to entries().

Return an iterator over all (name, value) pairs.

Source code in pywhatwgurl/interfaces.py
def items(self) -> Iterator[Tuple[str, str]]:  # type: ignore[override]
    """Return an iterator over all (name, value) pairs."""
    return self.entries()

for_each

Iterate through all values.

Note

Pythonic iteration (for k in params) is preferred. This method is primarily for WHATWG Spec compliance.

Parameters:

Name Type Description Default
callback _URLSearchParamsForEachCallback

Function to call for each element.

required
Source code in pywhatwgurl/search_params.py
def for_each(self, callback: _URLSearchParamsForEachCallback) -> None:
    for name, value in self._list:
        callback(value, name, self)

Size and Serialization

size

Return the total number of name-value pairs.

Note

len(params) is preferred. This method is primarily for WHATWG Spec compliance.

to_string

Return the query string suitable for use in a URL.

Note

str(params) is preferred. This method is primarily for WHATWG Spec compliance.

Returns:

Type Description
str

The serialized query string.

Source code in pywhatwgurl/search_params.py
def to_string(self) -> str:
    return _serialize_urlencoded(self._list)

Special Methods

Method Usage Description
__getitem__ params["key"] Get value (raises KeyError if not found)
__setitem__ params["key"] = "value" Set value (replaces existing)
__delitem__ del params["key"] Delete key (raises KeyError if not found)
__contains__ "key" in params Check if key exists
__len__ len(params) Get number of parameters
__iter__ for key in params Iterate over keys
__str__ str(params) Convert to query string