Skip to main content

A simple kd-tree in Python Tests

The kdtree package can construct, modify and search kd-trees.

Usage

>>> import kdtree

# Create an empty tree by specifying the number of
# dimensions its points will have
>>> emptyTree = kdtree.create(dimensions=3)

# A kd-tree can contain different kinds of points, for example tuples
>>> point1 = (2, 3, 4)

# Lists can also be used as points
>>> point2 = [4, 5, 6]

# Other objects that support indexing can be used, too
>>> import collections
>>> Point = collections.namedtuple('Point', 'x y z')
>>> point3 = Point(5, 3, 2)

# A tree is created from a list of points
>>> tree = kdtree.create([point1, point2, point3])

# Each (sub)tree is represented by its root node
>>> tree
<KDNode - [4, 5, 6]>

# Adds a tuple to the tree and returns its node
>>> tree.add( (5, 4, 3) )
<KDNode - (5, 4, 3)>

# Removes the previously added point and returns the new root
>>> tree = tree.remove( (5, 4, 3) )

# Retrieving the Tree in inorder
>>> list(tree.inorder())
[<KDNode - (2, 3, 4)>, <KDNode - [4, 5, 6]>, <KDNode - Point(x=5, y=3, z=2)>]

# Retrieving the Tree in level order
>>> list(kdtree.level_order(tree))
[<KDNode - [4, 5, 6]>, <KDNode - (2, 3, 4)>, <KDNode - Point(x=5, y=3, z=2)>]

# Find the nearest node to the location (1, 2, 3)
>>> tree.search_nn( (1, 2, 3) )
(<KDNode - (2, 3, 4)>, 3.0)

# Add a point to make the tree more interesting
>>> tree.add( (10, 2, 1) )
<KDNode - (10, 2, 1)>

# Visualize the Tree
>>> kdtree.visualize(tree)


                     [4, 5, 6]

           (2, 3, 4)       Point(x=5, y=3, z=2)

                            (10, 2, 1)

# Take the right subtree of the root
>>> subtree = tree.right

# and detach it
>>> tree.right = None
>>> kdtree.visualize(tree)

           [4, 5, 6]

      (2, 3, 4)

>>> kdtree.visualize(subtree)

      Point(x=5, y=3, z=2)

      (10, 2, 1)

# and re-attach it
>>> tree.right = subtree
>>> kdtree.visualize(tree)

                     [4, 5, 6]

           (2, 3, 4)       Point(x=5, y=3, z=2)

                            (10, 2, 1)

# Add a node to make the tree unbalanced
>>> tree.is_balanced
True
>>> tree.add( (6, 1, 5) )
<KDNode - (6, 1, 5)>
>>> tree.is_balanced
False
>>> kdtree.visualize(tree)

                                         [4, 5, 6]

                     (2, 3, 4)                           Point(x=5, y=3, z=2)

                                                     (10, 2, 1)

                                                             (6, 1, 5)

# rebalance the tree
>>> tree = tree.rebalance()
>>> tree.is_balanced
True
>>> kdtree.visualize(tree)

                Point(x=5, y=3, z=2)

           [4, 5, 6]            (10, 2, 1)

      (2, 3, 4)             (6, 1, 5)

Type hints

Type information is provided in the stub file kdtree.pyi, which is installed next to kdtree.py and, for mypy, as the stub-only package kdtree-stubs. Trees are generic in the type of their points:

tree = kdtree.create([(1, 2), (3, 4)])  # KDNode[tuple[int, int]]
node, dist = tree.search_nn((1, 1))     # KDNode[tuple[int, int]], float

The classes are only generic for type checkers; at runtime write annotations like kdtree.KDNode[tuple[int, int]] as strings or use from __future__ import annotations.

Adding a payload

Indexing a dict by a pair of floats is not a good idea, since there might be unexpected precision errors. Since KDTree expects a tuple-looking objects for nodes, you can make a class that looks like a tuple, but contains more data. This way you can store all your data in a kdtree, without using an additional indexed structure.

import kdtree

# This class emulates a tuple, but contains a useful payload
class Item(object):
    def __init__(self, x, y, data):
        self.coords = (x, y)
        self.data = data

    def __len__(self):
        return len(self.coords)

    def __getitem__(self, i):
        return self.coords[i]

    def __repr__(self):
        return 'Item({}, {}, {})'.format(self.coords[0], self.coords[1], self.data)

# Now we can add Items to the tree, which look like tuples to it
point1 = Item(2, 3, 'First')
point2 = Item(3, 4, 'Second')
point3 = Item(5, 2, ['some', 'list'])

# Again, from a list of points
tree = kdtree.create([point1, point2, point3])

#  The root node
print(tree)

# ...contains "data" field with an Item, which contains the payload in "data" field
print(tree.data.data)

# All functions work as intended, a payload is never lost
print(tree.search_nn([1, 2]))

Prints:

<KDNode - Item(3, 4, Second)>
Second
(<KDNode - Item(2, 3, First)>, 2.0)

Metadata

Release files for kdtree 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kdtree 1.1.1
File Size Uploaded Provenance Actions
kdtree-1.1.1.tar.gz 30.3 kB With provenance Details for kdtree-1.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kdtree 1.1.1
File Interpreter ABI Platform Actions
kdtree-1.1.1-py3-none-any.whl Python 3 none any Details for kdtree-1.1.1-py3-none-any.whl

Total release size: 44.1 kB

Release files / kdtree-1.1.1.tar.gz

Download URL kdtree-1.1.1.tar.gz
Size 30.3 kB
Tags Source
SHA-256 checksum
How to use checksums
1e2d60ce94f3bb9c7c26980612ea9399ea86ec3e1e8afe4ce0f17df2204e894b
BLAKE2b-256 checksum
How to use checksums
7aa6942bc2b9e808b857f8dd9f12dc9e1746e53a75fe88ebae9c4bdd199136a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Release files / kdtree-1.1.1-py3-none-any.whl

Download URL kdtree-1.1.1-py3-none-any.whl
Size 13.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9e31c4700a51c5bae8532b955b5c9f24a267fbacf68667a5747dea90dcde123b
BLAKE2b-256 checksum
How to use checksums
b28ee4b16bbf2a7797669c7a752ffca88a51eee10a98ce8892643df06920233f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Security for kdtree 1.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kdtree-1.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page