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 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.JSONPatchChangeTracker
¶
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
)