pycommons.ds package

Some common and shared data structures.

Submodules

pycommons.ds.cache module

A factory for functions checking whether argument values are new.

pycommons.ds.cache.str_is_new()[source]

Create a function returning True when seeing new str values.

Creates a function which returns True only the first time it receives a given string argument and False all subsequent times. This is based on https://stackoverflow.com/questions/27427067

Return type:

Callable[[str], bool]

Returns:

a function str_is_new(xx) that will return True the first time it encounters any value xx and False for all values it has already seen

>>> check = str_is_new()
>>> print(check("a"))
True
>>> print(check("a"))
False
>>> print(check("b"))
True
>>> print(check("b"))
False

pycommons.ds.immutable_map module

An immutable version of the typing.Mapping interface.

class pycommons.ds.immutable_map.K

the type variable for mapping keys

alias of TypeVar(‘K’)

class pycommons.ds.immutable_map.V

the type variable for mapping values

alias of TypeVar(‘V’)

pycommons.ds.immutable_map.immutable_mapping(a)[source]

Create an immutable view of a Mapping.

Parameters:

a (Mapping[TypeVar(K), TypeVar(V)]) – the input Mapping

Return type:

Mapping[TypeVar(K), TypeVar(V)]

Returns:

an immutable view on the Mapping a (the view will change if a is changed, but you cannot change a via the view)

>>> x = {1: 1, 2: 7, 3: 8}
>>> y = immutable_mapping(x)
>>> x is y
False
>>> x == y
True
>>> x[1] == y[1]
True
>>> x[2] == y[2]
True
>>> x[3] == y[3]
True
>>> z = immutable_mapping(x)
>>> x is z
False
>>> x == z
True
>>> y is z
False
>>> z = immutable_mapping(y)
>>> x is z
False
>>> y is z
True
>>> x == z
True
>>> x[9] = 23
>>> y[9] == x[9]
True
>>> try:
...     y[1] = 2
... except TypeError as te:
...     print(te)
'mappingproxy' object does not support item assignment
>>> try:
...     immutable_mapping(5)
... except TypeError as e:
...     print(e)
a should be an instance of typing.Mapping but is int, namely '5'.