Skip to content

Tracker Module

The tracker module provides automatic change tracking for Python objects, generating JSON Patch operations for efficient state synchronization.

Core Functions

langdiff.track_change

track_change(
    obj: T,
    tracker_cls: type[
        ChangeTracker
    ] = EfficientJSONPatchChangeTracker,
) -> tuple[T, DiffBuffer]

Wrap an object in a tracked proxy and return the tracker.

langdiff.apply_change

apply_change(obj: dict, operations: list[Operation])

Apply a JSON Patch to a Python dictionary.

Parameters:

Name Type Description Default
obj dict

The original dictionary to be patched.

required
operations list[Operation]

A list of operations to apply.

required

Returns:

Type Description

The patched dictionary.

Change Trackers

langdiff.ChangeTracker

Bases: DiffBuffer

track

Wraps the object in a tracked proxy.

langdiff.JSONPatchChangeTracker

Bases: ChangeTracker

Change tracker that collects changes in standard JSON Patch format.

langdiff.EfficientJSONPatchChangeTracker

Bases: JSONPatchChangeTracker

Change tracker that collects changes in extended JSON Patch format with specialized string append operation.

Operations

langdiff.Operation

Bases: TypedDict

Usage Examples

Basic Change Tracking

import langdiff as ld
from pydantic import BaseModel

class UserProfile(BaseModel):
    name: str = ""
    age: int = 0
    hobbies: list[str] = []

# Wrap object for tracking
profile, diff_buf = ld.track_change(UserProfile())

# Make changes
profile.name = "Alice"
profile.age = 25
profile.hobbies.append("reading")

# Get accumulated changes
changes = diff_buf.flush()
print(changes)
# [
#   {"op": "replace", "path": "/name", "value": "Alice"},
#   {"op": "replace", "path": "/age", "value": 25},
#   {"op": "add", "path": "/hobbies/-", "value": "reading"}
# ]

Different Tracker Types

# Standard JSON Patch (RFC 6902 compliant)
profile, diff_buf = ld.track_change(
    UserProfile(), 
    tracker_cls=ld.JSONPatchChangeTracker
)

# Efficient tracker with append operations (default)
profile, diff_buf = ld.track_change(
    UserProfile(), 
    tracker_cls=ld.EfficientJSONPatchChangeTracker
)

Applying Changes

# Original object
original = {"count": 0, "items": []}

# Changes to apply
changes = [
    {"op": "replace", "path": "/count", "value": 5},
    {"op": "add", "path": "/items/-", "value": "new item"}
]

# Apply changes
ld.apply_change(original, changes)
print(original)
# {"count": 5, "items": ["new item"]}