Persistent/Functional/Immutable Data Structures

0.20.0 · active · verified Sat Mar 28

Pyrsistent is a Python library providing persistent and immutable data structures, such as lists, dictionaries, and sets, that facilitate functional programming paradigms. Unlike mutable data structures, all operations that would typically modify a `pyrsistent` object instead return a new, updated copy, leaving the original untouched. This simplifies reasoning about program state by eliminating hidden side effects. The library is currently at version 0.20.0, released in October 2023, and is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the creation and immutable 'evolution' of `PVector` (list-like), `PMap` (dict-like), and `PRecord` (object-like) instances. Operations like `append`, `set`, or `discard` always return a new instance with the changes, ensuring the original data structure's integrity.

from pyrsistent import pvector, pmap, PRecord

# Create a persistent vector (list-like)
v1 = pvector([1, 2, 3])
v2 = v1.append(4) # Returns a new pvector, v1 remains unchanged
v3 = v2.set(1, 5)  # Replaces element at index 1

print(f"Original vector: {v1}") # Expected: pvector([1, 2, 3])
print(f"Appended vector: {v2}") # Expected: pvector([1, 2, 3, 4])
print(f"Modified vector: {v3}") # Expected: pvector([1, 5, 3, 4])

# Create a persistent map (dict-like)
m1 = pmap({'a': 1, 'b': 2})
m2 = m1.set('c', 3) # Returns a new pmap, m1 remains unchanged
m3 = m2.set('a', 5) # Updates value for key 'a'

print(f"Original map: {m1}") # Expected: pmap({'a': 1, 'b': 2})
print(f"Appended map: {m2}") # Expected: pmap({'a': 1, 'b': 2, 'c': 3})
print(f"Modified map: {m3}") # Expected: pmap({'a': 5, 'b': 2, 'c': 3})

# Define a persistent record
class User(PRecord):
    name = None
    age = None

user1 = User(name='Alice', age=30)
user2 = user1.set(age=31) # Returns a new User record

print(f"Original user: {user1}") # Expected: User(name='Alice', age=30)
print(f"Updated user: {user2}") # Expected: User(name='Alice', age=31)

view raw JSON →