pax_global_header00006660000000000000000000000064140014025110014476gustar00rootroot0000000000000052 comment=1a6a3457c94ee994d50514a59643ff7f55c7146b python-sortedcollections-2.1.0/000077500000000000000000000000001400140251100165545ustar00rootroot00000000000000python-sortedcollections-2.1.0/.github/000077500000000000000000000000001400140251100201145ustar00rootroot00000000000000python-sortedcollections-2.1.0/.github/workflows/000077500000000000000000000000001400140251100221515ustar00rootroot00000000000000python-sortedcollections-2.1.0/.github/workflows/integration.yml000066400000000000000000000021621400140251100252200ustar00rootroot00000000000000name: integration on: [push] jobs: checks: runs-on: ubuntu-latest strategy: max-parallel: 8 matrix: check: [bluecheck, doc8, docs, flake8, isortcheck, mypy, pylint, rstcheck] steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | pip install --upgrade pip pip install tox - name: Run checks with tox run: | tox -e ${{ matrix.check }} tests: needs: checks runs-on: ${{ matrix.os }} strategy: max-parallel: 8 matrix: os: [ubuntu-latest, macos-latest, windows-latest, ubuntu-16.04] python-version: [3.6, 3.7, 3.8, 3.9] steps: - name: Set up Python ${{ matrix.python-version }} x64 uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} architecture: x64 - uses: actions/checkout@v2 - name: Install tox run: | pip install --upgrade pip pip install tox - name: Test with tox run: tox -e py python-sortedcollections-2.1.0/.github/workflows/release.yml000066400000000000000000000013041400140251100243120ustar00rootroot00000000000000name: release on: push: tags: - v* jobs: upload: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | pip install --upgrade pip pip install -r requirements.txt - name: Create source dist run: python setup.py sdist - name: Create wheel dist run: python setup.py bdist_wheel - name: Upload with twine env: TWINE_USERNAME: ${{ secrets.TWINE_USERNAME }} TWINE_PASSWORD: ${{ secrets.TWINE_PASSWORD }} run: | ls -l dist/* twine upload dist/* python-sortedcollections-2.1.0/.gitignore000066400000000000000000000003211400140251100205400ustar00rootroot00000000000000# Python byte-code *.py[co] # virutalenv directories /env*/ # coverage files .coverage # setup sdist, test and upload directories /.tox/ /build/ /dist/ /sortedcollections.egg-info/ /docs/_build/ .DS_Store python-sortedcollections-2.1.0/.pylintrc000066400000000000000000000415651400140251100204340ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist= # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=1 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=print-statement, parameter-unpacking, unpacking-in-except, old-raise-syntax, backtick, long-suffix, old-ne-operator, old-octal-literal, import-star-module-level, non-ascii-bytes-literal, raw-checker-failed, bad-inline-option, locally-disabled, file-ignored, suppressed-message, useless-suppression, deprecated-pragma, use-symbolic-message-instead, apply-builtin, basestring-builtin, buffer-builtin, cmp-builtin, coerce-builtin, execfile-builtin, file-builtin, long-builtin, raw_input-builtin, reduce-builtin, standarderror-builtin, unicode-builtin, xrange-builtin, coerce-method, delslice-method, getslice-method, setslice-method, no-absolute-import, old-division, dict-iter-method, dict-view-method, next-method-called, metaclass-assignment, indexing-exception, raising-string, reload-builtin, oct-method, hex-method, nonzero-method, cmp-method, input-builtin, round-builtin, intern-builtin, unichr-builtin, map-builtin-not-iterating, zip-builtin-not-iterating, range-builtin-not-iterating, filter-builtin-not-iterating, using-cmp-argument, eq-without-hash, div-method, idiv-method, rdiv-method, exception-message-attribute, invalid-str-codec, sys-max-int, bad-python3-import, deprecated-string-function, deprecated-str-translate-call, deprecated-itertools-function, deprecated-types-field, next-method-defined, dict-items-not-iterating, dict-keys-not-iterating, dict-values-not-iterating, deprecated-operator-function, deprecated-urllib-function, xreadlines-attribute, deprecated-sys-function, exception-escape, comprehension-escape, super-with-arguments, raise-missing-from # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=c-extension-no-member [REPORTS] # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [LOGGING] # Format style used to check logging format string. `old` means using % # formatting, while `new` is for `{}` formatting. logging-format-style=old # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package.. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=yes # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=yes # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis. It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid defining new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 # List of optional constructs for which whitespace checking is disabled. `dict- # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. # `trailing-comma` allows a space between comma and closing bracket: (a, ). # `empty-line` allows space-only lines. no-space-check=trailing-comma, dict-separator # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Naming style matching correct class attribute names. class-attribute-naming-style=any # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=UPPER_CASE # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=i, j, k, ex, Run, _ # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [IMPORTS] # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=5 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Maximum number of boolean expressions in an if statement. max-bool-expr=5 # Maximum number of branch for function / method body. max-branches=12 # Maximum number of locals for function / method body. max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body. max-returns=6 # Maximum number of statements in function / method body. max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=2 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception". overgeneral-exceptions=Exception python-sortedcollections-2.1.0/LICENSE000066400000000000000000000010551400140251100175620ustar00rootroot00000000000000Copyright 2015-2021 Grant Jenks Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. python-sortedcollections-2.1.0/MANIFEST.in000066400000000000000000000000331400140251100203060ustar00rootroot00000000000000include README.rst LICENSE python-sortedcollections-2.1.0/README.rst000066400000000000000000000075351400140251100202550ustar00rootroot00000000000000Python Sorted Collections ========================= `Sorted Collections`_ is an Apache2 licensed Python sorted collections library. Features -------- - Pure-Python - Depends on the `Sorted Containers `_ module. - ValueSortedDict - Dictionary with (key, value) item pairs sorted by value. - ItemSortedDict - Dictionary with key-function support for item pairs. - NearestDict - Dictionary with nearest-key lookup. - OrderedDict - Ordered dictionary with numeric indexing support. - OrderedSet - Ordered set with numeric indexing support. - IndexableDict - Dictionary with numeric indexing support. - IndexableSet - Set with numeric indexing support. - SegmentList - List with fast random access insertion and deletion. - 100% code coverage testing. - Developed on Python 3.9 - Tested on CPython 3.6, 3.7, 3.8, and 3.9 .. image:: https://github.com/grantjenks/python-sortedcollections/workflows/integration/badge.svg :target: https://github.com/grantjenks/python-sortedcollections/actions?query=workflow%3Aintegration .. image:: https://github.com/grantjenks/python-sortedcollections/workflows/release/badge.svg :target: https://github.com/grantjenks/python-sortedcollections/actions?query=workflow%3Arelease Quickstart ---------- Installing `Sorted Collections`_ is simple with `pip `_:: $ pip install sortedcollections You can access documentation in the interpreter with Python's built-in `help` function: .. code-block:: python >>> from sortedcollections import ValueSortedDict >>> help(ValueSortedDict) # doctest: +SKIP .. _`Sorted Collections`: http://www.grantjenks.com/docs/sortedcollections/ Recipes ------- - `Value Sorted Dictionary Recipe`_ - `Item Sorted Dictionary Recipe`_ - `Nearest Dictionary Recipe`_ - `Ordered Dictionary Recipe`_ - `Ordered Set Recipe`_ - `Indexable Dictionary Recipe`_ - `Indexable Set Recipe`_ - `Segment List Recipe`_ .. _`Value Sorted Dictionary Recipe`: http://www.grantjenks.com/docs/sortedcollections/valuesorteddict.html .. _`Item Sorted Dictionary Recipe`: http://www.grantjenks.com/docs/sortedcollections/itemsorteddict.html .. _`Nearest Dictionary Recipe`: http://www.grantjenks.com/docs/sortedcollections/nearestdict.html .. _`Ordered Dictionary Recipe`: http://www.grantjenks.com/docs/sortedcollections/ordereddict.html .. _`Ordered Set Recipe`: http://www.grantjenks.com/docs/sortedcollections/orderedset.html .. _`Indexable Dictionary Recipe`: http://www.grantjenks.com/docs/sortedcollections/indexabledict.html .. _`Indexable Set Recipe`: http://www.grantjenks.com/docs/sortedcollections/indexableset.html .. _`Segment List Recipe`: http://www.grantjenks.com/docs/sortedcollections/segmentlist.html Reference and Indices --------------------- - `Sorted Collections Documentation`_ - `Sorted Collections at PyPI`_ - `Sorted Collections at Github`_ - `Sorted Collections Issue Tracker`_ .. _`Sorted Collections Documentation`: http://www.grantjenks.com/docs/sortedcollections/ .. _`Sorted Collections at PyPI`: https://pypi.python.org/pypi/sortedcollections/ .. _`Sorted Collections at Github`: https://github.com/grantjenks/python-sortedcollections .. _`Sorted Collections Issue Tracker`: https://github.com/grantjenks/python-sortedcollections/issues Sorted Collections License -------------------------- Copyright 2015-2021 Grant Jenks Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. python-sortedcollections-2.1.0/docs/000077500000000000000000000000001400140251100175045ustar00rootroot00000000000000python-sortedcollections-2.1.0/docs/Makefile000066400000000000000000000011041400140251100211400ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)python-sortedcollections-2.1.0/docs/_static/000077500000000000000000000000001400140251100211325ustar00rootroot00000000000000python-sortedcollections-2.1.0/docs/_static/gj-logo.png000066400000000000000000000626231400140251100232070ustar00rootroot00000000000000PNG  IHDRɧPLTE# $ !n$m$BἻ&"#,)*=9:l#AAk",**f!'#$e!qBi!n&o-QGA|`M832p.=::mIn'h!943QGB=:;dMb"/+*^"1--`"+'')%&_"b!hMm%610m%o+;65300n)F?;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3g-+0כfj`9lmRn5i.w^xQm'8t¢yq3rXZ!z>Gq9Fg= C4 rl  rc`0Dw !BXs? .h UoW/?*(OLjoЮD1.Mcغ൷鰀)-SМ!/UHRc ?A8j|,.ΘߤQ uzvL4{}~U 5"{qn?INĬ2MP1VZ< A6Y2O 2Ҳim?n܇&L- Ckk)S;#[n-յ '=9pC\>g3O55I41R\vW U#fF|S|.+T|.fT/7Uc rN5Z=L[@l:fD1 yOZ ,kZh_[qie`Ǻ! l`h m w,dR ΒA:Pvb?2ɓ;BJ10͏cp ~חv %h6B+j;)+I KI7##x)X]b2k˰4Zs7yS懤튟3wSt'TY^RWd@BR⪏. @e'hEPrEUHt5 o?׬ϐf)U.t\{n(^2V$v{w*r#UUTظ{e):>FW`1"(eу@w kCE".rv"]X* /_xaK gE#ٵԠ>v")|~ZB Xa켙|&թ}Mj&XJAm8Znӱfz=ێ ys&=IQ HwP?{0\չFO[$+?>{6 BYQ1/Ne. 'iq#za)D +U3MIja!E &sgn:޽9C޽XםWLGM"G"=\:H\_#ގt838RT`.Tdm~ykxK.<7;s?q3GsoW7G9l璘nwz:_o'M֫x撛WX|f{o--7gvwO=Tޟww_^~k!?=IENDB`python-sortedcollections-2.1.0/docs/_templates/000077500000000000000000000000001400140251100216415ustar00rootroot00000000000000python-sortedcollections-2.1.0/docs/_templates/gumroad.html000066400000000000000000000003471400140251100241710ustar00rootroot00000000000000

