Python Lenses

1.2.0 · active · verified Fri Apr 17

Lenses is a Python library inspired by functional programming concepts, providing a fluent API for immutable data manipulation. It allows for safe and concise modification, retrieval, and transformation of nested data structures (like dictionaries and lists) without mutating the original object. The current version is 1.2.0, with a moderate release cadence.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic `get()`, `set()`, and `modify()` operations for navigating and transforming nested immutable data structures.

from lenses import lens

data = {
    'user': {
        'id': 123,
        'name': 'Alice',
        'settings': {
            'theme': 'dark',
            'notifications': True
        }
    },
    'products': [{'id': 'A', 'price': 100}, {'id': 'B', 'price': 200}]
}

# Get a value
user_name = lens(data).user.name.get()
print(f"User name: {user_name}")

# Set a new value (returns a new data structure)
updated_data = lens(data).user.settings.theme.set('light')
print(f"Original theme: {data['user']['settings']['theme']}")
print(f"New theme: {updated_data['user']['settings']['theme']}")

# Modify a value (returns a new data structure)
increased_price_data = lens(data).products[0].price.modify(lambda p: p * 1.1)
print(f"Original product A price: {data['products'][0]['price']}")
print(f"Increased product A price: {increased_price_data['products'][0]['price']}")

view raw JSON →