or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-operations.mddata-manipulation.mdindex.mdpath-access.mdsearch-operations.md
tile.json

tessl/pypi-dpath

Filesystem-like pathing and searching for dictionaries

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/dpath@2.2.x

To install, run

npx @tessl/cli install tessl/pypi-dpath@2.2.0

index.mddocs/

dpath

A Python library for accessing and manipulating nested dictionaries using filesystem-like path notation. dpath enables developers to traverse, search, filter, and modify complex dictionary structures using xpath-style syntax with support for globbing patterns, providing intuitive path-based operations for hierarchical data.

Package Information

  • Package Name: dpath
  • Package Type: Python Library
  • Language: Python
  • Installation: pip install dpath
  • Minimum Python Version: 3.7+

Core Imports

import dpath

Access to main functions:

from dpath import new, get, set, delete, search, values, merge

Access to types and exceptions:

from dpath.types import MergeType, PathSegment, Filter, Glob, Path, Creator, Hints, ListIndex
from dpath.exceptions import PathNotFound, InvalidGlob, InvalidKeyName, FilteredValue

Access to configuration and version:

import dpath.options  # Configuration options
import dpath.version  # Version info

Legacy util module (deprecated):

import dpath.util  # Deprecated - use dpath directly instead

Basic Usage

import dpath

# Sample nested dictionary
data = {
    "users": {
        "john": {"age": 30, "city": "New York"},
        "jane": {"age": 25, "city": "Los Angeles"}
    },
    "settings": {
        "theme": "dark",
        "notifications": True
    }
}

# Get a single value
age = dpath.get(data, "users/john/age")  # Returns: 30

# Search for patterns
cities = dpath.search(data, "users/*/city")
# Returns: {'users': {'john': {'city': 'New York'}, 'jane': {'city': 'Los Angeles'}}}

# Get all matching values
all_cities = dpath.values(data, "users/*/city")  # Returns: ['New York', 'Los Angeles']

# Set a new value (creates path if it doesn't exist)
dpath.new(data, "users/bob/age", 35)

# Update existing values with glob patterns
dpath.set(data, "users/*/age", 999)  # Sets all user ages to 999

# Delete matching paths
dpath.delete(data, "users/john")  # Removes john's entire record

# Merge dictionaries deeply
other_data = {"users": {"alice": {"age": 28}}}
dpath.merge(data, other_data)  # Merges alice into existing users

Architecture

dpath uses a layered architecture that separates concerns for robust path manipulation:

  • Main API Layer: High-level functions (get, set, search, etc.) that handle user input validation and provide convenient interfaces
  • Segments Module: Core path manipulation logic that handles walking, matching, and modifying nested structures
  • Type System: Comprehensive type definitions and aliases for path segments, filters, and merge behaviors
  • Exception Handling: Specific exceptions for different error conditions in path operations

This design allows for powerful operations on nested data structures while maintaining type safety and providing clear error reporting.

Capabilities

Path Access Operations

Core functions for getting and setting values at specific paths in nested dictionaries, supporting both exact paths and glob patterns.

def get(obj, glob, separator="/", default=_DEFAULT_SENTINEL):
    """Get single value matching glob pattern."""
    pass

def new(obj, path, value, separator="/", creator=None):
    """Create new path and set value, creating missing keys."""
    pass

def set(obj, glob, value, separator="/", afilter=None):
    """Set value for all existing elements matching glob."""
    pass

Path Access

Search and Discovery

Powerful search capabilities for finding paths and values matching glob patterns, with support for filtering and yielding results.

def search(obj, glob, yielded=False, separator="/", afilter=None, dirs=True):
    """Search for paths/values matching glob pattern."""
    pass

def values(obj, glob, separator="/", afilter=None, dirs=True):
    """Get list of all values matching glob pattern."""
    pass

Search Operations

Data Manipulation

Operations for modifying dictionary structures including deletion and deep merging with configurable behavior.

def delete(obj, glob, separator="/", afilter=None):
    """Delete all elements matching glob pattern."""
    pass

def merge(dst, src, separator="/", afilter=None, flags=MergeType.ADDITIVE):
    """Deep merge source into destination dictionary."""
    pass

Data Manipulation

Advanced Path Operations

Low-level utilities for custom path manipulation and advanced use cases, providing direct access to the underlying path walking and matching algorithms.

# From dpath.segments module
def walk(obj, location=()):
    """Walk object yielding (segments, value) pairs."""
    pass

def match(segments, glob):
    """Check if segments match glob pattern."""
    pass

def view(obj, glob):
    """Create filtered view of object matching glob."""
    pass

Advanced Operations

Configuration and Utilities

Configuration options and version information, plus deprecated utility functions for backwards compatibility.

# Configuration options
dpath.options.ALLOW_EMPTY_STRING_KEYS = False  # Allow empty string keys in paths

# Version information  
dpath.version.__version__  # Package version string

# Deprecated util module (use dpath.* directly instead)
import dpath.util  # All functions mirror dpath.* with deprecation warnings

Type System

# Core type aliases
PathSegment = Union[int, str, bytes]
Filter = Callable[[Any], bool]  
Glob = Union[str, Sequence[str]]
Path = Union[str, Sequence[PathSegment]]
Hints = Sequence[Tuple[PathSegment, type]]
Creator = Callable[[Union[MutableMapping, List], Path, int, Optional[Hints]], None]

# Special list index class with negative index support
class ListIndex(int):
    """Integer that supports negative index comparison for list operations."""
    def __new__(cls, value: int, list_length: int): ...
    def __eq__(self, other): ...  # Supports negative index comparison

# Merge behavior flags
class MergeType(IntFlag):
    ADDITIVE = auto()    # Combine lists (default)
    REPLACE = auto()     # Replace instead of combining
    TYPESAFE = auto()    # Raise TypeError on type mismatches

# Exceptions
class PathNotFound(Exception): 
    """One or more elements of the requested path did not exist in the object"""
    pass

class InvalidGlob(Exception): 
    """The glob passed is invalid."""
    pass

class InvalidKeyName(Exception): 
    """This key contains the separator character or another invalid character"""
    pass

class FilteredValue(Exception): 
    """Unable to return a value, since the filter rejected it"""
    pass