py-radix

1.1.0 · active · verified Thu Apr 16

py-radix is a Python library that implements the radix tree (also known as a Patricia tree) data structure, primarily for efficient storage and retrieval of IPv4 and IPv6 network prefixes. This structure is commonly used for routing table lookups due to its ability to efficiently store prefixes of varying lengths and perform fast lookups of containing networks. The library is actively maintained, with version 1.1.0 released in late 2025, and consistently supports recent Python versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a Radix tree, add IPv4 and IPv6 network prefixes with associated data, and perform exact and best-match lookups. It also shows how to iterate through all stored nodes.

import radix

# Create a new tree
rtree = radix.Radix()

# Add nodes. Adding a node returns a RadixNode object.
# You can store arbitrary data in its 'data' dict.
rnode = rtree.add("10.0.0.0/8")
rnode.data["description"] = "Internal Network A"

# You can also specify networks using separate network and masklen, or packed binary addresses.
rnode = rtree.add(network="172.16.0.0", masklen=24)
rnode.data["location"] = "Branch Office"

# IPv6 prefixes are fully supported
rtree.add("2001:DB8::/32")

# Exact search returns a RadixNode if the prefix exists
found_node = rtree.search_exact("10.0.0.0/8")
if found_node:
    print(f"Found exact match: {found_node.prefix}, Data: {found_node.data}")

# Best-match search returns the longest matching prefix
best_match = rtree.search_best("10.0.0.123")
if best_match:
    print(f"Best match for 10.0.0.123: {best_match.prefix}, Data: {best_match.data}")

# Iterate over all nodes in the tree
print("\nAll prefixes in the tree:")
for node in rtree:
    print(node.prefix)

view raw JSON →