Package lazymap

lazymap

A lazy mapping whose values are evaluated when accessed

Installation

You can install this package with pip.

$ pip install lazymap

Documentation

Source Code - GitHub

PyPI - lazymap

Usage

A LazyMap is a mapping whose values can be evaluated only when they are accessed. This is useful when you need a mapping which might not need to evaluate all of its values, but it is unknown which values will be needed.

Not all values of a LazyMap need to be lazily evaluated. You can also store regular values in a LazyMap.

LazyMap also supports caching of values, so that they are only evaluated once, although this can be disabled on a per-object or per-key basis.

Importing

from lazymap import LazyMap

Creating a LazyMap

You can initialize a LazyMap and provide it with initial static values, initial lazy values, a default factory function for missing keys, and any combination of the above. Additionally you can enable (default) or disable caching for the entire LazyMap.

If a default factory function is provided, it will be called with the key as an argument when a key is accessed which is not in the LazyMap.

static = LazyMap({"a": 1, "b": 2})
lazy = LazyMap({"c": lambda: 3})
default = LazyMap(default=lambda key: key * 2)
uncached = LazyMap({"random": lambda: randint(0, 100)}, cache=False)

Creating a LazyMap from keys and a function

You can initialize a LazyMap from a set of keys and a function which will be used to evaluate the value of each key. This way, the values are only evaluated when they are accessed.

You can also pass allow_missing=True to the fromkeys constructor to also use the function as a default factory function for missing keys.

def expensive(key):
    print(f'Calculating value for key {key}...')
    return key * 2

from_keys = LazyMap.fromkeys((1, 2, 3), expensive)

Adding values to a LazyMap

You can add non-lazy values to a LazyMap just like you would a dictionary.

lazy_map = LazyMap()
lazy_map["a"] = 1 # not lazy

You can also add lazy values to a LazyMap with the lazy method.

def get_b():
    print('Calculating value of x...')
    sleep(1)
    return 42

lazy_map.lazy("x", get_x) # lazy
print(lazy_map["x"]) # Calls get_x

Caching values

By default, the lazy values of a LazyMap are only evaluated once. The value is then cached and returned on subsequent accesses.

You can also pass cache=True or cache=False when adding a lazy key with lazy() to override the default caching behaviour for that key.

lazy_map = LazyMap()

def get_value():
    sleep(1)
    return randint(0, 100)

lazy_map.lazy("cached", get_value)
lazy_map.lazy("uncached", get_value, cache=False)

print(lazy_map["cached"]) # 42
print(lazy_map["cached"]) # 42
print(lazy_map["uncached"]) # 69
print(lazy_map["uncached"]) # 13

Classes

class LazyMap (data: Optional[Mapping[~K, ~V]] = None, *, lazy: Optional[Mapping[~K, Callable[[], ~V]]] = None, default: Optional[Callable[[~K], ~V]] = None, cache: bool = True)

A mapping that lazily computes values on demand.

Args

data
Initial data to populate the map. If a mutable mapping is provided, it will be used directly, otherwise it will be converted to a dictionary.
lazy
Initial getters to populate the map. This is a mapping of keys to functions that take no arguments and return the value for the key. If a mutable mapping is provided, it will be used directly, otherwise it will be converted to a dictionary.
default
A callable that takes a key and returns a default value for that key. If a default factory is not provided, a KeyError will be raised for missing keys.
cache
Whether to cache the results of lazy evaluations by default.

Ancestors

  • collections.abc.MutableMapping
  • collections.abc.Mapping
  • collections.abc.Collection
  • collections.abc.Sized
  • collections.abc.Iterable
  • collections.abc.Container
  • typing.Generic

Static methods

def fromkeys(keys: Iterable[~K], getter: Callable[[~K], ~V], *, cache: bool = True, allow_missing: bool = False) ‑> typing_extensions.Self

Create a new LazyMap with the given keys and getter.

Args

keys
The keys to populate the map with.
getter
A function that takes a key and returns the value for that key.
cache
Whether to cache the results of the getter.
allow_missing
Whether to allow using the getter for unknown keys.

Methods

def lazy(self, key: ~K, getter: Callable[[], ~V], cache: Optional[bool] = None) ‑> None

Set a lazy value.

Args

key
The key for the value.
getter
A function that takes no arguments and returns the value.
cache
Whether to cache the result of the getter for this key.