CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-multidict

Dictionary-like collection where keys can occur multiple times, optimized for HTTP headers and URL query strings

Pending
Overview
Eval results
Files

mutable-multidict.mddocs/

Mutable Multidict Operations

The MultiDict class provides the core mutable multidict functionality with case-sensitive key handling. It maintains insertion order and allows multiple values per key while providing both dict-like access patterns and specialized multidict methods.

Capabilities

Construction

Create multidict instances from various data sources with flexible initialization patterns.

class MultiDict(MutableMultiMapping[_V]):
    def __init__(self, arg: MDArg[_V] = None, /, **kwargs: _V):
        """
        Create a mutable multidict.
        
        Parameters:
        - arg: Mapping, iterable of key-value pairs, or None
        - **kwargs: Additional key-value pairs
        
        Examples:
        MultiDict()  # Empty
        MultiDict([('key', 'value1'), ('key', 'value2')])  # From pairs
        MultiDict({'key': 'value'})  # From dict
        MultiDict(key='value')  # From kwargs
        """

Usage examples:

# Empty multidict
md = MultiDict()

# From list of tuples (preserves duplicates)
headers = MultiDict([
    ('Accept', 'text/html'),
    ('Accept', 'application/json'),
    ('Cache-Control', 'no-cache')
])

# From dictionary (single values)
params = MultiDict({'page': '1', 'size': '10'})

# From keyword arguments
cookies = MultiDict(session='abc123', theme='dark')

# Mixed initialization
data = MultiDict([('tags', 'python')], tags='web', priority='high')

Adding Values

Add new key-value pairs to the multidict without replacing existing values.

def add(self, key: str, value: _V) -> None:
    """
    Append a key-value pair to the multidict.
    
    Parameters:
    - key: The key to add
    - value: The value to add
    
    Does not replace existing values for the same key.
    """

Usage examples:

headers = MultiDict()
headers.add('Accept', 'text/html')
headers.add('Accept', 'application/json')  # Now has two Accept values
headers.add('User-Agent', 'MyApp/1.0')

print(headers.getall('Accept'))  # ['text/html', 'application/json']

Retrieving Values

Access values using various retrieval methods for different use cases.

def __getitem__(self, key: str) -> _V:
    """Get the first value for key. Raises KeyError if not found."""

def get(self, key: str, default: Optional[_T] = None) -> Union[_V, _T, None]:
    """Get the first value for key, return default if not found."""

def getone(self, key: str, default: _T = ...) -> Union[_V, _T]:
    """
    Get the first value for key.
    
    Parameters:
    - key: The key to retrieve
    - default: Value to return if key not found
    
    Returns:
    First value for the key, or default if not found
    
    Raises:
    KeyError if key not found and no default provided
    """

def getall(self, key: str, default: _T = ...) -> Union[List[_V], _T]:
    """
    Get all values for key as a list.
    
    Parameters:
    - key: The key to retrieve
    - default: Value to return if key not found
    
    Returns:
    List of all values for the key, or default if not found
    
    Raises:
    KeyError if key not found and no default provided
    """

Usage examples:

headers = MultiDict([
    ('Accept', 'text/html'),
    ('Accept', 'application/json'),
    ('User-Agent', 'MyApp/1.0')
])

# Get first value (dict-like)
print(headers['Accept'])  # 'text/html'
print(headers.get('Accept'))  # 'text/html'
print(headers.getone('Accept'))  # 'text/html'

# Get all values
print(headers.getall('Accept'))  # ['text/html', 'application/json']

# Safe access with defaults
print(headers.get('Authorization', 'None'))  # 'None'
print(headers.getall('Authorization', []))  # []

Modifying Values

Replace, update, or merge values in the multidict.

def __setitem__(self, key: str, value: _V) -> None:
    """Set key to value, replacing all existing values for key."""

def setdefault(self, key: str, default: _V = None) -> _V:
    """
    Get value for key, or set and return default if key not present.
    
    Parameters:
    - key: The key to check/set
    - default: Value to set if key not present
    
    Returns:
    Existing first value or the default value that was set
    """

