File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/pyrsistent.tar
Back
_helpers.py 0000644 00000006240 15030553060 0006716 0 ustar 00 from functools import wraps from pyrsistent._pmap import PMap, pmap from pyrsistent._pset import PSet, pset from pyrsistent._pvector import PVector, pvector def freeze(o, strict=True): """ Recursively convert simple Python containers into pyrsistent versions of those containers. - list is converted to pvector, recursively - dict is converted to pmap, recursively on values (but not keys) - set is converted to pset, but not recursively - tuple is converted to tuple, recursively. If strict == True (default): - freeze is called on elements of pvectors - freeze is called on values of pmaps Sets and dict keys are not recursively frozen because they do not contain mutable data by convention. The main exception to this rule is that dict keys and set elements are often instances of mutable objects that support hash-by-id, which this function can't convert anyway. >>> freeze(set([1, 2])) pset([1, 2]) >>> freeze([1, {'a': 3}]) pvector([1, pmap({'a': 3})]) >>> freeze((1, [])) (1, pvector([])) """ typ = type(o) if typ is dict or (strict and isinstance(o, PMap)): return pmap({k: freeze(v, strict) for k, v in o.items()}) if typ is list or (strict and isinstance(o, PVector)): curried_freeze = lambda x: freeze(x, strict) return pvector(map(curried_freeze, o)) if typ is tuple: curried_freeze = lambda x: freeze(x, strict) return tuple(map(curried_freeze, o)) if typ is set: # impossible to have anything that needs freezing inside a set or pset return pset(o) return o def thaw(o, strict=True): """ Recursively convert pyrsistent containers into simple Python containers. - pvector is converted to list, recursively - pmap is converted to dict, recursively on values (but not keys) - pset is converted to set, but not recursively - tuple is converted to tuple, recursively. If strict == True (the default): - thaw is called on elements of lists - thaw is called on values in dicts >>> from pyrsistent import s, m, v >>> thaw(s(1, 2)) {1, 2} >>> thaw(v(1, m(a=3))) [1, {'a': 3}] >>> thaw((1, v())) (1, []) """ typ = type(o) if isinstance(o, PVector) or (strict and typ is list): curried_thaw = lambda x: thaw(x, strict) return list(map(curried_thaw, o)) if isinstance(o, PMap) or (strict and typ is dict): return {k: thaw(v, strict) for k, v in o.items()} if typ is tuple: curried_thaw = lambda x: thaw(x, strict) return tuple(map(curried_thaw, o)) if isinstance(o, PSet): # impossible to thaw inside psets or sets return set(o) return o def mutant(fn): """ Convenience decorator to isolate mutation to within the decorated function (with respect to the input arguments). All arguments to the decorated function will be frozen so that they are guaranteed not to change. The return value is also frozen. """ @wraps(fn) def inner_f(*args, **kwargs): return freeze(fn(*[freeze(e) for e in args], **dict(freeze(item) for item in kwargs.items()))) return inner_f _pdeque.py 0000644 00000027653 15030553060 0006552 0 ustar 00 from collections.abc import Sequence, Hashable from itertools import islice, chain from numbers import Integral from pyrsistent._plist import plist class PDeque(object): """ Persistent double ended queue (deque). Allows quick appends and pops in both ends. Implemented using two persistent lists. A maximum length can be specified to create a bounded queue. Fully supports the Sequence and Hashable protocols including indexing and slicing but if you need fast random access go for the PVector instead. Do not instantiate directly, instead use the factory functions :py:func:`dq` or :py:func:`pdeque` to create an instance. Some examples: >>> x = pdeque([1, 2, 3]) >>> x.left 1 >>> x.right 3 >>> x[0] == x.left True >>> x[-1] == x.right True >>> x.pop() pdeque([1, 2]) >>> x.pop() == x[:-1] True >>> x.popleft() pdeque([2, 3]) >>> x.append(4) pdeque([1, 2, 3, 4]) >>> x.appendleft(4) pdeque([4, 1, 2, 3]) >>> y = pdeque([1, 2, 3], maxlen=3) >>> y.append(4) pdeque([2, 3, 4], maxlen=3) >>> y.appendleft(4) pdeque([4, 1, 2], maxlen=3) """ __slots__ = ('_left_list', '_right_list', '_length', '_maxlen', '__weakref__') def __new__(cls, left_list, right_list, length, maxlen=None): instance = super(PDeque, cls).__new__(cls) instance._left_list = left_list instance._right_list = right_list instance._length = length if maxlen is not None: if not isinstance(maxlen, Integral): raise TypeError('An integer is required as maxlen') if maxlen < 0: raise ValueError("maxlen must be non-negative") instance._maxlen = maxlen return instance @property def right(self): """ Rightmost element in dqueue. """ return PDeque._tip_from_lists(self._right_list, self._left_list) @property def left(self): """ Leftmost element in dqueue. """ return PDeque._tip_from_lists(self._left_list, self._right_list) @staticmethod def _tip_from_lists(primary_list, secondary_list): if primary_list: return primary_list.first if secondary_list: return secondary_list[-1] raise IndexError('No elements in empty deque') def __iter__(self): return chain(self._left_list, self._right_list.reverse()) def __repr__(self): return "pdeque({0}{1})".format(list(self), ', maxlen={0}'.format(self._maxlen) if self._maxlen is not None else '') __str__ = __repr__ @property def maxlen(self): """ Maximum length of the queue. """ return self._maxlen def pop(self, count=1): """ Return new deque with rightmost element removed. Popping the empty queue will return the empty queue. A optional count can be given to indicate the number of elements to pop. Popping with a negative index is the same as popleft. Executes in amortized O(k) where k is the number of elements to pop. >>> pdeque([1, 2]).pop() pdeque([1]) >>> pdeque([1, 2]).pop(2) pdeque([]) >>> pdeque([1, 2]).pop(-1) pdeque([2]) """ if count < 0: return self.popleft(-count) new_right_list, new_left_list = PDeque._pop_lists(self._right_list, self._left_list, count) return PDeque(new_left_list, new_right_list, max(self._length - count, 0), self._maxlen) def popleft(self, count=1): """ Return new deque with leftmost element removed. Otherwise functionally equivalent to pop(). >>> pdeque([1, 2]).popleft() pdeque([2]) """ if count < 0: return self.pop(-count) new_left_list, new_right_list = PDeque._pop_lists(self._left_list, self._right_list, count) return PDeque(new_left_list, new_right_list, max(self._length - count, 0), self._maxlen) @staticmethod def _pop_lists(primary_list, secondary_list, count): new_primary_list = primary_list new_secondary_list = secondary_list while count > 0 and (new_primary_list or new_secondary_list): count -= 1 if new_primary_list.rest: new_primary_list = new_primary_list.rest elif new_primary_list: new_primary_list = new_secondary_list.reverse() new_secondary_list = plist() else: new_primary_list = new_secondary_list.reverse().rest new_secondary_list = plist() return new_primary_list, new_secondary_list def _is_empty(self): return not self._left_list and not self._right_list def __lt__(self, other): if not isinstance(other, PDeque): return NotImplemented return tuple(self) < tuple(other) def __eq__(self, other): if not isinstance(other, PDeque): return NotImplemented if tuple(self) == tuple(other): # Sanity check of the length value since it is redundant (there for performance) assert len(self) == len(other) return True return False def __hash__(self): return hash(tuple(self)) def __len__(self): return self._length def append(self, elem): """ Return new deque with elem as the rightmost element. >>> pdeque([1, 2]).append(3) pdeque([1, 2, 3]) """ new_left_list, new_right_list, new_length = self._append(self._left_list, self._right_list, elem) return PDeque(new_left_list, new_right_list, new_length, self._maxlen) def appendleft(self, elem): """ Return new deque with elem as the leftmost element. >>> pdeque([1, 2]).appendleft(3) pdeque([3, 1, 2]) """ new_right_list, new_left_list, new_length = self._append(self._right_list, self._left_list, elem) return PDeque(new_left_list, new_right_list, new_length, self._maxlen) def _append(self, primary_list, secondary_list, elem): if self._maxlen is not None and self._length == self._maxlen: if self._maxlen == 0: return primary_list, secondary_list, 0 new_primary_list, new_secondary_list = PDeque._pop_lists(primary_list, secondary_list, 1) return new_primary_list, new_secondary_list.cons(elem), self._length return primary_list, secondary_list.cons(elem), self._length + 1 @staticmethod def _extend_list(the_list, iterable): count = 0 for elem in iterable: the_list = the_list.cons(elem) count += 1 return the_list, count def _extend(self, primary_list, secondary_list, iterable): new_primary_list, extend_count = PDeque._extend_list(primary_list, iterable) new_secondary_list = secondary_list current_len = self._length + extend_count if self._maxlen is not None and current_len > self._maxlen: pop_len = current_len - self._maxlen new_secondary_list, new_primary_list = PDeque._pop_lists(new_secondary_list, new_primary_list, pop_len) extend_count -= pop_len return new_primary_list, new_secondary_list, extend_count def extend(self, iterable): """ Return new deque with all elements of iterable appended to the right. >>> pdeque([1, 2]).extend([3, 4]) pdeque([1, 2, 3, 4]) """ new_right_list, new_left_list, extend_count = self._extend(self._right_list, self._left_list, iterable) return PDeque(new_left_list, new_right_list, self._length + extend_count, self._maxlen) def extendleft(self, iterable): """ Return new deque with all elements of iterable appended to the left. NB! The elements will be inserted in reverse order compared to the order in the iterable. >>> pdeque([1, 2]).extendleft([3, 4]) pdeque([4, 3, 1, 2]) """ new_left_list, new_right_list, extend_count = self._extend(self._left_list, self._right_list, iterable) return PDeque(new_left_list, new_right_list, self._length + extend_count, self._maxlen) def count(self, elem): """ Return the number of elements equal to elem present in the queue >>> pdeque([1, 2, 1]).count(1) 2 """ return self._left_list.count(elem) + self._right_list.count(elem) def remove(self, elem): """ Return new deque with first element from left equal to elem removed. If no such element is found a ValueError is raised. >>> pdeque([2, 1, 2]).remove(2) pdeque([1, 2]) """ try: return PDeque(self._left_list.remove(elem), self._right_list, self._length - 1) except ValueError: # Value not found in left list, try the right list try: # This is severely inefficient with a double reverse, should perhaps implement a remove_last()? return PDeque(self._left_list, self._right_list.reverse().remove(elem).reverse(), self._length - 1) except ValueError as e: raise ValueError('{0} not found in PDeque'.format(elem)) from e def reverse(self): """ Return reversed deque. >>> pdeque([1, 2, 3]).reverse() pdeque([3, 2, 1]) Also supports the standard python reverse function. >>> reversed(pdeque([1, 2, 3])) pdeque([3, 2, 1]) """ return PDeque(self._right_list, self._left_list, self._length) __reversed__ = reverse def rotate(self, steps): """ Return deque with elements rotated steps steps. >>> x = pdeque([1, 2, 3]) >>> x.rotate(1) pdeque([3, 1, 2]) >>> x.rotate(-2) pdeque([3, 1, 2]) """ popped_deque = self.pop(steps) if steps >= 0: return popped_deque.extendleft(islice(self.reverse(), steps)) return popped_deque.extend(islice(self, -steps)) def __reduce__(self): # Pickling support return pdeque, (list(self), self._maxlen) def __getitem__(self, index): if isinstance(index, slice): if index.step is not None and index.step != 1: # Too difficult, no structural sharing possible return pdeque(tuple(self)[index], maxlen=self._maxlen) result = self if index.start is not None: result = result.popleft(index.start % self._length) if index.stop is not None: result = result.pop(self._length - (index.stop % self._length)) return result if not isinstance(index, Integral): raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__) if index >= 0: return self.popleft(index).left shifted = len(self) + index if shifted < 0: raise IndexError( "pdeque index {0} out of range {1}".format(index, len(self)), ) return self.popleft(shifted).left index = Sequence.index Sequence.register(PDeque) Hashable.register(PDeque) def pdeque(iterable=(), maxlen=None): """ Return deque containing the elements of iterable. If maxlen is specified then len(iterable) - maxlen elements are discarded from the left to if len(iterable) > maxlen. >>> pdeque([1, 2, 3]) pdeque([1, 2, 3]) >>> pdeque([1, 2, 3, 4], maxlen=2) pdeque([3, 4], maxlen=2) """ t = tuple(iterable) if maxlen is not None: t = t[-maxlen:] length = len(t) pivot = int(length / 2) left = plist(t[:pivot]) right = plist(t[pivot:], reverse=True) return PDeque(left, right, length, maxlen) def dq(*elements): """ Return deque containing all arguments. >>> dq(1, 2, 3) pdeque([1, 2, 3]) """ return pdeque(elements) typing.pyi 0000644 00000024251 15030553060 0006602 0 ustar 00 # flake8: noqa: E704 # from https://gist.github.com/WuTheFWasThat/091a17d4b5cab597dfd5d4c2d96faf09 # Stubs for pyrsistent (Python 3.6) # from typing import Any from typing import Callable from typing import Dict from typing import Generic from typing import Hashable from typing import Iterator from typing import Iterable from typing import List from typing import Mapping from typing import Optional from typing import Sequence from typing import AbstractSet from typing import Sized from typing import Set from typing import Tuple from typing import TypeVar from typing import Type from typing import Union from typing import overload T = TypeVar('T') KT = TypeVar('KT') VT = TypeVar('VT') class PMap(Mapping[KT, VT], Hashable): def __add__(self, other: PMap[KT, VT]) -> PMap[KT, VT]: ... def __getitem__(self, key: KT) -> VT: ... def __getattr__(self, key: str) -> VT: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[KT]: ... def __len__(self) -> int: ... def copy(self) -> PMap[KT, VT]: ... def discard(self, key: KT) -> PMap[KT, VT]: ... def evolver(self) -> PMapEvolver[KT, VT]: ... def iteritems(self) -> Iterable[Tuple[KT, VT]]: ... def iterkeys(self) -> Iterable[KT]: ... def itervalues(self) -> Iterable[VT]: ... def remove(self, key: KT) -> PMap[KT, VT]: ... def set(self, key: KT, val: VT) -> PMap[KT, VT]: ... def transform(self, *transformations: Any) -> PMap[KT, VT]: ... def update(self, *args: Mapping): ... def update_with(self, update_fn: Callable[[VT, VT], VT], *args: Mapping) -> Any: ... class PMapEvolver(Generic[KT, VT]): def __delitem__(self, key: KT) -> None: ... def __getitem__(self, key: KT) -> VT: ... def __len__(self) -> int: ... def __setitem__(self, key: KT, val: VT) -> None: ... def is_dirty(self) -> bool: ... def persistent(self) -> PMap[KT, VT]: ... def remove(self, key: KT) -> PMapEvolver[KT, VT]: ... def set(self, key: KT, val: VT) -> PMapEvolver[KT, VT]: ... class PVector(Sequence[T], Hashable): def __add__(self, other: PVector[T]) -> PVector[T]: ... @overload def __getitem__(self, index: int) -> T: ... @overload def __getitem__(self, index: slice) -> PVector[T]: ... def __hash__(self) -> int: ... def __len__(self) -> int: ... def __mul__(self, other: PVector[T]) -> PVector[T]: ... def append(self, val: T) -> PVector[T]: ... def delete(self, index: int, stop: Optional[int]) -> PVector[T]: ... def evolver(self) -> PVectorEvolver[T]: ... def extend(self, obj: Iterable[T]) -> PVector[T]: ... def tolist(self) -> List[T]: ... def mset(self, *args: Iterable[Union[T, int]]) -> PVector[T]: ... def remove(self, value: T) -> PVector[T]: ... # Not compatible with MutableSequence def set(self, i: int, val: T) -> PVector[T]: ... def transform(self, *transformations: Any) -> PVector[T]: ... class PVectorEvolver(Sequence[T], Sized): def __delitem__(self, i: Union[int, slice]) -> None: ... @overload def __getitem__(self, index: int) -> T: ... # Not actually supported @overload def __getitem__(self, index: slice) -> PVectorEvolver[T]: ... def __len__(self) -> int: ... def __setitem__(self, index: int, val: T) -> None: ... def append(self, val: T) -> PVectorEvolver[T]: ... def delete(self, value: T) -> PVectorEvolver[T]: ... def extend(self, obj: Iterable[T]) -> PVectorEvolver[T]: ... def is_dirty(self) -> bool: ... def persistent(self) -> PVector[T]: ... def set(self, i: int, val: T) -> PVectorEvolver[T]: ... class PSet(AbstractSet[T], Hashable): def __contains__(self, element: object) -> bool: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[T]: ... def __len__(self) -> int: ... def add(self, element: T) -> PSet[T]: ... def copy(self) -> PSet[T]: ... def difference(self, iterable: Iterable) -> PSet[T]: ... def discard(self, element: T) -> PSet[T]: ... def evolver(self) -> PSetEvolver[T]: ... def intersection(self, iterable: Iterable) -> PSet[T]: ... def issubset(self, iterable: Iterable) -> bool: ... def issuperset(self, iterable: Iterable) -> bool: ... def remove(self, element: T) -> PSet[T]: ... def symmetric_difference(self, iterable: Iterable[T]) -> PSet[T]: ... def union(self, iterable: Iterable[T]) -> PSet[T]: ... def update(self, iterable: Iterable[T]) -> PSet[T]: ... class PSetEvolver(Generic[T], Sized): def __len__(self) -> int: ... def add(self, element: T) -> PSetEvolver[T]: ... def is_dirty(self) -> bool: ... def persistent(self) -> PSet[T]: ... def remove(self, element: T) -> PSetEvolver[T]: ... class PBag(Generic[T], Sized, Hashable): def __add__(self, other: PBag[T]) -> PBag[T]: ... def __and__(self, other: PBag[T]) -> PBag[T]: ... def __contains__(self, elem: object) -> bool: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[T]: ... def __len__(self) -> int: ... def __or__(self, other: PBag[T]) -> PBag[T]: ... def __sub__(self, other: PBag[T]) -> PBag[T]: ... def add(self, elem: T) -> PBag[T]: ... def count(self, elem: T) -> int: ... def remove(self, elem: T) -> PBag[T]: ... def update(self, iterable: Iterable[T]) -> PBag[T]: ... class PDeque(Sequence[T], Hashable): @overload def __getitem__(self, index: int) -> T: ... @overload def __getitem__(self, index: slice) -> PDeque[T]: ... def __hash__(self) -> int: ... def __len__(self) -> int: ... def __lt__(self, other: PDeque[T]) -> bool: ... def append(self, elem: T) -> PDeque[T]: ... def appendleft(self, elem: T) -> PDeque[T]: ... def extend(self, iterable: Iterable[T]) -> PDeque[T]: ... def extendleft(self, iterable: Iterable[T]) -> PDeque[T]: ... @property def left(self) -> T: ... # The real return type is Integral according to what pyrsistent # checks at runtime but mypy doesn't deal in numeric.*: # https://github.com/python/mypy/issues/2636 @property def maxlen(self) -> int: ... def pop(self, count: int = 1) -> PDeque[T]: ... def popleft(self, count: int = 1) -> PDeque[T]: ... def remove(self, elem: T) -> PDeque[T]: ... def reverse(self) -> PDeque[T]: ... @property def right(self) -> T: ... def rotate(self, steps: int) -> PDeque[T]: ... class PList(Sequence[T], Hashable): @overload def __getitem__(self, index: int) -> T: ... @overload def __getitem__(self, index: slice) -> PList[T]: ... def __hash__(self) -> int: ... def __len__(self) -> int: ... def __lt__(self, other: PList[T]) -> bool: ... def __gt__(self, other: PList[T]) -> bool: ... def cons(self, elem: T) -> PList[T]: ... @property def first(self) -> T: ... def mcons(self, iterable: Iterable[T]) -> PList[T]: ... def remove(self, elem: T) -> PList[T]: ... @property def rest(self) -> PList[T]: ... def reverse(self) -> PList[T]: ... def split(self, index: int) -> Tuple[PList[T], PList[T]]: ... T_PClass = TypeVar('T_PClass', bound='PClass') class PClass(Hashable): def __new__(cls, **kwargs: Any): ... def set(self: T_PClass, *args: Any, **kwargs: Any) -> T_PClass: ... @classmethod def create( cls: Type[T_PClass], kwargs: Any, _factory_fields: Optional[Any] = ..., ignore_extra: bool = ..., ) -> T_PClass: ... def serialize(self, format: Optional[Any] = ...): ... def transform(self, *transformations: Any): ... def __eq__(self, other: object): ... def __ne__(self, other: object): ... def __hash__(self): ... def __reduce__(self): ... def evolver(self) -> PClassEvolver: ... def remove(self: T_PClass, name: Any) -> T_PClass: ... class PClassEvolver: def __init__(self, original: Any, initial_dict: Any) -> None: ... def __getitem__(self, item: Any): ... def set(self, key: Any, value: Any): ... def __setitem__(self, key: Any, value: Any) -> None: ... def remove(self, item: Any): ... def __delitem__(self, item: Any) -> None: ... def persistent(self) -> PClass: ... def __getattr__(self, item: Any): ... class CheckedPMap(PMap[KT, VT]): __key_type__: Type[KT] __value_type__: Type[VT] def __new__(cls, source: Mapping[KT, VT] = ..., size: int = ...) -> CheckedPMap: ... @classmethod def create(cls, source_data: Mapping[KT, VT], _factory_fields: Any = ...) -> CheckedPMap[KT, VT]: ... def serialize(self, format: Optional[Any] = ...) -> Dict[KT, VT]: ... class CheckedPVector(PVector[T]): __type__: Type[T] def __new__(self, initial: Iterable[T] = ...) -> CheckedPVector: ... @classmethod def create(cls, source_data: Iterable[T], _factory_fields: Any = ...) -> CheckedPVector[T]: ... def serialize(self, format: Optional[Any] = ...) -> List[T]: ... class CheckedPSet(PSet[T]): __type__: Type[T] def __new__(cls, initial: Iterable[T] = ...) -> CheckedPSet: ... @classmethod def create(cls, source_data: Iterable[T], _factory_fields: Any = ...) -> CheckedPSet[T]: ... def serialize(self, format: Optional[Any] = ...) -> Set[T]: ... class InvariantException(Exception): invariant_errors: Tuple[Any, ...] = ... # possibly nested tuple missing_fields: Tuple[str, ...] = ... def __init__( self, error_codes: Any = ..., missing_fields: Any = ..., *args: Any, **kwargs: Any ) -> None: ... class CheckedTypeError(TypeError): source_class: Type[Any] expected_types: Tuple[Any, ...] actual_type: Type[Any] actual_value: Any def __init__( self, source_class: Any, expected_types: Any, actual_type: Any, actual_value: Any, *args: Any, **kwargs: Any ) -> None: ... class CheckedKeyTypeError(CheckedTypeError): ... class CheckedValueTypeError(CheckedTypeError): ... class CheckedType: ... class PTypeError(TypeError): source_class: Type[Any] = ... field: str = ... expected_types: Tuple[Any, ...] = ... actual_type: Type[Any] = ... def __init__( self, source_class: Any, field: Any, expected_types: Any, actual_type: Any, *args: Any, **kwargs: Any ) -> None: ... __pycache__/_pclass.cpython-310.pyc 0000644 00000023313 15030553060 0013100 0 ustar 00 o ���a�% � @ s� d dl mZmZmZmZ d dlmZmZmZm Z m Z mZ d dlm Z dd� ZG dd� de�Ze� Zdd � ZG d d� deed�ZG d d� de�ZdS )� )�InvariantException�CheckedType�_restore_pickle�store_invariants)� set_fields� check_type�is_field_ignore_extra_complaint�PFIELD_NO_INITIAL� serialize�check_global_invariants�� transformc C s t | �dko| d tkS )N� r )�lenr )�bases� r �4/usr/lib/python3/dist-packages/pyrsistent/_pclass.py� _is_pclass s r c s e Zd Z� fdd�Z� ZS )� PClassMetac sh t ||dd� t||dd� dtdd� |d D �� |d<