lazy_dict

Dictionary with lazy evaluation on access, via a supplied update function

class cmepy.lazy_dict.LazyDict(update_value, items=None)

A dictionary type that lazily updates values when they are accessed.

All the usual dictionary methods work as expected, with automatic lazy updates occuring behind the scenes whenever values are read from the dictionary.

The optional items argument, if specified, is a mapping instance used to initialise the items in the LazyDict.

The update_value argument required by the LazyDict constructor must be a function of the form:

update_value(k, existing_value, member) -> updated_value

This function is called whenever an item with the key k is read from the LazyDict. The second argument existing_value, is the value corresponding to the key k stored in the LazyDict, or None, if the key k is not contained in the LazyDict. The third argument member is a boolean value indicating if there is an existing value stored under the key k.

This function is used as follows by the LazyDict. Suppose that the value v has been stored in a LazyDict object lazy_dict under the key k, that is, lazy_dict[k] = v. Then subsequently accessing this value in the usual manner:

v_updated = lazy_dict[k]

is equivalent to the following two statements:

lazy_dict[k] = update_value(k, v, (k in lazy_dict))
v_updated = update_value(k, v, (k in lazy_dict))

Observe how the value stored in the LazyDict under the key k is first updated, using the provided function, with the updated value then being the one returned.

Previous topic

FSP example 2 : support expansion

Next topic

lexarrayset

This Page