def update(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None:
    """
    Update multidict with key-value pairs, replacing existing values.
    
    Parameters:
    - arg: Mapping, iterable of pairs, or None
    - **kwargs: Additional key-value pairs
    """

def extend(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None:
    """
    Add all key-value pairs from arg and kwargs, preserving existing values.
    
    Parameters:
    - arg: Mapping, iterable of pairs, or None  
    - **kwargs: Additional key-value pairs
    """

def merge(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None:
    """
    Add key-value pairs from arg and kwargs for keys not already present.
    
    Parameters:
    - arg: Mapping, iterable of pairs, or None
    - **kwargs: Additional key-value pairs
    """

Usage examples:

headers = MultiDict([('Accept', 'text/html'), ('Accept', 'application/json')])

# Replace all values for a key
headers['Accept'] = 'text/plain'  # Now only has 'text/plain'

# Set default value
headers.setdefault('User-Agent', 'DefaultAgent/1.0')

# Update with new values (replaces existing)
headers.update([('Accept', 'text/xml')])

# Extend with additional values
headers.extend([('Accept', 'application/json')])  # Now has both values

# Merge only adds new keys
headers.merge({'Authorization': 'Bearer token'})  # Adds if not present

Removing Values

Remove keys and values using various deletion methods.

def __delitem__(self, key: str) -> None:
    """Remove all values for key. Raises KeyError if not found."""

def pop(self, key: str) -> _V:
    """Remove and return the first value for key. Raises KeyError if not found."""

def pop(self, key: str, default: _T) -> Union[_V, _T]:
    """Remove and return the first value for key, or default if not found."""

def popone(self, key: str, default: _T = ...) -> Union[_V, _T]:
    """
    Remove and return the first value for key.
    
    Parameters:
    - key: The key to remove
    - default: Value to return if key not found
    
    Returns:
    First value that was removed, or default if not found
    
    Raises:
    KeyError if key not found and no default provided
    """

def popall(self, key: str, default: _T = ...) -> Union[List[_V], _T]:
    """
    Remove and return all values for key as a list.
    
    Parameters:
    - key: The key to remove
    - default: Value to return if key not found
    
    Returns:
    List of all values that were removed, or default if not found
    
    Raises:
    KeyError if key not found and no default provided
    """

def popitem(self) -> tuple[str, _V]:
    """
    Remove and return an arbitrary key-value pair.
    
    Returns:
    Tuple of (key, value)
    
    Raises:
    KeyError if multidict is empty
    """

def clear(self) -> None:
    """Remove all key-value pairs from the multidict."""

Usage examples:

headers = MultiDict([
    ('Accept', 'text/html'),
    ('Accept', 'application/json'), 
    ('User-Agent', 'MyApp/1.0')
])

# Remove all values for a key
del headers['User-Agent']

# Remove and get first value
first_accept = headers.popone('Accept')  # 'text/html'

# Remove and get all values  
remaining_accepts = headers.popall('Accept')  # ['application/json']

# Remove arbitrary item
key, value = headers.popitem()

# Clear all
headers.clear()

Collection Operations

Standard collection methods for iteration, copying, and inspection.

def __len__(self) -> int:
    """Return the number of key-value pairs (not unique keys)."""

def __iter__(self) -> Iterator[str]:
    """Iterate over keys in insertion order."""

def __contains__(self, key: object) -> bool:
    """Check if key is present in the multidict."""

def keys(self) -> KeysView[str]:
    """Return a view of keys."""

def values(self) -> ValuesView[_V]:
    """Return a view of values."""

def items(self) -> ItemsView[str, _V]:
    """Return a view of key-value pairs."""

def copy(self) -> 'MultiDict[_V]':
    """Return a shallow copy of the multidict."""

def __copy__(self) -> 'MultiDict[_V]':
    """Support for copy.copy() - returns a shallow copy."""

Usage examples:

headers = MultiDict([
    ('Accept', 'text/html'),
    ('Accept', 'application/json'),
    ('User-Agent', 'MyApp/1.0')
])

# Length is total key-value pairs
print(len(headers))  # 3

# Check key existence
print('Accept' in headers)  # True
print('Authorization' in headers)  # False

# Iterate over keys
for key in headers:
    print(f"{key}: {headers.getall(key)}")

# Work with views
print(list(headers.keys()))    # ['Accept', 'Accept', 'User-Agent']
print(list(headers.values()))  # ['text/html', 'application/json', 'MyApp/1.0']
print(list(headers.items()))   # [('Accept', 'text/html'), ...]

# Create a copy
headers_copy = headers.copy()

# View set operations (keys, values, items support set operations)
other_headers = MultiDict([('Accept', 'text/html'), ('Content-Type', 'application/json')])

# Set operations on keys
common_keys = headers.keys() & other_headers.keys()  # Intersection
all_keys = headers.keys() | other_headers.keys()    # Union
unique_keys = headers.keys() - other_headers.keys() # Difference

# Set operations on items
common_items = headers.items() & other_headers.items()
print(list(common_items))  # [('Accept', 'text/html')]

Install with Tessl CLI

npx tessl i tessl/pypi-multidict

docs

case-insensitive.md

immutable-proxies.md

index.md

mutable-multidict.md

string-types-utilities.md

tile.json