pax_global_header00006660000000000000000000000064147756044510014527gustar00rootroot0000000000000052 comment=c07a7419e0b234a428332a3477cb7c2b5c870ad6 orderly-set-5.3.2/000077500000000000000000000000001477560445100140075ustar00rootroot00000000000000orderly-set-5.3.2/.codecov.yml000066400000000000000000000000661477560445100162340ustar00rootroot00000000000000comment: layout: "diff" require_changes: true orderly-set-5.3.2/.coveragerc000066400000000000000000000000541477560445100161270ustar00rootroot00000000000000[run] branch = True source = orderly_set.py orderly-set-5.3.2/.flake8000066400000000000000000000000371477560445100151620ustar00rootroot00000000000000[flake8] max-line-length = 100 orderly-set-5.3.2/.github/000077500000000000000000000000001477560445100153475ustar00rootroot00000000000000orderly-set-5.3.2/.github/FUNDING.yml000066400000000000000000000000431477560445100171610ustar00rootroot00000000000000github: [seperman] ko_fi: seperman orderly-set-5.3.2/.github/ISSUE_TEMPLATE/000077500000000000000000000000001477560445100175325ustar00rootroot00000000000000orderly-set-5.3.2/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000011161477560445100222230ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior **Expected behavior** A clear and concise description of what you expected to happen. **OS, Orderly-set version and Python version (please complete the following information):** - OS: [e.g. Ubuntu] - Version [e.g. 20LTS] - Python Version [e.g. 3.9.12] - orderly-set Version [e.g. 5.8.0] **Additional context** Add any other context about the problem here. orderly-set-5.3.2/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000011231477560445100232540ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. orderly-set-5.3.2/.github/workflows/000077500000000000000000000000001477560445100174045ustar00rootroot00000000000000orderly-set-5.3.2/.github/workflows/main.yaml000066400000000000000000000032741477560445100212220ustar00rootroot00000000000000name: Unit Tests on: push: branches: [ "master", "dev" ] pull_request: branches: [ "master", "dev" ] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: [3.8, 3.9, "3.10", "3.11", "3.12", "3.13"] architecture: ["x64"] steps: - uses: actions/checkout@v4 - name: Setup Python ${{ matrix.python-version }} on ${{ matrix.architecture }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} architecture: ${{ matrix.architecture }} - name: Cache pip uses: actions/cache@v4 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('requirements-dev.txt') }} restore-keys: | ${{ runner.os }}-pip- ${{ runner.os }}- - name: Upgrade setuptools if: matrix.python-version == 3.12 run: | # workaround for 3.12, SEE: https://github.com/pypa/setuptools/issues/3661#issuecomment-1813845177 pip install --upgrade setuptools - name: Install dependencies run: pip install -r requirements-dev.txt - name: Test with pytest and get the coverage if: matrix.python-version == 3.12 run: | pytest --cov-report=xml --cov=orderly_set tests/ - name: Test with pytest and no coverage report if: matrix.python-version != 3.12 run: | pytest - name: Upload coverage to Codecov uses: codecov/codecov-action@v4 if: matrix.python-version == 3.12 env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} with: file: ./coverage.xml token: ${{ secrets.CODECOV_TOKEN }} env_vars: OS,PYTHON fail_ci_if_error: true orderly-set-5.3.2/.gitignore000066400000000000000000000002061477560445100157750ustar00rootroot00000000000000*.pyc *~ .DS_Store .*.swp *.egg-info dist/ .tox/ .coverage .pytest_cache htmlcov .eggs .venv .python-version build .idea coverage.xml orderly-set-5.3.2/.mailmap000066400000000000000000000007731477560445100154370ustar00rootroot00000000000000# Elia has used different names and e-mail addresses in the course of this project. Map them all to her current name and e-mail. Elia Robyn Lake Elia Robyn Lake Elia Robyn Lake Elia Robyn Lake Elia Robyn Lake Elia Robyn Lake Elia Robyn Lake orderly-set-5.3.2/.pre-commit-config.yaml000066400000000000000000000004731477560445100202740ustar00rootroot00000000000000files: 'orderly_set/' repos: - repo: https://github.com/psf/black rev: 22.3.0 hooks: - id: black - repo: https://github.com/pycqa/flake8 rev: 5.0.4 hooks: - id: flake8 - repo: https://github.com/pycqa/isort rev: 5.10.1 hooks: - id: isort args: ["--profile", "black"] orderly-set-5.3.2/AUTHORS.md000066400000000000000000000007701477560445100154620ustar00rootroot00000000000000# Authors Authors in the chronological orders of contributions - Raymond Hettiger - OrderedSet was implemented by Elia Robyn Lake (maiden name: Robyn Speer). - StableSet was implemented by Idan Miara, built upon the foundations of OrderedSet. - Jon Crall contributed changes and tests to make it fit the Python set API. - Roman Inflianskas added the original type annotations. - Sep Dehpour added OrderlySet and SortedSet. - Michał Górny cleaned up some small issues with mypy and deprecated use of orderly-set-5.3.2/CHANGELOG.md000066400000000000000000000057501477560445100156270ustar00rootroot00000000000000# Changelog Significant changes in major and minor releases of this library: ## Version 5.3.2 (2025) - Better support for freezing sets. ## Version 5.3.1 (2025) - Additional type hints ## Version 5.3.0 (2025) - Added freeze() to make stable sets immutable ## Version 5.2.x (2024) - Added Sorted Set and Orderly Set ## Version 5.2 (February 2022) - Major refactor - Added a StableSet implementation, as a base class for OrderedSet. - Added Many functions to OrderedSet, to be more complete and more compatible with other implementations. - popitem(last: bool = True), similar to `dict.popitem` (note minor incompatibility with another implementation (`orderedset`) that have the `last` keyword in the `pop` function) - move_to_end(key), similar to `dict.move_to_end` - __le__, __lt__, __ge__, __gt__ - to improve subset/superset testing - Minimum Python version is 3.8 (because __reversed__) - Fix: OrderedSet.update now raised a TypeError instead of a ValueError when the type of the input is incorrect - Added many new tests, and all the tests from 2 other implementations. ## Version 4.1 (January 2022) - Packaged using flit. Wheels now exist, and setuptools is no longer required. - This package now has a typical package structure, instead of being a single module. The code is in `orderly_set/__init__.py` instead of `orderly_set.py`. - There is an `orderly_set/py.typed` so that type checkers know about the types. - Use the type aliases `SetLike[T]` and `OrderedSetInitializer[T]` to simplify some types. - Updated the way overloaded type signatures are written to what MyPy currently expects. - Minimum Python version is 3.7. ## Version 4.0 (January 2020) - Added type signatures inline to the code, instead of using type stubs. - Dropped Python 2 support. The minimum supported Python version is 3.5. ## Version 3.1 (November 2018) - `__getitem__` accepts NumPy arrays of indices, and returns a list of elements with those indices. - Updated in-place operations that took O(N^2) time, such as .difference_update(), to take O(N) time. - Clarified whether various methods mutate or copy the OrderedSet. - Added `OrderedSet.get_loc` and `OrderedSet.get_indexer` as aliases for `OrderedSet.index`, for interoperability with `pandas.Index`. - Added type stubs in a .pyi file. ## Version 3.0 (June 2018) - Implemented the abstract base classes `collections.MutableSet` and `collections.Sequence`. - Changed the behavior of some methods to follow the MutableSet API. - Indexing an OrderedSet with `[:]` returns a copy, not the same object. ## Version 2.0 (December 2015) - Tuples are allowable values in the set, and are not treated as "fancy indexing". - Added `update` and `pop` methods. ## Version 1.4 (September 2015) - Added `discard` and `clear` methods. ## Version 1.3 (April 2015) - Added support for pickling. ## Version 1.2 (May 2014) - First Python 3 support. ## Version 1.1 (August 2013) - Added tests. - Removed a broken implementation of `discard`. ## Version 1.0 (August 2012) - First release. orderly-set-5.3.2/MANIFEST.in000066400000000000000000000000471477560445100155460ustar00rootroot00000000000000include tests/*.py include MIT-LICENSE orderly-set-5.3.2/MIT-LICENSE000066400000000000000000000021131477560445100154400ustar00rootroot00000000000000Copyright (c) 2012-2022 Elia Robyn Lake, 2023 Idan Miara, 2024 Sep Dehpour Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. orderly-set-5.3.2/README.md000066400000000000000000000120031477560445100152620ustar00rootroot00000000000000# Orderly Set 5.3.2 Orderly Set is a package containing multiple implementations of Ordered Set. ## OrderlySet This implementation keeps the order in all set operations except set difference operations. As a result, it can do set difference operations much faster than other implementations. Still 2X slower than of Python's built-in set. ## StableSet A StableSet is a mutable set that remembers its insertion order. Featuring: Fast O(1) insertion, deletion, iteration and membership testing. But slow O(N) Index Lookup. ## StableSetEq Same as StableSet but the order of items doesn't matter for equality comparisons. ## OrderedSet An OrderedSet is a mutable data structure that is a hybrid of a list and a set. It remembers its insertion order so that every entry has an index that can be looked up. Featuring: O(1) Index lookup, insertion, iteration and membership testing. But slow O(N) Deletion. ## SortedSet SortedSet is basically set but when printed, turned into string, or iterated over, returns the items in alphabetical order. # Installation `pip install orderly-set` # Usage examples An OrderedSet is created and used like a set: >>> from orderly_set import OrderedSet >>> letters = OrderedSet('abracadabra') >>> letters OrderedSet(['a', 'b', 'r', 'c', 'd']) >>> 'r' in letters True It is efficient to find the index of an entry in an OrderedSet, or find an entry by its index. To help with this use case, the `.add()` method returns the index of the added item, whether it was already in the set or not. >>> letters.index('r') 2 >>> letters[2] 'r' >>> letters.add('r') 2 >>> letters.add('x') 5 OrderedSets implement the union (`|`), intersection (`&`), and difference (`-`) operators like sets do. >>> letters |= OrderedSet('shazam') >>> letters OrderedSet(['a', 'b', 'r', 'c', 'd', 'x', 's', 'h', 'z', 'm']) >>> letters & set('aeiou') OrderedSet(['a']) >>> letters -= 'abcd' >>> letters OrderedSet(['r', 'x', 's', 'h', 'z', 'm']) The `__getitem__()` and `index()` methods have been extended to accept any iterable except a string, returning a list, to perform NumPy-like "fancy indexing". >>> letters = OrderedSet('abracadabra') >>> letters[[0, 2, 3]] ['a', 'r', 'c'] >>> letters.index(['a', 'r', 'c']) [0, 2, 3] OrderedSet implements `__getstate__` and `__setstate__` so it can be pickled, and implements the abstract base classes `collections.MutableSet` and `collections.Sequence`. OrderedSet can be used as a generic collection type, similar to the collections in the `typing` module like List, Dict, and Set. For example, you can annotate a variable as having the type `OrderedSet[str]` or `OrderedSet[Tuple[int, str]]`. # Authors Please check the [Authors](AUTHORS.md) file. # Comparisons ``` -- initialize a set -- Using Python dict time: 4.13 set time: 2.98 ordered_set.OrderedSet time: 15.77 orderly_set.OrderedSet time: 15.25 StableSet time: 4.78 OrderlySet time: 4.38 SortedSet time: 3.09 -- update a set -- Using Python dict: 6.77 set time: 2.46 ordered_set.OrderedSet time: 10.17 orderly_set.OrderedSet time: 10.06 StableSet time: 7.16 OrderlySet time: 6.77 SortedSet time: 2.46 -- update a set and get item -- ordered_set.OrderedSet time: 29.98 orderly_set.OrderedSet time: 29.57 StableSet time: 14.31 OrderlySet time: 14.23 SortedSet time: 9.03 -- set symmetric difference (xor) -- set time: 5.368663903005654 ordered_set.OrderedSet time: 39.25 orderly_set.OrderedSet time: 80.31 StableSet time: 42.81 OrderlySet time: 11.44 SortedSet time: 3.87 -- set difference (-) -- set time: 3.7398674299911363 ordered_set.OrderedSet time: 22.39 orderly_set.OrderedSet time: 38.00 StableSet time: 22.30 OrderlySet time: 8.92 SortedSet time: 3.03 ``` Despite what you see in the benchmarks, in DeepDiff OrderlySet performed better than SortedSet. A StableSet is a mutable set that remembers its insertion order. Featuring: Fast O(1) insertion, deletion, iteration and membership testing. But slow O(N) Index Lookup. An OrderedSet is a mutable data structure that is a hybrid of a list and a set. It remembers its insertion order so that every entry has an index that can be looked up. Featuring: O(1) Index lookup, insertion, iteration and membership testing. But slow O(N) Deletion. Both have similar interfaces but differ in respect of their implementation and performance. The original implementation of OrderedSet was a [recipe posted to ActiveState Recipes][recipe] by Raymond Hettiger, released under the MIT license. [recipe]: https://code.activestate.com/recipes/576694-orderedset/ Hettiger's implementation kept its content in a doubly-linked list referenced by a dict. As a result, looking up an item by its index was an O(N) operation, while deletion was O(1). This version of OrderedSet makes different trade-offs for the sake of efficient lookups. Its content is a standard Python list instead of a doubly-linked list. This provides O(1) lookups by index at the expense of O(N) deletion, as well as slightly faster iteration. orderly-set-5.3.2/benchmarks/000077500000000000000000000000001477560445100161245ustar00rootroot00000000000000orderly-set-5.3.2/benchmarks/ordered_set_benchmark.py000066400000000000000000000100441477560445100230060ustar00rootroot00000000000000def main(): import timeit from functools import partial from random import randint from ordered_set import OrderedSet as OS1 from orderly_set import OrderedSet as OS2 from orderly_set import StableSet as OS3 from orderly_set import OrderlySet as OS5 from orderly_set import SortedSet as OS6 # from sortedcollections import OrderedSet as OS4 item_count = 10_000 item_range = item_count * 2 items = [randint(0, item_range) for _ in range(item_count)] items_b = [randint(0, item_range) for _ in range(item_count)] oset1a = OS1(items) oset2a = OS2(items) oset1b = OS1(items_b) oset2b = OS2(items_b) assert oset1a.difference(oset1b) == oset2a.difference(oset2b) assert oset1a.intersection(oset1b) == oset2a.intersection(oset2b) oset1c = OS1(items) oset2c = OS2(items) oset1c.add(item_range + 1) oset2c.add(item_range + 1) assert oset1c == oset2c for i in range(item_range): assert (i in oset1a) == (i in oset2a) if i in oset1a: assert oset1a.index(i) == oset2a.index(i) def init_set(T, items) -> set: return T(items) def init_set_list(T, items) -> list: return list(T(items)) def init_set_d(items) -> dict: return dict.fromkeys(items) def init_set_d_list(items) -> list: return list(dict.fromkeys(items)) def update(s: set, items) -> set: s.update(items) return s def update_and_get_item(set_type: set, items, items_b) -> set: set_ = set_type(items) if set_: set_[0] set_.update(items_b) set_[0] return set_ def update_d(s: dict, items) -> dict: d2 = dict.fromkeys(items) s.update(d2) return s def symmetric_diff(s: set, s2: set) -> dict: return s ^ s2 def diff(s: set, s2: set) -> dict: return s - s2 orderly_sets_types = [OS1, OS2, OS3, OS5, OS6] # OS4 is too slow orderly_set_type_names = ['ordered_set.OrderedSet', 'orderly_set.OrderedSet', 'StableSet', 'OrderlySet', 'SortedSet'] # 'sortedcollections.OrderedSet' is too slow set_types = [set] + orderly_sets_types set_type_names = ['set'] + orderly_set_type_names oss = [init_set(T, items) for T in set_types] oss_b = [init_set(T, items_b) for T in set_types] od = init_set_d(items) osls = [init_set_list(T, items) for T in set_types[1:-1]] + [init_set_d_list(items)] for x in osls: assert osls[0] == x osls = [update(init_set(T, items), items_b) for T in orderly_sets_types[:-1]] + [ update_d(init_set_d(items), items_b) ] osls = [list(x) for x in osls] for x in osls: assert osls[0] == x number = 10000 repeats = 3 for i in range(repeats): print(f"----- series {i} ------") # print("-- initialize a set --") # print(f"Using Python dict time: {timeit.timeit(partial(init_set_d, items),number=number)}") # for idx, T in zip(set_type_names, set_types): # print(f"{idx} time: {timeit.timeit(partial(init_set, T, items),number=number)}") # print("-- update a set --") # print(f"Using Python dict: {timeit.timeit(partial(update_d, od, items_b),number=number)}") # for idx, os in zip(set_type_names, oss): # print(f"{idx} time: {timeit.timeit(partial(update, os, items_b),number=number)}") print("-- update a set and get item --") for idx, os in zip(orderly_set_type_names, orderly_sets_types): print(f"{idx} time: {timeit.timeit(partial(update_and_get_item, os, items, items_b),number=number)}") print("-- set symmetric difference (xor) --") for idx, set1, set2 in zip(set_type_names, oss, oss_b): print(f"{idx} time: {timeit.timeit(partial(symmetric_diff, set1, set2),number=number)}") print("-- set difference (-) --") for idx, set1, set2 in zip(set_type_names, oss, oss_b): print(f"{idx} time: {timeit.timeit(partial(diff, set1, set2),number=number)}") if __name__ == '__main__': main() orderly-set-5.3.2/orderly_set/000077500000000000000000000000001477560445100163425ustar00rootroot00000000000000orderly-set-5.3.2/orderly_set/__init__.py000066400000000000000000000003071477560445100204530ustar00rootroot00000000000000from orderly_set.sets import OrderedSet, StableSet, StableSetEq, OrderlySet, SortedSet # NOQA __all__ = [ "OrderedSet", "StableSet", "StableSetEq", "OrderlySet", "SortedSet", ] orderly-set-5.3.2/orderly_set/py.typed000066400000000000000000000000001477560445100200270ustar00rootroot00000000000000orderly-set-5.3.2/orderly_set/sets.py000066400000000000000000001212541477560445100176770ustar00rootroot00000000000000import itertools import itertools as it from typing import ( AbstractSet, Any, Dict, Iterable, Iterator, List, MutableSet, Optional, Sequence, Set, TypeVar, Union, overload, Hashable, ) SLICE_ALL = slice(None) T = TypeVar("T") S = TypeVar("S", bound="StableSet") # SetLike[T] is either a set of elements of type T, or a sequence, which # we will convert to a StableSet or to an OrderedSet by adding its elements in order. SetLike = Union[AbstractSet[T], Sequence[T]] SetInitializer = Union[AbstractSet[T], Sequence[T], Iterable[T]] def _is_atomic(obj: object) -> bool: """ Returns True for objects which are iterable but should not be iterated in the context of indexing a StableSet or an OrderedSet. When we index by an iterable, usually that means we're being asked to look up a list of things. However, in the case of the .index() method, we shouldn't handle strings and tuples like other iterables. They're not sequences of things to look up, they're the single, atomic thing we're trying to find. As an example, oset.index('hello') should give the index of 'hello' in an StableSet of strings. It shouldn't give the indexes of each individual character. """ return isinstance(obj, (str, tuple)) class StableSet(MutableSet[T], Sequence[T]): """ A StableSet is a custom MutableSet that remembers its insertion order. Featuring: Fast O(1) insertion, deletion, iteration and membership testing. But slow O(N) Index Lookup. StableSet is meant to be a drop-in replacement for `set` when iteration in insertion order is the only additional requirement over the built-in `set`. Equality: StableSet, like `set` and `dict_keys` [dict.keys()], and unlike OrderdSet, disregards the items order when checking equality. Like `set` it may be equal only to other instances of AbstractSet (like `set`, `dict_keys` or StableSet). This implementation of StableSet is based on the built-in dict type. In Python 3.6 and later, the built-in dict type is inherently ordered. If you ignore the dictionary values, that also gives you a simple ordered set, with fast O(1) insertion, deletion, iteration and membership testing. However, dict does not provide the list-like random access features of StableSet. So we have to convert it to a list in O(N) to look up the index of an entry or look up an entry by its index. Example: >>> StableSet([1, 1, 2, 3, 2]) StableSet([1, 2, 3]) """ __slots__ = ("_map", "_is_mutable") _map: Dict[T, Any] def __init__(self, initial: Optional[SetInitializer[T]] = None): self._map = dict.fromkeys(initial) if initial else {} self._is_mutable = True def __len__(self) -> int: """ Returns the number of unique elements in the ordered set Example: >>> len(StableSet([])) 0 >>> len(StableSet([1, 2])) 2 """ return self._map.__len__() @overload def __getitem__(self, index: slice) -> "StableSet[T]": ... @overload def __getitem__(self, index: Sequence[int]) -> List[T]: ... @overload def __getitem__(self, index: int) -> T: ... # concrete implementation def __getitem__(self, index): """ Get the item at a given index. If `index` is a slice, you will get back that slice of items, as a new StableSet. If `index` is a list or a similar iterable, you'll get a list of items corresponding to those indices. This is similar to NumPy's "fancy indexing". The result is not a StableSet because you may ask for duplicate indices, and the number of elements returned should be the number of elements asked for. Example: >>> oset = StableSet([1, 2, 3]) >>> oset[1] 2 """ if isinstance(index, int): if index < 0: index = len(self._map) + index try: return next(itertools.islice(self._map.keys(), index, index + 1)) except StopIteration: raise IndexError(f"index {index} out of range") elif isinstance(index, slice) and index == SLICE_ALL: return self.copy() items = list(self._map.keys()) if isinstance(index, Iterable): return [items[i] for i in index] elif isinstance(index, slice) or hasattr(index, "__index__"): result = items[index] if isinstance(result, list): return self.__class__(result) else: return result else: raise TypeError(f"Don't know how to index a StableSet by {index}") # Define the gritty details of how a StableSet is serialized as a pickle. # We leave off type annotations, because the only code that should interact # with this is a generalized tool such as pickle. def __getstate__(self): if len(self) == 0: # In pickle, the state can't be an empty list. # We need to return a truthy value, or else __setstate__ won't be run. # # This could have been done more gracefully by always putting the state # in a tuple, but this way is backwards- and forwards- compatible with # previous versions of StableSet. return (None,) else: return list(self) def __setstate__(self, state): if state == (None,): self.__init__([]) else: self.__init__(state) def __contains__(self, key: Any) -> bool: """ Test if the item is in this ordered set. Example: >>> 1 in StableSet([1, 3, 2]) True >>> 5 in StableSet([1, 3, 2]) False """ # return key in self._map return self._map.__contains__(key) def __iter__(self) -> Iterator[T]: """ Example: >>> list(iter(StableSet([1, 2, 3]))) [1, 2, 3] """ # return iter(self._map.keys()) return self._map.keys().__iter__() def __reversed__(self) -> Iterator[T]: """ Supported from Python >= 3.8 Example: >>> list(reversed(StableSet([1, 2, 3]))) [3, 2, 1] """ return reversed(self._map.keys()) def __repr__(self) -> str: if not self: return f"{self.__class__.__name__}()" return f"{self.__class__.__name__}({list(self)!r})" __str__ = __repr__ def __and__(self, other: SetLike[T]) -> "StableSet[T]": # the parent implementation of this is backwards return self.intersection(other) # sub, or, xor that support ordering # (left hand and right hand - as the operands order does matter) # based on the implementations of the super class (Set(Collection)), # see _collections_abc.py def __sub__(self: S, other: AbstractSet[T]) -> S: cls = type( self if isinstance(self, StableSet) else other if isinstance(other, StableSet) else StableSet ) if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = cls(other) return cls(value for value in self if value not in other) def __rsub__(self: S, other: AbstractSet[T]) -> S: cls = type( self if isinstance(self, StableSet) else other if isinstance(other, StableSet) else StableSet ) if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = cls(other) return cls(value for value in other if value not in self) def __or__(self: S, other: AbstractSet[T]) -> S: cls = type( self if isinstance(self, StableSet) else other if isinstance(other, StableSet) else StableSet ) if not isinstance(other, Iterable): return NotImplemented chain = (e for s in (self, other) for e in s) return cls(chain) def __ror__(self: S, other: AbstractSet[T]) -> S: cls = type( self if isinstance(self, StableSet) else other if isinstance(other, StableSet) else StableSet ) if not isinstance(other, Iterable): return NotImplemented chain = (e for s in (other, self) for e in s) return cls(chain) def __xor__(self: S, other: AbstractSet[T]) -> S: if not isinstance(other, Iterable): return NotImplemented return (self - other) | (other - self) def __rxor__(self: S, other: AbstractSet[T]) -> S: if not isinstance(other, Iterable): return NotImplemented return (other - self) | (self - other) def __eq__(self, other: object) -> bool: if not isinstance(other, Iterable): return False if len(self._map) != len(other): return False if isinstance(other, StableSet): return self._map == other._map if not isinstance(other, list): other = list(other) return list(self._map.keys()) == other def clear(self) -> None: """ Remove all items from this StableSet. """ if self._is_mutable is False: raise ValueError("This object is not mutable.") self._map.clear() def copy(self) -> "StableSet[T]": """ Return a shallow copy of this object. Example: >>> this = StableSet([1, 2, 3]) >>> other = this.copy() >>> this == other True >>> this is other False """ return self.__class__(self) # Technically type-incompatible with MutableSet, because we return an # int instead of nothing. This is also one of the things that makes # StableSet convenient to use. def add(self, key: T) -> int: # pyright: ignore """ Add `key` as an item to this StableSet, then return its index. If `key` is already in the StableSet, return the index it already had. Example: >>> oset = StableSet() >>> oset.append(3) 0 >>> print(oset) StableSet([3]) """ if self._is_mutable is False: raise ValueError("This object is not mutable.") self._map[key] = None return len(self._map) - 1 append = add def update(self, sequence: SetLike[T]) -> int: """ Update the set with the given iterable sequence, then return the index of the last element inserted. Example: >>> oset = StableSet([1, 2, 3]) >>> oset.update([3, 1, 5, 1, 4]) 4 >>> print(oset) StableSet([1, 2, 3, 5, 4]) """ if self._is_mutable is False: raise ValueError("This object is not mutable.") other_map = dict.fromkeys(sequence) self._map.update(other_map) return len(self._map) - 1 @overload def index(self, key: Sequence[T]) -> List[int]: ... @overload def index(self, key: T) -> int: ... # concrete implementation def index(self, key: Union[T, Sequence[T]]) -> Union[int, List[int]]: # pyright: ignore """ Get the index of a given entry, raising an IndexError if it's not present `key` can be an iterable of entries that is not a string, in which case this returns a list of indices. Example: >>> oset = StableSet([1, 2, 3]) >>> oset.index(2) 1 """ try: if isinstance(key, Iterable) and not _is_atomic(key): return [self.index(subkey) for subkey in key] for index, item in enumerate(self._map.keys()): if item == key: return index raise KeyError(key) # return list(self._map.keys()).index(key) except ValueError: raise KeyError(key) # Provide some compatibility with pd.Index get_loc = index get_indexer = index def pop(self, index: int = -1) -> T: """ Remove and return item at index (default last). Raises KeyError if the set is empty. Raises IndexError if index is out of range. Example: >>> oset = StableSet([1, 2, 3]) >>> oset.pop() 3 """ if self._is_mutable is False: raise ValueError("This object is not mutable.") if not self._map: raise KeyError("Set is empty") if index == -1: elem, _ = self._map.popitem() return elem elif index == 0: elem = next(iter(self._map.keys())) else: elem = next(itertools.islice(self._map.keys(), index, index + 1)) self._map.pop(elem) return elem def popitem(self, last: bool = True): """Remove and return an item from the set. Items are returned in LIFO order if last is true or FIFO order if false. """ if self._is_mutable is False: raise ValueError("This object is not mutable.") if not self._map: raise KeyError("Set is empty") if last: elem, _ = self._map.popitem() return elem elem = next(iter(self._map.keys())) self._map.pop(elem) return elem def move_to_end(self, key) -> None: """Move an existing element to the end. Raise KeyError if the element does not exist. """ if self._is_mutable is False: raise ValueError("This object is not mutable.") self._map.pop(key) self._map[key] = None def discard(self, value: T) -> None: """ Remove an element. Do not raise an exception if absent. The MutableSet mixin uses this to implement the .remove() method, which *does* raise an error when asked to remove a non-existent item. Example: >>> oset = StableSet([1, 2, 3]) >>> oset.discard(2) >>> print(oset) StableSet([1, 3]) >>> oset.discard(2) >>> print(oset) StableSet([1, 3]) """ if self._is_mutable is False: raise ValueError("This object is not mutable.") self._map.pop(value, None) def union(self, *sets: SetLike[T]) -> "StableSet[T]": """ Combines all unique items. Each item order is defined by its first appearance. Example: >>> oset = StableSet.union(StableSet([3, 1, 4, 1, 5]), [1, 3], [2, 0]) >>> print(oset) StableSet([3, 1, 4, 5, 2, 0]) >>> oset.union([8, 9]) StableSet([3, 1, 4, 5, 2, 0, 8, 9]) >>> oset | {10} StableSet([3, 1, 4, 5, 2, 0, 10]) """ cls = type(self if isinstance(self, StableSet) else StableSet) containers = map(list, it.chain([self], sets)) # type: ignore items = it.chain.from_iterable(containers) return cls(items) # type: ignore def intersection(self: S, *sets: SetLike[T]) -> S: """ Returns elements in common between all sets. Order is defined only by the first set. Example: >>> oset = StableSet.intersection(StableSet([0, 1, 2, 3]), [1, 2, 3]) >>> print(oset) StableSet([1, 2, 3]) >>> oset.intersection([2, 4, 5], [1, 2, 3, 4]) StableSet([2]) >>> oset.intersection() StableSet([1, 2, 3]) """ cls = type(self if isinstance(self, StableSet) else StableSet) items: SetInitializer[T] = self if sets: common = set.intersection(*map(set, sets)) # type: ignore items = (item for item in self if item in common) return cls(items) def difference(self: S, *sets: SetLike[T]) -> S: """ Returns all elements that are in this set but not the others. Example: >>> StableSet([1, 2, 3]).difference(StableSet([2])) StableSet([1, 3]) >>> StableSet([1, 2, 3]).difference(StableSet([2]), StableSet([3])) StableSet([1]) >>> StableSet([1, 2, 3]) - StableSet([2]) StableSet([1, 3]) >>> StableSet([1, 2, 3]).difference() StableSet([1, 2, 3]) """ cls = type(self if isinstance(self, StableSet) else StableSet) items: SetInitializer[T] = self if sets: other = set.union(*map(set, sets)) # type: ignore items = (item for item in self if item not in other) return cls(items) def symmetric_difference(self: S, other: SetLike[T]) -> S: """ Return the symmetric difference of two StableSets as a new set. That is, the new set will contain all elements that are in exactly one of the sets. Their order will be preserved, with elements from `self` preceding elements from `other`. Example: >>> this = StableSet([1, 4, 3, 5, 7]) >>> other = StableSet([9, 7, 1, 3, 2]) >>> this.symmetric_difference(other) StableSet([4, 5, 9, 2]) """ cls = type( self if isinstance(self, StableSet) else other if isinstance(other, StableSet) else StableSet ) diff1 = cls(self).difference(other) diff2 = cls(other).difference(self) return diff1.union(diff2) def difference_update(self, *sets: SetLike[T]) -> None: """ Update this StableSet to remove items from one or more other sets. Example: >>> this = StableSet([1, 2, 3]) >>> this.difference_update(StableSet([2, 4])) >>> print(this) StableSet([1, 3]) >>> this = StableSet([1, 2, 3, 4, 5]) >>> this.difference_update(StableSet([2, 4]), StableSet([1, 4, 6])) >>> print(this) StableSet([3, 5]) """ if self._is_mutable is False: raise ValueError("This object is not mutable.") items_to_remove = set() # type: Set[T] for other in sets: items_as_set = set(other) # type: Set[T] items_to_remove |= items_as_set self._map = dict.fromkeys( [item for item in self._map if item not in items_to_remove] ) def intersection_update(self, other: SetLike[T]) -> T: """ Update this StableSet to keep only items in another set, preserving their order in this set. Example: >>> this = StableSet([1, 4, 3, 5, 7]) >>> other = StableSet([9, 7, 1, 3, 2]) >>> this.intersection_update(other) StableSet([1, 3, 7]) >>> print(this) StableSet([1, 3, 7]) """ if self._is_mutable is False: raise ValueError("This object is not mutable.") other = set(other) self._map = dict.fromkeys([item for item in self._map if item in other]) return self __iand__ = intersection_update def symmetric_difference_update(self, other: SetLike[T]) -> None: """ Update this StableSet to remove items from another set, then add items from the other set that were not present in this set. Example: >>> this = StableSet([1, 4, 3, 5, 7]) >>> other = StableSet([9, 7, 1, 3, 2]) >>> this.symmetric_difference_update(other) >>> print(this) StableSet([4, 5, 9, 2]) """ if self._is_mutable is False: raise ValueError("This object is not mutable.") items_to_add = [item for item in other if item not in self] items_to_remove = set(other) self._map = dict.fromkeys( [item for item in self._map if item not in items_to_remove] + items_to_add ) def issubset(self, other: SetLike[T]) -> bool: """ Report whether another set contains this set. Example: >>> StableSet([1, 2, 3]).issubset({1, 2}) False >>> StableSet([1, 2, 3]).issubset({1, 2, 3, 4}) True >>> StableSet([1, 2, 3]).issubset({1, 4, 3, 5}) False """ if len(self) > len(other): # Fast check for obvious cases return False return all(item in other for item in self) def issuperset(self, other: SetLike[T]) -> bool: """ Report whether this set contains another set. Example: >>> StableSet([1, 2]).issuperset([1, 2, 3]) False >>> StableSet([1, 2, 3, 4]).issuperset({1, 2, 3}) True >>> StableSet([1, 4, 3, 5]).issuperset({1, 2, 3}) False """ if len(self) < len(other): # Fast check for obvious cases return False return all(item in self for item in other) def isorderedsubset(self: SetLike, other: SetLike, non_consecutive: bool = False) -> bool: if len(self) > len(other): return False if non_consecutive: i = 0 self_len = len(self) for other_item in other: if other_item == self[i]: i += 1 if i == self_len: return True return False else: for self_item, other_item in zip(self, other): if not self_item == other_item: return False return True def isorderedsuperset(self, other: SetLike, non_consecutive: bool = False) -> bool: return StableSet.isorderedsubset(other, self, non_consecutive) def get(self) -> Hashable: return next(iter(self._map)) def freeze(self) -> None: """ Once this function is run, the object becomes immutable """ self._is_mutable = False class OrderlySet(StableSet[T]): """ OrderlySet keeps the order when adding but if you do difference, subtraction, etc, you lose the order. The new results will have a random order but they will keep that order. """ def __sub__(self, other): other = other if isinstance(other, (set, frozenset)) else set(other) result = set(self) - other return OrderlySet(result) def __rsub__(self, other): other = other if isinstance(other, (set, frozenset)) else set(other) result = other - set(self) return OrderlySet(result) def __xor__(self, other): other = other if isinstance(other, (set, frozenset)) else set(other) result = set(self) ^ other return OrderlySet(result) __rxor__ = __xor__ def __eq__(self, other): if not isinstance(other, Iterable): return False if len(self._map) != len(other): return False if isinstance(other, StableSet): return self._map == other._map if not isinstance(other, (set, frozenset)): other = set(other) return set(self._map.keys()) == other def __ge__(self, other): if not isinstance(other, Iterable): return False if len(self._map) < len(other): return False if not isinstance(other, (set, frozenset)): other = set(other) return set(self._map.keys()) >= other def __gt__(self, other): if not isinstance(other, Iterable): return False if len(self._map) <= len(other): return False if not isinstance(other, (set, frozenset)): other = set(other) return set(self._map.keys()) > other def __le__(self, other): if not isinstance(other, Iterable): return False if len(self._map) > len(other): return False if not isinstance(other, (set, frozenset)): other = set(other) return set(self._map.keys()) <= other def __lt__(self, other): if not isinstance(other, Iterable): return False if len(self._map) >= len(other): return False if not isinstance(other, (set, frozenset)): other = set(other) return set(self._map.keys()) < other class StableSetEq(StableSet[T]): """ StableSetEq is a StableSet with a modified quality operator. StableSetEq, like `set` and `dict_keys` [dict.keys()], and unlike OrderdSet, disregards the items order when checking equality. Unlike StableSet, `set`, or `dict_keys` - A StableSetEq can also equal be equal to a Sequence: `StableSet([1, 2]) == [1, 2]` and `StableSet([1, 2]) == [2, 1]`; but `set([1, 2]) != [1, 2]` """ def __eq__(self, other: Any) -> bool: """ Returns true even if the containers don't have the same items in order. Example: >>> oset = StableSetEq([1, 3, 2]) >>> oset == [1, 3, 2] True >>> oset == [1, 2, 3] True >>> oset == [2, 3] False >>> oset == StableSetEq([3, 2, 1]) True """ if not isinstance(other, AbstractSet): try: other = set(other) except TypeError: # If `other` can't be converted into a set, it's not equal. return False return self._map.keys() == other def __le__(self, other: SetLike[T]): return len(self) <= len(other) and ( self._map.keys() <= other if isinstance(other, AbstractSet) else self._map.keys() <= set(other) ) def __lt__(self, other: SetLike[T]): return len(self) < len(other) and ( self._map.keys() < other if isinstance(other, AbstractSet) else self._map.keys() < set(other) ) def __ge__(self, other: SetLike[T]): return len(self) >= len(other) and ( self._map.keys() >= other if isinstance(other, AbstractSet) else self._map.keys() >= set(other) ) def __gt__(self, other: SetLike[T]): return len(self) > len(other) and ( self._map.keys() > other if isinstance(other, AbstractSet) else self._map.keys() > set(other) ) class OrderedSet(StableSet[T]): """ An OrderedSet is a mutable data structure that is a hybrid of a list and a set. It remembers its insertion order so that every entry has an index that can be looked up. Featuring: O(1) Index lookup, insertion, iteration and membership testing. But slow O(N) Deletion. Using OrderedSet over StableSet is advised only if you require fast Index lookup - Otherwise using StableSet is advised as it is much faster and has a smaller memory footprint. In some aspects OrderedSet behaves like a `set` and in other aspects it behaves like a list. Equality: OrderedSet, like `list` and `odict_keys` [OrderdDict.keys()], and unlike OrderdSet, regards the items order when checking equality. Unlike `set`, An OrderedSet can also equal be equal to a Sequence: `StableSet([1, 2]) == [1, 2]` and `StableSet([1, 2]) != [2, 1]`; but `set([1, 2]) != [1, 2]` The original implementation of OrderedSet was a recipe posted by Raymond Hettiger, https://code.activestate.com/recipes/576694-orderedset/ Released under the MIT license. Hettiger's implementation kept its content in a doubly-linked list referenced by a dict. As a result, looking up an item by its index was an O(N) operation, while deletion was O(1). This version makes different trade-offs for the sake of efficient lookups. Its content is a standard Python list instead of a doubly-linked list. This provides O(1) lookups by index at the expense of O(N) deletion, as well as slightly faster iteration. Example: >>> OrderedSet([1, 1, 2, 3, 2]) OrderedSet([1, 2, 3]) """ __slots__ = ("_items", "_is_mutable") _items: List[T] def __init__(self, initial: Optional[SetInitializer[T]] = None): self._items = [] self._map = {} self._is_mutable = True if initial is not None: # In terms of duck-typing, the default __ior__ is compatible with # the types we use, but it doesn't expect all the types we # support as values for `initial`. self |= initial # type: ignore def __getitem__(self, index): if isinstance(index, int): return self._items[index] elif isinstance(index, slice) and index == SLICE_ALL: return self.copy() elif isinstance(index, Iterable): return [self._items[i] for i in index] elif isinstance(index, slice) or hasattr(index, "__index__"): result = self._items[index] if isinstance(result, list): return self.__class__(result) else: return result else: raise TypeError("Don't know how to index an OrderedSet by %r" % index) def __eq__(self, other: Any) -> bool: """ Returns true if the containers have the same items. If `other` is a Sequence, then order is checked, otherwise it is ignored. Example: >>> oset = OrderedSet([1, 3, 2]) >>> oset == [1, 3, 2] True >>> oset == [1, 2, 3] False >>> oset == [2, 3] False >>> oset == OrderedSet([3, 2, 1]) False """ if isinstance(other, Sequence): # Check that this OrderedSet contains the same elements, in the # same order, as the other object. return len(self) == len(other) and self._items == list(other) try: other_as_set = set(other) except TypeError: # If `other` can't be converted into a set, it's not equal. return False else: return self._map.keys() == other_as_set def __le__(self, other: SetLike[T]): return len(self) <= len(other) and ( self._map.keys() <= other if isinstance(other, AbstractSet) else self._items <= other if isinstance(other, list) else self._items <= list(other) ) def __lt__(self, other: SetLike[T]): return len(self) < len(other) and ( self._map.keys() < other if isinstance(other, AbstractSet) else self._items < other if isinstance(other, list) else self._items < list(other) ) def __ge__(self, other: SetLike[T]): return len(self) >= len(other) and ( self._map.keys() >= other if isinstance(other, AbstractSet) else self._items >= other if isinstance(other, list) else self._items >= list(other) ) def __gt__(self, other: SetLike[T]): return len(self) > len(other) and ( self._map.keys() > other if isinstance(other, AbstractSet) else self._items > other if isinstance(other, list) else self._items > list(other) ) def clear(self) -> None: if self._is_mutable is False: raise ValueError("This object is not mutable.") del self._items[:] self._map.clear() def add(self, key: T) -> int: if self._is_mutable is False: raise ValueError("This object is not mutable.") if key not in self._map: self._map[key] = len(self._items) self._items.append(key) return self._map[key] def update(self, sequence: SetLike[T]) -> int: if self._is_mutable is False: raise ValueError("This object is not mutable.") item_index = 0 for item in sequence: item_index = self.add(item) return item_index def index(self, key): if isinstance(key, Iterable) and not _is_atomic(key): return [self.index(subkey) for subkey in key] return self._map[key] def pop(self, index: int = -1) -> T: if self._is_mutable is False: raise ValueError("This object is not mutable.") if not self._items: raise KeyError("Set is empty") elem = self._items[index] del self._items[index] del self._map[elem] return elem def popitem(self, last: bool = True): if self._is_mutable is False: raise ValueError("This object is not mutable.") if not self._items: raise KeyError("Set is empty") index = -1 if last else 0 elem = self._items[index] del self._items[index] del self._map[elem] return elem def move_to_end(self, key): if self._is_mutable is False: raise ValueError("This object is not mutable.") if key in self: self.discard(key) self.add(key) else: raise KeyError(key) def discard(self, key: T) -> None: if self._is_mutable is False: raise ValueError("This object is not mutable.") if key in self: i = self._map[key] del self._items[i] del self._map[key] for k, v in self._map.items(): if v >= i: self._map[k] = v - 1 def _update_items(self, items: list) -> None: """ Replace the 'items' list of this OrderedSet with a new one, updating self._map accordingly. """ self._items = items self._map = {item: idx for (idx, item) in enumerate(items)} def difference_update(self, *sets: SetLike[T]) -> None: if self._is_mutable is False: raise ValueError("This object is not mutable.") items_to_remove = set() # type: Set[T] for other in sets: items_as_set = set(other) # type: Set[T] items_to_remove |= items_as_set self._update_items( [item for item in self._items if item not in items_to_remove] ) def intersection_update(self, other: SetLike[T]) -> T: if self._is_mutable is False: raise ValueError("This object is not mutable.") other = set(other) self._update_items([item for item in self._items if item in other]) return self __iand__ = intersection_update def symmetric_difference_update(self, other: SetLike[T]) -> None: if self._is_mutable is False: raise ValueError("This object is not mutable.") items_to_add = [item for item in other if item not in self] items_to_remove = set(other) self._update_items( [item for item in self._items if item not in items_to_remove] + items_to_add ) class SortedSet: def __init__(self, *args, set_=None, **kwargs): self._is_mutable = True self._sorted = None if set_: self.set_ = set_ else: self.set_ = set(*args, **kwargs) def __iter__(self): yield from self._get_sorted() def __str__(self) -> str: if not self: return f"{self.__class__.__name__}()" return f"{self.__class__.__name__}({self._get_sorted()!r})" __repr__ = __str__ def _get_sorted(self, reverse=False): if self._sorted is None: try: self._sorted = sorted(self.set_, reverse=reverse) except Exception: self._sorted = sorted(self.set_, key=lambda x: str(x), reverse=reverse) return self._sorted def get(self): """ Get a random element """ return next(iter(self.set_)) def __and__(self, other): # Intersection result = self.set_ & other return SortedSet(set_=result) intersection = __and__ __rand__ = __and__ def intersection_update(self, other): self.set_.intersection_update(other) return self __iand__ = intersection_update def __or__(self, other): # Union result = self.set_ | other return SortedSet(set_=result) union = __ror__ = __or__ def __sub__(self, other): # Difference result = self.set_ - other return SortedSet(set_=result) difference = __sub__ def difference_update(self, *sets): self._sorted = None self.set_.difference_update(*sets) def isdisjoint(self, other): return self.set_.isdisjoint(other) def __xor__(self, other): # Symmetric difference result = self.set_ ^ other return SortedSet(set_=result) symmetric_difference = __rxor__ = __xor__ def symmetric_difference_update(self, other): self._sorted = None self.set_.symmetric_difference_update(other) def __rsub__(self, other): result = other - self.set_ return SortedSet(set_=result) def add(self, item): self._sorted = None self.set_.add(item) def clear(self): self._sorted = None self.set_.clear() def discard(self, key): self._sorted = None self.set_.discard(key) def copy(self): return SortedSet(set_=set(self.set_)) def __le__(self, other): return self.set_.issubset(other) issubset = __le__ def __lt__(self, other): return self.set_ < other def __ge__(self, other): return self.set_.issuperset(other) issuperset = __ge__ def __gt__(self, other): return self.set_ > other def remove(self, key): self._sorted = None self.set_.remove(key) def update(self, sequence): self._sorted = None self.set_.update(sequence) def __len__(self): return len(self.set_) if self.set_ else 0 def __eq__(self, other): if not isinstance(other, Iterable): return False if len(self.set_) != len(other): return False if isinstance(other, SortedSet): return self.set_ == other.set_ if not isinstance(other, (set, frozenset)): other = set(other) return self.set_ == other def __reversed__(self): if self._sorted is None: self._get_sorted() return reversed(self._sorted) def __getitem__(self, index): items = self._get_sorted() if isinstance(index, int): return items[index] elif isinstance(index, slice) and index == SLICE_ALL: return self.copy() if isinstance(index, Iterable): return [items[i] for i in index] elif isinstance(index, slice) or hasattr(index, "__index__"): result = items[index] if isinstance(result, list): return self.__class__(result) else: return result else: raise TypeError(f"Don't know how to index a SortedSet by {index}") def index(self, key): # NOQA """ Get the index of a given entry, raising an IndexError if it's not present `key` can be an iterable of entries that is not a string, in which case this returns a list of indices. Example: >>> oset = StableSet([1, 2, 3]) >>> oset.index(2) 1 """ items = self._get_sorted() try: if isinstance(key, Iterable) and not _is_atomic(key): return [self.index(subkey) for subkey in key] for index, item in enumerate(items): if item == key: return index raise KeyError(key) # return list(self._map.keys()).index(key) except ValueError: raise KeyError(key) # Provide some compatibility with pd.Index get_loc = index get_indexer = index def pop(self, index=None): if index is None: self._sorted = None return self.set_.pop() items = self._get_sorted() result = items.pop(index) self.set_.remove(result) return result def isorderedsubset(self: SetLike, other: SetLike, non_consecutive: bool = False) -> bool: if len(self) > len(other): return False if non_consecutive: i = 0 self_len = len(self) for other_item in other: if other_item == self[i]: i += 1 if i == self_len: return True return False else: for self_item, other_item in zip(self, other): if not self_item == other_item: return False return True def isorderedsuperset(self, other: SetLike, non_consecutive: bool = False) -> bool: return StableSet.isorderedsubset(other, self, non_consecutive) orderly-set-5.3.2/pytest.ini000066400000000000000000000002131477560445100160340ustar00rootroot00000000000000[pytest] addopts = --pdbcls=IPython.terminal.debugger:Pdb --doctest-modules --doctest-glob=README.md --doctest-glob=*.py --ignore=setup.py orderly-set-5.3.2/requirements-dev.txt000066400000000000000000000000741477560445100200500ustar00rootroot00000000000000pytest black mypy pre-commit pytest-cov bump2version==1.0.1 orderly-set-5.3.2/setup.cfg000066400000000000000000000004371477560445100156340ustar00rootroot00000000000000[bumpversion] current_version = 5.3.2 commit = False tag = False tag_name = {new_version} [flake8] max-line-length = 120 builtins = json statistics = true ignore = E202 exclude = ./data,./src,.svn,CVS,.bzr,.hg,.git,__pycache__ [bumpversion:file:setup.py] [bumpversion:file:README.md] orderly-set-5.3.2/setup.py000066400000000000000000000023611477560445100155230ustar00rootroot00000000000000from setuptools import setup version = '5.3.2' with open('README.md') as file: long_description = file.read() setup(name='orderly-set', version=version, description='Orderly set', url='https://github.com/seperman/orderly-set', download_url='https://github.com/seperman/orderly-set/tarball/master', author='Seperman', author_email='sep@zepworks.com', license='MIT', packages=['orderly_set'], zip_safe=True, include_package_data=True, long_description=long_description, long_description_content_type='text/markdown', install_requires=None, python_requires='>=3.8', classifiers=[ "Intended Audience :: Developers", "Operating System :: OS Independent", "Topic :: Software Development", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: Implementation :: PyPy", "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: MIT License" ], ) orderly-set-5.3.2/tests/000077500000000000000000000000001477560445100151515ustar00rootroot00000000000000orderly-set-5.3.2/tests/__init__.py000066400000000000000000000015451477560445100172670ustar00rootroot00000000000000from orderly_set import OrderedSet, StableSet, StableSetEq, OrderlySet, SortedSet stable_sets = [StableSet] stableeq_sets = [StableSetEq] ordered_sets = [OrderedSet, OrderlySet, SortedSet] # from orderedset import OrderedSet as OrderedSet2 # ordered_sets += [OrderedSet2] set_and_stable_sets = [set] + stable_sets stables = stableeq_sets + stable_sets stableeq_and_orderly_sets = stableeq_sets + ordered_sets stableeq_and_orderly_sets_except_sorted_set = stableeq_sets + [OrderedSet, OrderlySet] stable_and_orderly_sets = stable_sets + stableeq_sets + ordered_sets stable_and_orderly_sets_except_sorted_set = stable_sets + stableeq_sets + [OrderedSet, OrderlySet] sets_and_stable_sets = [set] + stable_sets + stableeq_sets all_sets = [set] + stable_sets + stableeq_sets + ordered_sets all_sets_except_orderly_set = [set] + stable_sets + stableeq_sets + [OrderedSet] orderly-set-5.3.2/tests/pytest_util.py000066400000000000000000000007511477560445100201130ustar00rootroot00000000000000def assertEqual(a, b): assert a == b def assertNotEqual(a, b): assert a != b def assertTrue(a): assert a is True def assertFalse(a): assert a is False def assertLessEqual(a, b): assert a <= b def assertLess(a, b): assert a < b def assertGreaterEqual(a, b): assert a >= b def assertGreater(a, b): assert a > b def assertIn(a, b): assert a in b def assertNotIn(a, b): assert a not in b def assertIsNot(a, b): assert a is not b orderly-set-5.3.2/tests/test_ordered_set_1.py000066400000000000000000000362421477560445100213100ustar00rootroot00000000000000import itertools as it import json import operator import pickle import random import tempfile from collections import OrderedDict, deque from pathlib import Path import pytest from tests import ( StableSet, all_sets, all_sets_except_orderly_set, SortedSet, sets_and_stable_sets, stable_and_orderly_sets, stableeq_and_orderly_sets, OrderedSet, stable_and_orderly_sets_except_sorted_set, ) @pytest.mark.parametrize("set_t", all_sets) def test_pickle(set_t): set1 = set_t("abracadabra") roundtrip = pickle.loads(pickle.dumps(set1)) assert roundtrip == set1 @pytest.mark.parametrize("set_t", all_sets) def test_empty_pickle(set_t): empty_oset = set_t() empty_roundtrip = pickle.loads(pickle.dumps(empty_oset)) assert empty_roundtrip == empty_oset @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_order(set_t): set1 = set_t("abracadabra") assert len(set1) == 5 set2 = set_t(["a", "b", "r", "c", "d"]) assert set1 == set2 if set_t is SortedSet: assert list(reversed(set1)) == ['r', 'd', 'c', 'b', 'a'] else: assert list(reversed(set1)) == ["d", "c", "r", "b", "a"] @pytest.mark.parametrize("set_t", all_sets) def test_binary_operations(set_t): set1 = set_t("abracadabra") set2 = set_t("simsalabim") assert set1 != set2 assert set1 & set2 == set_t(["a", "b"]) assert set1 | set2 == set_t(["a", "b", "r", "c", "d", "s", "i", "m", "l"]) assert set1 - set2 == set_t(["r", "c", "d"]) @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_indexing(set_t): set1 = set_t("abracadabra") assert set1[0] == "a" if set_t is SortedSet: assert set1[3] == "d" else: assert set1[3] == "c" assert set1[:] == set1 assert set1.copy() == set1 assert set1 is set1 assert set1[:] is not set1 assert set1.copy() is not set1 assert set1.index("b") == 1 if set_t is SortedSet: assert set1[[1, 2]] == ["b", "c"] assert set1[1:3] == set_t(["b", "c"]) assert set1.index(["b", "r"]) == [1, 4] else: assert set1[[1, 2]] == ["b", "r"] assert set1[1:3] == set_t(["b", "r"]) assert set1.index(["b", "r"]) == [1, 2] with pytest.raises(KeyError): set1.index("br") with pytest.raises(IndexError): set1[100] set1[[100, 0]] set1.index("br") class FancyIndexTester: """ Make sure we can index by a NumPy ndarray, without having to import NumPy. """ def __init__(self, indices): self.indices = indices def __iter__(self): return iter(self.indices) def __index__(self): raise TypeError("NumPy arrays have weird __index__ methods") def __eq__(self, other): # Emulate NumPy being fussy about the == operator raise TypeError @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_fancy_index_class(set_t): set1 = set_t("abracadabra") indexer = FancyIndexTester([1, 0, 4, 3, 0, 2]) if set_t is SortedSet: assert "".join(set1[indexer]) == "bardac" else: assert "".join(set1[indexer]) == "badcar" @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_pandas_compat(set_t): set1 = set_t("abracadabra") assert set1.get_loc("b") == 1 if set_t is SortedSet: assert set1.get_indexer(["b", "r"]) == [1, 4] else: assert set1.get_indexer(["b", "r"]) == [1, 2] @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_tuples(set_t): set1 = set_t() tup = ("tuple", 1) set1.add(tup) assert set1.index(tup) == 0 assert set1[0] == tup @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_remove(set_t): set1 = set_t("abracadabra") set1.remove("a") set1.remove("b") assert set1 == set_t("rcd") if set_t is not SortedSet: assert set1[0] == "r" assert set1[1] == "c" assert set1[2] == "d" assert set1.index("r") == 0 assert set1.index("c") == 1 assert set1.index("d") == 2 assert "a" not in set1 assert "b" not in set1 assert "r" in set1 # Make sure we can .discard() something that's already gone, plus # something that was never there set1.discard("a") set1.discard("a") @pytest.mark.parametrize("set_t", all_sets) def test_remove_error(set_t): # If we .remove() an element that's not there, we get a KeyError set1 = set_t("abracadabra") with pytest.raises(KeyError): set1.remove("z") @pytest.mark.parametrize("set_t", all_sets) def test_clear(set_t): set1 = set_t("abracadabra") set1.clear() assert len(set1) == 0 assert set1 == set_t() @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_update(set_t): set1 = set_t("abcd") result = set1.update("efgh") if set_t is not SortedSet: assert result == 7 assert len(set1) == 8 assert "".join(set1) == "abcdefgh" set2 = set_t("abcd") result = set2.update("cdef") if set_t is not SortedSet: assert result == 5 assert len(set2) == 6 assert "".join(set2) == "abcdef" @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_pop(set_t): set1 = set_t("ab") elem = set1.pop() assert elem == "b" elem = set1.pop() assert elem == "a" pytest.raises(KeyError, set1.pop) @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_pop_by_index(set_t): set1 = set_t("abcde") elem = set1.pop(1) assert elem == "b" elem = set1.pop(1) assert elem == "c" elem = set1.pop(0) assert elem == "a" elem = set1.pop(-1) assert elem == "e" elem = set1.pop(-1) assert elem == "d" pytest.raises(KeyError, set1.pop) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_popitem(set_t): set1 = set_t("abcd") elem = set1.popitem() assert elem == "d" elem = set1.popitem(last=True) assert elem == "c" elem = set1.popitem(last=False) assert elem == "a" elem = set1.popitem() assert elem == "b" pytest.raises(KeyError, set1.popitem) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_move_to_end(set_t): set1 = set_t("abcd") set1.move_to_end("a") assert list(set1) == ["b", "c", "d", "a"] with pytest.raises(KeyError): set1.move_to_end("z") @pytest.mark.parametrize("set_t", all_sets) def test_getitem_type_error(set_t): set1 = set_t("ab") with pytest.raises(TypeError): set1["a"] @pytest.mark.parametrize("set_t", all_sets) def test_update_type_error(set_t): set1 = set_t("ab") with pytest.raises(TypeError): # not ValueError # noinspection PyTypeChecker set1.update(3) @pytest.mark.parametrize("set_t", all_sets) def test_empty_repr(set_t): set1 = set_t() set_class_name = set_t.__name__ assert repr(set1) == f"{set_class_name}()" @pytest.mark.parametrize("set_t", all_sets) def test_eq_wrong_type(set_t): set1 = set_t() assert set1 != 2 @pytest.mark.parametrize("set_t", all_sets) def test_ordered_equality(set_t): # Ordered set checks order against sequences. set1 = set_t([1, 2]) assert set1 == set_t([1, 2]) if set_t is not StableSet: assert set1 == {1, 2} assert set1 == {2, 1} @pytest.mark.parametrize("set_t", stableeq_and_orderly_sets) def test_ordered_equality_non_set(set_t): set1 = set_t([1, 2]) assert set1 == [1, 2] assert set1 == (1, 2) assert set1 == deque([1, 2]) @pytest.mark.parametrize("set_t", sets_and_stable_sets) def test_ordered_equality_unorderly_sets(set_t): set1 = set_t([1, 2]) assert set1 == set_t([2, 1]) if set_t is not StableSet: assert set1 == {2, 1} @pytest.mark.parametrize("set_t", [OrderedSet]) def test_ordered_inequality(set_t): # Equal Ordered set checks order against sequences. set1 = set_t([1, 2]) assert set1 != set_t([2, 1]) assert set1 != [2, 1] assert set1 != [2, 1, 1] assert set1 != (2, 1) assert set1 != (2, 1, 1) assert set1 != deque([2, 1]) assert set1 != deque([2, 2, 1]) @pytest.mark.parametrize("set_t", all_sets) def test_comparisons(set_t): # Comparison operators on sets actually test for subset and superset. assert set_t([1, 2]) < set_t([1, 2, 3]) assert set_t([1, 2]) > set_t([1]) assert set_t([1, 2]) > {1} @pytest.mark.parametrize("set_t", all_sets) def test_unordered_equality(set_t): # Unordered set checks order against non-sequences. if set_t is not StableSet: assert set_t([1, 2]) == {1, 2} assert set_t([1, 2]) == frozenset([2, 1]) assert set_t([1, 2]) == {2: 2, 1: 1}.keys() assert set_t([1, 2]) == OrderedDict([(2, 2), (1, 1)]).keys() assert set_t([1, 2]) == {1: 1, 2: 2}.keys() @pytest.mark.parametrize("set_t", [OrderedSet]) def test_unordered_equality_orderly_set(set_t): assert set_t([1, 2]) == {1: 1, 2: 2}.values() assert set_t([1, 2]) == {1: "a", 2: "b"} # Corner case: OrderedDict is not a Sequence, so we don't check for order, # even though it does have the concept of order. assert set_t([1, 2]) == OrderedDict([(2, 2), (1, 1)]) # Corner case: We have to treat iterators as unordered because there # is nothing to distinguish an ordered and unordered iterator assert set_t([1, 2]) == iter([1, 2]) assert set_t([1, 2]) == iter([2, 1]) assert set_t([1, 2]) == iter([2, 1, 1]) @pytest.mark.parametrize("set_t", all_sets) def test_unordered_inequality(set_t): assert set_t([1, 2]) != set([]) assert set_t([1, 2]) != frozenset([2, 1, 3]) assert set_t([1, 2]) != {2: "b"} assert set_t([1, 2]) != {1: 1, 4: 2}.keys() assert set_t([1, 2]) != {1: 1, 2: 3}.values() # Corner case: OrderedDict is not a Sequence, so we don't check for order, # even though it does have the concept of order. assert set_t([1, 2]) != OrderedDict([(2, 2), (3, 1)]) def allsame_(iterable, eq=operator.eq): """returns True of all items in iterable equal each other""" iter_ = iter(iterable) try: first = next(iter_) except StopIteration: return True return all(eq(first, item) for item in iter_) def check_results_(results, datas, name): """ helper for binary operator tests. check that all results have the same value, but are different items. data and name are used to indicate what sort of tests is run. """ if not allsame_(results): raise AssertionError( "Not all same {} for {} with datas={}".format(results, name, datas) ) for a, b in it.combinations(results, 2): if not isinstance(a, (bool, int)): assert a is not b, name + " should all be different items" def _operator_consistency_testdata(set_t): """ Predefined and random data used to test operator consistency. """ # test case 1 a = set_t([5, 3, 1, 4]) b = set_t([1, 4]) yield a, b # first set is empty a = set_t([]) b = set_t([3, 1, 2]) yield a, b # second set is empty a = set_t([3, 1, 2]) b = set_t([]) yield a, b # both sets are empty a = set_t([]) b = set_t([]) yield a, b # random test cases rng = random.Random(0) x, y = 20, 20 for _ in range(10): a = set_t(rng.randint(0, x) for _ in range(y)) b = set_t(rng.randint(0, x) for _ in range(y)) yield a, b yield b, a datasets_t = list(_operator_consistency_testdata(set_t) for set_t in all_sets) datasets_t_except_orderly_set = list(_operator_consistency_testdata(set_t) for set_t in all_sets_except_orderly_set) datasets = [item for sublist in datasets_t for item in sublist] datasets_except_orderly_set = [item for sublist in datasets_t_except_orderly_set for item in sublist] @pytest.mark.parametrize("a, b", datasets) def test_operator_consistency_isect(a, b): result1 = a.copy() result1.intersection_update(b) result2 = a & b result3 = a.intersection(b) check_results_([result1, result2, result3], datas=(a, b), name="isect") @pytest.mark.parametrize("a, b", datasets) def test_operator_consistency_difference(a, b): result1 = a.copy() result1.difference_update(b) result2 = a - b result3 = a.difference(b) check_results_([result1, result2, result3], datas=(a, b), name="difference") @pytest.mark.parametrize("a, b", datasets_except_orderly_set) def test_operator_consistency_xor(a, b): result1 = a.copy() result1.symmetric_difference_update(b) result2 = a ^ b result3 = a.symmetric_difference(b) check_results_([result1, result2, result3], datas=(a, b), name="xor") @pytest.mark.parametrize("a, b", datasets) def test_operator_consistency_union(a, b): result1 = a.copy() result1.update(b) result2 = a | b result3 = a.union(b) check_results_([result1, result2, result3], datas=(a, b), name="union") @pytest.mark.parametrize("a, b", datasets) def test_operator_consistency_subset(a, b): result1 = a <= b result2 = a.issubset(b) result3 = set(a).issubset(set(b)) check_results_([result1, result2, result3], datas=(a, b), name="subset") @pytest.mark.parametrize("a, b", datasets) def test_operator_consistency_superset(a, b): result1 = a >= b result2 = a.issuperset(b) result3 = set(a).issuperset(set(b)) check_results_([result1, result2, result3], datas=(a, b), name="superset") @pytest.mark.parametrize("a, b", datasets) def test_operator_consistency_disjoint(a, b): result1 = a.isdisjoint(b) result2 = len(a.intersection(b)) == 0 check_results_([result1, result2], datas=(a, b), name="disjoint") @pytest.mark.parametrize("set_t", all_sets) def test_bitwise_and_consistency(set_t): # Specific case that was failing without explicit __and__ definition a = set_t([12, 13, 1, 8, 16, 15, 9, 11, 18, 6, 4, 3, 19, 17]) b = set_t([19, 4, 9, 3, 2, 10, 15, 17, 11, 13, 20, 6, 14, 16, 8]) result1 = a.copy() result1.intersection_update(b) # This requires a custom & operation apparently result2 = a & b result3 = a.intersection(b) check_results_([result1, result2, result3], datas=(a, b), name="isect") @pytest.mark.skip("Not implemented yet") @pytest.mark.parametrize("set_t", all_sets) def test_json(set_t): a = set_t([1, 2, 3]) json_data = json.dumps(a) b = json.loads(json_data) assert a == b @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_stability(set_t, override=False): """if you run this test twice it should fail with `set` and succeed with `StableSet`""" items = "abcdabcd" filename = Path(tempfile.gettempdir()) / f"data_{set_t.__name__}.pickle" if override or not filename.is_file(): sitems0 = list(set_t(items)) print(f"saving {filename}") print(sitems0) with open(filename, "wb") as f: pickle.dump(sitems0, f, pickle.HIGHEST_PROTOCOL) print(f"loading {filename}") with open(filename, "rb") as f: sitems = pickle.load(f) print(sitems) for i in range(100): new_sitems = list(set_t(items)) print(new_sitems) assert sitems == new_sitems, f"{sitems} != {new_sitems}" def test_equality_in_stable_set(): oset = StableSet([1, 3, 2]) assert oset == [1, 3, 2] orderly-set-5.3.2/tests/test_ordered_set_2.py000066400000000000000000000372741477560445100213170ustar00rootroot00000000000000# The following tests are based on # https://github.com/simonpercivall/orderedset/blob/master/tests/test_orderedset.py # Thus shall be under the license: # https://github.com/simonpercivall/orderedset/blob/master/LICENSE import copy import gc import pickle import weakref import pytest from tests import ( all_sets, all_sets_except_orderly_set, OrderedSet, ordered_sets, stable_and_orderly_sets, stables, stableeq_sets, stable_and_orderly_sets_except_sorted_set, stableeq_and_orderly_sets_except_sorted_set, SortedSet, StableSet, ) from tests.pytest_util import ( assertEqual, assertFalse, assertGreater, assertGreaterEqual, assertIsNot, assertLess, assertLessEqual, assertNotEqual, assertNotIn, assertTrue, ) datasets = [list(range(10))] @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_add_new(set_t, lst: list): oset = set_t(lst) lst = copy.copy(lst) item = 10 lst.append(item) oset.add(item) assert list(oset) == lst @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stables) def test_add_new_when_immutable_fails(set_t, lst: list): oset = set_t(lst) lst = copy.copy(lst) item = 10 lst.append(item) oset.add(item) assert list(oset) == lst oset.freeze() with pytest.raises(ValueError): oset.add("banana") @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_add_existing(set_t, lst: list): oset = set_t(lst) lst = copy.copy(lst) oset.add(1) oset.add(3) assert list(oset) == lst @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_discard(set_t, lst: list): oset = set_t([1, 2, 3]) oset.discard(1) assertNotIn(1, oset) oset.discard(4) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_pop(set_t): oset = set_t([1, 2, 3]) v = oset.pop() assert v == 3 assertNotIn(v, oset) v = oset.popitem(last=False) assert v == 1 assertNotIn(v, oset) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_remove(set_t, lst: list): oset = set_t(lst) lst = copy.copy(lst) oset.remove(3) lst.remove(3) assert list(oset) == lst @pytest.mark.parametrize("set_t", all_sets) def test_clear(set_t): val = frozenset([1]) oset = set_t() ws = weakref.WeakKeyDictionary() oset.add(val) ws[val] = 1 oset.clear() assert list(oset) == [] del val gc.collect() assert list(ws) == [] @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_copy(set_t, lst: list): oset1 = set_t(lst) oset2 = oset1.copy() assertIsNot(oset1, oset2) assert oset1 == oset2 oset1.clear() assertNotEqual(oset1, oset2) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_reduce(set_t, lst: list): oset = set_t(lst) oset2 = copy.copy(oset) assert oset == oset2 oset3 = pickle.loads(pickle.dumps(oset)) assert oset == oset3 oset.add(-1) if set_t is SortedSet: assert oset == oset2 else: assert oset != oset2 @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_difference_and_update(set_t, lst: list): list1 = [1, 2, 3] list2 = [3, 4, 5] oset1 = set_t(list1) oset2 = set_t(list2) # right hand oset3 = oset2 - list1 assert oset3 == set_t([4, 5]) assert oset2.difference(oset1) == oset3 oset3 = list2 - oset1 assert oset3 == set_t([4, 5]) assert oset2.difference(oset1) == oset3 oset3 = oset1 - oset2 assert oset3 == set_t([1, 2]) assert oset1.difference(oset2) == oset3 # left hand oset3 = oset1 - list2 assert oset3 == set_t([1, 2]) assert oset1.difference(oset2) == oset3 oset3 = list1 - oset2 assert oset3 == set_t([1, 2]) assert oset1.difference(oset2) == oset3 oset4 = oset1.copy() oset4 -= oset2 assert oset4 == oset3 oset5 = oset1.copy() oset5.difference_update(oset2) assert oset5 == oset3 if isinstance(oset5, StableSet): oset5.freeze() with pytest.raises(ValueError): oset5 -= oset2 @pytest.mark.parametrize("set_t", all_sets) def test_intersection_and_update(set_t): oset1 = set_t([1, 2, 3]) oset2 = set_t([3, 4, 5]) oset3 = oset1 & oset2 assert oset3 == set_t([3]) oset4 = oset1.copy() oset4 &= oset2 assert oset4 == oset3 oset5 = oset1.copy() oset5.intersection_update(oset2) assert oset5 == oset3 if isinstance(oset5, StableSet): oset5.freeze() with pytest.raises(ValueError): oset5 &= oset2 @pytest.mark.parametrize("set_t", all_sets) def test_issubset(set_t): oset1 = set_t([1, 2, 3]) oset2 = set_t([1, 2]) assertTrue(oset2 < oset1) assertTrue(oset2.issubset(oset1)) oset2 = set_t([1, 2, 3]) assertTrue(oset2 <= oset1) assertTrue(oset1 <= oset2) assertTrue(oset2.issubset(oset1)) oset2 = set_t([1, 2, 3, 4]) assertFalse(oset2 < oset1) assertFalse(oset2.issubset(oset1)) assertTrue(oset1 < oset2) # issubset compares unordered for all sets oset2 = set_t([4, 3, 2, 1]) assertTrue(oset1 < oset2) @pytest.mark.parametrize("set_t", all_sets) def test_issuperset(set_t): oset1 = set_t([1, 2, 3]) oset2 = set_t([1, 2]) assertTrue(oset1 > oset2) assertTrue(oset1.issuperset(oset2)) oset2 = set_t([1, 2, 3]) assertTrue(oset1 >= oset2) assertTrue(oset2 >= oset1) assertTrue(oset1.issubset(oset2)) oset2 = set_t([1, 2, 3, 4]) assertFalse(oset1 > oset2) assertFalse(oset1.issuperset(oset2)) assertTrue(oset2 > oset1) # issubset compares underordered for all sets oset2 = set_t([4, 3, 2, 1]) assertTrue(oset2 > oset1) @pytest.mark.parametrize("set_t", all_sets_except_orderly_set) def test_symmetric_difference_and_update(set_t): oset1 = set_t([1, 2, 3]) oset2 = set_t([2, 3, 4]) oset3 = oset1 ^ oset2 assert oset3 == set_t([1, 4]) oset4 = oset1.copy() assert oset4.symmetric_difference(oset2) == oset3 oset4 ^= oset2 assert oset4 == oset3 oset5 = oset1.copy() oset5.symmetric_difference_update(oset2) assert oset5 == oset3 @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stableeq_and_orderly_sets_except_sorted_set) def test_union_and_update(set_t, lst: list): oset = set_t(lst) lst = copy.copy(lst) oset2 = oset | [3, 9, 27] assert oset2 == lst + [27] oset2 = [3, 9, 27] | oset assert oset2 == [3, 9, 27, 0, 1, 2, 4, 5, 6, 7, 8] # make sure original oset isn't changed assert oset == lst oset1 = set_t(lst) oset2 = set_t(lst) oset3 = oset1 | oset2 assert oset3 == oset1 assert oset3 == oset1.union(oset2) oset1 |= set_t("abc") assert oset1 == oset2 | "abc" oset1 = set_t(lst) oset1.update("abc") assert oset1 == oset2 | "abc" if isinstance(oset1, StableSet): oset1.freeze() with pytest.raises(ValueError): oset1 |= oset2 @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_union_with_iterable(set_t): oset1 = set_t([1]) assert oset1 | [2, 1] == set_t([1, 2]) oset2 = [2] | oset1 assert oset2 == set_t([2, 1]) oset2 = [1, 2] | set_t([3, 1, 2, 4]) assert oset2 == set_t([1, 2, 3, 4]) # union with unordered set should work, though the order will be arbitrary oset2 = oset1 | set([2]) assert oset2 == set_t([1, 2]) oset2 = set([2]) | oset1 assert oset2 == set_t([2, 1]) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_symmetric_difference_with_iterable(set_t): oset1 = set_t([1]) assert oset1 ^ [1] == set_t([]) assert [1] ^ oset1 == set_t([]) assert set_t([3, 1, 4, 2]) ^ [3, 4] == set_t([1, 2]) assert [3, 1, 4, 2] ^ set_t([3, 4]) == set_t([1, 2]) assert set_t([3, 1, 4, 2]) ^ set([3, 4]) == set_t([1, 2]) oset2 = set([3, 1, 4]) ^ set_t([3, 4, 2]) assert oset2 == set_t([1, 2]) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_intersection_with_iterable(set_t): assert [1, 2, 3] & set_t([3, 2]) == set_t([2, 3]) assert set_t([3, 2] & set_t([1, 2, 3])) == set_t([3, 2]) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_difference_with_iterable(set_t): assert set_t([1, 2, 3, 4]) - [3, 2] == set_t([1, 4]) assert [3, 2, 4, 1] - set_t([2, 4]) == set_t([3, 1]) @pytest.mark.parametrize("set_t", all_sets) def test_isdisjoint(set_t): assertTrue(set_t().isdisjoint(set_t())) assertTrue(set_t([1]).isdisjoint(set_t([2]))) assertFalse(set_t([1, 2]).isdisjoint(set_t([2, 3]))) @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_index(set_t): oset = set_t("abcd") assert oset.index("b") == 1 @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_getitem(set_t): oset = set_t("abcd") assert oset[2] == "c" @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_getitem_slice(set_t): oset = set_t("abcdef") assert oset[:2] == set_t("ab") assert oset[2:] == set_t("cdef") assert oset[::-1] == set_t("fedcba") assert oset[1:-1:2] == set_t("bd") assert oset[1::2] == set_t("bdf") @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_len(set_t, lst: list): oset = set_t(lst) assert len(oset) == len(lst) oset.remove(0) assert len(oset) == len(lst) - 1 @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_contains(set_t, lst: list): oset = set_t(lst) assertTrue(1 in oset) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_iter_mutated(set_t, lst: list): oset = set_t(lst) it = iter(oset) oset.add("a") with pytest.raises(RuntimeError): next(it) it = reversed(oset) oset.add("b") with pytest.raises(RuntimeError): next(it) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_iter_and_valid_order(set_t, lst: list): oset = set_t(lst) assert list(oset) == lst oset = set_t(lst + lst) assert list(oset) == lst @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_reverse_order(set_t, lst: list): oset = set_t(lst) assert list(reversed(oset)) == list(reversed(lst)) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_eq(set_t, lst: list): oset1 = set_t(lst) oset2 = set_t(lst) assertNotEqual(oset1, None) assert oset1 == oset2 assert oset1 == set(lst) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", ordered_sets) def test_eq_list(set_t, lst: list): assert set_t(lst) == list(lst) @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_repr(set_t): oset = set_t([1]) set_class_name = set_t.__name__ assert repr(oset) == f"{set_class_name}([1])" @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_subset(set_t, lst: list): oset1 = set_t([1, 2, 3]) oset2 = set_t([1, 2, 3, 4]) oset3 = set_t([1, 2, 4, 3]) oset4 = set_t([1, 3, 2, 4]) assertTrue(oset1.isorderedsubset(oset2)) assertFalse(oset1.isorderedsubset(oset3)) assertFalse(oset2.isorderedsubset(oset3)) assertFalse(oset1.isorderedsubset(oset4)) assertTrue(oset1 < oset2) assertTrue(oset1 < oset3) assertFalse(oset2 < oset3) assertTrue(oset1 < oset4) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_subset_non_consecutive(set_t, lst: list): oset1 = set_t([1, 2, 3]) oset2 = set_t([6, 1, 2, 5, 3, 4]) oset3 = set_t([6, 1, 2, 5, 4, 3]) oset4 = set_t([6, 1, 3, 5, 2, 4]) assertTrue(oset1.isorderedsubset(oset2, non_consecutive=True)) assertTrue(oset1.isorderedsubset(oset3, non_consecutive=True)) assertFalse(oset2.isorderedsubset(oset3, non_consecutive=True)) assertFalse(oset1.isorderedsubset(oset4, non_consecutive=True)) assertTrue(oset1 < oset2) assertTrue(oset1 < oset3) assertFalse(oset2 < oset3) assertTrue(oset1 < oset4) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_superset(set_t, lst: list): oset1 = set_t([1, 2, 3]) oset2 = set_t([1, 2, 3, 4]) oset3 = set_t([1, 2, 4, 3]) oset4 = set_t([1, 3, 2, 4]) if set_t is not SortedSet: assertTrue(oset2.isorderedsuperset(oset1)) assertFalse(oset3.isorderedsuperset(oset1)) assertFalse(oset3.isorderedsuperset(oset2)) assertFalse(oset4.isorderedsuperset(oset1)) assertTrue(oset2 > oset1) assertTrue(oset3 > oset1) assertFalse(oset3 > oset2) assertTrue(oset4 > oset1) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_superset_non_consecutive(set_t, lst: list): oset1 = set_t([1, 2, 3]) oset2 = set_t([6, 1, 2, 5, 3, 4]) oset3 = set_t([6, 1, 2, 5, 4, 3]) oset4 = set_t([6, 1, 3, 5, 2, 4]) if set_t is not SortedSet: assertTrue(oset2.isorderedsuperset(oset1, non_consecutive=True)) assertTrue(oset3.isorderedsuperset(oset1, non_consecutive=True)) assertFalse(oset3.isorderedsuperset(oset2, non_consecutive=True)) assertFalse(oset4.isorderedsuperset(oset1, non_consecutive=True)) assertTrue(oset2 > oset1) assertTrue(oset3 > oset1) assertFalse(oset3 > oset2) assertTrue(oset4 > oset1) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", all_sets) def test_ordering(set_t, lst: list): oset1 = set_t(lst) oset2 = set_t(lst) assertLessEqual(oset2, oset1) assertLessEqual(oset2, set(oset1)) assertGreaterEqual(oset1, oset2) assertGreaterEqual(oset1, set(oset2)) oset3 = set_t(lst[:-1]) assertLess(oset3, oset1) assertLess(oset3, set(oset1)) assertGreater(oset1, oset3) assertGreater(oset1, set(oset3)) oset4 = set_t(lst[1:]) assertFalse(oset3 < oset4) assertFalse(oset3 < set(oset4)) assertFalse(oset3 >= oset4) assertFalse(oset3 >= set(oset4)) assertFalse(oset3 < oset4) assertFalse(oset3 < set(oset4)) assertFalse(oset3 >= oset4) assertFalse(oset3 >= set(oset4)) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stableeq_and_orderly_sets_except_sorted_set) def test_ordering_with_lists(set_t, lst: list): oset1 = set_t(lst) oset2 = set_t(lst) assert oset2 <= oset1 assert oset2 <= list(oset1) assert oset1 <= list(oset2) oset3 = set_t(lst[:-1]) assertLess(oset3, list(oset1)) assertGreater(oset1, list(oset3)) oset4 = set_t(lst[1:]) assertFalse(oset3 < list(oset4)) assertFalse(oset3 >= list(oset4)) assertFalse(oset3 < list(oset4)) assertFalse(oset3 >= list(oset4)) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", [OrderedSet]) def test_eq_reversed_orderedset(set_t, lst: list): oset1 = set_t(lst) oset2 = set_t(reversed(lst)) assertNotEqual(oset1, oset2) @pytest.mark.parametrize("lst", datasets) @pytest.mark.parametrize("set_t", stableeq_sets) def test_eq_reversed_stableset(set_t, lst: list): oset1 = set_t(lst) oset2 = set_t(reversed(lst)) assert oset1 == oset2 orderly-set-5.3.2/tests/test_ordered_set_3.py000066400000000000000000000054641477560445100213140ustar00rootroot00000000000000# The following tests are based on # https://github.com/bustawin/ordered-set-37/blob/master/test/test_testing.py # Thus shall be under the license: # https://github.com/bustawin/ordered-set-37/blob/master/LICENSE.md from pathlib import Path import pytest from tests import all_sets, stable_and_orderly_sets, SortedSet, stable_and_orderly_sets_except_sorted_set TESTS = Path(__file__).parent @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_add(set_t): x = set_t([1, 2, -1, "bar"]) x.add(0) if set_t is SortedSet: assert list(x) == [-1, 0, 1, 2, 'bar'] else: assert list(x) == [1, 2, -1, "bar", 0] @pytest.mark.parametrize("set_t", all_sets) def test_discard(set_t): x = set_t([1, 2, -1]) x.discard(2) if set_t is SortedSet: assert list(x) == [-1, 1] else: assert list(x) == [1, -1] @pytest.mark.parametrize("set_t", all_sets) def test_discard_ignores_missing_element(set_t): x = set_t() x.discard(1) # This does not raise @pytest.mark.parametrize("set_t", all_sets) def test_remove(set_t): x = set_t([1]) x.remove(1) assert not x @pytest.mark.parametrize("set_t", all_sets) def test_remove_raises_missing_element(set_t): x = set_t() with pytest.raises(KeyError): x.remove(1) @pytest.mark.parametrize("set_t", stable_and_orderly_sets_except_sorted_set) def test_getitem(set_t): x = set_t([1, 2, -1]) assert x[0] == 1 assert x[1] == 2 assert x[2] == -1 with pytest.raises(IndexError): x[3] @pytest.mark.parametrize("set_t", all_sets) def test_len(set_t): x = set_t([1]) assert len(x) == 1 @pytest.mark.parametrize("set_t", all_sets) def test_iter(set_t): for x in set_t([1]): assert x == 1 @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_str(set_t): x = set_t([1, 2, 3]) assert str(x) == f"{set_t.__name__}([1, 2, 3])" @pytest.mark.parametrize("set_t", stable_and_orderly_sets) def test_repr(set_t): x = set_t([1, 2, 3]) assert str(x) == f"{set_t.__name__}([1, 2, 3])" @pytest.mark.parametrize("set_t", all_sets) def test_eq(set_t): x = set_t([1, 2, 3]) y = set_t([1, 2, 3]) assert x == y assert x is not y @pytest.mark.parametrize("set_t", all_sets) def test_init_empty(set_t): x = set_t() assert len(x) == 0 x.add(2) assert len(x) == 1 @pytest.mark.skip("Not ready yet") @pytest.mark.parametrize("set_t", all_sets) def test_typing_mypy(set_t, do_assert: bool = True): """Checks the typing values with mypy.""" import mypy.api fixture = TESTS / "_test_mypy.py" module = TESTS.parent / "orderly_sets" *_, error = mypy.api.run([str(module), str(fixture)]) if do_assert: assert not error else: print(*_) if __name__ == "__main__": test_typing_mypy(False) orderly-set-5.3.2/tox.ini000066400000000000000000000001241477560445100153170ustar00rootroot00000000000000[tox] envlist = pypy3, py38, py39, py310 [testenv] deps = pytest commands = pytest