PyTricia

raw JSON →
1.3.0 verified Mon Apr 27 auth: no python

PyTricia is an efficient IP address storage and lookup module for Python, based on the Patricia trie data structure. It supports IPv4 and IPv6, longest-prefix matching, and set operations. Current version 1.3.0 is stable with no known breaking changes. Release cadence is low (last release 2025).

pip install pytricia
error KeyError: <ip_address>
cause Trying to look up an IP that is not contained in any inserted prefix, or using an IP without /32.
fix
Ensure the IP is covered by an inserted prefix. For exact host lookup, insert with /32. Use pt.get(ip, None) to avoid exception.
error ValueError: invalid prefix
cause Passing a string that is not a valid CIDR prefix (e.g., missing slash, invalid address).
fix
Check input format: e.g., '10.0.0.0/8' is valid. Use ipaddress module to parse and validate.
error TypeError: 'PyTricia' object does not support item assignment
cause Attempting to assign a value without having imported pytricia correctly or using a read-only view.
fix
Ensure you have created an instance: pt = pytricia.PyTricia() then use pt[prefix] = value.
gotcha PyTricia expects prefix strings in CIDR notation (e.g., '10.0.0.0/8'). Do not pass IP addresses without prefix length; for host lookups, use the IP with /32 or use get_key() which returns the matching prefix.
fix Always provide a prefix length when inserting. For single IPs, use e.g., '192.168.1.1/32'.
gotcha PyTricia does not support non-ASCII or non-CIDR inputs; all prefixes must be valid IPv4 or IPv6 CIDR strings. Passing a malformed string raises ValueError.
fix Validate input with ipaddress.ip_network(prefix, strict=False) before inserting.
gotcha Values stored in the trie are not validated; they can be any Python object. However, retrieving a key that does not exist raises KeyError. Use pt.get(key, default) or check containment with 'in' first.
fix Use 'prefix in pt' before accessing pt[prefix] to avoid KeyError.
pip install pytricia==1.3.0

Basic usage: insert, lookup, longest-prefix match, containment check, iteration, and deletion.

import pytricia

# Initialize a new trie
pt = pytricia.PyTricia()

# Insert a prefix
pt["10.0.0.0/8"] = "internal"
pt["10.1.0.0/16"] = "subnet"

# Lookup an IP
result = pt["10.1.0.5"]
print(result)  # prints 'subnet'

# Longest prefix match
import ipaddress
net = pt.get_key("10.1.0.5")
print(net)  # prints '10.1.0.0/16'

# Check containment
print("10.0.0.0/8" in pt)  # True

# Iterate over prefixes
for prefix in pt:
    print(prefix, pt[prefix])

# Delete a prefix
del pt["10.1.0.0/16"]