from abc import abstractmethod, ABCMeta from collections.abc import Sequence, Hashable from numbers import Integral import operator from typing import TypeVar, Generic
def _index_or_slice(index, stop): if stop isNone: return index
return slice(index, stop)
class PythonPVector(object): """
Support structure for PVector that implements structural sharing for vectors using a trie. """
__slots__ = ('_count', '_shift', '_root', '_tail', '_tail_offset', '__weakref__')
def __getitem__(self, index): if isinstance(index, slice): # There are more conditions than the below where it would be OK to # return ourselves, implement those... if index.start isNoneand index.stop isNoneand index.step isNone: return self
# This is a bit nasty realizing the whole structure as a list before # slicing it but it is the fastest way I've found to date, and it's easy :-) return _EMPTY_PVECTOR.extend(self.tolist()[index])
def __iter__(self): # This is kind of lazy and will produce some memory overhead but it is the fasted method # by far of those tried since it uses the speed of the built in python list directly. return iter(self.tolist())
def __eq__(self, other): return self is other or (hasattr(other, '__len__') and self._count == len(other)) and compare_pvector(self, other, operator.eq)
def _fill_list(self, node, shift, the_list): if shift:
shift -= SHIFT for n in node:
self._fill_list(n, shift, the_list) else:
the_list.extend(node)
def tolist(self): """
The fastest way to convert the vector into a python list. """
the_list = []
self._fill_list(self._root, self._shift, the_list)
the_list.extend(self._tail) return the_list
def _totuple(self): """
Returns the content as a python tuple. """ return tuple(self.tolist())
def __hash__(self): # Taking the easy way out again... return hash(self._totuple())
def set(self, index, val):
self[index] = val return self
def __setitem__(self, index, val): ifnot isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__)
if index < 0:
index += self._count + len(self._extra_tail)
if 0 <= index < self._count:
node = self._cached_leafs.get(index >> SHIFT) if node:
node[index & BIT_MASK] = val elif index >= self._tail_offset: if id(self._tail) notin self._dirty_nodes:
self._tail = list(self._tail)
self._dirty_nodes[id(self._tail)] = True
self._cached_leafs[index >> SHIFT] = self._tail
self._tail[index & BIT_MASK] = val else:
self._root = self._do_set(self._shift, self._root, index, val) elif self._count <= index < self._count + len(self._extra_tail):
self._extra_tail[index - self._count] = val elif index == self._count + len(self._extra_tail):
self._extra_tail.append(val) else: raise IndexError("Index out of range: %s" % (index,))
def _do_set(self, level, node, i, val): if id(node) in self._dirty_nodes:
ret = node else:
ret = list(node)
self._dirty_nodes[id(ret)] = True
if level == 0:
ret[i & BIT_MASK] = val
self._cached_leafs[i >> SHIFT] = ret else:
sub_index = (i >> level) & BIT_MASK # >>>
ret[sub_index] = self._do_set(level - SHIFT, node[sub_index], i, val)
return ret
def delete(self, index): del self[index] return self
def __delitem__(self, key): if self._orig_pvector: # All structural sharing bets are off, base evolver on _extra_tail only
l = PythonPVector(self._count, self._shift, self._root, self._tail).tolist()
l.extend(self._extra_tail)
self._reset(_EMPTY_PVECTOR)
self._extra_tail = l
del self._extra_tail[key]
def persistent(self):
result = self._orig_pvector if self.is_dirty():
result = PythonPVector(self._count, self._shift, self._root, self._tail).extend(self._extra_tail)
self._reset(result)
def set(self, i, val): # This method could be implemented by a call to mset() but doing so would cause # a ~5 X performance penalty on PyPy (considered the primary platform for this implementation # of PVector) so we're keeping this implementation for now.
ifnot isinstance(i, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(i).__name__)
if i < 0:
i += self._count
if 0 <= i < self._count: if i >= self._tail_offset:
new_tail = list(self._tail)
new_tail[i & BIT_MASK] = val return PythonPVector(self._count, self._shift, self._root, new_tail)
return PythonPVector(self._count, self._shift, self._do_set(self._shift, self._root, i, val), self._tail)
if i == self._count: return self.append(val)
raise IndexError("Index out of range: %s" % (i,))
def _do_set(self, level, node, i, val):
ret = list(node) if level == 0:
ret[i & BIT_MASK] = val else:
sub_index = (i >> level) & BIT_MASK # >>>
ret[sub_index] = self._do_set(level - SHIFT, node[sub_index], i, val)
return ret
@staticmethod def _node_for(pvector_like, i): if 0 <= i < pvector_like._count: if i >= pvector_like._tail_offset: return pvector_like._tail
node = pvector_like._root for level in range(pvector_like._shift, 0, -SHIFT):
node = node[(i >> level) & BIT_MASK] # >>>
def extend(self, obj): # Mutates the new vector directly for efficiency but that's only an # implementation detail, once it is returned it should be considered immutable
l = obj.tolist() if isinstance(obj, PythonPVector) else list(obj) if l:
new_vector = self.append(l[0])
new_vector._mutating_extend(l[1:]) return new_vector
return self
def _push_tail(self, level, parent, tail_node): """ if parent is leaf, insert node, else does it map to an existing child? ->
node_to_insert = push node one more level else alloc new path
return node_to_insert placed in copy of parent """
ret = list(parent)
if level == SHIFT:
ret.append(tail_node) return ret
def delete(self, index, stop=None):
l = self.tolist() del l[_index_or_slice(index, stop)] return _EMPTY_PVECTOR.extend(l)
def remove(self, value):
l = self.tolist()
l.remove(value) return _EMPTY_PVECTOR.extend(l)
class PVector(Generic[T_co],metaclass=ABCMeta): """
Persistent vector implementation. Meant as a replacement for the cases where you would normally
use a Python list.
Do not instantiate directly, instead use the factory functions :py:func:`v` and :py:func:`pvector` to
create an instance.
Heavily influenced by the persistent vector available in Clojure. Initially this was more or
less just a port of the Java code for the Clojure vector. It has since been modified and to
some extent optimized for usage in Python.
The vector is organized as a trie, any mutating method will return a new vector that contains the changes. No
updates are done to the original vector. Structural sharing between vectors are applied where possible to save
space and to avoid making complete copies.
This structure corresponds most closely to the built in list type andis intended as a replacement. Where the
semantics are the same (more or less) the same function names have been used but for some cases it isnot possible, for example assignments.
The PVector implements the Sequence protocol andis Hashable.
Inserts are amortized O(1). Random access is log32(n) where n is the size of the vector.
The following are examples of some common operations on persistent vectors:
@abstractmethod def evolver(self): """
Create a new evolver for this pvector. The evolver acts as a mutable view of the vector with"transaction like" semantics. No part of the underlying vector i updated, it is still
fully immutable. Furthermore multiple evolvers created from the same pvector do not
interfere with each other.
You may want to use an evolver instead of working directly with the pvector in the
following cases:
* Multiple updates are done to the same vector and the intermediate results are of no
interest. In this case using an evolver may be a more efficient and easier to work with.
* You need to pass a vector into a legacy function or a function that you have no control
over which performs in place mutations of lists. In this case pass an evolver instance
instead and then create a new pvector from the evolver once the function returns.
The following example illustrates a typical workflow when working with evolvers. It also
displays most of the API (which i kept small by design, you should not be tempted to
use evolvers in excess ;-)).
Create the evolver and perform various mutating updates to it:
@abstractmethod def extend(self, obj): """ Return a new vector with all values in obj appended to it. Obj may be another
PVector or any other Iterable.
@abstractmethod def index(self, value, *args, **kwargs): """ Return first index of value. Additional indexes may be supplied to limit the search to a
sub range of the vector.
@abstractmethod def count(self, value): """ Return the number of times that value appears in the vector.
>>> v1 = v(1, 4, 3, 4)
>>> v1.count(4)
2 """
@abstractmethod def transform(self, *transformations): """
Transform arbitrarily complex combinations of PVectors and PMaps. A transformation
consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation.
>>> from pyrsistent import freeze, ny
>>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'},
... {'author': 'Steve', 'content': 'A slightly longer article'}],
... 'weather': {'temperature': '11C', 'wind': '5m/s'}})
>>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...'iflen(c) > 25 else c)
>>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...'if len(c) > 15 else c)
>>> very_short_news.articles[0].content 'A short article'
>>> very_short_news.articles[1].content 'A slightly long...'
When nothing has been transformed the original data structure is kept
>>> short_news is news_paper True
>>> very_short_news is news_paper False
>>> very_short_news.articles[0] is news_paper.articles[0] True """
@abstractmethod def delete(self, index, stop=None): """
Delete a portion of the vector by index or range.
try: # Use the C extension as underlying trie implementation if it is available import os if os.environ.get('PYRSISTENT_NO_C_EXTENSION'):
pvector = python_pvector else: from pvectorc import pvector
PVector.register(type(pvector())) except ImportError:
pvector = python_pvector
def v(*elements): """
Create a new persistent vector containing all parameters to this function.
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.