Give Support

If you or your organization uses Sorted Collections, consider financial support:

Give to Python Sorted Collections

python-sortedcollections-2.1.0/docs/conf.py000066400000000000000000000136361400140251100210140ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. import os import sys sys.path.insert(0, os.path.abspath('..')) import sortedcollections # -- Project information ----------------------------------------------------- project = 'Sorted Collections' copyright = 'Apache 2.0' author = 'Grant Jenks' # The short X.Y version version = sortedcollections.__version__ # The full version, including alpha/beta/rc tags release = sortedcollections.__version__ # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'logo': 'gj-logo.png', 'logo_name': True, 'logo_text_align': 'center', 'analytics_id': 'UA-19364636-2', 'show_powered_by': False, 'show_related': True, 'github_user': 'grantjenks', 'github_repo': 'python-sortedcollections', 'github_type': 'star', } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. html_sidebars = { '**': [ 'about.html', 'gumroad.html', 'localtoc.html', 'relations.html', 'searchbox.html', ] } # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'SortedCollectionsDoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'SortedCollections.tex', 'Sorted Collections Documentation', 'Grant Jenks', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'sortedcollections', 'Sorted Collections Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'SortedCollections', 'Sorted Collections Documentation', author, 'SortedCollections', 'Python Sorted Collections library.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # -- Extension configuration ------------------------------------------------- # -- Options for todo extension ---------------------------------------------- # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True python-sortedcollections-2.1.0/docs/index.rst000066400000000000000000000002671400140251100213520ustar00rootroot00000000000000.. include:: ../README.rst .. toctree:: :hidden: valuesorteddict itemsorteddict nearestdict ordereddict orderedset indexabledict indexableset segmentlist python-sortedcollections-2.1.0/docs/indexabledict.rst000066400000000000000000000002121400140251100230300ustar00rootroot00000000000000Indexable Dictionary Recipe =========================== .. autoclass:: sortedcollections.IndexableDict :special-members: :members: python-sortedcollections-2.1.0/docs/indexableset.rst000066400000000000000000000001731400140251100227060ustar00rootroot00000000000000Indexable Set Recipe ==================== .. autoclass:: sortedcollections.IndexableSet :special-members: :members: python-sortedcollections-2.1.0/docs/itemsorteddict.rst000066400000000000000000000002171400140251100232610ustar00rootroot00000000000000Item Sorted Dictionary Recipe ============================= .. autoclass:: sortedcollections.ItemSortedDict :special-members: :members: python-sortedcollections-2.1.0/docs/make.bat000066400000000000000000000014231400140251100211110ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=. set BUILDDIR=_build if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd python-sortedcollections-2.1.0/docs/nearestdict.rst000066400000000000000000000002041400140251100225370ustar00rootroot00000000000000Nearest Dictionary Recipe ========================= .. autoclass:: sortedcollections.NearestDict :special-members: :members: python-sortedcollections-2.1.0/docs/ordereddict.rst000066400000000000000000000006221400140251100225260ustar00rootroot00000000000000Ordered Dictionary Recipe ========================= .. autoclass:: sortedcollections.OrderedDict :special-members: :members: .. autoclass:: sortedcollections.ordereddict.KeysView :special-members: :members: .. autoclass:: sortedcollections.ordereddict.ItemsView :special-members: :members: .. autoclass:: sortedcollections.ordereddict.ValuesView :special-members: :members: python-sortedcollections-2.1.0/docs/orderedset.rst000066400000000000000000000001651400140251100224000ustar00rootroot00000000000000Ordered Set Recipe ================== .. autoclass:: sortedcollections.OrderedSet :special-members: :members: python-sortedcollections-2.1.0/docs/segmentlist.rst000066400000000000000000000001701400140251100225720ustar00rootroot00000000000000Segment List Recipe =================== .. autoclass:: sortedcollections.SegmentList :special-members: :members: python-sortedcollections-2.1.0/docs/valuesorteddict.rst000066400000000000000000000002221400140251100234330ustar00rootroot00000000000000Value Sorted Dictionary Recipe ============================== .. autoclass:: sortedcollections.ValueSortedDict :special-members: :members: python-sortedcollections-2.1.0/mypy.ini000066400000000000000000000001001400140251100202420ustar00rootroot00000000000000[mypy] [mypy-sortedcontainers.*] ignore_missing_imports = True python-sortedcollections-2.1.0/requirements.txt000066400000000000000000000001261400140251100220370ustar00rootroot00000000000000-e . blue coverage doc8 mypy pylint pytest pytest-cov rstcheck sphinx tox twine wheel python-sortedcollections-2.1.0/setup.py000066400000000000000000000031531400140251100202700ustar00rootroot00000000000000import pathlib import re from setuptools import setup from setuptools.command.test import test as TestCommand class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import tox errno = tox.cmdline(self.test_args) exit(errno) with open('README.rst') as reader: readme = reader.read() init_text = (pathlib.Path('sortedcollections') / '__init__.py').read_text() match = re.search(r"^__version__ = '(.+)'$", init_text, re.MULTILINE) version = match.group(1) setup( name='sortedcollections', version=version, description='Python Sorted Collections', long_description=readme, author='Grant Jenks', author_email='contact@grantjenks.com', url='http://www.grantjenks.com/docs/sortedcollections/', license='Apache 2.0', packages=['sortedcollections'], install_requires=['sortedcontainers'], tests_require=['tox'], cmdclass={'test': Tox}, classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ), ) python-sortedcollections-2.1.0/sortedcollections/000077500000000000000000000000001400140251100223135ustar00rootroot00000000000000python-sortedcollections-2.1.0/sortedcollections/__init__.py000066400000000000000000000016521400140251100244300ustar00rootroot00000000000000"""Python Sorted Collections SortedCollections is an Apache2 licensed Python sorted collections library. >>> from sortedcollections import ValueSortedDict >>> vsd = ValueSortedDict({'a': 2, 'b': 1, 'c': 3}) >>> list(vsd.keys()) ['b', 'a', 'c'] :copyright: (c) 2015-2021 by Grant Jenks. :license: Apache 2.0, see LICENSE for more details. """ from sortedcontainers import ( SortedDict, SortedList, SortedListWithKey, SortedSet, ) from .nearestdict import NearestDict from .ordereddict import OrderedDict from .recipes import ( IndexableDict, IndexableSet, ItemSortedDict, OrderedSet, SegmentList, ValueSortedDict, ) __all__ = [ 'IndexableDict', 'IndexableSet', 'ItemSortedDict', 'NearestDict', 'OrderedDict', 'OrderedSet', 'SegmentList', 'SortedDict', 'SortedList', 'SortedListWithKey', 'SortedSet', 'ValueSortedDict', ] __version__ = '2.1.0' python-sortedcollections-2.1.0/sortedcollections/nearestdict.py000066400000000000000000000074451400140251100252040ustar00rootroot00000000000000"""NearestDict implementation. One primary use case for this data structure is storing data by a `datetime.datetime` or `float` key. """ from sortedcontainers import SortedDict class NearestDict(SortedDict): """A dict using nearest-key lookup. A :class:`SortedDict` subclass that uses nearest-key lookup instead of exact-key lookup. Optionally, you can specify a rounding mode to return the nearest key less than or equal to or greater than or equal to the provided key. When using :attr:`NearestDict.NEAREST` the keys must support subtraction to allow finding the nearest key (by find the key with the smallest difference to the given one). Additional methods: * :meth:`NearestDict.nearest_key` Example usage: >>> d = NearestDict({1.0: 'foo'}) >>> d[1.0] 'foo' >>> d[0.0] 'foo' >>> d[2.0] 'foo' """ NEAREST_PREV = -1 NEAREST = 0 NEAREST_NEXT = 1 def __init__(self, *args, **kwargs): """Initialize a NearestDict instance. Optional `rounding` argument dictates how :meth:`NearestDict.nearest_key` rounds. It must be one of :attr:`NearestDict.NEAREST_NEXT`, :attr:`NearestDict.NEAREST`, or :attr:`NearestDict.NEAREST_PREV`. (Default: :attr:`NearestDict.NEAREST`) :params rounding: how to round on nearest-key lookup (optional) :params args: positional arguments for :class:`SortedDict`. :params kwargs: keyword arguments for :class:`SortedDict`. """ self.rounding = kwargs.pop('rounding', self.NEAREST) super().__init__(*args, **kwargs) def nearest_key(self, request): """Return nearest-key to `request`, respecting `self.rounding`. >>> d = NearestDict({1.0: 'foo'}) >>> d.nearest_key(0.0) 1.0 >>> d.nearest_key(2.0) 1.0 >>> d = NearestDict({1.0: 'foo'}, rounding=NearestDict.NEAREST_PREV) >>> d.nearest_key(0.0) Traceback (most recent call last): ... KeyError: 'No key below 0.0 found' >>> d.nearest_key(2.0) 1.0 :param request: nearest-key lookup value :return: key nearest to `request`, respecting `rounding` :raises KeyError: if no appropriate key can be found """ key_list = self.keys() if not key_list: raise KeyError('NearestDict is empty') index = self.bisect_left(request) if index >= len(key_list): if self.rounding == self.NEAREST_NEXT: raise KeyError(f'No key above {request!r} found') return key_list[index - 1] if key_list[index] == request: return key_list[index] if index == 0 and self.rounding == self.NEAREST_PREV: raise KeyError(f'No key below {request!r} found') if self.rounding == self.NEAREST_PREV: return key_list[index - 1] if self.rounding == self.NEAREST_NEXT: return key_list[index] if abs(key_list[index - 1] - request) < abs(key_list[index] - request): return key_list[index - 1] return key_list[index] def __getitem__(self, request): """Return item corresponding to :meth:`.nearest_key`. :param request: nearest-key lookup value :return: item corresponding to key nearest `request` :raises KeyError: if no appropriate item can be found >>> d = NearestDict({1.0: 'foo'}) >>> d[0.0] 'foo' >>> d[2.0] 'foo' >>> d = NearestDict({1.0: 'foo'}, rounding=NearestDict.NEAREST_NEXT) >>> d[0.0] 'foo' >>> d[2.0] Traceback (most recent call last): ... KeyError: 'No key above 2.0 found' """ key = self.nearest_key(request) return super().__getitem__(key) python-sortedcollections-2.1.0/sortedcollections/ordereddict.py000066400000000000000000000135721400140251100251650ustar00rootroot00000000000000"""Ordered dictionary implementation. """ from itertools import count from operator import eq from sortedcontainers import SortedDict from sortedcontainers.sortedlist import recursive_repr from .recipes import abc NONE = object() class KeysView(abc.KeysView, abc.Sequence): "Read-only view of mapping keys." # noqa pylint: disable=too-few-public-methods,protected-access,too-many-ancestors def __getitem__(self, index): "``keys_view[index]``" _nums = self._mapping._nums if isinstance(index, slice): nums = _nums._list[index] return [_nums[num] for num in nums] return _nums[_nums._list[index]] class ItemsView(abc.ItemsView, abc.Sequence): "Read-only view of mapping items." # noqa pylint: disable=too-few-public-methods,protected-access,too-many-ancestors def __getitem__(self, index): "``items_view[index]``" _mapping = self._mapping _nums = _mapping._nums if isinstance(index, slice): nums = _nums._list[index] keys = [_nums[num] for num in nums] return [(key, _mapping[key]) for key in keys] num = _nums._list[index] key = _nums[num] return key, _mapping[key] class ValuesView(abc.ValuesView, abc.Sequence): "Read-only view of mapping values." # noqa pylint: disable=too-few-public-methods,protected-access,too-many-ancestors def __getitem__(self, index): "``items_view[index]``" _mapping = self._mapping _nums = _mapping._nums if isinstance(index, slice): nums = _nums._list[index] keys = [_nums[num] for num in nums] return [_mapping[key] for key in keys] num = _nums._list[index] key = _nums[num] return _mapping[key] class OrderedDict(dict): """Dictionary that remembers insertion order and is numerically indexable. Keys are numerically indexable using dict views. For example:: >>> ordered_dict = OrderedDict.fromkeys('abcde') >>> keys = ordered_dict.keys() >>> keys[0] 'a' >>> keys[-2:] ['d', 'e'] The dict views support the sequence abstract base class. """ # pylint: disable=super-init-not-called def __init__(self, *args, **kwargs): self._keys = {} self._nums = SortedDict() self._keys_view = self._nums.keys() self._count = count() self.update(*args, **kwargs) def __setitem__(self, key, value, dict_setitem=dict.__setitem__): "``ordered_dict[key] = value``" if key not in self: num = next(self._count) self._keys[key] = num self._nums[num] = key dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): "``del ordered_dict[key]``" dict_delitem(self, key) num = self._keys.pop(key) del self._nums[num] def __iter__(self): "``iter(ordered_dict)``" return iter(self._nums.values()) def __reversed__(self): "``reversed(ordered_dict)``" nums = self._nums for key in reversed(nums): yield nums[key] def clear(self, dict_clear=dict.clear): "Remove all items from mapping." dict_clear(self) self._keys.clear() self._nums.clear() def popitem(self, last=True): """Remove and return (key, value) item pair. Pairs are returned in LIFO order if last is True or FIFO order if False. """ index = -1 if last else 0 num = self._keys_view[index] key = self._nums[num] value = self.pop(key) return key, value update = __update = abc.MutableMapping.update def keys(self): "Return set-like and sequence-like view of mapping keys." return KeysView(self) def items(self): "Return set-like and sequence-like view of mapping items." return ItemsView(self) def values(self): "Return set-like and sequence-like view of mapping values." return ValuesView(self) def pop(self, key, default=NONE): """Remove given key and return corresponding value. If key is not found, default is returned if given, otherwise raise KeyError. """ if key in self: value = self[key] del self[key] return value if default is NONE: raise KeyError(key) return default def setdefault(self, key, default=None): """Return ``mapping.get(key, default)``, also set ``mapping[key] = default`` if key not in mapping. """ if key in self: return self[key] self[key] = default return default @recursive_repr() def __repr__(self): "Text representation of mapping." return f'{self.__class__.__name__}({list(self.items())!r})' __str__ = __repr__ def __reduce__(self): "Support for pickling serialization." return (self.__class__, (list(self.items()),)) def copy(self): "Return shallow copy of mapping." return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): """Return new mapping with keys from iterable. If not specified, value defaults to None. """ return cls((key, value) for key in iterable) def __eq__(self, other): "Test self and other mapping for equality." if isinstance(other, OrderedDict): return dict.__eq__(self, other) and all(map(eq, self, other)) return dict.__eq__(self, other) __ne__ = abc.MutableMapping.__ne__ def _check(self): "Check consistency of internal member variables." # pylint: disable=protected-access keys = self._keys nums = self._nums for key, value in keys.items(): assert nums[value] == key nums._check() python-sortedcollections-2.1.0/sortedcollections/recipes.py000066400000000000000000000231611400140251100243220ustar00rootroot00000000000000"""Sorted collections recipes implementations. """ from collections import abc from copy import deepcopy from itertools import count from sortedcontainers import SortedDict, SortedKeyList, SortedSet from sortedcontainers.sortedlist import recursive_repr class IndexableDict(SortedDict): """Dictionary that supports numerical indexing. Keys are numerically indexable using dict views. For example:: >>> indexable_dict = IndexableDict.fromkeys('abcde') >>> keys = indexable_dict.keys() >>> sorted(keys[:]) == ['a', 'b', 'c', 'd', 'e'] True The dict views support the sequence abstract base class. """ def __init__(self, *args, **kwargs): super().__init__(hash, *args, **kwargs) class IndexableSet(SortedSet): """Set that supports numerical indexing. Values are numerically indexable. For example:: >>> indexable_set = IndexableSet('abcde') >>> sorted(indexable_set[:]) == ['a', 'b', 'c', 'd', 'e'] True `IndexableSet` implements the sequence abstract base class. """ # pylint: disable=too-many-ancestors def __init__(self, *args, **kwargs): super().__init__(*args, key=hash, **kwargs) def __reduce__(self): return self.__class__, (set(self),) class ItemSortedDict(SortedDict): """Sorted dictionary with key-function support for item pairs. Requires key function callable specified as the first argument. The callable must accept two arguments, key and value, and return a value used to determine the sort order. For example:: def multiply(key, value): return key * value mapping = ItemSortedDict(multiply, [(3, 2), (4, 1), (2, 5)]) list(mapping) == [4, 3, 2] Above, the key/value item pairs are ordered by ``key * value`` according to the callable given as the first argument. """ def __init__(self, *args, **kwargs): assert args and callable(args[0]) args = list(args) func = self._func = args[0] def key_func(key): "Apply key function to (key, value) item pair." return func(key, self[key]) args[0] = key_func super().__init__(*args, **kwargs) def __delitem__(self, key): "``del mapping[key]``" if key not in self: raise KeyError(key) self._list_remove(key) dict.__delitem__(self, key) def __setitem__(self, key, value): "``mapping[key] = value``" if key in self: self._list_remove(key) dict.__delitem__(self, key) dict.__setitem__(self, key, value) self._list_add(key) _setitem = __setitem__ def copy(self): "Return shallow copy of the mapping." return self.__class__(self._func, iter(self.items())) __copy__ = copy def __deepcopy__(self, memo): items = (deepcopy(item, memo) for item in self.items()) return self.__class__(self._func, items) class ValueSortedDict(SortedDict): """Sorted dictionary that maintains (key, value) item pairs sorted by value. - ``ValueSortedDict()`` -> new empty dictionary. - ``ValueSortedDict(mapping)`` -> new dictionary initialized from a mapping object's (key, value) pairs. - ``ValueSortedDict(iterable)`` -> new dictionary initialized as if via:: d = ValueSortedDict() for k, v in iterable: d[k] = v - ``ValueSortedDict(**kwargs)`` -> new dictionary initialized with the name=value pairs in the keyword argument list. For example:: ValueSortedDict(one=1, two=2) An optional key function callable may be specified as the first argument. When so, the callable will be applied to the value of each item pair to determine the comparable for sort order as with Python's builtin ``sorted`` function. """ def __init__(self, *args, **kwargs): args = list(args) if args and callable(args[0]): func = self._func = args[0] def key_func(key): "Apply key function to ``mapping[value]``." return func(self[key]) args[0] = key_func else: self._func = None def key_func(key): "Return mapping value for key." return self[key] if args and args[0] is None: args[0] = key_func else: args.insert(0, key_func) super().__init__(*args, **kwargs) def __delitem__(self, key): "``del mapping[key]``" if key not in self: raise KeyError(key) self._list_remove(key) dict.__delitem__(self, key) def __setitem__(self, key, value): "``mapping[key] = value``" if key in self: self._list_remove(key) dict.__delitem__(self, key) dict.__setitem__(self, key, value) self._list_add(key) _setitem = __setitem__ def copy(self): "Return shallow copy of the mapping." return self.__class__(self._func, iter(self.items())) __copy__ = copy def __reduce__(self): items = [(key, self[key]) for key in self._list] args = (self._func, items) return (self.__class__, args) @recursive_repr() def __repr__(self): items = ', '.join(f'{key!r}: {self[key]!r}' for key in self._list) return f'{self.__class__.__name__}({self._func!r}, {{{items}}})' class OrderedSet(abc.MutableSet, abc.Sequence): """Like OrderedDict, OrderedSet maintains the insertion order of elements. For example:: >>> ordered_set = OrderedSet('abcde') >>> list(ordered_set) == list('abcde') True >>> ordered_set = OrderedSet('edcba') >>> list(ordered_set) == list('edcba') True OrderedSet also implements the collections.Sequence interface. """ # pylint: disable=too-many-ancestors def __init__(self, iterable=()): # pylint: disable=super-init-not-called self._keys = {} self._nums = SortedDict() self._keys_view = self._nums.keys() self._count = count() self |= iterable def __contains__(self, key): "``key in ordered_set``" return key in self._keys count = __contains__ def __iter__(self): "``iter(ordered_set)``" return iter(self._nums.values()) def __reversed__(self): "``reversed(ordered_set)``" _nums = self._nums for key in reversed(_nums): yield _nums[key] def __getitem__(self, index): "``ordered_set[index]`` -> element; lookup element at index." num = self._keys_view[index] return self._nums[num] def __len__(self): "``len(ordered_set)``" return len(self._keys) def index(self, value): "Return index of value." # pylint: disable=arguments-differ try: return self._keys[value] except KeyError: raise ValueError(f'{value!r} is not in {type(self).__name__}') def add(self, value): "Add element, value, to set." if value not in self._keys: num = next(self._count) self._keys[value] = num self._nums[num] = value def discard(self, value): "Remove element, value, from set if it is a member." num = self._keys.pop(value, None) if num is not None: del self._nums[num] def __repr__(self): "Text representation of set." return f'{type(self).__name__}({list(self)!r})' __str__ = __repr__ class SegmentList(SortedKeyList): """List that supports fast random insertion and deletion of elements. SegmentList is a special case of a SortedList initialized with a key function that always returns 0. As such, several SortedList methods are not implemented for SegmentList. """ # pylint: disable=too-many-ancestors def __init__(self, iterable=()): super().__init__(iterable, self.zero) @staticmethod def zero(_): "Return 0." return 0 def __setitem__(self, index, value): if isinstance(index, slice): raise NotImplementedError pos, idx = self._pos(index) self._lists[pos][idx] = value def append(self, value): if self._len: pos = len(self._lists) - 1 self._lists[pos].append(value) self._keys[pos].append(0) self._expand(pos) else: self._lists.append([value]) self._keys.append([0]) self._maxes.append(0) self._len += 1 def extend(self, values): for value in values: self.append(value) def insert(self, index, value): if index == self._len: self.append(value) return pos, idx = self._pos(index) self._lists[pos].insert(idx, value) self._keys[pos].insert(idx, 0) self._expand(pos) self._len += 1 def reverse(self): values = list(self) values.reverse() self.clear() self.extend(values) def sort(self, key=None, reverse=False): "Stable sort in place." values = sorted(self, key=key, reverse=reverse) self.clear() self.extend(values) def _not_implemented(self, *args, **kwargs): "Not implemented." raise NotImplementedError add = _not_implemented bisect = _not_implemented bisect_left = _not_implemented bisect_right = _not_implemented bisect_key = _not_implemented bisect_key_left = _not_implemented bisect_key_right = _not_implemented irange = _not_implemented irange_key = _not_implemented update = _not_implemented python-sortedcollections-2.1.0/tests/000077500000000000000000000000001400140251100177165ustar00rootroot00000000000000python-sortedcollections-2.1.0/tests/__init__.py000066400000000000000000000000001400140251100220150ustar00rootroot00000000000000python-sortedcollections-2.1.0/tests/test_doctest.py000066400000000000000000000010701400140251100227720ustar00rootroot00000000000000import doctest import sortedcollections import sortedcollections.ordereddict import sortedcollections.recipes def test_sortedcollections(): failed, attempted = doctest.testmod(sortedcollections) assert attempted > 0 assert failed == 0 def test_sortedcollections_ordereddict(): failed, attempted = doctest.testmod(sortedcollections.ordereddict) assert attempted > 0 assert failed == 0 def test_sortedcollections_recipes(): failed, attempted = doctest.testmod(sortedcollections.recipes) assert attempted > 0 assert failed == 0 python-sortedcollections-2.1.0/tests/test_itemsorteddict.py000066400000000000000000000036321400140251100243560ustar00rootroot00000000000000"Test sortedcollections.ItemSortedDict" import copy import pytest from sortedcollections import ItemSortedDict def key_func(key, value): return key def value_func(key, value): return value alphabet = 'abcdefghijklmnopqrstuvwxyz' def test_init(): temp = ItemSortedDict(key_func) temp._check() def test_init_args(): temp = ItemSortedDict(key_func, enumerate(alphabet)) assert len(temp) == 26 assert temp[0] == 'a' assert temp[25] == 'z' assert temp.keys()[4] == 4 temp._check() def test_init_kwargs(): temp = ItemSortedDict(key_func, a=0, b=1, c=2) assert len(temp) == 3 assert temp['a'] == 0 assert temp.keys()[0] == 'a' temp._check() def test_getitem(): temp = ItemSortedDict(value_func, enumerate(reversed(alphabet))) assert temp[0] == 'z' assert temp.keys()[0] == 25 assert list(temp) == list(reversed(range(26))) def test_delitem(): temp = ItemSortedDict(value_func, enumerate(reversed(alphabet))) del temp[25] assert temp.keys()[0] == 24 def test_delitem_error(): temp = ItemSortedDict(value_func, enumerate(reversed(alphabet))) with pytest.raises(KeyError): del temp[-1] def test_setitem(): temp = ItemSortedDict(value_func, enumerate(reversed(alphabet))) temp[25] = '!' del temp[25] iloc = temp.keys() assert iloc[0] == 24 temp[25] = 'a' assert iloc[0] == 25 def test_copy(): temp = ItemSortedDict(value_func, enumerate(reversed(alphabet))) that = temp.copy() assert temp == that assert temp._key != that._key def test_deepcopy(): temp = ItemSortedDict(value_func, enumerate(reversed(alphabet))) that = copy.deepcopy(temp) assert temp == that assert temp._key != that._key def test_update(): temp = ItemSortedDict(lambda key, value: value) for index, letter in enumerate(alphabet): pair = {index: letter} temp.update(pair) python-sortedcollections-2.1.0/tests/test_nearestdict.py000066400000000000000000000024121400140251100236330ustar00rootroot00000000000000import pytest from sortedcollections import NearestDict def test_basic(): d = NearestDict() with pytest.raises(KeyError): d[0] d[0] = 'a' assert d[0] == 'a' d[0] = 'b' assert d[0] == 'b' def test_iteration(): # In sorted order by key exp_items = ( (0, 'a'), (1, 'b'), (2, 'c'), ) d = NearestDict() for k, v in exp_items: d[k] = v for act, exp in zip(d.items(), exp_items): assert act == exp def test_nearest(): d = NearestDict(rounding=NearestDict.NEAREST) d[0] = 'a' d[3] = 'b' assert d[-1] == 'a' assert d[0] == 'a' assert d[1] == 'a' assert d[2] == 'b' assert d[3] == 'b' assert d[4] == 'b' def test_nearest_prev(): d = NearestDict(rounding=NearestDict.NEAREST_PREV) d[0] = 'a' d[3] = 'b' with pytest.raises(KeyError): d[-1] assert d[0] == 'a' assert d[1] == 'a' assert d[2] == 'a' assert d[3] == 'b' assert d[4] == 'b' def test_nearest_next(): d = NearestDict(rounding=NearestDict.NEAREST_NEXT) d[0] = 'a' d[3] = 'b' assert d[-1] == 'a' assert d[0] == 'a' assert d[1] == 'b' assert d[2] == 'b' assert d[3] == 'b' with pytest.raises(KeyError): d[4] python-sortedcollections-2.1.0/tests/test_ordereddict.py000066400000000000000000000070101400140251100236150ustar00rootroot00000000000000"Test sortedcollections.OrderedDict" import pickle import pytest from sortedcollections import OrderedDict pairs = dict(enumerate(range(10))) def test_init(): od = OrderedDict() assert len(od) == 0 od._check() od = OrderedDict(enumerate(range(10))) assert len(od) == 10 od._check() od = OrderedDict(a=0, b=1, c=2) assert len(od) == 3 od._check() od = OrderedDict(pairs) assert len(od) == 10 od._check() def test_setitem(): od = OrderedDict() od['alice'] = 0 od['bob'] = 1 od['carol'] = 2 assert len(od) == 3 od['carol'] = 2 assert len(od) == 3 od._check() def test_delitem(): od = OrderedDict(pairs) assert len(od) == 10 for value in range(10): del od[value] assert len(od) == 0 od._check() def test_iter_reversed(): od = OrderedDict([('b', 0), ('a', 1), ('c', 2)]) assert list(od) == ['b', 'a', 'c'] assert list(reversed(od)) == ['c', 'a', 'b'] od._check() def test_clear(): od = OrderedDict(pairs) assert len(od) == 10 od.clear() assert len(od) == 0 od._check() def test_popitem(): od = OrderedDict(enumerate(range(10))) for num in reversed(range(10)): key, value = od.popitem() assert num == key == value od._check() od = OrderedDict(enumerate(range(10))) for num in range(10): key, value = od.popitem(last=False) assert num == key == value od._check() def test_keys(): od = OrderedDict(enumerate(range(10))) assert list(reversed(od.keys())) == list(reversed(range(10))) assert od.keys()[:3] == [0, 1, 2] od._check() def test_items(): items = list(enumerate(range(10))) od = OrderedDict(enumerate(range(10))) assert list(reversed(od.items())) == list(reversed(items)) assert od.items()[:3] == [(0, 0), (1, 1), (2, 2)] od._check() def test_values(): od = OrderedDict(enumerate(range(10))) assert list(reversed(od.values())) == list(reversed(range(10))) assert od.values()[:3] == [0, 1, 2] od._check() def test_iloc(): od = OrderedDict(enumerate(range(10))) iloc = od.keys() for num in range(10): assert iloc[num] == num iloc[-1] == 9 assert len(iloc) == 10 od._check() def test_pop(): od = OrderedDict(enumerate(range(10))) for num in range(10): assert od.pop(num) == num od._check() assert od.pop(0, 'thing') == 'thing' assert od.pop(1, default='thing') == 'thing' od._check() def test_pop_error(): od = OrderedDict() with pytest.raises(KeyError): od.pop(0) def test_setdefault(): od = OrderedDict() od.setdefault(0, False) assert od[0] is False od.setdefault(1, default=True) assert od[1] is True od.setdefault(2) assert od[2] is None assert od.setdefault(0) is False assert od.setdefault(1) is True def test_repr(): od = OrderedDict() assert repr(od) == 'OrderedDict([])' assert str(od) == 'OrderedDict([])' def test_reduce(): od = OrderedDict(enumerate(range(10))) data = pickle.dumps(od) copy = pickle.loads(data) assert od == copy def test_copy(): od = OrderedDict(enumerate(range(10))) copy = od.copy() assert od == copy def test_fromkeys(): od = OrderedDict.fromkeys('abc') assert od == {'a': None, 'b': None, 'c': None} od._check() def test_equality(): od = OrderedDict.fromkeys('abc') assert od == {'a': None, 'b': None, 'c': None} assert od != {} assert od != OrderedDict() od._check() python-sortedcollections-2.1.0/tests/test_orderedset.py000066400000000000000000000034351400140251100234740ustar00rootroot00000000000000"Test sortedcollections.OrderedSet." import random import pytest from sortedcollections import OrderedSet def test_init(): os = OrderedSet() assert len(os) == 0 def test_contains(): os = OrderedSet(range(100)) assert len(os) == 100 for value in range(100): assert value in os assert os.count(value) == 1 assert -1 not in os assert 100 not in os def test_iter(): os = OrderedSet(range(100)) assert list(os) == list(range(100)) names = ['eve', 'carol', 'alice', 'dave', 'bob'] os = OrderedSet(names) assert list(os) == names def test_reversed(): os = OrderedSet(range(100)) assert list(reversed(os)) == list(reversed(range(100))) names = ['eve', 'carol', 'alice', 'dave', 'bob'] os = OrderedSet(names) assert list(reversed(os)) == list(reversed(names)) def test_getitem(): values = list(range(100)) random.shuffle(values) os = OrderedSet(values) assert len(os) == len(values) for index in range(len(os)): assert os[index] == values[index] def test_index(): values = list(range(100)) random.shuffle(values) os = OrderedSet(values) assert len(os) == len(values) for value in values: assert values.index(value) == os.index(value) def test_index_error(): os = OrderedSet(range(10)) with pytest.raises(ValueError): os.index(10) def test_add(): os = OrderedSet() for value in range(100): os.add(value) assert len(os) == 100 os.add(0) assert len(os) == 100 for value in range(100): assert value in os def test_discard(): os = OrderedSet(range(100)) for value in range(200): os.discard(value) assert len(os) == 0 def test_repr(): os = OrderedSet() assert repr(os) == 'OrderedSet([])' python-sortedcollections-2.1.0/tests/test_recipes.py000066400000000000000000000026231400140251100227640ustar00rootroot00000000000000"Test sortedcollections.recipes" import pickle import pytest from sortedcollections import IndexableDict, IndexableSet, SegmentList def test_index_dict(): mapping = IndexableDict(enumerate(range(10))) iloc = mapping.keys() for value in range(10): assert iloc[value] == value def test_index_set(): set_values = IndexableSet(range(10)) for index in range(10): assert set_values[index] == index def test_index_set_pickle(): set_values1 = IndexableSet(range(10)) data = pickle.dumps(set_values1) set_values2 = pickle.loads(data) assert set_values1 == set_values2 def test_segment_list(): values = [5, 1, 3, 2, 4, 8, 6, 7, 9, 0] sl = SegmentList(values) assert list(sl) == values sl.sort() assert list(sl) == list(range(10)) sl.reverse() assert list(sl) == list(reversed(range(10))) sl.reverse() sl.append(10) assert list(sl) == list(range(11)) sl.extend(range(11, 15)) assert list(sl) == list(range(15)) del sl[5:] assert list(sl) == list(range(5)) sl[2] = 'c' sl.insert(3, 'd') sl.insert(6, 'e') assert list(sl) == [0, 1, 'c', 'd', 3, 4, 'e'] def test_segment_list_bisect(): sl = SegmentList() with pytest.raises(NotImplementedError): sl.bisect(0) def test_segment_list_setitem_slice(): sl = SegmentList() with pytest.raises(NotImplementedError): sl[:] = [0] python-sortedcollections-2.1.0/tests/test_valuesorteddict.py000066400000000000000000000040511400140251100245300ustar00rootroot00000000000000"Test sortedcollections.ValueSortedDict" import pickle import pytest from sortedcollections import ValueSortedDict def identity(value): return value alphabet = 'abcdefghijklmnopqrstuvwxyz' def test_init(): temp = ValueSortedDict() temp._check() def test_init_args(): temp = ValueSortedDict(enumerate(alphabet)) assert len(temp) == 26 assert temp[0] == 'a' assert temp[25] == 'z' assert temp.keys()[4] == 4 temp._check() def test_init_kwargs(): temp = ValueSortedDict(None, a=0, b=1, c=2) assert len(temp) == 3 assert temp['a'] == 0 assert temp.keys()[0] == 'a' temp._check() def test_getitem(): temp = ValueSortedDict(identity, enumerate(reversed(alphabet))) assert temp[0] == 'z' assert temp.keys()[0] == 25 assert list(temp) == list(reversed(range(26))) def test_delitem(): temp = ValueSortedDict(identity, enumerate(reversed(alphabet))) del temp[25] assert temp.keys()[0] == 24 def test_delitem_error(): temp = ValueSortedDict(identity, enumerate(reversed(alphabet))) with pytest.raises(KeyError): del temp[-1] def test_setitem(): temp = ValueSortedDict(identity, enumerate(reversed(alphabet))) temp[25] = '!' del temp[25] assert temp.keys()[0] == 24 temp[25] = 'a' assert temp.keys()[0] == 25 def test_copy(): temp = ValueSortedDict(identity, enumerate(reversed(alphabet))) that = temp.copy() assert temp == that assert temp._key != that._key def test_pickle(): original = ValueSortedDict(identity, enumerate(reversed(alphabet))) data = pickle.dumps(original) duplicate = pickle.loads(data) assert original == duplicate class Negater: def __call__(self, value): return -value def __repr__(self): return 'negate' def test_repr(): temp = ValueSortedDict(Negater()) assert repr(temp) == 'ValueSortedDict(negate, {})' def test_update(): temp = ValueSortedDict() for index, letter in enumerate(alphabet): pair = {index: letter} temp.update(pair) python-sortedcollections-2.1.0/tox.ini000066400000000000000000000031321400140251100200660ustar00rootroot00000000000000[tox] envlist=bluecheck,doc8,docs,isortcheck,flake8,mypy,pylint,rstcheck,py36,py37,py38,py39 skip_missing_interpreters=True [testenv] commands=pytest deps= pytest pytest-cov [testenv:blue] commands=blue {toxinidir}/setup.py {toxinidir}/sortedcollections {toxinidir}/tests deps=blue [testenv:bluecheck] commands=blue --check {toxinidir}/setup.py {toxinidir}/sortedcollections {toxinidir}/tests deps=blue [testenv:doc8] deps=doc8 commands=doc8 docs [testenv:docs] allowlist_externals=make changedir=docs commands=make html deps=sphinx [testenv:flake8] commands=flake8 {toxinidir}/setup.py {toxinidir}/sortedcollections {toxinidir}/tests deps=flake8 [testenv:isort] commands=isort {toxinidir}/setup.py {toxinidir}/sortedcollections {toxinidir}/tests deps=isort [testenv:isortcheck] commands=isort --check {toxinidir}/setup.py {toxinidir}/sortedcollections {toxinidir}/tests deps=isort [testenv:mypy] commands=mypy {toxinidir}/sortedcollections deps=mypy [testenv:pylint] commands=pylint {toxinidir}/sortedcollections deps=pylint [testenv:rstcheck] commands=rstcheck {toxinidir}/README.rst deps=rstcheck [testenv:uploaddocs] allowlist_externals=rsync changedir=docs commands= rsync -azP --stats --delete _build/html/ \ grantjenks.com:/srv/www/www.grantjenks.com/public/docs/sortedcollections/ [isort] multi_line_output = 3 include_trailing_comma = True force_grid_wrap = 0 use_parentheses = True ensure_newline_before_comments = True line_length = 79 [pytest] addopts= --cov-branch --cov-fail-under=100 --cov-report=term-missing --cov=sortedcollections --doctest-glob="*.rst"