SyncRef

class thread_factory.concurrency.sync_types.sync_ref.SyncRef(obj)[source]

Bases: ISync, Generic[T]


A thread-safe mutable reference to any Python object.

This class allows atomic read/write access, in-place mutation, and transactional control over the wrapped value. It supports compare-and-set, lambda-based transformation, and deep copying for safe inter-thread communication.

Common use cases include:

  • Shared mutable state across threads

  • Agent memory cells

  • Snapshot-style history

  • Dynamic live references (SyncRef[List[Task]], etc.)

Examples:

>>> ref = SyncRef({"key": 42})
>>> ref.update(lambda d: d.update({"key": 99}))
>>> with ref.locked() as obj:
...     obj["other"] = 100
>>> snapshot = ref.get()
>>> ref.cas(snapshot, {"key": 0})
cas(expected: T, new: T) bool[source]

Compare-and-set: if current value is expected (by identity), replace it with new.

Parameters:
  • expected (T) – Expected object reference (not equality).

  • new (T) – Replacement if matched.

Returns:

True if replacement occurred.

Return type:

bool

get() T[source]

Return a snapshot of the current value.

Returns:

A thread-safe read of the internal value.

Return type:

T

locked() Iterator[T][source]

Context manager that locks the object and yields the live reference.

Example

>>> with ref.locked() as obj:
...     obj["key"] = 1
Yields:

T – The internal object (locked during use).

map(fn: Callable[[T], R]) R

Alias for transform() – supports functional pipelines.

modify(fn: Callable[[T], R]) R[source]

Apply a functional update: store and return the result.

Equivalent to: new_val = fn(old_val); set(new_val)

Parameters:

fn (Callable[[T], R]) – A transformer function.

Returns:

The new value.

Return type:

R

set(obj: T) None[source]

Replace the internal value with a new object.

Parameters:

obj (T) – The new value to store.

property snapshot: T

Alias for get() – read-only snapshot of the internal value.

swap(new: T) T[source]

Replace the value and return the old one.

Parameters:

new (T) – New value to store.

Returns:

Previous stored value.

Return type:

T

transform(fn: Callable[[T], R]) R[source]

Read-only application of a function to the stored value.

Parameters:

fn (Callable[[T], R]) – A transformation function.

Returns:

The result of applying the function.

Return type:

R

update(mutator: Callable[[T], Any]) T[source]

Atomically mutate the internal value in place.

The provided function receives the current value and can mutate it. Avoid reentrant calls to the same SyncRef within this function.

Parameters:

mutator (Callable[[T], Any]) – A function that modifies the internal value.

Returns:

The mutated value (same reference).

Return type:

T