or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# dpath

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: dpath

7

- **Package Type**: Python Library

8

- **Language**: Python

9

- **Installation**: `pip install dpath`

10

- **Minimum Python Version**: 3.7+

11

12

## Core Imports

13

14

```python

15

import dpath

16

```

17

18

Access to main functions:

19

20

```python

21

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

22

```

23

24

Access to types and exceptions:

25

26

```python

27

from dpath.types import MergeType, PathSegment, Filter, Glob, Path, Creator, Hints, ListIndex

28

from dpath.exceptions import PathNotFound, InvalidGlob, InvalidKeyName, FilteredValue

29

```

30

31

Access to configuration and version:

32

33

```python

34

import dpath.options # Configuration options

35

import dpath.version # Version info

36

```

37

38

Legacy util module (deprecated):

39

40

```python

41

import dpath.util # Deprecated - use dpath directly instead

42

```

43

44

## Basic Usage

45

46

```python

47

import dpath

48

49

# Sample nested dictionary

50

data = {

51

"users": {

52

"john": {"age": 30, "city": "New York"},

53

"jane": {"age": 25, "city": "Los Angeles"}

54

},

55

"settings": {

56

"theme": "dark",

57

"notifications": True

58

}

59

}

60

61

# Get a single value

62

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

63

64

# Search for patterns

65

cities = dpath.search(data, "users/*/city")

66

# Returns: {'users': {'john': {'city': 'New York'}, 'jane': {'city': 'Los Angeles'}}}

67

68

# Get all matching values

69

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

70

71

# Set a new value (creates path if it doesn't exist)

72

dpath.new(data, "users/bob/age", 35)

73

74

# Update existing values with glob patterns

75

dpath.set(data, "users/*/age", 999) # Sets all user ages to 999

76

77

# Delete matching paths

78

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

79

80

# Merge dictionaries deeply

81

other_data = {"users": {"alice": {"age": 28}}}

82

dpath.merge(data, other_data) # Merges alice into existing users

83

```

84

85

## Architecture

86

87

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

88

89

- **Main API Layer**: High-level functions (`get`, `set`, `search`, etc.) that handle user input validation and provide convenient interfaces

90

- **Segments Module**: Core path manipulation logic that handles walking, matching, and modifying nested structures

91

- **Type System**: Comprehensive type definitions and aliases for path segments, filters, and merge behaviors

92

- **Exception Handling**: Specific exceptions for different error conditions in path operations

93

94

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

95

96

## Capabilities

97

98

### Path Access Operations

99

100

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

101

102

```python { .api }

103

def get(obj, glob, separator="/", default=_DEFAULT_SENTINEL):

104

"""Get single value matching glob pattern."""

105

pass

106

107

def new(obj, path, value, separator="/", creator=None):

108

"""Create new path and set value, creating missing keys."""

109

pass

110

111

def set(obj, glob, value, separator="/", afilter=None):

112

"""Set value for all existing elements matching glob."""

113

pass

114

```

115

116

[Path Access](./path-access.md)

117

118

### Search and Discovery

119

120

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

121

122

```python { .api }

123

def search(obj, glob, yielded=False, separator="/", afilter=None, dirs=True):

124

"""Search for paths/values matching glob pattern."""

125

pass

126

127

def values(obj, glob, separator="/", afilter=None, dirs=True):

128

"""Get list of all values matching glob pattern."""

129

pass

130

```

131

132

[Search Operations](./search-operations.md)

133

134

### Data Manipulation

135

136

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

137

138

```python { .api }

139

def delete(obj, glob, separator="/", afilter=None):

140

"""Delete all elements matching glob pattern."""

141

pass

142

143

def merge(dst, src, separator="/", afilter=None, flags=MergeType.ADDITIVE):

144

"""Deep merge source into destination dictionary."""

145

pass

146

```

147

148

[Data Manipulation](./data-manipulation.md)

149

150

### Advanced Path Operations

151

152

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

153

154

```python { .api }

155

# From dpath.segments module

156

def walk(obj, location=()):

157

"""Walk object yielding (segments, value) pairs."""

158

pass

159

160

def match(segments, glob):

161

"""Check if segments match glob pattern."""

162

pass

163

164

def view(obj, glob):

165

"""Create filtered view of object matching glob."""

166

pass

167

```

168

169

[Advanced Operations](./advanced-operations.md)

170

171

### Configuration and Utilities

172

173

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

174

175

```python { .api }

176

# Configuration options

177

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

178

179

# Version information

180

dpath.version.__version__ # Package version string

181

182

# Deprecated util module (use dpath.* directly instead)

183

import dpath.util # All functions mirror dpath.* with deprecation warnings

184

```

185

186

## Type System

187

188

```python { .api }

189

# Core type aliases

190

PathSegment = Union[int, str, bytes]

191

Filter = Callable[[Any], bool]

192

Glob = Union[str, Sequence[str]]

193

Path = Union[str, Sequence[PathSegment]]

194

Hints = Sequence[Tuple[PathSegment, type]]

195

Creator = Callable[[Union[MutableMapping, List], Path, int, Optional[Hints]], None]

196

197

# Special list index class with negative index support

198

class ListIndex(int):

199

"""Integer that supports negative index comparison for list operations."""

200

def __new__(cls, value: int, list_length: int): ...

201

def __eq__(self, other): ... # Supports negative index comparison

202

203

# Merge behavior flags

204

class MergeType(IntFlag):

205

ADDITIVE = auto() # Combine lists (default)

206

REPLACE = auto() # Replace instead of combining

207

TYPESAFE = auto() # Raise TypeError on type mismatches

208

209

# Exceptions

210

class PathNotFound(Exception):

211

"""One or more elements of the requested path did not exist in the object"""

212

pass

213

214

class InvalidGlob(Exception):

215

"""The glob passed is invalid."""

216

pass

217

218

class InvalidKeyName(Exception):

219

"""This key contains the separator character or another invalid character"""

220

pass

221

222

class FilteredValue(Exception):

223

"""Unable to return a value, since the filter rejected it"""

224

pass

225

```