0
# Pyrsistent
1
2
A comprehensive Python library providing persistent/immutable data structures. Pyrsistent enables functional programming patterns by offering immutable alternatives to Python's built-in collections (dict, list, set) that never modify in-place but return new instances with requested changes, enabling safer concurrent programming and easier reasoning about program state.
3
4
## Package Information
5
6
- **Package Name**: pyrsistent
7
- **Language**: Python
8
- **Installation**: `pip install pyrsistent`
9
10
## Core Imports
11
12
```python
13
import pyrsistent
14
```
15
16
Common imports for working with specific data structures:
17
18
```python
19
from pyrsistent import pmap, pvector, pset, freeze, thaw
20
```
21
22
For type checking and records:
23
24
```python
25
from pyrsistent import PRecord, PClass, field
26
```
27
28
For type annotations:
29
30
```python
31
from typing import Union, Mapping, Iterable, Tuple, TypeVar, Any
32
KT = TypeVar('KT') # Key type
33
VT = TypeVar('VT') # Value type
34
T = TypeVar('T') # Element type
35
```
36
37
## Basic Usage
38
39
```python
40
from pyrsistent import pmap, pvector, pset, freeze, thaw
41
42
# Create persistent collections
43
pm = pmap({'name': 'John', 'age': 30})
44
pv = pvector([1, 2, 3, 4, 5])
45
ps = pset([1, 2, 3, 3, 4]) # Duplicate 3 is automatically removed
46
47
# All operations return new instances
48
pm2 = pm.set('age', 31) # pm is unchanged
49
pv2 = pv.append(6) # pv is unchanged
50
ps2 = ps.add(5) # ps is unchanged
51
52
print(pm2) # pmap({'name': 'John', 'age': 31})
53
print(pv2) # pvector([1, 2, 3, 4, 5, 6])
54
print(ps2) # pset([1, 2, 3, 4, 5])
55
56
# Convert between mutable and immutable
57
regular_dict = {'a': 1, 'b': [2, 3], 'c': {4, 5}}
58
persistent = freeze(regular_dict) # Recursively converts to persistent
59
mutable = thaw(persistent) # Recursively converts back to mutable
60
```
61
62
## Architecture
63
64
Pyrsistent provides two main categories of persistent data structures:
65
66
- **Core Collections**: Immutable versions of Python's built-in collections with structural sharing for memory efficiency
67
- **Type-Checked Collections**: Enhanced versions with runtime type validation and invariant checking
68
- **Record Types**: Fixed-schema data structures for structured data modeling
69
70
All collections use structural sharing through Hash Array Mapped Tries (HAMT) and similar data structures, enabling O(log32 n) performance for most operations while minimizing memory usage.
71
72
## Capabilities
73
74
### Core Persistent Collections
75
76
Immutable alternatives to Python's built-in collections including persistent map (dict), vector (list), set, bag (multiset), list (linked), and deque (double-ended queue). All operations return new instances with structural sharing for efficiency.
77
78
```python { .api }
79
def pmap(initial: Union[Mapping[KT, VT], Iterable[Tuple[KT, VT]]] = {}, pre_size: int = 0) -> PMap[KT, VT]: ...
80
def pvector(iterable: Iterable[T] = ()) -> PVector[T]: ...
81
def pset(iterable: Iterable[T] = (), pre_size: int = 8) -> PSet[T]: ...
82
def pbag(elements: Iterable[T]) -> PBag[T]: ...
83
def plist(iterable: Iterable[T] = (), reverse: bool = False) -> PList[T]: ...
84
def pdeque(iterable: Iterable[T] = None, maxlen: int = None) -> PDeque[T]: ...
85
```
86
87
[Core Collections](./core-collections.md)
88
89
### Type-Checked Collections
90
91
Runtime type validation for persistent collections with optional invariant checking. Provides CheckedPMap, CheckedPVector, and CheckedPSet with customizable type constraints and validation rules.
92
93
```python { .api }
94
class CheckedPMap(PMap):
95
__key_type__: type
96
__value_type__: type
97
98
class CheckedPVector(PVector):
99
__type__: type
100
101
class CheckedPSet(PSet):
102
__type__: type
103
104
def optional(*types) -> tuple: ...
105
```
106
107
[Type-Checked Collections](./type-checked-collections.md)
108
109
### Records and Classes
110
111
Structured data types with fixed schemas, type checking, and serialization support. PRecord provides a dict-like interface while PClass provides an object-like interface, both with field specifications and validation.
112
113
```python { .api }
114
class PRecord(PMap):
115
def set(self, *args, **kwargs) -> 'PRecord': ...
116
@classmethod
117
def create(cls, kwargs: dict, ignore_extra: bool = False) -> 'PRecord': ...
118
def serialize(self, format=None) -> dict: ...
119
120
class PClass:
121
def set(self, *args, **kwargs) -> 'PClass': ...
122
@classmethod
123
def create(cls, kwargs: dict, ignore_extra: bool = False) -> 'PClass': ...
124
def serialize(self, format=None) -> dict: ...
125
126
def field(type=(), invariant=..., initial=..., mandatory: bool = False, factory=..., serializer=...) -> 'PField': ...
127
```
128
129
[Records and Classes](./records-and-classes.md)
130
131
### Utilities and Transformations
132
133
Helper functions for converting between mutable and immutable structures, applying transformations, and accessing nested data. Includes freeze/thaw conversion, transformation functions, and nested access utilities.
134
135
```python { .api }
136
def freeze(obj, strict: bool = True): ...
137
def thaw(obj, strict: bool = True): ...
138
def mutant(fn) -> callable: ...
139
def get_in(keys: Iterable, coll: Mapping, default=None, no_default: bool = False): ...
140
def inc(x: int) -> int: ...
141
def discard(evolver, key) -> None: ...
142
```
143
144
[Utilities and Transformations](./utilities.md)