pax_global_header00006660000000000000000000000064136137613350014522gustar00rootroot0000000000000052 comment=d0d0d293b1d65581477741fa812a56df5c8d9c5b natsort-7.0.1/000077500000000000000000000000001361376133500132215ustar00rootroot00000000000000natsort-7.0.1/.coveragerc000066400000000000000000000006061361376133500153440ustar00rootroot00000000000000[report] # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain if tests don't hit defensive assertion code: raise AssertionError raise NotImplementedError raise$ # Don't complain if non-runnable code isn't run: if 0: if __name__ == .__main__.: ignore_errors = True natsort-7.0.1/.github/000077500000000000000000000000001361376133500145615ustar00rootroot00000000000000natsort-7.0.1/.github/ISSUE_TEMPLATE/000077500000000000000000000000001361376133500167445ustar00rootroot00000000000000natsort-7.0.1/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000013761361376133500214450ustar00rootroot00000000000000--- name: Bug report about: Report unexpected behavior, a crash, or incorrect results --- **Describe the bug** A clear and concise description of what the bug is. **Expected behavior** A clear and concise description of what you expected to happen. **Environment (please complete the following information):** - Python Version: [e.g. 3.6] - OS [e.g. Windows, Fedora] - If the bug involves `LOCALE` or `humansorted`: - Is `PyICU` installed? - Do you have a locale set? If so, to what? **To Reproduce** Include a Minimum, Complete, Verifiable Example. If there is a traceback (or error message), **please** include the *entire* traceback (or error message), even if you think it is too big. See https://stackoverflow.com/help/mcve for an explanation. natsort-7.0.1/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000011231361376133500224660ustar00rootroot00000000000000--- name: Feature request about: Suggest or request an enhancement --- **Describe the feature or enhancement** Be as descriptive and precise as possible. **Provide a concrete example of how the feature or enhancement will improve `natsort`** Code examples are an excellent way to show how this feature or enhancement will help. To make your case stronger, show the current workaround due to the lack of the feature. What is the return-on-investment for including the feature or enhancement? **Would you be willing to submit a Pull Request for this feature?** Extra help is *always* welcome. natsort-7.0.1/.github/ISSUE_TEMPLATE/question.md000066400000000000000000000003711361376133500211360ustar00rootroot00000000000000--- name: Question about: Inquiry about natsort --- - [ ] I have read the [`natsort` documentation](https://natsort.readthedocs.io/en/master/) and the [README](https://github.com/SethMMorton/natsort#natsort), and my question is still not answered natsort-7.0.1/.gitignore000066400000000000000000000006051361376133500152120ustar00rootroot00000000000000*.py[co] # Packages *.egg *.eggs *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg .python-version # We are using MANIFEST.in instead MANIFEST # Installer logs pip-log.txt # Unit test / coverage reports .hypothesis .coverage .tox .cache .pytest_cache .pytest .envrc .venv #Translations *.mo #Mr Developer .mr.developer.cfg # PyCharm .idea # VSCode .vscode natsort-7.0.1/.travis.yml000066400000000000000000000073621361376133500153420ustar00rootroot00000000000000dist: xenial language: python cache: - pip - directories: - $HOME/.pyenv_cache python: - 3.5 - 3.6 - 3.7 - 3.8 # Explicitly include other jobs/configurations not defined by the above settings jobs: include: # For Python 3.8 do some extra configurations. # Linux with both "icu" and "fastnumbers" - python: 3.8 name: "Test with ICU and fastnumbers" env: WITH_EXTRAS="fast,icu" addons: apt: packages: - libicu-dev - language-pack-de - language-pack-en # For MacOS and Windows, only run Python 3.8 without "icu" to test native locales - language: sh os: osx name: "Test on MacOS" env: TOXENV=py38 before_install: - export PYENV_VERSION="3.8.1" - export PYENV_VERSION_STRING="Python ${PYENV_VERSION}" - wget https://github.com/praekeltfoundation/travis-pyenv/releases/download/0.4.0/setup-pyenv.sh - source setup-pyenv.sh # - language: sh # os: windows # name: "Test on Windows" # env: TOXENV=py38 # before_install: # - choco install python --version=3.8.1 # - export PATH="/c/Python38:/c/Python38/Scripts:$PATH" # This "code quality" stage does static analysis and formatting checks. # Platform- and Python-version-independent. # No python version specified, will use the first listed in the python: list. - stage: code quality python: 3.6 # black requires >= 3.6 name: "Formatting" install: pip install black script: black --quiet --check --diff - stage: code quality name: "Static Analysis" install: pip install flake8 flake8-import-order flake8-bugbear pep8-naming script: flake8 - stage: code quality name: "Package Validation" install: pip install twine check-manifest script: - check-manifest --ignore ".github*,*.md,.coveragerc" - python setup.py sdist - twine check dist/* # The "deploy" stage will actually upload the package to PyPI. # For non-tags, we deploy to the test PyPI, for tags it's for real. # Platform- and Python-version-independent. # No python version specified, will use the first listed in the python: list. - stage: deploy name: "Deploy to PyPI (real on tagged commits, test otherwise)" install: skip script: skip deploy: - provider: pypi server: https://test.pypi.org/legacy/ user: SethMMorton password: secure: "Va9uj9+6uDHMH6qcB3Z35MKDvqBDSLai0+cQN2rWjAZfhYq1H3B2TKb/cToN1dhy96t2Q7u7sXeWy9ptiJRACUOXeabL0+Ao3tFpRAgF7YBV9WUsoz9ux7waDoyMRrv1Oztbztg8sR6T3Sltz7Utd9Uf1TlYINO6D8poO7g2Cdo=" distributions: sdist --format=gztar bdist_wheel skip_existing: true on: tags: false repo: SethMMorton/natsort branch: master - provider: pypi user: SethMMorton password: secure: "Va9uj9+6uDHMH6qcB3Z35MKDvqBDSLai0+cQN2rWjAZfhYq1H3B2TKb/cToN1dhy96t2Q7u7sXeWy9ptiJRACUOXeabL0+Ao3tFpRAgF7YBV9WUsoz9ux7waDoyMRrv1Oztbztg8sR6T3Sltz7Utd9Uf1TlYINO6D8poO7g2Cdo=" distributions: sdist --format=gztar bdist_wheel skip_existing: true on: tags: true repo: SethMMorton/natsort branch: master # The remainder of the code should be the same no matter the configuration/OS install: - python -m pip install -U pip - python -m pip install tox tox-travis codacy-coverage codecov script: - tox stages: - code quality - test # Only deploy on master branch and from the main repository - name: deploy if: (branch = master OR tag IS present) AND repo = SethMMorton/natsort after_success: - coverage xml - python-codacy-coverage -r coverage.xml - codecov natsort-7.0.1/CHANGELOG.md000066400000000000000000000437551361376133500150500ustar00rootroot00000000000000Unreleased --- [7.0.1] - 2020-01-27 --- ### Fixed - Bug where that caused incorrect sorting when using locales that have a `"."` character as the thousands separator. [7.0.0] - 2020-01-08 --- ### Added - Ability to deploy directly from TravisCI ([@hugovk](https://github.com/hugovk), issue #106) - Release checklist in `RELEASING.md` ([@hugovk](https://github.com/hugovk), issue #106) ### Changed - Updated auxillary shell scripts to be written in python, and added ability to call these from `tox` - Improved Travis-CI experience - Update testing dependency versions ### Removed - Support for Python 2 [6.2.0] - 2019-11-13 --- ### Added - Support for Python 3.8 ([@hugovk](https://github.com/hugovk), issue #104) ### Changed - `index_natsorted` internally now uses tuples for index-element pairs instead of lists - Added a TOC to the README - Python 3.4 is no longer included in testing ### Fixed - Pin testing dependencies to prevent CI breaking due to third-party library changes ### Removed - Introduction page in documentation [6.1.0] - 2019-11-09 --- ### Added - Expose `numeric_regex_chooser` as a public function for ease in making key functions - Example in the documentation on how to sort numbers with units - Automated testing support for macos and Windows (issue #91) ### Changed - Update CHANGELOG format to style from https://keepachangelog.com/ (issue #92) ### Fixed - Removed dependency on `sudo` in TravisCI configuration ([@hugovk](https://github.com/hugovk), issue #99) - Documentation typos ([@jdufresne](https://github.com/jdufresne), issue #94) ([@cpburnz](https://github.com/cpburnz), issue #95) [6.0.0] - 2019-02-04 --- ### Changed - Simply Travis-CI configuration ([@jdufresne](https://github.com/jdufresne), issue #88) ### Fixed - Fix README rendering in PyPI ([@altendky](https://github.com/altendky), issue #89) ### Removed - Drop support for Python 2.6 and 3.3 ([@jdufresne](https://github.com/jdufresne), issue #70) - Remove deprecated APIs (kwargs `number_type`, `signed`, `exp`, `as_path`, `py3_safe`; enums `ns.TYPESAFE`, `ns.DIGIT`, `ns.VERSION`; functions `versorted`, `index_versorted`) (issue #81) - Remove `pipenv` as a dependency for building (issue #86) [5.5.0] - 2018-11-18 --- ### Added - `CHANGELOG.rst` to the top-level of the repository (issue #85) ### Changed - Documentation, packaging, and CI cleanup ([@jdufresne](https://github.com/jdufresne), issues #69, #71-#80) - Consolidate API documentation into a single page (issue #82) ### Deprecated - Formally deprecated old or misleading APIs (issue #83) ### Fixed - Add back support for very old versions of setuptools (issue #84) [5.4.1] - 2018-09-09 --- ### Changed - Code format and quality checking infrastructure (issue #68) ### Fixed - Error in a newly added test (issues #65, #67) [5.4.0] - 2018-09-06 --- ### Changed - Re-expose `natsort_key` as "public" and remove the associated `DepricationWarning` - Better developer documentation - Refactor tests (issue #66) - Bump allowed [`fastnumbers`](https://github.com/SethMMorton/fastnumbers) version [5.3.3] - 2018-07-07 --- ### Added - Enable Python 3.7 support in Travis-CI (issue #61) ### Changed - Update docs with a FAQ and quick how-it-works (issue #60) ### Fixed - `StopIteration` error in the testing code [5.3.2] - 2018-05-17 --- ### Fixed - Bug that prevented install on old versions of `setuptools` (issues #55, #56) - Revert layout from `src/natsort/` back to `natsort/` to make user testing simpler (issues #57, #58) [5.3.1] - 2018-05-14 --- ### Added - [`bumpversion`](https://github.com/c4urself/bump2version) infrastructure - Extras can be installed by "[]" notation ### Changed - No bugfixes or features, just infrastructure and installation updates - Move to defining dependencies with `Pipfile` - Development layout is now `src/natsort/` instead of `natsort/` [5.3.0] - 2018-04-20 --- ### Added - Ability to consider unicode-decimal numbers as numbers (issues #52, #54) ### Fixed - Bug in assessing [`fastnumbers`](https://github.com/SethMMorton/fastnumbers) version at import-time ([@hholzgra](https://github.com/hholzgra), issues #51, #53) [5.2.0] - 2018-02-14 --- ### Added - `ns.NUMAFTER` to cause numbers to be placed after non-numbers (issues #48, #49) - `natcmp` function (Python 2 only) ([@rinslow](https://github.com/rinslow), issue #47) [5.1.1] - 2017-11-11 --- ### Added - Additional unicode number support for Python 3.7 - Information on how to install and test (issue #46) [5.1.0] - 2017-08-19 --- ### Changed - All Unicode input is now normalized (issue #44, #45) ### Fixed - `StopIteration` warning on Python 3.6+ ([@lykinsbd](https://github.com/lykinsbd), issues #42, #43) [5.0.3] - 2017-04-30 --- - Improved development infrastructure - Migrated documentation to ReadTheDocs [5.0.2] - 2017-01-02 --- ### Added - Additional unicode number support for Python 3.6 - "how does it work?" section to the documentation ### Changed - Renamed several internal functions and variables to improve clarity - Improved documentation examples [5.0.1] - 2016-06-04 --- ### Added - The `ns` enum attributes can now be imported from the top-level namespace ### Fixed - Bug with the `from natsort import *` mechanism - Bug with using `natsort` with `python -OO` (issues #38, #39) [5.0.0] - 2016-05-08 --- ### Added - `chain_functions` function for convenience in creating a complex user-given `key` from several existing functions ### Changed - `ns.LOCALE`/`humansorted` now accounts for thousands separators (issue #36) - Refactored entire codebase to be more functional (as in use functions as units). Previously, the code was rather monolithic and difficult to follow. The goal is that with the code existing in smaller units, contributing will be easier (issue #37) - Increased speed of execution (came for free with the new functional approach because the new factory function paradigm eliminates most `if` branches during execution). For the most cases, the code is 30-40% faster than version 4.0.4. If using `ns.LOCALE` or `humansorted`, the code is 1100% faster than version 4.0.4 - Improved clarity of documentaion with regards to locale-aware sorting ### Deprecated - `ns.TYPESAFE` option as it is now always on (due to a new iterator-based algorithm, the typesafe function is now cheap) [4.0.4] - 2015-11-01 --- ### Changed - Improved coverage of unit tests - Unit tests use new and improved hypothesis library ### Fixed - Compatibility issues with Python 3.5 [4.0.3] - 2015-06-25 --- ### Fixed - Bad install on last release (sorry guys!) (issue #30) [4.0.2] - 2015-06-24 --- ### Changed - Consolidated under-the-hood compatibility functionality ### Fixed - Python 2.6 and Python 3.2 compatibility. Unit testing is now performed for these versions ([@dpetzold](https://github.com/dpetzold), issue #29) [4.0.1] - 2015-06-04 --- ### Added - Support for sorting NaN by internally converting to -Infinity or +Infinity (issue #27) [4.0.0] - 2015-05-17 --- ### Changed - Made default behavior of `natsort` search for unsigned ints, rather than signed floats. This is a backwards-incompatible change but in 99% of use cases it should not require any end-user changes (issue #20) - Improved handling of locale-aware sorting on systems where the underlying locale library is broken (issue #34)) - Greatly improved all unit tests by adding the `hypothesis` library [3.5.6] - 2015-04-06 --- ### Added - `UNGROUPLETTERS` algorithm to get the case-grouping behavior of an ordinal sort when using `LOCALE` (issue #23) - Convenience functions `decoder`, `as_ascii`, and `as_utf8` for dealing with bytes types [3.5.5] - 2015-04-04 --- ### Added - `realsorted` and `index_realsorted` functions for forward-compatibility with >= 4.0.0 ### Changed - Made explanation of when to use `TYPESAFE` more clear in the docs [3.5.4] - 2015-04-02 --- ### Fixed - Bug where a `TypeError` was raised if a string containing a leading number was sorted with alpha-only strings when `LOCALE` is used (issue #22) [3.5.3] - 2015-03-26 --- ### Changed - Documentation updates to better describe locale bug, and illustrate upcoming default behavior change - Internal improvements, including making test suite more granular ### Fixed - Bug where `--reverse-filter` option in shell script was not getting checked for correctness [3.5.2] - 2015-01-13 --- ### Added - A `pathlib.Path` object is converted to a `str` if `ns.PATH` is enabled (issue #16) [3.5.1] - 2014-09-25 --- ### Changed - Refactored modules so that only the public API was in `natsort.py` and `ns_enum.py` - Refactored all import statements to be absolute, not relative ### Fixed - Bug that caused list/tuples to fail when using `ns.LOWECASEFIRST` or `ns.IGNORECASE` (issue #15) [3.5.0] - 2014-09-02 --- ### Added - `alg` argument to the `natsort` functions. This argument accepts an enum that is used to indicate the options the user wishes to use. The `number_type`, `signed`, `exp`, `as_path`, and `py3_safe` options are being deprecated and will become (undocumented) keyword-only options in `natsort` version 4.0.0 - The `humansorted` convenience function as a convenience to locale-aware sorting - The user can now modify how `natsort` handles the case of non-numeric characters (issue #14) - The user can now instruct `natsort` to use locale-aware sorting, which allows `natsort` to perform true "human sorting" (issue #14) - Locale functionality to the shell script [3.4.1] - 2014-08-12 --- ### Changed - `natsort` will now use the [`fastnumbers`](https://github.com/SethMMorton/fastnumbers) module if it is installed. This gives up to an extra 30% boost in speed over the previous performance enhancements - Made documentation point to more `natsort` resources, and also added a new example in the examples section [3.4.0] - 2014-07-19 --- ### Added - `natsort_keygen` function that will generate a wrapped version of `natsort_key` that is easier to call. `natsort_key` is now set to deprecate at natsort version 4.0.0 - `as_path` option to `natsorted` & co. that will try to treat input strings as filepaths. This will help yield correct results for OS-generated inputs like `['/p/q/o.x', '/p/q (1)/o.x', '/p/q (10)/o.x', '/p/q/o (1).x']` (issue #3) - `order_by_index` function to help in using the output of `index_natsorted` and `index_versorted` - `reverse` option to `natsorted` & co. to make it's API more similar to the builtin 'sorted' - More unit tests - Auxillary test code that helps in profiling and stress-testing - Support for coveralls.io ### Changed - Massive performance enhancements for string input (1.8x-2.0x), at the expense of reduction in speed for numeric input (~2.0x) - note that sorting numbers\ still only takes 0.6x the time of sorting strings - Entire codebase is now PyFlakes and PEP8 compliant - Reworked the documentation, moving most of it to PyPI's hosting platform ### Fixed - Bug that caused user's options to the `natsort_key` to not be passed on to recursive calls of `natsort_key` (issue #12) [3.3.0] - 2014-06-28 --- ### Added - `versorted` method for more convenient sorting of versions (issue #11) - Unit test coverage (99%) ### Changed - Updated command-line tool `--number_type` option with 'version' and 'ver' to make it more clear how to sort version numbers - Moved unit-testing mechanism from being docstring-based to actual unit tests in actual functions (issue #10) - Made docstrings for public functions mirror the README API - Connected `natsort` development to Travis-CI to help ensure quality releases [3.2.1] - 2014-06-20 --- ### Fixed - Re-"Fixed" unorderable types issue on Python 3.x - this workaround is for when the problem occurs in the middle of the string (issue #7 again) [3.2.0] - 2014-05-07 --- ### Fixed - "Fixed" unorderable types issue on Python 3.x with a workaround that attempts to replicate the Python 2.x behavior by putting all the numbers (or strings that begin with numbers) first (issue #7) ### Removed - Now explicitly excluding `__pycache__` from releases by adding a prune statement to MANIFEST.in [3.1.2] - 2014-05-05 --- ### Added - `setup.cfg` to support universal wheels (issue #6) - Python 3.0 and Python 3.1 as requiring the argparse module [3.1.1] - 2014-03-01 --- ### Added - Ability to sort lists of lists (issue #5) ### Changed - Cleaned up import statements [3.1.0] - 2014-01-20 --- ### Added - `signed` and `exp` options to allow finer tuning of the sorting - Doctests - New shell script options that correspond to `signed` and `exp` - In the shell script the user can now specify multiple numbers to exclude or multiple ranges ### Changed - Entire codebase now works for both Python 2 and Python 3 without needing to run `2to3` - Updated all doctests - Further simplified the `natsort` base code by removing unneeded functions. - Simplified documentation where possible - Improved the shell script code - Made the shell script documentation less "path"-centric to make it clear it is not just for sorting file paths ### Removed - The shell script filesystem-based options because these can be achieved better though a pipeline by which to filter [3.0.2] - 2013-10-01 --- ### Changed - Made float, int, and digit searching algorithms all share the same base function - Made the `__version__` variable available when importing the module ### Fixed - Outdated comments [3.0.1] - 2013-08-15 --- ### Added - Support for unicode strings (issue #2) ### Fixed - Empty string removal function ### Removed - Extraneous `string2int` function [3.0.0] - 2013-07-13 --- ### Added - A `number_type` argument to the sorting functions to specify how liberal to be when deciding what a number is ### Changed - Reworked the documentation [2.2.0] - 2013-06-25 --- ### Added - `key` attribute to `natsorted` and `index_natsorted` so that it mimics the functionality of the built-in `sorted` (issue #1) - Tests to reflect the new functionality, as well as tests demonstrating how to get similar functionality using `natsort_key` [2.1.0] - 2012-12-05 --- ### Changed - Reorganized package - Now using a platform independent shell script generator (`entry_points` from distribute) - Can now execute `natsort` from command line with `python -m natsort` as well [2.0.2] - 2012-11-30 --- ### Added - The `use_2to3` option to `setup.py` - Include `distribute_setup.py` to the distribution - Dependency to the `argparse` module (for python2.6) [2.0.1] - 2012-11-21 --- ### Added - Tests into the natsort.py file iteself ### Changed - Reorganized directory structure [2.0.0] - 2012-11-16 --- ### Added - Better README documentation - Doctests ### Changed - Sorting algorithm to support floats (including exponentials) and basic version number support [7.0.1]: https://github.com/SethMMorton/natsort/compare/7.0.0...7.0.1 [7.0.0]: https://github.com/SethMMorton/natsort/compare/6.2.0...7.0.0 [6.2.0]: https://github.com/SethMMorton/natsort/compare/6.1.0...6.2.0 [6.1.0]: https://github.com/SethMMorton/natsort/compare/6.0.0...6.1.0 [6.0.0]: https://github.com/SethMMorton/natsort/compare/5.5.0...6.0.0 [5.5.0]: https://github.com/SethMMorton/natsort/compare/5.4.1...5.5.0 [5.4.1]: https://github.com/SethMMorton/natsort/compare/5.4.0...5.4.1 [5.4.0]: https://github.com/SethMMorton/natsort/compare/5.3.3...5.4.0 [5.3.3]: https://github.com/SethMMorton/natsort/compare/5.3.2...5.3.3 [5.3.2]: https://github.com/SethMMorton/natsort/compare/5.3.1...5.3.2 [5.3.1]: https://github.com/SethMMorton/natsort/compare/5.3.0...5.3.1 [5.3.0]: https://github.com/SethMMorton/natsort/compare/5.2.0...5.3.0 [5.2.0]: https://github.com/SethMMorton/natsort/compare/5.1.1...5.2.0 [5.1.1]: https://github.com/SethMMorton/natsort/compare/5.1.0...5.1.1 [5.1.0]: https://github.com/SethMMorton/natsort/compare/5.0.3...5.1.0 [5.0.3]: https://github.com/SethMMorton/natsort/compare/5.0.2...5.0.3 [5.0.2]: https://github.com/SethMMorton/natsort/compare/5.0.1...5.0.2 [5.0.1]: https://github.com/SethMMorton/natsort/compare/5.0.0...5.0.1 [5.0.0]: https://github.com/SethMMorton/natsort/compare/4.0.4...5.0.0 [4.0.4]: https://github.com/SethMMorton/natsort/compare/4.0.3...4.0.4 [4.0.3]: https://github.com/SethMMorton/natsort/compare/4.0.2...4.0.3 [4.0.2]: https://github.com/SethMMorton/natsort/compare/4.0.1...4.0.2 [4.0.1]: https://github.com/SethMMorton/natsort/compare/4.0.0...4.0.1 [4.0.0]: https://github.com/SethMMorton/natsort/compare/3.5.6...4.0.0 [3.5.6]: https://github.com/SethMMorton/natsort/compare/3.5.5...3.5.6 [3.5.5]: https://github.com/SethMMorton/natsort/compare/3.5.4...3.5.5 [3.5.4]: https://github.com/SethMMorton/natsort/compare/3.5.3...3.5.4 [3.5.3]: https://github.com/SethMMorton/natsort/compare/3.5.2...3.5.3 [3.5.2]: https://github.com/SethMMorton/natsort/compare/3.5.1...3.5.2 [3.5.1]: https://github.com/SethMMorton/natsort/compare/3.5.0...3.5.1 [3.5.0]: https://github.com/SethMMorton/natsort/compare/3.4.1...3.5.0 [3.4.1]: https://github.com/SethMMorton/natsort/compare/3.4.0...3.4.1 [3.4.0]: https://github.com/SethMMorton/natsort/compare/3.3.0...3.4.0 [3.3.0]: https://github.com/SethMMorton/natsort/compare/3.2.1...3.3.0 [3.2.1]: https://github.com/SethMMorton/natsort/compare/3.2.0...3.2.1 [3.2.0]: https://github.com/SethMMorton/natsort/compare/3.1.2...3.2.0 [3.1.2]: https://github.com/SethMMorton/natsort/compare/3.1.1...3.1.2 [3.1.1]: https://github.com/SethMMorton/natsort/compare/3.1.0...3.1.1 [3.1.0]: https://github.com/SethMMorton/natsort/compare/3.0.2...3.1.0 [3.0.2]: https://github.com/SethMMorton/natsort/compare/3.0.1...3.0.2 [3.0.1]: https://github.com/SethMMorton/natsort/compare/3.0.0...3.0.1 [3.0.0]: https://github.com/SethMMorton/natsort/compare/2.2.0...3.0.0 [2.2.0]: https://github.com/SethMMorton/natsort/compare/2.1.0...2.2.0 [2.1.0]: https://github.com/SethMMorton/natsort/compare/2.0.2...2.1.0 [2.0.2]: https://github.com/SethMMorton/natsort/compare/2.0.1...2.0.2 [2.0.1]: https://github.com/SethMMorton/natsort/compare/2.0.0...2.0.1 [2.0.0]: https://github.com/SethMMorton/natsort/releases/tag/2.0.0 natsort-7.0.1/CODE_OF_CONDUCT.md000066400000000000000000000063101361376133500160200ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at drtuba78@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html][version] [homepage]: https://www.contributor-covenant.org/ [version]: https://www.contributor-covenant.org/version/1/4/code-of-conduct.html natsort-7.0.1/CONTRIBUTING.md000066400000000000000000000041521361376133500154540ustar00rootroot00000000000000# Contributing If you have an idea for how to improve `natsort`, please contribute! It can be as simple as a bug fix or documentation update, or as complicated as a more robust algorithm. Contributions that change the public API of `natsort` will have to ensure that the library does not become less usable after the contribution and is backwards-compatible (unless there is a good reason not to be). I do not have strong opinions on how one should contribute, so I have copy/pasted some text verbatim from the [Contributor's Guide](http://docs.python-requests.org/en/latest/dev/contributing/) section of [Kenneth Reitz's](http://docs.python-requests.org/en/latest/dev/contributing/) excellent [requests](https://github.com/kennethreitz/requests) library in lieu of coming up with my own. > ### Steps for Submitting Code > When contributing code, you'll want to follow this checklist: > - Fork the repository on GitHub. > - Run the tests to confirm they all pass on your system. If they don't, you'll need to investigate why they fail. If you're unable to diagnose this yourself, raise it as a bug report. > - Write tests that demonstrate your bug or feature. Ensure that they fail. > - Make your change. > - Run the entire test suite again, confirming that all tests pass including the ones you just added. > - Send a GitHub Pull Request to the main repository's master branch. GitHub Pull Requests are the expected method of code collaboration on this project. > ### Documentation Contributions > Documentation improvements are always welcome! The documentation files live in the docs/ directory of the codebase. They're written in [reStructuredText](http://docutils.sourceforge.net/rst.html), and use [Sphinx](http://sphinx-doc.org/index.html) to generate the full suite of documentation. > When contributing documentation, please do your best to follow the style of the documentation files. This means a soft-limit of 79 characters wide in your text files and a semi-formal, yet friendly and approachable, prose style. > When presenting Python code, use single-quoted strings ('hello' instead of "hello"). natsort-7.0.1/LICENSE000066400000000000000000000020471361376133500142310ustar00rootroot00000000000000Copyright (c) 2012-2020 Seth M. Morton 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. natsort-7.0.1/MANIFEST.in000066400000000000000000000002431361376133500147560ustar00rootroot00000000000000include LICENSE include CHANGELOG.md include tox.ini include RELEASING.md graft dev graft docs graft natsort graft tests global-exclude *.py[cod] __pycache__ *.so natsort-7.0.1/README.rst000066400000000000000000000470161361376133500147200ustar00rootroot00000000000000natsort ======= .. image:: https://img.shields.io/pypi/v/natsort.svg :target: https://pypi.org/project/natsort/ .. image:: https://img.shields.io/pypi/pyversions/natsort.svg :target: https://pypi.org/project/natsort/ .. image:: https://img.shields.io/pypi/l/natsort.svg :target: https://github.com/SethMMorton/natsort/blob/master/LICENSE .. image:: https://img.shields.io/travis/SethMMorton/natsort/master.svg?label=travis-ci :target: https://travis-ci.com/SethMMorton/natsort .. image:: https://codecov.io/gh/SethMMorton/natsort/branch/master/graph/badge.svg :target: https://codecov.io/gh/SethMMorton/natsort .. image:: https://api.codacy.com/project/badge/Grade/f2bf04b1fc5d4792bf546f6e497cf4b8 :target: https://www.codacy.com/app/SethMMorton/natsort Simple yet flexible natural sorting in Python. - Source Code: https://github.com/SethMMorton/natsort - Downloads: https://pypi.org/project/natsort/ - Documentation: https://natsort.readthedocs.io/ - `Examples and Recipes `_ - `How Does Natsort Work? `_ - `API `_ - `Quick Description`_ - `Quick Examples`_ - `FAQ`_ - `Requirements`_ - `Optional Dependencies`_ - `Installation`_ - `How to Run Tests`_ - `How to Build Documentation`_ - `Deprecation Schedule`_ - `History`_ **NOTE**: Please see the `Deprecation Schedule`_ section for changes in ``natsort`` version 7.0.0. Quick Description ----------------- When you try to sort a list of strings that contain numbers, the normal python sort algorithm sorts lexicographically, so you might not get the results that you expect: .. code-block:: pycon >>> a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> sorted(a) ['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in', '7 ft 6 in'] Notice that it has the order ('1', '10', '2') - this is because the list is being sorted in lexicographical order, which sorts numbers like you would letters (i.e. 'b', 'ba', 'c'). ``natsort`` provides a function ``natsorted`` that helps sort lists "naturally" ("naturally" is rather ill-defined, but in general it means sorting based on meaning and not computer code point). Using ``natsorted`` is simple: .. code-block:: pycon >>> from natsort import natsorted >>> a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> natsorted(a) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] ``natsorted`` identifies numbers anywhere in a string and sorts them naturally. Below are some other things you can do with ``natsort`` (also see the `examples `_ for a quick start guide, or the `api `_ for complete details). **Note**: ``natsorted`` is designed to be a drop-in replacement for the built-in ``sorted`` function. Like ``sorted``, ``natsorted`` `does not sort in-place`. To sort a list and assign the output to the same variable, you must explicitly assign the output to a variable: .. code-block:: pycon >>> a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> natsorted(a) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] >>> print(a) # 'a' was not sorted; "natsorted" simply returned a sorted list ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> a = natsorted(a) # Now 'a' will be sorted because the sorted list was assigned to 'a' >>> print(a) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] Please see `Generating a Reusable Sorting Key and Sorting In-Place`_ for an alternate way to sort in-place naturally. Quick Examples -------------- - `Sorting Versions`_ - `Sorting by Real Numbers (i.e. Signed Floats)`_ - `Locale-Aware Sorting (or "Human Sorting")`_ - `Further Customizing Natsort`_ - `Sorting Mixed Types`_ - `Handling Bytes on Python 3`_ - `Generating a Reusable Sorting Key and Sorting In-Place`_ - `Other Useful Things`_ Sorting Versions ++++++++++++++++ ``natsort`` does not actually *comprehend* version numbers. It just so happens that the most common versioning schemes are designed to work with standard natural sorting techniques; these schemes include ``MAJOR.MINOR``, ``MAJOR.MINOR.PATCH``, ``YEAR.MONTH.DAY``. If your data conforms to a scheme like this, then it will work out-of-the-box with ``natsorted`` (as of ``natsort`` version >= 4.0.0): .. code-block:: pycon >>> a = ['version-1.9', 'version-2.0', 'version-1.11', 'version-1.10'] >>> natsorted(a) ['version-1.9', 'version-1.10', 'version-1.11', 'version-2.0'] If you need to versions that use a more complicated scheme, please see `these examples `_. Sorting by Real Numbers (i.e. Signed Floats) ++++++++++++++++++++++++++++++++++++++++++++ This is useful in scientific data analysis (and was the default behavior of ``natsorted`` for ``natsort`` version < 4.0.0). Use the ``realsorted`` function: .. code-block:: pycon >>> from natsort import realsorted, ns >>> # Note that when interpreting as signed floats, the below numbers are >>> # +5.10, -3.00, +5.30, +2.00 >>> a = ['position5.10.data', 'position-3.data', 'position5.3.data', 'position2.data'] >>> natsorted(a) ['position2.data', 'position5.3.data', 'position5.10.data', 'position-3.data'] >>> natsorted(a, alg=ns.REAL) ['position-3.data', 'position2.data', 'position5.10.data', 'position5.3.data'] >>> realsorted(a) # shortcut for natsorted with alg=ns.REAL ['position-3.data', 'position2.data', 'position5.10.data', 'position5.3.data'] Locale-Aware Sorting (or "Human Sorting") +++++++++++++++++++++++++++++++++++++++++ This is where the non-numeric characters are also ordered based on their meaning, not on their ordinal value, and a locale-dependent thousands separator and decimal separator is accounted for in the number. This can be achieved with the ``humansorted`` function: .. code-block:: pycon >>> a = ['Apple', 'apple15', 'Banana', 'apple14,689', 'banana'] >>> natsorted(a) ['Apple', 'Banana', 'apple14,689', 'apple15', 'banana'] >>> import locale >>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 'en_US.UTF-8' >>> natsorted(a, alg=ns.LOCALE) ['apple15', 'apple14,689', 'Apple', 'banana', 'Banana'] >>> from natsort import humansorted >>> humansorted(a) # shortcut for natsorted with alg=ns.LOCALE ['apple15', 'apple14,689', 'Apple', 'banana', 'Banana'] You may find you need to explicitly set the locale to get this to work (as shown in the example). Please see `locale issues `_ and the `Optional Dependencies`_ section below before using the ``humansorted`` function. Further Customizing Natsort +++++++++++++++++++++++++++ If you need to combine multiple algorithm modifiers (such as ``ns.REAL``, ``ns.LOCALE``, and ``ns.IGNORECASE``), you can combine the options using the bitwise OR operator (``|``). For example, .. code-block:: pycon >>> a = ['Apple', 'apple15', 'Banana', 'apple14,689', 'banana'] >>> natsorted(a, alg=ns.REAL | ns.LOCALE | ns.IGNORECASE) ['Apple', 'apple15', 'apple14,689', 'Banana', 'banana'] >>> # The ns enum provides long and short forms for each option. >>> ns.LOCALE == ns.L True >>> # You can also customize the convenience functions, too. >>> natsorted(a, alg=ns.REAL | ns.LOCALE | ns.IGNORECASE) == realsorted(a, alg=ns.L | ns.IC) True >>> natsorted(a, alg=ns.REAL | ns.LOCALE | ns.IGNORECASE) == humansorted(a, alg=ns.R | ns.IC) True All of the available customizations can be found in the documentation for `the ns enum `_. You can also add your own custom transformation functions with the ``key`` argument. These can be used with ``alg`` if you wish. .. code-block:: pycon >>> a = ['apple2.50', '2.3apple'] >>> natsorted(a, key=lambda x: x.replace('apple', ''), alg=ns.REAL) ['2.3apple', 'apple2.50'] Sorting Mixed Types +++++++++++++++++++ You can mix and match ``int``, ``float``, and ``str`` (or ``unicode``) types when you sort: .. code-block:: pycon >>> a = ['4.5', 6, 2.0, '5', 'a'] >>> natsorted(a) [2.0, '4.5', '5', 6, 'a'] >>> # On Python 2, sorted(a) would return [2.0, 6, '4.5', '5', 'a'] >>> # On Python 3, sorted(a) would raise an "unorderable types" TypeError Handling Bytes on Python 3 ++++++++++++++++++++++++++ ``natsort`` does not officially support the `bytes` type on Python 3, but convenience functions are provided that help you decode to `str` first: .. code-block:: pycon >>> from natsort import as_utf8 >>> a = [b'a', 14.0, 'b'] >>> # On Python 2, natsorted(a) would would work as expected. >>> # On Python 3, natsorted(a) would raise a TypeError (bytes() < str()) >>> natsorted(a, key=as_utf8) == [14.0, b'a', 'b'] True >>> a = [b'a56', b'a5', b'a6', b'a40'] >>> # On Python 2, natsorted(a) would would work as expected. >>> # On Python 3, natsorted(a) would return the same results as sorted(a) >>> natsorted(a, key=as_utf8) == [b'a5', b'a6', b'a40', b'a56'] True Generating a Reusable Sorting Key and Sorting In-Place ++++++++++++++++++++++++++++++++++++++++++++++++++++++ Under the hood, ``natsorted`` works by generating a custom sorting key using ``natsort_keygen`` and then passes that to the built-in ``sorted``. You can use the ``natsort_keygen`` function yourself to generate a custom sorting key to sort in-place using the ``list.sort`` method. .. code-block:: pycon >>> from natsort import natsort_keygen >>> natsort_key = natsort_keygen() >>> a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> natsorted(a) == sorted(a, key=natsort_key) True >>> a.sort(key=natsort_key) >>> a ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] All of the algorithm customizations mentioned in the `Further Customizing Natsort`_ section can also be applied to ``natsort_keygen`` through the *alg* keyword option. Other Useful Things +++++++++++++++++++ - recursively descend into lists of lists - automatic unicode normalization of input data - `controlling the case-sensitivity `_ - `sorting file paths correctly `_ - `allow custom sorting keys `_ - `accounting for units `_ FAQ --- How do I debug ``natsort.natsorted()``? The best way to debug ``natsorted()`` is to generate a key using ``natsort_keygen()`` with the same options being passed to ``natsorted``. One can take a look at exactly what is being done with their input using this key - it is highly recommended to `look at this issue describing how to debug `_ for *how* to debug, and also to review the `How Does Natsort Work? `_ page for *why* ``natsort`` is doing that to your data. If you are trying to sort custom classes and running into trouble, please take a look at https://github.com/SethMMorton/natsort/issues/60. In short, custom classes are not likely to be sorted correctly if one relies on the behavior of ``__lt__`` and the other rich comparison operators in their custom class - it is better to use a ``key`` function with ``natsort``, or use the ``natsort`` key as part of your rich comparison operator definition. ``natsort`` gave me results I didn't expect, and it's a terrible library! Did you try to debug using the above advice? If so, and you still cannot figure out the error, then please `file an issue `_. How *does* ``natsort`` work? If you don't want to read `How Does Natsort Work? `_, here is a quick primer. ``natsort`` provides a `key function `_ that can be passed to `list.sort() `_ or `sorted() `_ in order to modify the default sorting behavior. This key is generated on-demand with the key generator ``natsort.natsort_keygen()``. ``natsort.natsorted()`` is essentially a wrapper for the following code: .. code-block:: pycon >>> from natsort import natsort_keygen >>> natsort_key = natsort_keygen() >>> sorted(['1', '10', '2'], key=natsort_key) ['1', '2', '10'] Users can further customize ``natsort`` sorting behavior with the ``key`` and/or ``alg`` options (see details in the `Further Customizing Natsort`_ section). The key generated by ``natsort_keygen`` *always* returns a ``tuple``. It does so in the following way (*some details omitted for clarity*): 1. Assume the input is a string, and attempt to split it into numbers and non-numbers using regular expressions. Numbers are then converted into either ``int`` or ``float``. 2. If the above fails because the input is not a string, assume the input is some other sequence (e.g. ``list`` or ``tuple``), and recursively apply the key to each element of the sequence. 3. If the above fails because the input is not iterable, assume the input is an ``int`` or ``float``, and just return the input in a ``tuple``. Because a ``tuple`` is always returned, a ``TypeError`` should not be common unless one tries to do something odd like sort an ``int`` against a ``list``. Shell script ------------ ``natsort`` comes with a shell script called ``natsort``, or can also be called from the command line with ``python -m natsort``. Requirements ------------ ``natsort`` requires Python 3.5 or greater. Python 3.4 is unofficially supported, meaning that support has not been removed, but it is no longer tested. Optional Dependencies --------------------- fastnumbers +++++++++++ The most efficient sorting can occur if you install the `fastnumbers `_ package (version >=2.0.0); it helps with the string to number conversions. ``natsort`` will still run (efficiently) without the package, but if you need to squeeze out that extra juice it is recommended you include this as a dependency. ``natsort`` will not require (or check) that `fastnumbers `_ is installed at installation. PyICU +++++ It is recommended that you install `PyICU `_ if you wish to sort in a locale-dependent manner, see https://natsort.readthedocs.io/en/master/locale_issues.html for an explanation why. Installation ------------ Use ``pip``! .. code-block:: console $ pip install natsort If you want to install the `Optional Dependencies`_, you can use the `"extras" notation `_ at installation time to install those dependencies as well - use ``fast`` for `fastnumbers `_ and ``icu`` for `PyICU `_. .. code-block:: console # Install both optional dependencies. $ pip install natsort[fast,icu] # Install just fastnumbers $ pip install natsort[fast] How to Run Tests ---------------- Please note that ``natsort`` is NOT set-up to support ``python setup.py test``. The recommended way to run tests is with `tox `_. After installing ``tox``, running tests is as simple as executing the following in the ``natsort`` directory: .. code-block:: console $ tox ``tox`` will create virtual a virtual environment for your tests and install all the needed testing requirements for you. You can specify a particular python version with the ``-e`` flag, e.g. ``tox -e py36``. Static analysis is done with ``tox -e flake8``. You can see all available testing environments with ``tox --listenvs``. If you do not wish to use ``tox``, you can install the testing dependencies with the ``dev/requirements.txt`` file and then run the tests manually using `pytest `_. .. code-block:: console $ pip install -r dev/requirements.txt $ python -m pytest Note that above I invoked ``python -m pytest`` instead of just ``pytest`` - this is because `the former puts the CWD on sys.path `_. How to Build Documentation -------------------------- If you want to build the documentation for ``natsort``, it is recommended to use ``tox``: .. code-block:: console $ tox -e docs This will place the documentation in ``build/sphinx/html``. If you do not which to use ``tox``, you can do the following: .. code-block:: console $ pip install sphinx sphinx_rtd_theme $ python setup.py build_sphinx Deprecation Schedule -------------------- Dropped Python 2.7 Support ++++++++++++++++++++++++++ ``natsort`` version 7.0.0 dropped support for Python 2.7. The version 6.X branch will remain as a "long term support" branch where bug fixes are applied so that users who cannot update from Python 2.7 will not be forced to use a buggy ``natsort`` version (bug fixes will need to be requested; by default only the 7.X branch will be updated). New features would not be added to version 6.X, only bug fixes. Dropped Deprecated APIs +++++++++++++++++++++++ In ``natsort`` version 6.0.0, the following APIs and functions were removed - ``number_type`` keyword argument (deprecated since 3.4.0) - ``signed`` keyword argument (deprecated since 3.4.0) - ``exp`` keyword argument (deprecated since 3.4.0) - ``as_path`` keyword argument (deprecated since 3.4.0) - ``py3_safe`` keyword argument (deprecated since 3.4.0) - ``ns.TYPESAFE`` (deprecated since version 5.0.0) - ``ns.DIGIT`` (deprecated since version 5.0.0) - ``ns.VERSION`` (deprecated since version 5.0.0) - ``versorted()`` (discouraged since version 4.0.0, officially deprecated since version 5.5.0) - ``index_versorted()`` (discouraged since version 4.0.0, officially deprecated since version 5.5.0) In general, if you want to determine if you are using deprecated APIs you can run your code with the following flag .. code-block:: console $ python -Wdefault::DeprecationWarning my-code.py By default ``DeprecationWarnings`` are not shown, but this will cause them to be shown. Alternatively, you can just set the environment variable ``PYTHONWARNINGS`` to "default::DeprecationWarning" and then run your code. Dropped Pipenv for Development ++++++++++++++++++++++++++++++ ``natsort`` version 6.0.0 no longer uses `Pipenv `_ to install development dependencies. Dropped Python 2.6 and 3.3 Support ++++++++++++++++++++++++++++++++++ ``natsort`` version 6.0.0 dropped support for Python 2.6 and Python 3.3. Author ------ Seth M. Morton History ------- Please visit the changelog `on GitHub `_ or `in the documentation `_. natsort-7.0.1/RELEASING.md000066400000000000000000000024601361376133500150560ustar00rootroot00000000000000# Release Checklist - [ ] Get master to the appropriate code release state. [Travis CI](https://travis-ci.com/SethMMorton/natsort) must be passing: [![Build Status](https://travis-ci.com/SethMMorton/natsort.svg?branch=master)](https://travis-ci.com/SethMMorton/natsort) - [ ] Ensure that the `CHANGELOG.md` includes the changes made since last release. Please follow the style outlined in https://keepachangelog.com/. All new entries should be added into the "Unreleased" section. - [ ] Bump the version number. Specify either "major", "minor", or "patch": ```bash tox -e bump patch ``` This will take care of updating the `CHANGELOG.md` with the correct release information. - [ ] Push the bumped commit: ```bash git push ``` - [ ] Check that the [Travis CI build](https://travis-ci.com/SethMMorton/natsort) has deployed correctly to [the test PyPI](https://test.pypi.org/project/natsort/#history). - [ ] Push the tag: ```bash git push --tags ``` - [ ] Check that the tagged [Travis CI build](https://travis-ci.com/SethMMorton/natsort) has deployed correctly to [PyPI](https://pypi.org/project/natsort/#history). - [ ] Check installation: ```bash python -m pip uninstall -y natsort && python -m pip install -U natsort ``` natsort-7.0.1/dev/000077500000000000000000000000001361376133500137775ustar00rootroot00000000000000natsort-7.0.1/dev/README.md000066400000000000000000000014061361376133500152570ustar00rootroot00000000000000# Development Collateral This file contains some files useful for development. - `bump.py` - Execute `bumpversion` then post-processes the CHANGELOG to handle corner-cases that `bumpversion` cannot. Requires [`bump2version`](https://github.com/c4urself/bump2version), which is the maintained fork of [`bumpversion`](https://github.com/peritus/bumpversion). It is not really intended to be called directly, but instead through `tox -e bump`. - `clean.py` - This file cleans most files that are created during development. Run in the project home directory. It is not really intended to be called directly, but instead through `tox -e clean`. - `requirements.in` - Our direct requirements to run tests. - `requirements.txt` - All pinned requirements to run tests. natsort-7.0.1/dev/bump.py000077500000000000000000000043561361376133500153270ustar00rootroot00000000000000#! /usr/bin/env python """ Cross-platform bump of version with special CHANGELOG modification. INTENDED TO BE CALLED FROM PROJECT ROOT, NOT FROM dev/! """ import subprocess import sys try: bump_type = sys.argv[1] except IndexError: sys.exit("Must pass 'bump_type' argument!") else: if bump_type not in ("major", "minor", "patch"): sys.exit('bump_type must be one of "major", "minor", or "patch"!') def git(cmd, *args): """Wrapper for calling git""" try: subprocess.run(["git", cmd, *args], check=True, text=True) except subprocess.CalledProcessError as e: print("Call to git failed!", file=sys.stderr) print("STDOUT:", e.stdout, file=sys.stderr) print("STDERR:", e.stderr, file=sys.stderr) sys.exit(e.returncode) def bumpversion(severity, *args, catch=False): """Wrapper for calling bumpversion""" cmd = ["bump2version", *args, severity] try: if catch: return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout else: subprocess.run(cmd, check=True, text=True) except subprocess.CalledProcessError as e: print("Call to bump2version failed!", file=sys.stderr) print("STDOUT:", e.stdout, file=sys.stderr) print("STDERR:", e.stderr, file=sys.stderr) sys.exit(e.returncode) # Do a dry run of the bump to find what the current version is and what it will become. data = bumpversion(bump_type, "--dry-run", "--list", catch=True) data = dict(x.split("=") for x in data.splitlines()) # Execute the bumpversion. bumpversion(bump_type) # Post-process the changelog with things that bumpversion is not good at updating. with open("CHANGELOG.md") as fl: changelog = fl.read().replace( "", "\n[{new}]: {url}/{current}...{new}".format( new=data["new_version"], current=data["current_version"], url="https://github.com/SethMMorton/natsort/compare" ) ) with open("CHANGELOG.md", "w") as fl: fl.write(changelog) # Finally, add the CHANGELOG.md changes to the previous commit. git("add", "CHANGELOG.md") git("commit", "--amend", "--no-edit") git("tag", "--force", data["new_version"], "HEAD") natsort-7.0.1/dev/clean.py000077500000000000000000000014141361376133500154360ustar00rootroot00000000000000#! /usr/bin/env python """ Cross-platform clean of working directory. INTENDED TO BE CALLED FROM PROJECT ROOT, NOT FROM dev/! """ import pathlib import shutil # Directories to obliterate dirs = [ pathlib.Path("build"), pathlib.Path("dist"), pathlib.Path(".pytest_cache"), pathlib.Path(".hypothesis"), pathlib.Path(".tox"), ] dirs += pathlib.Path.cwd().glob("*.egg-info") for d in dirs: if d.is_dir(): shutil.rmtree(d, ignore_errors=True) elif d.is_file(): d.unlink() # just in case there is a file. # Clean up any stray __pycache__. for d in pathlib.Path.cwd().rglob("__pycache__"): shutil.rmtree(d, ignore_errors=True) # Shouldn't be any .pyc left, but just in case for f in pathlib.Path.cwd().rglob("*.pyc"): f.unlink() natsort-7.0.1/dev/requirements.in000066400000000000000000000001741361376133500170540ustar00rootroot00000000000000coverage pytest pytest-cov pytest-mock hypothesis # pytest-faulthandler; platform_python_implementation == 'CPython' semver natsort-7.0.1/dev/requirements.txt000066400000000000000000000012461361376133500172660ustar00rootroot00000000000000# # This file is autogenerated by pip-compile # To update, run: # # pip-compile requirements.in # attrs==19.3.0 # via hypothesis, pytest coverage==5.0.2 hypothesis==5.1.1 importlib-metadata==1.3.0 # via pluggy, pytest more-itertools==8.0.2 # via pytest, zipp packaging==20.0 # via pytest pluggy==0.13.1 # via pytest py==1.8.1 # via pytest pyparsing==2.4.6 # via packaging pytest-cov==2.8.1 pytest-mock==2.0.0 pytest==5.3.2 semver==2.9.0 six==1.13.0 # via packaging sortedcontainers==2.1.0 # via hypothesis wcwidth==0.1.8 # via pytest zipp==0.6.0 # via importlib-metadata natsort-7.0.1/docs/000077500000000000000000000000001361376133500141515ustar00rootroot00000000000000natsort-7.0.1/docs/api.rst000066400000000000000000000045731361376133500154650ustar00rootroot00000000000000.. default-domain:: py .. currentmodule:: natsort .. _api: natsort API =========== .. contents:: :local: Standard API ------------ :func:`~natsort.natsorted` ++++++++++++++++++++++++++ .. autofunction:: natsorted The :class:`~natsort.ns` enum +++++++++++++++++++++++++++++ .. autodata:: ns :annotation: :func:`~natsort.natsort_key` ++++++++++++++++++++++++++++ .. autofunction:: natsort_key :func:`~natsort.natsort_keygen` +++++++++++++++++++++++++++++++ .. autofunction:: natsort_keygen Convenience Functions --------------------- :func:`~natsort.realsorted` +++++++++++++++++++++++++++ .. autofunction:: realsorted :func:`~natsort.humansorted` ++++++++++++++++++++++++++++ .. autofunction:: humansorted :func:`~natsort.index_natsorted` ++++++++++++++++++++++++++++++++ .. autofunction:: index_natsorted :func:`~natsort.index_realsorted` +++++++++++++++++++++++++++++++++ .. autofunction:: index_realsorted :func:`~natsort.index_humansorted` ++++++++++++++++++++++++++++++++++ .. autofunction:: index_humansorted :func:`~natsort.order_by_index` +++++++++++++++++++++++++++++++ .. autofunction:: order_by_index .. _bytes_help: Help With Bytes On Python 3 +++++++++++++++++++++++++++ The official stance of :mod:`natsort` is to not support `bytes` for sorting; there is just too much that can go wrong when trying to automate conversion between `bytes` and `str`. But rather than completely give up on `bytes`, :mod:`natsort` provides three functions that make it easy to quickly decode `bytes` to `str` so that sorting is possible. .. autofunction:: decoder .. autofunction:: as_ascii .. autofunction:: as_utf8 .. _function_help: Help With Creating Function Keys ++++++++++++++++++++++++++++++++ If you need to create a complicated *key* argument to (for example) :func:`natsorted` that is actually multiple functions called one after the other, the following function can help you easily perform this action. It is used internally to :mod:`natsort`, and has been exposed publicly for the convenience of the user. .. autofunction:: chain_functions If you need to be able to search your input for numbers using the same definition as :mod:`natsort`, you can do so using the following function. Given your chosen algorithm (selected using the :class:`~natsort.ns` enum), the corresponding regular expression to locate numbers will be returned. .. autofunction:: numeric_regex_chooser natsort-7.0.1/docs/changelog.rst000066400000000000000000000001041361376133500166250ustar00rootroot00000000000000.. _changelog: Changelog ========= .. mdinclude:: ../CHANGELOG.md natsort-7.0.1/docs/conf.py000066400000000000000000000211321361376133500154470ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # natsort documentation build configuration file, created by # sphinx-quickstart on Thu Jul 17 21:01:29 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os # 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. # sys.path.insert(0, os.path.abspath('.')) # -- 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.autosummary', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.napoleon', 'm2r', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = ['.rst', '.md'] # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'natsort' # noinspection PyShadowingBuiltins copyright = '2014, Seth M. Morton' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = '7.0.1' # The short X.Y version. version = '.'.join(release.split('.')[0:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # exclude_patterns = ['solar/*'] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' highlight_language = 'python' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. on_rtd = os.environ.get('READTHEDOCS') == 'True' if on_rtd: html_theme = 'default' else: import sphinx_rtd_theme # noqa: F401 html_theme = 'sphinx_rtd_theme' # html_theme = 'solar' # 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 = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['.'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'natsortdoc' # -- 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': '', } # 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 = [ ('index', 'natsort.tex', 'natsort Documentation', 'Seth M. Morton', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'natsort', 'natsort Documentation', ['Seth M. Morton'], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- 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 = [ ('index', 'natsort', 'natsort Documentation', 'Seth M. Morton', 'natsort', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'python': ('https://docs.python.org/3', None)} natsort-7.0.1/docs/examples.rst000066400000000000000000000344661361376133500165360ustar00rootroot00000000000000.. default-domain:: py .. currentmodule:: natsort .. _examples: Examples and Recipes ==================== If you want more detailed examples than given on this page, please see https://github.com/SethMMorton/natsort/tree/master/tests. .. contents:: :local: Basic Usage ----------- In the most basic use case, simply import :func:`~natsorted` and use it as you would :func:`sorted`: .. code-block:: pycon >>> a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> sorted(a) ['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in', '7 ft 6 in'] >>> from natsort import natsorted, ns >>> natsorted(a) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] Sort Version Numbers -------------------- As of :mod:`natsort` version >= 4.0.0, :func:`~natsorted` will work for well-behaved version numbers, like ``MAJOR.MINOR.PATCH``. .. _rc_sorting: Sorting More Expressive Versioning Schemes ++++++++++++++++++++++++++++++++++++++++++ By default, if you wish to sort versions that are not as simple as ``MAJOR.MINOR.PATCH`` (or similar), you may not get the results you expect: .. code-block:: pycon >>> a = ['1.2', '1.2rc1', '1.2beta2', '1.2beta1', '1.2alpha', '1.2.1', '1.1', '1.3'] >>> natsorted(a) ['1.1', '1.2', '1.2.1', '1.2alpha', '1.2beta1', '1.2beta2', '1.2rc1', '1.3'] To make the '1.2' pre-releases come before '1.2.1', you need to use the following recipe: .. code-block:: pycon >>> natsorted(a, key=lambda x: x.replace('.', '~')) ['1.1', '1.2', '1.2alpha', '1.2beta1', '1.2beta2', '1.2rc1', '1.2.1', '1.3'] If you also want '1.2' after all the alpha, beta, and rc candidates, you can modify the above recipe: .. code-block:: pycon >>> natsorted(a, key=lambda x: x.replace('.', '~')+'z') ['1.1', '1.2alpha', '1.2beta1', '1.2beta2', '1.2rc1', '1.2', '1.2.1', '1.3'] Please see `this issue `_ to see why this works. Sorting Rigorously Defined Versioning Schemes (e.g. SemVer or PEP 440) """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" If you know you are using a versioning scheme that follows a well-defined format for which there is third-party module support, you should use those modules to assist in sorting. Some examples might be `PEP 440 `_ or `SemVer `_. If we are being honest, using these methods to parse a version means you don't need to use :mod:`natsort` - you should probably just use :func:`sorted` directly. Here's an example with SemVer: .. code-block:: pycon >>> from semver import parse_version_info >>> a = ['3.4.5-pre.1', '3.4.5', '3.4.5-pre.2+build.4'] >>> sorted(a, key=parse_version_info) ['3.4.5-pre.1', '3.4.5-pre.2+build.4', '3.4.5'] .. _path_sort: Sort OS-Generated Paths ----------------------- In some cases when sorting file paths with OS-Generated names, the default :mod:`~natsorted` algorithm may not be sufficient. In cases like these, you may need to use the ``ns.PATH`` option: .. code-block:: pycon >>> a = ['./folder/file (1).txt', ... './folder/file.txt', ... './folder (1)/file.txt', ... './folder (10)/file.txt'] >>> natsorted(a) ['./folder (1)/file.txt', './folder (10)/file.txt', './folder/file (1).txt', './folder/file.txt'] >>> natsorted(a, alg=ns.PATH) ['./folder/file.txt', './folder/file (1).txt', './folder (1)/file.txt', './folder (10)/file.txt'] Locale-Aware Sorting (Human Sorting) ------------------------------------ .. note:: Please read :ref:`locale_issues` before using ``ns.LOCALE``, :func:`humansorted`, or :func:`index_humansorted`. You can instruct :mod:`natsort` to use locale-aware sorting with the ``ns.LOCALE`` option. In addition to making this understand non-ASCII characters, it will also properly interpret non-'.' decimal separators and also properly order case. It may be more convenient to just use the :func:`humansorted` function: .. code-block:: pycon >>> from natsort import humansorted >>> import locale >>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 'en_US.UTF-8' >>> a = ['Apple', 'corn', 'Corn', 'Banana', 'apple', 'banana'] >>> natsorted(a, alg=ns.LOCALE) ['apple', 'Apple', 'banana', 'Banana', 'corn', 'Corn'] >>> humansorted(a) ['apple', 'Apple', 'banana', 'Banana', 'corn', 'Corn'] You may find that if you do not explicitly set the locale your results may not be as you expect... I have found that it depends on the system you are on. If you use `PyICU `_ (see below) then you should not need to do this. .. _case_sort: Controlling Case When Sorting ----------------------------- For non-numbers, by default :mod:`natsort` used ordinal sorting (i.e. it sorts by the character's value in the ASCII table). For example: .. code-block:: pycon >>> a = ['Apple', 'corn', 'Corn', 'Banana', 'apple', 'banana'] >>> natsorted(a) ['Apple', 'Banana', 'Corn', 'apple', 'banana', 'corn'] There are times when you wish to ignore the case when sorting, you can easily do this with the ``ns.IGNORECASE`` option: .. code-block:: pycon >>> natsorted(a, alg=ns.IGNORECASE) ['Apple', 'apple', 'Banana', 'banana', 'corn', 'Corn'] Note thats since Python's sorting is stable, the order of equivalent elements after lowering the case is the same order they appear in the original list. Upper-case letters appear first in the ASCII table, but many natural sorting methods place lower-case first. To do this, use ``ns.LOWERCASEFIRST``: .. code-block:: pycon >>> natsorted(a, alg=ns.LOWERCASEFIRST) ['apple', 'banana', 'corn', 'Apple', 'Banana', 'Corn'] It may be undesirable to have the upper-case letters grouped together and the lower-case letters grouped together; most would expect all "a"s to bet together regardless of case, and all "b"s, and so on. To achieve this, use ``ns.GROUPLETTERS``: .. code-block:: pycon >>> natsorted(a, alg=ns.GROUPLETTERS) ['Apple', 'apple', 'Banana', 'banana', 'Corn', 'corn'] You might combine this with ``ns.LOWERCASEFIRST`` to get what most would expect to be "natural" sorting: .. code-block:: pycon >>> natsorted(a, alg=ns.G | ns.LF) ['apple', 'Apple', 'banana', 'Banana', 'corn', 'Corn'] Customizing Float Definition ---------------------------- You can make :func:`~natsorted` search for any float that would be a valid Python float literal, such as 5, 0.4, -4.78, +4.2E-34, etc. using the ``ns.FLOAT`` key. You can disable the exponential component of the number with ``ns.NOEXP``. .. code-block:: pycon >>> a = ['a50', 'a51.', 'a+50.4', 'a5.034e1', 'a+50.300'] >>> natsorted(a, alg=ns.FLOAT) ['a50', 'a5.034e1', 'a51.', 'a+50.300', 'a+50.4'] >>> natsorted(a, alg=ns.FLOAT | ns.SIGNED) ['a50', 'a+50.300', 'a5.034e1', 'a+50.4', 'a51.'] >>> natsorted(a, alg=ns.FLOAT | ns.SIGNED | ns.NOEXP) ['a5.034e1', 'a50', 'a+50.300', 'a+50.4', 'a51.'] For convenience, the ``ns.REAL`` option is provided which is a shortcut for ``ns.FLOAT | ns.SIGNED`` and can be used to sort on real numbers. This can be easily accessed with the :func:`~realsorted` convenience function. Please note that the behavior of the :func:`~realsorted` function was the default behavior of :func:`~natsorted` for :mod:`natsort` version < 4.0.0: .. code-block:: pycon >>> natsorted(a, alg=ns.REAL) ['a50', 'a+50.300', 'a5.034e1', 'a+50.4', 'a51.'] >>> from natsort import realsorted >>> realsorted(a) ['a50', 'a+50.300', 'a5.034e1', 'a+50.4', 'a51.'] .. _custom_sort: Using a Custom Sorting Key -------------------------- Like the built-in ``sorted`` function, ``natsorted`` can accept a custom sort key so that: .. code-block:: pycon >>> from operator import attrgetter, itemgetter >>> a = [['a', 'num4'], ['b', 'num8'], ['c', 'num2']] >>> natsorted(a, key=itemgetter(1)) [['c', 'num2'], ['a', 'num4'], ['b', 'num8']] >>> class Foo: ... def __init__(self, bar): ... self.bar = bar ... def __repr__(self): ... return "Foo('{}')".format(self.bar) >>> b = [Foo('num3'), Foo('num5'), Foo('num2')] >>> natsorted(b, key=attrgetter('bar')) [Foo('num2'), Foo('num3'), Foo('num5')] .. _unit_sorting: Accounting for Units When Sorting +++++++++++++++++++++++++++++++++ :mod:`natsort` does not come with any pre-built mechanism to sort units, but you can write your own `key` to do this. Below, I will demonstrate sorting imperial lengths (e.g. feet an inches), but of course you can extend this to any set of units you need. This example is based on code `from this issue `_, and uses the function :func:`natsort.numeric_regex_chooser` to build a regular expression that will parse numbers in the same manner as :mod:`natsort` itself. .. code-block:: pycon >>> import re >>> import natsort >>> >>> # Define how each unit will be transformed >>> conversion_mapping = { ... "in": 1, ... "inch": 1, ... "inches": 1, ... "ft": 12, ... "feet": 12, ... "foot": 12, ... } >>> >>> # This regular expression searches for numbers and units >>> all_units = "|".join(conversion_mapping.keys()) >>> float_re = natsort.numeric_regex_chooser(natsort.FLOAT | natsort.SIGNED) >>> unit_finder = re.compile(r"({})\s*({})".format(float_re, all_units), re.IGNORECASE) >>> >>> def unit_replacer(matchobj): ... """ ... Given a regex match object, return a replacement string where units are modified ... """ ... number = matchobj.group(1) ... unit = matchobj.group(2) ... new_number = float(number) * conversion_mapping[unit] ... return "{} in".format(new_number) ... >>> # Demo time! >>> data = ['1 ft', '5 in', '10 ft', '2 in'] >>> [unit_finder.sub(unit_replacer, x) for x in data] ['12.0 in', '5.0 in', '120.0 in', '2.0 in'] >>> >>> natsort.natsorted(data, key=lambda x: unit_finder.sub(unit_replacer, x)) ['2 in', '5 in', '1 ft', '10 ft'] Generating a Natsort Key ------------------------ If you need to sort a list in-place, you cannot use :func:`~natsorted`; you need to pass a key to the :meth:`list.sort` method. The function :func:`~natsort_keygen` is a convenient way to generate these keys for you: .. code-block:: pycon >>> from natsort import natsort_keygen >>> a = ['a50', 'a51.', 'a50.4', 'a5.034e1', 'a50.300'] >>> natsort_key = natsort_keygen(alg=ns.FLOAT) >>> a.sort(key=natsort_key) >>> a ['a50', 'a50.300', 'a5.034e1', 'a50.4', 'a51.'] :func:`~natsort_keygen` has the same API as :func:`~natsorted` (minus the `reverse` option). Sorting Multiple Lists According to a Single List ------------------------------------------------- Sometimes you have multiple lists, and you want to sort one of those lists and reorder the other lists according to how the first was sorted. To achieve this you could use the :func:`~index_natsorted` in combination with the convenience function :func:`~order_by_index`: .. code-block:: pycon >>> from natsort import index_natsorted, order_by_index >>> a = ['a2', 'a9', 'a1', 'a4', 'a10'] >>> b = [4, 5, 6, 7, 8] >>> c = ['hi', 'lo', 'ah', 'do', 'up'] >>> index = index_natsorted(a) >>> order_by_index(a, index) ['a1', 'a2', 'a4', 'a9', 'a10'] >>> order_by_index(b, index) [6, 4, 7, 5, 8] >>> order_by_index(c, index) ['ah', 'hi', 'do', 'lo', 'up'] Returning Results in Reverse Order ---------------------------------- Just like the :func:`sorted` built-in function, you can supply the ``reverse`` option to return the results in reverse order: .. code-block:: pycon >>> a = ['a2', 'a9', 'a1', 'a4', 'a10'] >>> natsorted(a, reverse=True) ['a10', 'a9', 'a4', 'a2', 'a1'] Sorting Bytes on Python 3 ------------------------- Python 3 is rather strict about comparing strings and bytes, and this can make it difficult to deal with collections of both. Because of the challenge of guessing which encoding should be used to decode a bytes array to a string, :mod:`natsort` does *not* try to guess and automatically convert for you; in fact, the official stance of :mod:`natsort` is to not support sorting bytes. Instead, some decoding convenience functions have been provided to you (see :ref:`bytes_help`) that allow you to provide a codec for decoding bytes through the ``key`` argument that will allow :mod:`natsort` to convert byte arrays to strings for sorting; these functions know not to raise an error if the input is not a byte array, so you can use the key on any arbitrary collection of data. .. code-block:: pycon >>> from natsort import as_ascii >>> a = [b'a', 14.0, 'b'] >>> # On Python 2, natsorted(a) would would work as expected. >>> # On Python 3, natsorted(a) would raise a TypeError (bytes() < str()) >>> natsorted(a, key=as_ascii) == [14.0, b'a', 'b'] True Additionally, regular expressions cannot be run on byte arrays, making it so that :mod:`natsort` cannot parse them for numbers. As a result, if you run :mod:`natsort` on a list of bytes, you will get results that are like Python's default sorting behavior. Of course, you can use the decoding functions to solve this: .. code-block:: pycon >>> from natsort import as_utf8 >>> a = [b'a56', b'a5', b'a6', b'a40'] >>> natsorted(a) # doctest: +SKIP [b'a40', b'a5', b'a56', b'a6'] >>> natsorted(a, key=as_utf8) == [b'a5', b'a6', b'a40', b'a56'] True If you need a codec different from ASCII or UTF-8, you can use :func:`decoder` to generate a custom key: .. code-block:: pycon >>> from natsort import decoder >>> a = [b'a56', b'a5', b'a6', b'a40'] >>> natsorted(a, key=decoder('latin1')) == [b'a5', b'a6', b'a40', b'a56'] True Sorting a Pandas DataFrame -------------------------- As of Pandas version 0.16.0, the sorting methods do not accept a ``key`` argument, so you cannot simply pass :func:`natsort_keygen` to a Pandas DataFrame and sort. This request has been made to the Pandas devs; see `issue 3942 `_ if you are interested. If you need to sort a Pandas DataFrame, please check out `this answer on StackOverflow `_ for ways to do this without the ``key`` argument to ``sort``. natsort-7.0.1/docs/howitworks.rst000066400000000000000000001407021361376133500171270ustar00rootroot00000000000000.. default-domain:: py .. currentmodule:: natsort .. _howitworks: How Does Natsort Work? ====================== .. contents:: :local: :mod:`natsort` works by breaking strings into smaller sub-components (numbers or everything else), and returning these components in a tuple. Sorting tuples in Python is well-defined, and this fact is used to sort the input strings properly. But how does one break a string into sub-components? And what does one do to those components once they are split? Below I will explain the algorithm that was chosen for the :mod:`natsort` module, and some of the thinking that went into those design decisions. I will also mention some of the stumbling blocks I ran into because `getting sorting right is surprisingly hard`_. If you are impatient, you can skip to :ref:`tldr1` for the algorithm in the simplest case, and :ref:`tldr2` to see what extra code is needed to handle special cases. First, How Does Natural Sorting Work At a High Level? ----------------------------------------------------- If I want to compare '2 ft 7 in' to '2 ft 11 in', I might do the following .. code-block:: pycon >>> '2 ft 7 in' < '2 ft 11 in' False We as humans know that the above should be true, but why does Python think it is false? Here is how it is performing the comparison: .. code-block:: '2' <=> '2' ==> equal, so keep going ' ' <=> ' ' ==> equal, so keep going 'f' <=> 'f' ==> equal, so keep going 't' <=> 't' ==> equal, so keep going ' ' <=> ' ' ==> equal, so keep going '7' <=> '1' ==> different, use result of '7' < '1' '7' evaluates as greater than '1' so the statement is false. When sorting, if a value is less than another it is placed first, so in our above example '2 ft 11 in' would end up before '2 ft 7 in', which is not correct. What to do? The best way to handle this is to break the string into sub-components of numbers and non-numbers, and then convert the numeric parts into :func:`float` or :func:`int` types. This will force Python to actually understand the context of what it is sorting and then "do the right thing." Luckily, it handles sorting lists of strings right out-of-the-box, so the only hard part is actually making this string-to-list transformation and then Python will handle the rest. .. code-block:: '2 ft 7 in' ==> (2, ' ft ', 7, ' in') '2 ft 11 in' ==> (2, ' ft ', 11, ' in') When Python compares the two, it roughly follows the below logic: .. code-block:: 2 <=> 2 ==> equal, so keep going ' ft ' <=> ' ft ' ==> a string is a special type of sequence - evaluate each character individually || --> ' ' <=> ' ' ==> equal, so keep going 'f' <=> 'f' ==> equal, so keep going 't' <=> 't' ==> equal, so keep going ' ' <=> ' ' ==> equal, so keep going <== Back to parent sequence 7 <=> 11 ==> different, use the result of 7 < 11 Clearly, seven is less than eleven, so our comparison is as we expect, and we would get the sorting order we wanted. At its heart, :mod:`natsort` is simply a tool to break strings into tuples, turning numbers in strings (i.e. ``'79'``) into *ints* and *floats* as it does this. Natsort's Approach ------------------ .. contents:: :local: Decomposing Strings Into Sub-Components +++++++++++++++++++++++++++++++++++++++ The first major hurtle to overcome is to decompose the string into sub-components. Remarkably, this turns out to be the easy part, owing mostly to Python's easy access to regular expressions. Breaking an arbitrary string based on a pattern is pretty straightforward. .. code-block:: pycon >>> import re >>> re.split(r'(\d+)', '2 ft 11 in') ['', '2', ' ft ', '11', ' in'] Clear (assuming you can read regular expressions) and concise. The reason I began developing :mod:`natsort` in the first place was because I needed to handle the natural sorting of strings containing *real numbers*, not just unsigned integers as the above example contains. By real numbers, I mean those like ``-45.4920E-23``. :mod:`natsort` can handle just about any number definition; to that end, here are all the regular expressions used in :mod:`natsort`: .. code-block:: pycon >>> unsigned_int = r'([0-9]+)' >>> signed_int = r'([-+]?[0-9]+)' >>> unsigned_float = r'((?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?)' >>> signed_float = r'([-+]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?)' >>> unsigned_float_no_exponent = r'((?:[0-9]+\.?[0-9]*|\.[0-9]+))' >>> signed_float_no_exponent = r'([-+]?(?:[0-9]+\.?[0-9]*|\.[0-9]+))' Note that ``"inf"`` and ``"nan"`` are deliberately omitted from the float definition because you wouldn't want (for example) ``"banana"`` to be converted into ``['ba', 'nan', 'a']``, Let's see an example: .. code-block:: pycon >>> re.split(signed_float, 'The mass of 3 electrons is 2.732815068E-30 kg') ['The mass of ', '3', ' electrons is ', '2.732815068E-30', ' kg'] .. note:: It is a bit of a lie to say the above are the complete regular expressions. In the actual code there is also handling for non-ASCII unicode characters (such as ⑦), but I will ignore that aspect of :mod:`natsort` in this discussion. Now, when the user wants to change the definition of a number, it is as easy as changing the pattern supplied to the regular expression engine. Choosing the right default is hard, though (well, in this case it shouldn't have been but I was rather thick-headed). In retrospect, it should have been obvious that since essentially all the code examples I had/have seen for natural sorting were for *unsigned integers*, I should have made the default definition of a number an *unsigned integer*. But, in the brash days of my youth I assumed that since my use case was real numbers, everyone else would be happier sorting by real numbers; so, I made the default definition of a number a *signed float with exponent*. `This astonished`_ `a lot`_ `of people`_ (`and some people aren't very nice when they are astonished`_). Starting with :mod:`natsort` version 4.0.0 the default number definition was changed to an *unsigned integer* which satisfies the "least astonishment" principle, and I have not heard a complaint since. Coercing Strings Containing Numbers Into Numbers ++++++++++++++++++++++++++++++++++++++++++++++++ There has been some debate on Stack Overflow as to what method is best to coerce a string to a number if it can be coerced, and leaving it alone otherwise (see `this one for coercion`_ and `this one for checking`_ for some high traffic questions), but it mostly boils down to two different solutions, shown here: .. code-block:: pycon >>> def coerce_try_except(x): ... try: ... return int(x) ... except ValueError: ... return x ... >>> def coerce_regex(x): ... # Note that precompiling the regex is more performant, ... # but I do not show that here for clarity's sake. ... return int(x) if re.match(r'[-+]?\d+$', x) else x ... Here are some timing results run on my machine: .. code-block:: pycon In [0]: numbers = list(map(str, range(100))) # A list of numbers as strings In [1]: not_numbers = ['banana' + x for x in numbers] In [2]: %timeit [coerce_try_except(x) for x in numbers] 10000 loops, best of 3: 51.1 µs per loop In [3]: %timeit [coerce_try_except(x) for x in not_numbers] 1000 loops, best of 3: 289 µs per loop In [4]: %timeit [coerce_regex(x) for x in not_numbers] 10000 loops, best of 3: 67.6 µs per loop In [5]: %timeit [coerce_regex(x) for x in numbers] 10000 loops, best of 3: 123 µs per loop What can we learn from this? The ``try: except`` method (arguably the most "pythonic" of the solutions) is best for numeric input, but performs over 5X slower for non-numeric input. Conversely, the regular expression method, though slower than ``try: except`` for both input types, is more efficient for non-numeric input than for input that can be converted to an ``int``. Further, even though the regular expression method is slower for both input types, it is always at least twice as fast as the worst case for the ``try: except``. Why do I care? Shouldn't I just pick a method and not worry about it? Probably. However, I am very conscious about the performance of :mod:`natsort`, and want it to be a true drop-in replacement for :func:`sorted` without having to incur a performance penalty. For the purposes of :mod:`natsort`, there is no clear winner between the two algorithms - the data being passed to this function will likely be a mix of numeric and non-numeric string content. Do I use the ``try: except`` method and hope the speed gains on numbers will offset the non-number performance, or do I use regular expressions and take the more stable performance? It turns out that within the context of :mod:`natsort`, some assumptions can be made that make a hybrid approach attractive. Because all strings are pre-split into numeric and non-numeric content *before* being passed to this coercion function, the assumption can be made that *if a string begins with a digit or a sign, it can be coerced into a number*. .. code-block:: pycon >>> def coerce_to_int(x): ... if x[0] in '0123456789+-': ... try: ... return int(x) ... except ValueError: ... return x ... else: ... return x ... So how does this perform compared to the standard coercion methods? .. code-block:: pycon In [6]: %timeit [coerce_to_int(x) for x in numbers] 10000 loops, best of 3: 71.6 µs per loop In [7]: %timeit [coerce_to_int(x) for x in not_numbers] 10000 loops, best of 3: 26.4 µs per loop The hybrid method eliminates most of the time wasted on numbers checking that it is in fact a number before passing to :func:`int`, and eliminates the time wasted in the exception stack for input that is not a number. That's as fast as we can get, right? In pure Python, probably. At least, it's close. But because I am crazy and a glutton for punishment, I decided to see if I could get any faster writing a C extension. It's called `fastnumbers`_ and contains a C implementation of the above coercion functions called :func:`fast_int`. How does it fair? Pretty well. .. code-block:: pycon In [8]: %timeit [fast_int(x) for x in numbers] 10000 loops, best of 3: 30.9 µs per loop In [9]: %timeit [fast_int(x) for x in not_numbers] 10000 loops, best of 3: 30 µs per loop During development of :mod:`natsort`, I wanted to ensure that using it did not get in the way of a user's program by introducing a performance penalty to their code. To that end, I do not feel like my adventures down the rabbit hole of optimization of coercion functions was a waste; I can confidently look users in the eye and say I considered every option in ensuring :mod:`natsort` is as efficient as possible. This is why if `fastnumbers`_ is installed it will be used for this step, and otherwise the hybrid method will be used. .. note:: Modifying the hybrid coercion function for floats is straightforward. .. code-block:: pycon >>> def coerce_to_float(x): ... if x[0] in '.0123456789+-' or x.lower().lstrip()[:3] in ('nan', 'inf'): ... try: ... return float(x) ... except ValueError: ... return x ... else: ... return x ... .. _tldr1: TL;DR 1 - The Simple "No Special Cases" Algorithm +++++++++++++++++++++++++++++++++++++++++++++++++ At this point, our :mod:`natsort` algorithm is essentially the following: .. code-block:: pycon >>> import re >>> def natsort_key(x, as_float=False, signed=False): ... if as_float: ... regex = signed_float if signed else unsigned_float ... else: ... regex = signed_int if signed else unsigned_int ... split_input = re.split(regex, x) ... split_input = filter(None, split_input) # removes null strings ... coerce = coerce_to_float if as_float else coerce_to_int ... return tuple(coerce(s) for s in split_input) ... I have written the above for clarity and not performance. This pretty much matches `most natural sort solutions for python on Stack Overflow`_ (except the above includes customization of the definition of a number). Special Cases Everywhere! ------------------------- .. contents:: :local: .. image:: special_cases_everywhere.jpg If what I described in :ref:`TL;DR 1 ` were all that :mod:`natsort` needed to do then there probably wouldn't be much need for a third-party module, right? Probably. But it turns out that in real-world data there are a lot of special cases that need to be handled, and in true `80%/20%`_ fashion, the majority of the code in :mod:`natsort` is devoted to handling special cases like those described below. Sorting Filesystem Paths ++++++++++++++++++++++++ `The first major special case I encountered was sorting filesystem paths`_ (if you go to the link, you will see I didn't handle it well for a year... this was before I fully realized how much functionality I could really add to :mod:`natsort`). Let's apply the :func:`natsort_key` from above to some filesystem paths that you might see being auto-generated from your operating system: .. code-block:: pycon >>> paths = ['Folder (10)/file.tar.gz', ... 'Folder/file.tar.gz', ... 'Folder (1)/file (1).tar.gz', ... 'Folder (1)/file.tar.gz'] >>> sorted(paths, key=natsort_key) ['Folder (1)/file (1).tar.gz', 'Folder (1)/file.tar.gz', 'Folder (10)/file.tar.gz', 'Folder/file.tar.gz'] Well that's not right! What is ``'Folder/file.tar.gz'`` doing at the end? It has to do with the numerical ASCII code assigned to the space and ``/`` characters in the `ASCII table`_. According to the `ASCII table`_, the space character (number 32) comes before the ``/`` character (number 47). If we remove the common prefix in all of the above strings (``'Folder'``), we can see why this happens: .. code-block:: pycon >>> ' (1)/file.tar.gz' < '/file.tar.gz' True >>> ' ' < '/' True This isn't very convenient... how do we solve it? We can split the path across the path separators and then sort. A convenient way do to this is with the :data:`Path.parts ` property from :mod:`pathlib`: .. code-block:: pycon >>> import pathlib >>> sorted(paths, key=lambda x: tuple(natsort_key(s) for s in pathlib.Path(x).parts)) ['Folder/file.tar.gz', 'Folder (1)/file (1).tar.gz', 'Folder (1)/file.tar.gz', 'Folder (10)/file.tar.gz'] Almost! It seems like there is some funny business going on in the final filename component as well. We can solve that nicely and quickly with :data:`Path.suffixes ` and :data:`Path.stem `. .. code-block:: pycon >>> def decompose_path_into_components(x): ... path_split = list(pathlib.Path(x).parts) ... # Remove the final filename component from the path. ... final_component = pathlib.Path(path_split.pop()) ... # Split off all the extensions. ... suffixes = final_component.suffixes ... stem = final_component.name.replace(''.join(suffixes), '') ... # Remove the '.' prefix of each extension, and make that ... # final component a list of the stem and each suffix. ... final_component = [stem] + [x[1:] for x in suffixes] ... # Replace the split final filename component. ... path_split.extend(final_component) ... return path_split ... >>> def natsort_key_with_path_support(x): ... return tuple(natsort_key(s) for s in decompose_path_into_components(x)) ... >>> sorted(paths, key=natsort_key_with_path_support) ['Folder/file.tar.gz', 'Folder (1)/file.tar.gz', 'Folder (1)/file (1).tar.gz', 'Folder (10)/file.tar.gz'] This works because in addition to breaking the input by path separators, the final filename component is separated from its extensions as well [#f1]_. *Then*, each of these separated components is sent to the :mod:`natsort` algorithm, so the result is a tuple of tuples. Once that is done, we can see how comparisons can be done in the expected manner. .. code-block:: pycon >>> a = natsort_key_with_path_support('Folder (1)/file (1).tar.gz') >>> a (('Folder (', 1, ')'), ('file (', 1, ')'), ('tar',), ('gz',)) >>> >>> b = natsort_key_with_path_support('Folder/file.tar.gz') >>> b (('Folder',), ('file',), ('tar',), ('gz',)) >>> >>> a > b True Comparing Different Types on Python 3 +++++++++++++++++++++++++++++++++++++ `The second major special case I encountered was sorting of different types`_. If you are on Python 2 (i.e. legacy Python), this mostly doesn't matter *too* much since it uses an arbitrary heuristic to allow traditionally un-comparable types to be compared (such as comparing ``'a'`` to ``1``). However, on Python 3 (i.e. Python) it simply won't let you perform such nonsense, raising a :exc:`TypeError` instead. You can imagine that a module that breaks strings into tuples of numbers and strings is walking a dangerous line if it does not have special handling for comparing numbers and strings. My imagination was not so great at first. Let's take a look at all the ways this can fail with real-world data. .. code-block:: pycon >>> def natsort_key_with_poor_real_number_support(x): ... split_input = re.split(signed_float, x) ... split_input = filter(None, split_input) # removes null strings ... return tuple(coerce_to_float(s) for s in split_input) >>> >>> sorted([5, '4'], key=natsort_key_with_poor_real_number_support) Traceback (most recent call last): ... TypeError: ... >>> >>> sorted(['12 apples', 'apples'], key=natsort_key_with_poor_real_number_support) Traceback (most recent call last): ... TypeError: ... >>> >>> sorted(['version5.3.0', 'version5.3rc1'], key=natsort_key_with_poor_real_number_support) Traceback (most recent call last): ... TypeError: ... Let's break these down. #. The integer ``5`` is sent to ``re.split`` which expects only strings or bytes, which is a no-no. #. ``natsort_key_with_poor_real_number_support('12 apples') < natsort_key_with_poor_real_number_support('apples')`` is the same as ``(12.0, ' apples') < ('apples',)``, and thus a number gets compared to a string [#f2]_ which also is a no-no. #. This one scores big on the astonishment scale, especially if one accidentally uses signed integers or real numbers when they mean to use unsigned integers. ``natsort_key_with_poor_real_number_support('version5.3.0') < natsort_key_with_poor_real_number_support('version5.3rc1')`` is the same as ``('version', 5.3, 0.0) < ('version', 5.3, 'rc', 1.0)``, so in the third element a number gets compared to a string, once again the same old no-no. (The same would happen with ``'version5-3'`` and ``'version5-a'``, which would become ``('version', 5, -3)`` and ``('version', 5, '-a')``). As you might expect, the solution to the first issue is to wrap the ``re.split`` call in a ``try: except:`` block and handle the number specially if a :exc:`TypeError` is raised. The second and third cases *could* be handled in a "special case" manner, meaning only respond and do something different if these problems are detected. But a less error-prone method is to ensure that the data is correct-by-construction, and this can be done by ensuring that the returned tuples *always* start with a string, and then alternate in a string-number-string-number-string pattern; this can be achieved by adding an empty string wherever the pattern is not followed [#f3]_. This ends up working out pretty nicely because empty strings are always "less" than any non-empty string, and we typically want numbers to come before strings. Let's take a look at how this works out. .. code-block:: pycon >>> from natsort.utils import sep_inserter >>> list(sep_inserter(iter(['apples']), '')) ['apples'] >>> >>> list(sep_inserter(iter([12, ' apples']), '')) ['', 12, ' apples'] >>> >>> list(sep_inserter(iter(['version', 5, -3]), '')) ['version', 5, '', -3] >>> >>> from natsort import natsort_keygen, ns >>> natsort_key_with_good_real_number_support = natsort_keygen(alg=ns.REAL) >>> >>> sorted([5, '4'], key=natsort_key_with_good_real_number_support) ['4', 5] >>> >>> sorted(['12 apples', 'apples'], key=natsort_key_with_good_real_number_support) ['12 apples', 'apples'] >>> >>> sorted(['version5.3.0', 'version5.3rc1'], key=natsort_key_with_good_real_number_support) ['version5.3.0', 'version5.3rc1'] How the "good" version works will be given in `TL;DR 2 - Handling Crappy, Real-World Input`_. Handling NaN ++++++++++++ `A rather unexpected special case I encountered was sorting collections containing NaN`_. Let's see what happens when you try to sort a plain old list of numbers when there is a **NaN** floating around in there. .. code-block:: pycon >>> danger = [7, float('nan'), 22.7, 19, -14, 59.123, 4] >>> sorted(danger) [7, nan, -14, 4, 19, 22.7, 59.123] Clearly that isn't correct, and for once it isn't my fault! `It's hard to compare floating point numbers`_. By definition, **NaN** is unorderable to any other number, and is never equal to any other number, including itself. .. code-block:: pycon >>> nan = float('nan') >>> 5 > nan False >>> 5 < nan False >>> 5 == nan False >>> 5 != nan True >>> nan == nan False >>> nan != nan True The implication of all this for us is that if there is an **NaN** in the data-set we are trying to sort, the data-set will end up being sorted in two separate yet individually sorted sequences - the one *before* the **NaN**, and the one *after*. This is because the ``<`` operation that is used to sort always returns :const:`False` with **NaN**. Because :mod:`natsort` aims to sort sequences in a way that does not surprise the user, keeping this behavior is not acceptable (I don't require my users to know how **NaN** will behave in a sorting algorithm). The simplest way to satisfy the "least astonishment" principle is to substitute **NaN** with some other value. But what value is *least* astonishing? I chose to replace **NaN** with :math:`-\infty` so that these poorly behaved elements always end up at the front where the users will most likely be alerted to their presence. .. code-block:: pycon >>> def fix_nan(x): ... if x != x: # only true for NaN ... return float('-inf') ... else: ... return x ... Let's check out :ref:`TL;DR 2 ` to see how this can be incorporated into the simple key function from :ref:`TL;DR 1 `. .. _tldr2: TL;DR 2 - Handling Crappy, Real-World Input +++++++++++++++++++++++++++++++++++++++++++ Let's see how our elegant key function from :ref:`TL;DR 1 ` has become bastardized in order to support handling mixed real-world data and user customizations. .. code-block:: pycon >>> def natsort_key(x, as_float=False, signed=False, as_path=False): ... if as_float: ... regex = signed_float if signed else unsigned_float ... else: ... regex = signed_int if signed else unsigned_int ... try: ... if as_path: ... x = decompose_path_into_components(x) # Decomposes into list of strings ... # If this raises a TypeError, input is not a string. ... split_input = re.split(regex, x) ... except TypeError: ... try: ... # Does this need to be applied recursively (list-of-list)? ... return tuple(map(natsort_key, x)) ... except TypeError: ... # Must be a number ... ret = ('', fix_nan(x)) # Maintain string-number-string pattern ... return (ret,) if as_path else ret # as_path returns tuple-of-tuples ... else: ... split_input = filter(None, split_input) # removes null strings ... # Note that the coerce_to_int/coerce_to_float functions ... # are also modified to use the fix_nan function. ... if as_float: ... coerced_input = (coerce_to_float(s) for s in split_input) ... else: ... coerced_input = (coerce_to_int(s) for s in split_input) ... return tuple(sep_inserter(coerced_input, '')) ... And this doesn't even show handling :class:`bytes` type! Notice that we have to do non-obvious things like modify the return form of numbers when ``as_path`` is given, just to avoid comparing strings and numbers for the case in which a user provides input like ``['/home/me', 42]``. Let's take it out for a spin! .. code-block:: pycon >>> danger = [7, float('nan'), 22.7, '19', '-14', '59.123', 4] >>> sorted(danger, key=lambda x: natsort_key(x, as_float=True, signed=True)) [nan, '-14', 4, 7, '19', 22.7, '59.123'] >>> >>> paths = ['Folder (1)/file.tar.gz', ... 'Folder/file.tar.gz', ... 123456] >>> sorted(paths, key=lambda x: natsort_key(x, as_path=True)) [123456, 'Folder/file.tar.gz', 'Folder (1)/file.tar.gz'] Here Be Dragons: Adding Locale Support -------------------------------------- .. contents:: :local: Probably the most challenging special case I had to handle was getting :mod:`natsort` to handle sorting the non-numerical parts of input correctly, and also allowing it to sort the numerical bits in different locales. This was in no way what I originally set out to do with this library, so I was `caught a bit off guard when the request was initially made`_. I discovered the :mod:`locale` library, and assumed that if it's part of Python's StdLib there can't be too many dragons, right? .. admonition:: INCOMPLETE LIST OF DRAGONS - https://github.com/SethMMorton/natsort/issues/21 - https://github.com/SethMMorton/natsort/issues/22 - https://github.com/SethMMorton/natsort/issues/23 - https://github.com/SethMMorton/natsort/issues/36 - https://github.com/SethMMorton/natsort/issues/44 - https://bugs.python.org/issue2481 - https://bugs.python.org/issue23195 - https://stackoverflow.com/questions/3412933/python-not-sorting-unicode-properly-strcoll-doesnt-help - https://stackoverflow.com/questions/22203550/sort-dictionary-by-key-using-locale-collation - https://stackoverflow.com/questions/33459384/unicode-character-not-in-range-when-calling-locale-strxfrm - https://stackoverflow.com/questions/36431810/sort-numeric-lines-with-thousand-separators - https://stackoverflow.com/questions/45734562/how-can-i-get-a-reasonable-string-sorting-with-python These can be summed up as follows: #. :mod:`locale` is a thin wrapper over your operating system's *locale* library, so if *that* is broken (like it is on BSD and OSX) then :mod:`locale` is broken in Python. #. Because of a bug in legacy Python (i.e. Python 2), there is no uniform way to use the :mod:`locale` sorting functionality between legacy Python and Python 3. #. People have differing opinions of how capitalization should affect word order. #. There is no built-in way to handle locale-dependent thousands separators and decimal points *robustly*. #. Proper handling of Unicode is complicated. #. Proper handling of :mod:`locale` is complicated. Easily over half of the code in :mod:`natsort` is in some way dealing with some aspect of :mod:`locale` or basic case handling. It would have been impossible to get right without a `really good`_ `testing strategy`_. Don't expect any more TL;DR's... if you want to see how all this is fully incorporated into the :mod:`natsort` algorithm then please take a look `at the code`_. However, I will hint at how specific steps are taken in each section. Let's see how we can handle some of the dragons, one-by-one. Basic Case Control Support ++++++++++++++++++++++++++ Without even thinking about the mess that is adding :mod:`locale` support, :mod:`natsort` can introduce support for controlling how case is interpreted. First, let's take a look at how it is sorted by default (due to where characters lie on the `ASCII table`_). .. code-block:: pycon >>> a = ['Apple', 'corn', 'Corn', 'Banana', 'apple', 'banana'] >>> sorted(a) ['Apple', 'Banana', 'Corn', 'apple', 'banana', 'corn'] All uppercase letters come before lowercase letters in the `ASCII table`_, so all capitalized words appear first. Not everyone agrees that this is the correct order. Some believe that the capitalized words should be last (``['apple', 'banana', 'corn', 'Apple', 'Banana', 'Corn']``). Some believe that both the lowercase and uppercase versions should appear together (``['Apple', 'apple', 'Banana', 'banana', 'Corn', 'corn']``). Some believe that both should be true ☹. Some people don't care at all [#f4]_. Solving the first case (I call it *LOWERCASEFIRST*) is actually pretty easy... just call the :meth:`str.swapcase` method on the input. .. code-block:: pycon >>> sorted(a, key=lambda x: x.swapcase()) ['apple', 'banana', 'corn', 'Apple', 'Banana', 'Corn'] The last (i call it *IGNORECASE*) should be super easy, right? Simply call :meth:`str.lowercase` on the input. This will work but may not always give the correct answer on non-latin character sets. It's a good thing that in Python 3.3 :meth:`str.casefold` was introduced, which does a better job of removing all case information from unicode characters in non-latin alphabets. .. code-block:: pycon >>> def remove_case(x): ... try: ... return x.casefold() ... except AttributeError: # Legacy Python backwards compatibility ... return x.lowercase() ... >>> sorted(a, key=remove_case) ['Apple', 'apple', 'Banana', 'banana', 'corn', 'Corn'] The middle case (I call it *GROUPLETTERS*) is less straightforward. The most efficient way to handle this is to duplicate each character with its lowercase version and then the original character. .. code-block:: pycon >>> import itertools >>> def groupletters(x): ... return ''.join(itertools.chain.from_iterable((remove_case(y), y) for y in x)) ... >>> groupletters('Apple') 'aAppppllee' >>> groupletters('apple') 'aappppllee' >>> sorted(a, key=groupletters) ['Apple', 'apple', 'Banana', 'banana', 'Corn', 'corn'] The effect of this is that both ``'Apple'`` and ``'apple'`` are placed adjacent to each other because their transformations both begin with ``'a'``, and then the second character can be used to order them appropriately with respect to each other. There's a problem with this, though. Within the context of :mod:`natsort` we are trying to correctly sort numbers and those should be left alone. .. code-block:: pycon >>> a = ['Apple5', 'apple', 'Apple4E10', 'Banana'] >>> sorted(a, key=lambda x: natsort_key(x, as_float=True)) ['Apple5', 'Apple4E10', 'Banana', 'apple'] >>> sorted(a, key=lambda x: natsort_key(groupletters(x), as_float=True)) ['Apple4E10', 'Apple5', 'apple', 'Banana'] >>> groupletters('Apple4E10') 'aAppppllee44eE1100' We messed up the numbers! Looks like :func:`groupletters` needs to be applied *after* the strings are broken into their components. I'm not going to show how this is done here, but basically it requires applying the function in the ``else:`` block of :func:`coerce_to_int`/:func:`coerce_to_float`. .. code-block:: pycon >>> better_groupletters = natsort_keygen(alg=ns.GROUPLETTERS | ns.REAL) >>> better_groupletters('Apple4E10') ('aAppppllee', 40000000000.0) >>> sorted(a, key=better_groupletters) ['Apple5', 'Apple4E10', 'apple', 'Banana'] Of course, applying both *LOWERCASEFIRST* and *GROUPLETTERS* is just a matter of turning on both functions. Basic Unicode Support +++++++++++++++++++++ Unicode is hard and complicated. Here's an example. .. code-block:: pycon >>> b = [b'\x66', b'\x65', b'\xc3\xa9', b'\x65\xcc\x81', b'\x61', b'\x7a'] >>> a = [x.decode('utf8') for x in b] >>> a # doctest: +SKIP ['f', 'e', 'é', 'é', 'a', 'z'] >>> sorted(a) # doctest: +SKIP ['a', 'e', 'é', 'f', 'z', 'é'] There are more than one way to represent the character 'é' in Unicode. In fact, many characters have multiple representations. This is a challenge because comparing the two representations would return ``False`` even though they *look* the same. .. code-block:: pycon >>> a[2] == a[3] False Alas, since characters are compared based on the numerical value of their representation, sorting Unicode often gives unexpected results (like seeing 'é' come both *before* and *after* 'z'). The original approach that :mod:`natsort` took with respect to non-ASCII Unicode characters was to say "just use the :mod:`locale` or :mod:`PyICU` library" and then cross it's fingers and hope those libraries take care of it. As you will find in the following sections, that comes with its own baggage, and turned out to not always work anyway (see https://stackoverflow.com/q/45734562/1399279). A more robust approach is to handle the Unicode out-of-the-box without invoking a heavy-handed library like :mod:`locale` or :mod:`PyICU`. To do this, we must use *normalization*. To fully understand Unicode normalization, `check out some official Unicode documentation`_. Just kidding... that's too much text. The following StackOverflow answers do a good job at explaining Unicode normalization in simple terms: https://stackoverflow.com/a/7934397/1399279 and https://stackoverflow.com/a/7931547/1399279. Put simply, normalization ensures that Unicode characters with multiple representations are in some canonical and consistent representation so that (for example) comparisons of the characters can be performed in a sane way. The following discussion assumes you at least read the StackOverflow answers. Looking back at our 'é' example, we can see that the two versions were constructed with the byte strings ``b'\xc3\xa9'`` and ``b'\x65\xcc\x81'``. The former representation is actually `LATIN SMALL LETTER E WITH ACUTE `_ and is a single character in the Unicode standard. This is known as the *compressed form* and corresponds to the 'NFC' normalization scheme. The latter representation is actually the letter 'e' followed by `COMBINING ACUTE ACCENT `_ and so is two characters in the Unicode standard. This is known as the *decompressed form* and corresponds to the 'NFD' normalization scheme. Since the first character in the decompressed form is actually the letter 'e', when compared to other ASCII characters it fits where you might expect. Unfortunately, all Unicode compressed form characters come after the ASCII characters and so they always will be placed after 'z' when sorting. It seems that most Unicode data is stored and shared in the compressed form which makes it challenging to sort. This can be solved by normalizing all incoming Unicode data to the decompressed form ('NFD') and *then* sorting. .. code-block:: pycon >>> import unicodedata >>> c = [unicodedata.normalize('NFD', x) for x in a] >>> c # doctest: +SKIP ['f', 'e', 'é', 'é', 'a', 'z'] >>> sorted(c) # doctest: +SKIP ['a', 'e', 'é', 'é', 'f', 'z'] Huzzah! Sane sorting without having to resort to :mod:`locale`! Using Locale to Compare Strings +++++++++++++++++++++++++++++++ The :mod:`locale` module is actually pretty cool, and provides lowly spare-time programmers like myself a way to handle the daunting task of proper locale-dependent support of their libraries and utilities. Having said that, it can be a bit of a bear to get right, `although they do point out in the documentation that it will be painful to use`_. Aside from the caveats spelled out in that link, it turns out that just comparing strings with :mod:`locale` in a cross-platform and cross-python-version manner is not as straightforward as one might hope. First, how to use :mod:`locale` to compare strings? It's actually pretty straightforward. Simply run the input through the :mod:`locale` transformation function :func:`locale.strxfrm`. .. code-block:: pycon >>> import locale, sys >>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 'en_US.UTF-8' >>> a = ['a', 'b', 'ä'] >>> sorted(a) ['a', 'b', 'ä'] >>> # The below fails on OSX, so don't run doctest on darwin. >>> is_osx = sys.platform == 'darwin' >>> sorted(a, key=locale.strxfrm) if not is_osx else ['a', 'ä', 'b'] ['a', 'ä', 'b'] >>> >>> a = ['apple', 'Banana', 'banana', 'Apple'] >>> sorted(a, key=locale.strxfrm) if not is_osx else ['apple', 'Apple', 'banana', 'Banana'] ['apple', 'Apple', 'banana', 'Banana'] It turns out that locale-aware sorting groups numbers in the same way as turning on *GROUPLETTERS* and *LOWERCASEFIRST*. The trick is that you have to apply :func:`locale.strxfrm` only to non-numeric characters; otherwise, numbers won't be parsed properly. Therefore, it must be applied as part of the :func:`coerce_to_int`/:func:`coerce_to_float` functions in a manner similar to :func:`groupletters`. As you might have guessed, there is a small problem. It turns out the there is a bug in the legacy Python implementation of :func:`locale.strxfrm` that causes it to outright fail for :func:`unicode` input (https://bugs.python.org/issue2481). :func:`locale.strcoll` works, but is intended for use with ``cmp``, which does not exist in current Python implementations. Luckily, the :func:`functools.cmp_to_key` function makes :func:`locale.strcoll` behave like :func:`locale.strxfrm`. Handling Broken Locale On OSX ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ But what if the underlying *locale* implementation that :mod:`locale` relies upon is simply broken? It turns out that the *locale* library on OSX (and other BSD systems) is broken (and for some reason has never been fixed?), and so :mod:`locale` does not work as expected. How do I define doesn't work as expected? .. code-block:: pycon >>> a = ['apple', 'Banana', 'banana', 'Apple'] >>> sorted(a) ['Apple', 'Banana', 'apple', 'banana'] >>> >>> sorted(a, key=locale.strxfrm) if is_osx else sorted(a) ['Apple', 'Banana', 'apple', 'banana'] IT'S SORTING AS IF :func:`locale.stfxfrm` WAS NEVER USED!! (and it's worse once non-ASCII characters get thrown into the mix.) I'm really not sure why this is considered OK for the OSX/BSD maintainers to not fix, but it's more than frustrating for poor developers who have been dragged into the *locale* game kicking and screaming. **. So, how to deal with this situation? There are two ways to do so. #. Detect if :mod:`locale` is sorting incorrectly (i.e. ``dumb``) by seeing if ``'A'`` is sorted before ``'a'`` (incorrect) or not. .. code-block:: pycon >>> # This is genuinely the name of this function. >>> # See natsort.compat.locale.py >>> def dumb_sort(): ... return locale.strxfrm('A') < locale.strxfrm('a') ... If a ``dumb`` *locale* implementation is found, then automatically turn on *LOWERCASEFIRST* and *GROUPLETTERS*. #. Use an alternate library if installed. `ICU `_ is a great and powerful library that has a pretty decent Python port called (you guessed it) `PyICU `_. If a user has this library installed on their computer, :mod:`natsort` chooses to use that instead of :mod:`locale`. With a little bit of planning, one can write a set of wrapper functions that call the correct library under the hood such that the business logic never has to know what library is being used (see `natsort.compat.locale.py`_). Let me tell you, this little complication really makes a challenge of testing the code, since one must set up different environments on different operating systems in order to test all possible code paths. Not to mention that certain checks *will* fail for certain operating systems and environments so one must be diligent in either writing the tests not to fail, or ignoring those tests when on offending environments. Handling Locale-Aware Numbers +++++++++++++++++++++++++++++ `Thousands separator support`_ is a problem that I knew would someday be requested but had decided to push off until a rainy day. One day it finally rained, and I decided to tackle the problem. So what is the problem? Consider the number ``1,234,567`` (assuming the ``','`` is the thousands separator). Try to run that through :func:`int` and you will get a :exc:`ValueError`. To handle this properly the thousands separators must be removed. .. code-block:: pycon >>> float('1,234,567'.replace(',', '')) 1234567.0 What if, in our current locale, the thousands separator is ``'.'`` and the ``','`` is the decimal separator (like for the German locale *de_DE*)? .. code-block:: pycon >>> float('1.234.567'.replace('.', '').replace(',', '.')) 1234567.0 >>> float('1.234.567,89'.replace('.', '').replace(',', '.')) 1234567.89 This is pretty much what :func:`locale.atoi` and :func:`locale.atof` do under the hood. So what's the problem? Why doesn't :mod:`natsort` just use this method under its hood? Well, let's take a look at what would happen if we send some possible :mod:`natsort` input through our the above function: .. code-block:: pycon >>> natsort_key('1,234 apples, please.'.replace(',', '')) ('', 1234, ' apples please.') >>> natsort_key('Sir, €1.234,50 please.'.replace('.', '').replace(',', '.'), as_float=True) ('Sir. €', 1234.5, ' please') Any character matching the thousands separator was dropped, and anything matching the decimal separator was changed to ``'.'``! If these characters were critical to how your data was ordered, this would break :mod:`natsort`. The first solution one might consider would be to first decompose the input into sub-components (like we did for the *GROUPLETTERS* method above) and then only apply these transformations on the number components. This is a chicken-and-egg problem, though, because *we cannot appropriately separate out the numbers because of the thousands separators and non-'.' decimal separators* (well, at least not without making multiple passes over the data which I do not consider to be a valid option). Regular expressions to the rescue! With regular expressions, we can remove the thousands separators and change the decimal separator only when they are actually within a number. Once the input has been pre-processed with this regular expression, all the infrastructure shown previously will work. Beware, these regular expressions will make your eyes bleed. .. code-block:: pycon >>> decimal = ',' # Assume German locale, so decimal separator is ',' >>> # Look-behind assertions cannot accept range modifiers, so instead of i.e. >>> # (?>> nodecimal = r'(?>> strip_thousands = r''' ... (?<=[0-9]{{1}}) # At least 1 number ... (?>> re.sub(strip_thousands, '', 'Sir, €1.234,50 please.', flags=re.X) 'Sir, €1234,50 please.' >>> >>> # The decimal point must be preceded by a number or after >>> # a number. This option only needs to be performed in the >>> # case when the decimal separator for the locale is not '.'. >>> switch_decimal = r'(?<=[0-9]){decimal}|{decimal}(?=[0-9])' >>> switch_decimal = switch_decimal.format(decimal=decimal) >>> re.sub(switch_decimal, '.', 'Sir, €1234,50 please.', flags=re.X) 'Sir, €1234.50 please.' >>> >>> natsort_key('Sir, €1234.50 please.', as_float=True) ('Sir, €', 1234.5, ' please.') Final Thoughts -------------- My hope is that users of :mod:`natsort` never have to think about or worry about all the bookkeeping or any of the details described above, and that using :mod:`natsort` seems to magically "just work". For those of you who took the time to read this engineering description, I hope it has enlightened you to some of the issues that can be encountered when code is released into the wild and has to accept "real-world data", or to what happens to developers who naïvely make bold assumptions that are counter to what the rest of the world assumes. .. rubric:: Footnotes .. [#f1] To anyone looking through the actual code, you will note that I don't actually use :mod:`pathlib` to split the paths... I wrote my own version to avoid adding an external dependency of :mod:`pathlib` on Python < 3.4. .. [#f2] *"But if you hadn't removed the leading empty string from re.split this wouldn't have happened!!"* I can hear you saying. Well, that's true. I don't have a *great* reason for having done that except that in an earlier non-optimal incarnation of the algorithm I needed to it, and it kind of stuck, and it made other parts of the code easier if the assumption that there were no empty strings was valid. .. [#f3] I'm not going to show how this is implemented in this document, but if you are interested you can look at the code to :func:`sep_inserter` in `util.py`_. .. [#f4] Handling each of these is straightforward, but coupled with the rapidly fracturing execution paths presented in :ref:`TL;DR 2 ` one can imagine this will get out of hand quickly. If you take a look at `natsort.py`_ and `util.py`_ you can observe that to avoid this I take a more functional approach to construting the :mod:`natsort` algorithm as opposed to the procedural approach illustrated in :ref:`TL;DR 1 ` and :ref:`TL;DR 2 `. .. _ASCII table: https://www.asciitable.com/ .. _getting sorting right is surprisingly hard: http://www.compciv.org/guides/python/fundamentals/sorting-collections-with-sorted/ .. _This astonished: https://github.com/SethMMorton/natsort/issues/19 .. _a lot: https://stackoverflow.com/questions/29548742/python-natsort-sort-strings-recursively .. _of people: https://stackoverflow.com/questions/24045348/sort-set-of-numbers-in-the-form-xx-yy-in-python .. _and some people aren't very nice when they are astonished: https://github.com/xolox/python-naturalsort/blob/ed3e6b6ffaca3bdea3b76e08acbb8bd2a5fee463/README.rst#why-another-natsort-module .. _fastnumbers: https://github.com/SethMMorton/fastnumbers .. _as part of my testing: https://github.com/SethMMorton/natsort/blob/master/test_natsort/slow_splitters.py .. _this one for coercion: https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python .. _this one for checking: https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float .. _most natural sort solutions for python on Stack Overflow: https://stackoverflow.com/q/4836710/1399279 .. _80%/20%: https://en.wikipedia.org/wiki/Pareto_principle .. _The first major special case I encountered was sorting filesystem paths: https://github.com/SethMMorton/natsort/issues/3 .. _The second major special case I encountered was sorting of different types: https://github.com/SethMMorton/natsort/issues/7 .. _A rather unexpected special case I encountered was sorting collections containing NaN: https://github.com/SethMMorton/natsort/issues/27 .. _It's hard to compare floating point numbers: http://www.drdobbs.com/cpp/its-hard-to-compare-floating-point-numbe/240149806 .. _caught a bit off guard when the request was initially made: https://github.com/SethMMorton/natsort/issues/14 .. _at the code: https://github.com/SethMMorton/natsort/tree/master/natsort .. _natsort.py: https://github.com/SethMMorton/natsort/blob/master/natsort/natsort.py .. _util.py: https://github.com/SethMMorton/natsort/blob/master/natsort/util.py .. _although they do point out in the documentation that it will be painful to use: https://docs.python.org/3/library/locale.html#background-details-hints-tips-and-caveats .. _natsort.compat.locale.py: https://github.com/SethMMorton/natsort/blob/master/natsort/compat/locale.py .. _Thousands separator support: https://github.com/SethMMorton/natsort/issues/36 .. _really good: https://hypothesis.readthedocs.io/en/latest/ .. _testing strategy: https://docs.pytest.org/en/latest/ .. _check out some official Unicode documentation: https://unicode.org/reports/tr15/ natsort-7.0.1/docs/index.rst000066400000000000000000000020051361376133500160070ustar00rootroot00000000000000.. natsort documentation master file, created by sphinx-quickstart on Thu Jul 17 21:01:29 2014. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. natsort: Simple yet flexible natural sorting in Python. ======================================================= - Source Code: https://github.com/SethMMorton/natsort - Downloads: https://pypi.org/project/natsort/ - Documentation: https://natsort.readthedocs.io/ Please see the `GitHub main page `_ for everything else, including - Quick description - Basic examples - FAQ - Requirements and optional dependencies - Installation instructions - Testing instructions - Deprecation schedule .. toctree:: :maxdepth: 2 :numbered: howitworks.rst examples.rst api.rst locale_issues.rst shell.rst changelog.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` natsort-7.0.1/docs/locale_issues.rst000066400000000000000000000106021361376133500175340ustar00rootroot00000000000000.. default-domain:: py .. currentmodule:: natsort .. _locale_issues: Possible Issues with :func:`~natsort.humansorted` or ``ns.LOCALE`` ================================================================== Being Locale-Aware Means Both Numbers and Non-Numbers ----------------------------------------------------- In addition to modifying how characters are sorted, ``ns.LOCALE`` will take into account locale-dependent thousands separators (and locale-dependent decimal separators if ``ns.FLOAT`` is enabled). This means that if you are in a locale that uses commas as the thousands separator, a number like ``123,456`` will be interpreted as ``123456``. If this is not what you want, you may consider using ``ns.LOCALEALPHA`` which will only enable locale-aware sorting for non-numbers (similarly, ``ns.LOCALENUM`` enables locale-aware sorting only for numbers). Regenerate Key With :func:`~natsort.natsort_keygen` After Changing Locale ------------------------------------------------------------------------- When :func:`~natsort.natsort_keygen` is called it returns a key function that hard-codes the provided settings. This means that the key returned when ``ns.LOCALE`` is used contins the settings specifed by the locale *loaded at the time the key is generated*. If you change the locale, you should regenerate the key to account for the new locale. Corollary: Do Not Reuse :func:`~natsort.natsort_keygen` After Changing Locale +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ If you change locale, the old function will not work as expected. The :mod:`locale` library works with a global state. When :func:`~natsort.natsort_keygen` is called it does the best job that it can to make the returned function as static as possible and independent of the global state, but the :func:`locale.strxfrm` function must access this global state to work; therefore, if you change locale and use ``ns.LOCALE`` then you should discard the old key. .. note:: If you use `PyICU`_ then you may be able to reuse keys after changing locale. The :mod:`locale` Module From the StdLib Has Issues --------------------------------------------------- :mod:`natsort` will use `PyICU`_ for :func:`~natsort.humansorted` or ``ns.LOCALE`` if it is installed. If not, it will fall back on the :mod:`locale` library from the Python stdlib. If you do not have `PyICU`_ installed, please keep the following known problems and issues in mind. .. note:: Remember, if you have `PyICU`_ installed you shouldn't need to worry about any of these. Explicitly Set the Locale Before Using ``ns.LOCALE`` ++++++++++++++++++++++++++++++++++++++++++++++++++++ I have found that unless you explicitly set a locale, the sorted order may not be what you expect. Setting this is straightforward (in the below example I use 'en_US.UTF-8', but you should use your locale): .. code-block:: pycon >>> import locale >>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 'en_US.UTF-8' .. _bug_note: The :mod:`locale` Module Is Broken on Mac OS X ++++++++++++++++++++++++++++++++++++++++++++++ It's not Python's fault, but the OS... the locale library for BSD-based systems (of which Mac OS X is one) is broken. See the following links: - https://stackoverflow.com/questions/3412933/python-not-sorting-unicode-properly-strcoll-doesnt-help - https://bugs.python.org/issue23195 - https://github.com/SethMMorton/natsort/issues/21 (contains instructons on installing) - https://stackoverflow.com/questions/33459384/unicode-character-not-in-range-when-calling-locale-strxfrm - https://github.com/SethMMorton/natsort/issues/34 Of course, installing `PyICU`_ fixes this, but if you don't want to or cannot install this there is some hope. 1. As of ``natsort`` version 4.0.0, ``natsort`` is configured to compensate for a broken ``locale`` library. When sorting non-numbers it will handle case as you expect, but it will still not be able to comprehend non-ASCII characters properly. Additionally, it has a built-in lookup table of thousands separators that are incorrect on OS X/BSD (but is possible it is not complete... please file an issue if you see it is not complete) 2. Use "\*.ISO8859-1" locale (i.e. 'en_US.ISO8859-1') rather than "\*.UTF-8" locale. I have found that these have fewer issues than "UTF-8", but your mileage may vary. .. _PyICU: https://pypi.org/project/PyICU natsort-7.0.1/docs/requirements.in000066400000000000000000000000041361376133500172160ustar00rootroot00000000000000m2r natsort-7.0.1/docs/requirements.txt000066400000000000000000000002501361376133500174320ustar00rootroot00000000000000# # This file is autogenerated by pip-compile # To update, run: # # pip-compile # docutils==0.15.2 # via m2r m2r==0.2.1 mistune==0.8.4 # via m2r natsort-7.0.1/docs/shell.rst000066400000000000000000000136411361376133500160170ustar00rootroot00000000000000.. default-domain:: py .. currentmodule:: natsort .. _shell: Shell Script ============ The ``natsort`` shell script is automatically installed when you install :mod:`natsort` with pip. Below is the usage and some usage examples for the ``natsort`` shell script. Usage ----- .. code-block:: usage: natsort [-h] [--version] [-p] [-f LOW HIGH] [-F LOW HIGH] [-e EXCLUDE] [-r] [-t {digit,int,float,version,ver}] [--nosign] [--noexp] [--locale] [entries [entries ...]] Performs a natural sort on entries given on the command-line. A natural sort sorts numerically then alphabetically, and will sort by numbers in the middle of an entry. positional arguments: entries The entries to sort. Taken from stdin if nothing is given on the command line. optional arguments: -h, --help show this help message and exit --version show program's version number and exit -p, --paths Interpret the input as file paths. This is not strictly necessary to sort all file paths, but in cases where there are OS-generated file paths like "Folder/" and "Folder (1)/", this option is needed to make the paths sorted in the order you expect ("Folder/" before "Folder (1)/"). -f LOW HIGH, --filter LOW HIGH Used for keeping only the entries that have a number falling in the given range. -F LOW HIGH, --reverse-filter LOW HIGH Used for excluding the entries that have a number falling in the given range. -e EXCLUDE, --exclude EXCLUDE Used to exclude an entry that contains a specific number. -r, --reverse Returns in reversed order. -t {digit,int,float,version,ver,real,f,i,r,d}, --number-type {digit,int,float,version,ver,real,f,i,r,d}, --number_type {digit,int,float,version,ver,real,f,i,r,d} Choose the type of number to search for. "float" will search for floating-point numbers. "int" will only search for integers. "digit", "version", and "ver" are synonyms for "int"."real" is a shortcut for "float" with --sign. "i" and "d" are synonyms for "int", "f" is a synonym for "float", and "r" is a synonym for "real".The default is int. --nosign Do not consider "+" or "-" as part of a number, i.e. do not take sign into consideration. This is the default. -s, --sign Consider "+" or "-" as part of a number, i.e. take sign into consideration. The default is unsigned. --noexp Do not consider an exponential as part of a number, i.e. 1e4, would be considered as 1, "e", and 4, not as 10000. This only effects the --number-type=float. -l, --locale Causes natsort to use locale-aware sorting. You will get the best results if you install PyICU. Description ----------- ``natsort`` was originally written to aid in computational chemistry research so that it would be easy to analyze large sets of output files named after the parameter used: .. code-block:: console $ ls *.out mode1000.35.out mode1243.34.out mode744.43.out mode943.54.out (Obviously, in reality there would be more files, but you get the idea.) Notice that the shell sorts in lexicographical order. This is the behavior of programs like ``find`` as well as ``ls``. The problem is passing these files to an analysis program causes them not to appear in numerical order, which can lead to bad analysis. To remedy this, use ``natsort``: .. code-block:: console $ natsort *.out mode744.43.out mode943.54.out mode1000.35.out mode1243.34.out $ natsort -t r *.out | xargs your_program ``-t r`` is short for ``--number-type real``. You can also place natsort in the middle of a pipe: .. code-block:: console $ find . -name "*.out" | natsort -t r | xargs your_program To sort version numbers, use the default ``--number-type``: .. code-block:: console $ ls * prog-1.10.zip prog-1.9.zip prog-2.0.zip $ natsort * prog-1.9.zip prog-1.10.zip prog-2.0.zip In general, all ``natsort`` shell script options mirror the :func:`~natsorted` API, with notable exception of the ``--filter``, ``--reverse-filter``, and ``--exclude`` options. These three options are used as follows: .. code-block:: console $ ls *.out mode1000.35.out mode1243.34.out mode744.43.out mode943.54.out $ natsort -t r *.out -f 900 1100 # Select only numbers between 900-1100 mode943.54.out mode1000.35.out $ natsort -t r *.out -F 900 1100 # Select only numbers NOT between 900-1100 mode744.43.out mode1243.34.out $ natsort -t r *.out -e 1000.35 # Exclude 1000.35 from search mode744.43.out mode943.54.out mode1243.34.out If you are sorting paths with OS-generated filenames, you may require the ``--paths``/``-p`` option: .. code-block:: console $ find . ! -path . -type f ./folder/file (1).txt ./folder/file.txt ./folder (1)/file.txt ./folder (10)/file.txt ./folder (2)/file.txt $ find . ! -path . -type f | natsort ./folder (1)/file.txt ./folder (2)/file.txt ./folder (10)/file.txt ./folder/file (1).txt ./folder/file.txt $ find . ! -path . -type f | natsort -p ./folder/file.txt ./folder/file (1).txt ./folder (1)/file.txt ./folder (2)/file.txt ./folder (10)/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B% [;l<RV.vxrtd@Di&1ՃE!B"c#PZc\J -Y"e loS\4*CsL /Qަ17l,H0zl(T( U/8h/#%*VC"+RPb4Gu38Iڶ UB͊et4`4wW'raWJz*f>b«a=$5խlf:]/XbͬgLU 1B}%qpePP m\=NI O)0p]>w!5Mo=E'7,u1mQIy B$wQM9wp%@iͻeQDbېzȞH8WC)]ykE-w5a1ѡgF5\"]#nǺH@PG=&(KRi@ UVz~ّ ϩ8X)ؤBrURІ%VE7y#٩c* RhG4T^"[b$#hfHZPz_lHTe-IہDY_f程' f=n)&~`Jid/A &G;H&ͧ gg1306ԶmLZ79w+>Q\r mpԯGW?natsort-7.0.1/natsort/000077500000000000000000000000001361376133500147135ustar00rootroot00000000000000natsort-7.0.1/natsort/__init__.py000066400000000000000000000013751361376133500170320ustar00rootroot00000000000000# -*- coding: utf-8 -*- from natsort.natsort import ( as_ascii, as_utf8, decoder, humansorted, index_humansorted, index_natsorted, index_realsorted, natsort_key, natsort_keygen, natsorted, ns, numeric_regex_chooser, order_by_index, realsorted, ) from natsort.utils import chain_functions __version__ = "7.0.1" __all__ = [ "natsort_key", "natsort_keygen", "natsorted", "humansorted", "realsorted", "index_natsorted", "index_humansorted", "index_realsorted", "order_by_index", "decoder", "as_ascii", "as_utf8", "ns", "chain_functions", "numeric_regex_chooser", ] # Add the ns keys to this namespace for convenience. globals().update(ns._asdict()) natsort-7.0.1/natsort/__main__.py000066400000000000000000000215341361376133500170120ustar00rootroot00000000000000# -*- coding: utf-8 -*- import sys import natsort from natsort.utils import regex_chooser def main(*arguments): """ Performs a natural sort on entries given on the command-line. Arguments are read from sys.argv. """ from argparse import ArgumentParser, RawDescriptionHelpFormatter from textwrap import dedent parser = ArgumentParser( description=dedent(main.__doc__), formatter_class=RawDescriptionHelpFormatter ) parser.add_argument( "--version", action="version", version="%(prog)s {}".format(natsort.__version__), ) parser.add_argument( "-p", "--paths", default=False, action="store_true", help="Interpret the input as file paths. This is not " "strictly necessary to sort all file paths, but in cases " 'where there are OS-generated file paths like "Folder/" ' 'and "Folder (1)/", this option is needed to make the ' 'paths sorted in the order you expect ("Folder/" before ' '"Folder (1)/").', ) parser.add_argument( "-f", "--filter", nargs=2, type=float, metavar=("LOW", "HIGH"), action="append", help="Used for keeping only the entries that have a number " "falling in the given range.", ) parser.add_argument( "-F", "--reverse-filter", nargs=2, type=float, metavar=("LOW", "HIGH"), action="append", dest="reverse_filter", help="Used for excluding the entries that have a number " "falling in the given range.", ) parser.add_argument( "-e", "--exclude", type=float, action="append", help="Used to exclude an entry that contains a specific number.", ) parser.add_argument( "-r", "--reverse", action="store_true", default=False, help="Returns in reversed order.", ) parser.add_argument( "-t", "--number-type", "--number_type", dest="number_type", choices=("int", "float", "real", "f", "i", "r"), default="int", help='Choose the type of number to search for. "float" will search ' 'for floating-point numbers. "int" will only search for ' 'integers. "real" is a shortcut for "float" with --sign. ' '"i" is a synonym for "int", "f" is a synonym for ' '"float", and "r" is a synonym for "real".' "The default is %(default)s.", ) parser.add_argument( "--nosign", default=False, action="store_false", dest="signed", help='Do not consider "+" or "-" as part of a number, i.e. do not ' "take sign into consideration. This is the default.", ) parser.add_argument( "-s", "--sign", default=False, action="store_true", dest="signed", help='Consider "+" or "-" as part of a number, i.e. ' "take sign into consideration. The default is unsigned.", ) parser.add_argument( "--noexp", default=True, action="store_false", dest="exp", help="Do not consider an exponential as part of a number, i.e. 1e4, " 'would be considered as 1, "e", and 4, not as 10000. This only ' "effects the --number-type=float.", ) parser.add_argument( "-l", "--locale", action="store_true", default=False, help="Causes natsort to use locale-aware sorting. You will get the " "best results if you install PyICU.", ) parser.add_argument( "entries", nargs="*", default=sys.stdin, help="The entries to sort. Taken from stdin if nothing is given on " "the command line.", ) args = parser.parse_args(arguments or None) # Make sure the filter range is given properly. Does nothing if no filter args.filter = check_filters(args.filter) args.reverse_filter = check_filters(args.reverse_filter) # Remove trailing whitespace from all the entries entries = [e.strip() for e in args.entries] # Sort by directory then by file within directory and print. sort_and_print_entries(entries, args) def range_check(low, high): """ Verify that that given range has a low lower than the high. Parameters ---------- low : {float, int} high : {float, int} Returns ------- tuple : low, high Raises ------ ValueError Low is greater than or equal to high. """ if low >= high: raise ValueError("low >= high") else: return low, high def check_filters(filters): """ Execute range_check for every element of an iterable. Parameters ---------- filters : iterable The collection of filters to check. Each element must be a two-element tuple of floats or ints. Returns ------- The input as-is, or None if it evaluates to False. Raises ------ ValueError Low is greater than or equal to high for any element. """ if not filters: return None try: return [range_check(f[0], f[1]) for f in filters] except ValueError as err: raise ValueError("Error in --filter: " + str(err)) def keep_entry_range(entry, lows, highs, converter, regex): """ Check if an entry falls into a desired range. Every number in the entry will be extracted using *regex*, if any are within a given low to high range the entry will be kept. Parameters ---------- entry : str lows : iterable Collection of low values against which to compare the entry. highs : iterable Collection of high values against which to compare the entry. converter : callable Function to convert a string to a number. regex : regex object Regular expression to locate numbers in a string. Returns ------- True if the entry should be kept, False otherwise. """ return any( low <= converter(num) <= high for num in regex.findall(entry) for low, high in zip(lows, highs) ) def keep_entry_value(entry, values, converter, regex): """ Check if an entry does not match a given value. Every number in the entry will be extracted using *regex*, if any match a given value the entry will not be kept. Parameters ---------- entry : str values : iterable Collection of values against which to compare the entry. converter : callable Function to convert a string to a number. regex : regex object Regular expression to locate numbers in a string. Returns ------- True if the entry should be kept, False otherwise. """ return not any(converter(num) in values for num in regex.findall(entry)) def sort_and_print_entries(entries, args): """Sort the entries, applying the filters first if necessary.""" # Extract the proper number type. is_float = args.number_type in ("float", "real", "f", "r") signed = args.signed or args.number_type in ("real", "r") alg = ( natsort.ns.FLOAT * is_float | natsort.ns.SIGNED * signed | natsort.ns.NOEXP * (not args.exp) | natsort.ns.PATH * args.paths | natsort.ns.LOCALE * args.locale ) # Pre-remove entries that don't pass the filtering criteria # Make sure we use the same searching algorithm for filtering # as for sorting. do_filter = args.filter is not None or args.reverse_filter is not None if do_filter or args.exclude: inp_options = ( natsort.ns.FLOAT * is_float | natsort.ns.SIGNED * signed | natsort.ns.NOEXP * (not args.exp) ) regex = regex_chooser(inp_options) if args.filter is not None: lows, highs = ([f[0] for f in args.filter], [f[1] for f in args.filter]) entries = [ entry for entry in entries if keep_entry_range(entry, lows, highs, float, regex) ] if args.reverse_filter is not None: lows, highs = ( [f[0] for f in args.reverse_filter], [f[1] for f in args.reverse_filter], ) entries = [ entry for entry in entries if not keep_entry_range(entry, lows, highs, float, regex) ] if args.exclude: exclude = set(args.exclude) entries = [ entry for entry in entries if keep_entry_value(entry, exclude, float, regex) ] # Print off the sorted results for entry in natsort.natsorted(entries, reverse=args.reverse, alg=alg): print(entry) if __name__ == "__main__": try: main() except ValueError as a: sys.exit(str(a)) except KeyboardInterrupt: sys.exit(1) natsort-7.0.1/natsort/compat/000077500000000000000000000000001361376133500161765ustar00rootroot00000000000000natsort-7.0.1/natsort/compat/__init__.py000066400000000000000000000000001361376133500202750ustar00rootroot00000000000000natsort-7.0.1/natsort/compat/fake_fastnumbers.py000066400000000000000000000055551361376133500221010ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ This module is intended to replicate some of the functionality from the fastnumbers module in the event that module is not installed. """ # Std. lib imports. import unicodedata # Local imports. from natsort.unicode_numbers import decimal_chars NAN_INF = [ "INF", "INf", "Inf", "inF", "iNF", "InF", "inf", "iNf", "NAN", "nan", "NaN", "nAn", "naN", "NAn", "nAN", "Nan", ] NAN_INF.extend(["+" + x[:2] for x in NAN_INF] + ["-" + x[:2] for x in NAN_INF]) NAN_INF = frozenset(NAN_INF) ASCII_NUMS = "0123456789+-" POTENTIAL_FIRST_CHAR = frozenset(decimal_chars + list(ASCII_NUMS + ".")) # noinspection PyIncorrectDocstring def fast_float( x, key=lambda x: x, nan=None, _uni=unicodedata.numeric, _nan_inf=NAN_INF, _first_char=POTENTIAL_FIRST_CHAR, ): """ Convert a string to a float quickly, return input as-is if not possible. We don't need to accept all input that the real fast_int accepts because natsort is controlling what is passed to this function. Parameters ---------- x : str String to attempt to convert to a float. key : callable Single-argument function to apply to *x* if conversion fails. nan : object Value to return instead of NaN if NaN would be returned. Returns ------- *str* or *float* """ if x[0] in _first_char or x.lstrip()[:3] in _nan_inf: try: x = float(x) return nan if nan is not None and x != x else x except ValueError: try: return _uni(x, key(x)) if len(x) == 1 else key(x) except TypeError: # pragma: no cover return key(x) else: try: return _uni(x, key(x)) if len(x) == 1 else key(x) except TypeError: # pragma: no cover return key(x) # noinspection PyIncorrectDocstring def fast_int( x, key=lambda x: x, _uni=unicodedata.digit, _first_char=POTENTIAL_FIRST_CHAR, ): """ Convert a string to a int quickly, return input as-is if not possible. We don't need to accept all input that the real fast_int accepts because natsort is controlling what is passed to this function. Parameters ---------- x : str String to attempt to convert to an int. key : callable Single-argument function to apply to *x* if conversion fails. Returns ------- *str* or *int* """ if x[0] in _first_char: try: return int(x) except ValueError: try: return _uni(x, key(x)) if len(x) == 1 else key(x) except TypeError: # pragma: no cover return key(x) else: try: return _uni(x, key(x)) if len(x) == 1 else key(x) except TypeError: # pragma: no cover return key(x) natsort-7.0.1/natsort/compat/fastnumbers.py000066400000000000000000000012521361376133500211010ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Interface for natsort to access fastnumbers functions without having to worry if it is actually installed. """ from distutils.version import StrictVersion # If the user has fastnumbers installed, they will get great speed # benefits. If not, we use the simulated functions that come with natsort. try: # noinspection PyPackageRequirements from fastnumbers import fast_float, fast_int, __version__ as fn_ver # Require >= version 2.0.0. if StrictVersion(fn_ver) < StrictVersion("2.0.0"): raise ImportError # pragma: no cover except ImportError: from natsort.compat.fake_fastnumbers import fast_float, fast_int # noqa: F401 natsort-7.0.1/natsort/compat/locale.py000066400000000000000000000073621361376133500200170ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Interface for natsort to access locale functionality without having to worry about if it is using PyICU or the built-in locale. """ # Std. lib imports. import sys # This string should be sorted after any other byte string because # it contains the max unicode character repeated 20 times. # You would need some odd data to come after that. null_string = "" null_string_max = chr(sys.maxunicode) * 20 # strxfrm can be buggy (especially on BSD-based systems), # so prefer icu if available. try: # noqa: C901 import icu from locale import getlocale null_string_locale = b"" # This string should in theory be sorted after any other byte # string because it contains the max byte char repeated many times. # You would need some odd data to come after that. null_string_locale_max = b"x7f" * 50 def dumb_sort(): return False # If using icu, get the locale from the current global locale, def get_icu_locale(): try: return icu.Locale(".".join(getlocale())) except TypeError: # pragma: no cover return icu.Locale() def get_strxfrm(): return icu.Collator.createInstance(get_icu_locale()).getSortKey def get_thousands_sep(): sep = icu.DecimalFormatSymbols.kGroupingSeparatorSymbol return icu.DecimalFormatSymbols(get_icu_locale()).getSymbol(sep) def get_decimal_point(): sep = icu.DecimalFormatSymbols.kDecimalSeparatorSymbol return icu.DecimalFormatSymbols(get_icu_locale()).getSymbol(sep) except ImportError: import locale from locale import strxfrm null_string_locale = null_string null_string_locale_max = null_string_max # On some systems, locale is broken and does not sort in the expected # order. We will try to detect this and compensate. def dumb_sort(): return strxfrm("A") < strxfrm("a") def get_strxfrm(): return strxfrm def get_thousands_sep(): sep = locale.localeconv()["thousands_sep"] # If this locale library is broken, some of the thousands separator # characters are incorrectly blank. Here is a lookup table of the # corrections I am aware of. if dumb_sort(): try: loc = ".".join(locale.getlocale()) except TypeError: # No locale loaded, default to ',' return "," return { "de_DE.ISO8859-15": ".", "es_ES.ISO8859-1": ".", "de_AT.ISO8859-1": ".", "de_at": "\xa0", "nl_NL.UTF-8": ".", "es_es": ".", "fr_CH.ISO8859-15": "\xa0", "fr_CA.ISO8859-1": "\xa0", "de_CH.ISO8859-1": ".", "fr_FR.ISO8859-15": "\xa0", "nl_NL.ISO8859-1": ".", "ca_ES.UTF-8": ".", "nl_NL.ISO8859-15": ".", "de_ch": "'", "ca_es": ".", "de_AT.ISO8859-15": ".", "ca_ES.ISO8859-1": ".", "de_AT.UTF-8": ".", "es_ES.UTF-8": ".", "fr_fr": "\xa0", "es_ES.ISO8859-15": ".", "de_DE.ISO8859-1": ".", "nl_nl": ".", "fr_ch": "\xa0", "fr_ca": "\xa0", "de_DE.UTF-8": ".", "ca_ES.ISO8859-15": ".", "de_CH.ISO8859-15": ".", "fr_FR.ISO8859-1": "\xa0", "fr_CH.ISO8859-1": "\xa0", "de_de": ".", "fr_FR.UTF-8": "\xa0", "fr_CA.ISO8859-15": "\xa0", }.get(loc, sep) else: return sep def get_decimal_point(): return locale.localeconv()["decimal_point"] natsort-7.0.1/natsort/natsort.py000066400000000000000000000410141361376133500167570ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Along with ns_enum.py, this module contains all of the natsort public API. The majority of the "work" is defined in utils.py. """ from functools import partial from operator import itemgetter import natsort.compat.locale from natsort import utils from natsort.ns_enum import NS_DUMB, ns def decoder(encoding): """ Return a function that can be used to decode bytes to unicode. Parameters ---------- encoding : str The codec to use for decoding. This must be a valid unicode codec. Returns ------- decode_function A function that takes a single argument and attempts to decode it using the supplied codec. Any `UnicodeErrors` are raised. If the argument was not of `bytes` type, it is simply returned as-is. See Also -------- as_ascii as_utf8 Examples -------- >>> f = decoder('utf8') >>> f(b'bytes') == 'bytes' True >>> f(12345) == 12345 True >>> # On Python 3, without decoder this would return [b'a10', b'a2'] >>> natsorted([b'a10', b'a2'], key=decoder('utf8')) == [b'a2', b'a10'] True >>> # On Python 3, without decoder this would raise a TypeError. >>> natsorted([b'a10', 'a2'], key=decoder('utf8')) == ['a2', b'a10'] True """ return partial(utils.do_decoding, encoding=encoding) def as_ascii(s): """ Function to decode an input with the ASCII codec, or return as-is. Parameters ---------- s : object Returns ------- output If the input was of type `bytes`, the return value is a `str` decoded with the ASCII codec. Otherwise, the return value is identically the input. See Also -------- decoder """ return utils.do_decoding(s, "ascii") def as_utf8(s): """ Function to decode an input with the UTF-8 codec, or return as-is. Parameters ---------- s : object Returns ------- output If the input was of type `bytes`, the return value is a `str` decoded with the UTF-8 codec. Otherwise, the return value is identically the input. See Also -------- decoder """ return utils.do_decoding(s, "utf-8") def natsort_keygen(key=None, alg=ns.DEFAULT): """ Generate a key to sort strings and numbers naturally. This key is designed for use as the `key` argument to functions such as the `sorted` builtin. The user may customize the generated function with the arguments to `natsort_keygen`, including an optional `key` function. Parameters ---------- key : callable, optional A key used to manipulate the input value before parsing for numbers. It is **not** applied recursively. It should accept a single argument and return a single value. alg : ns enum, optional This option is used to control which algorithm `natsort` uses when sorting. For details into these options, please see the :class:`ns` class documentation. The default is `ns.INT`. Returns ------- out : function A function that parses input for natural sorting that is suitable for passing as the `key` argument to functions such as `sorted`. See Also -------- natsorted natsort_key Examples -------- `natsort_keygen` is a convenient way to create a custom key to sort lists in-place (for example).:: >>> a = ['num5.10', 'num-3', 'num5.3', 'num2'] >>> a.sort(key=natsort_keygen(alg=ns.REAL)) >>> a ['num-3', 'num2', 'num5.10', 'num5.3'] """ try: ns.DEFAULT | alg except TypeError: msg = "natsort_keygen: 'alg' argument must be from the enum 'ns'" raise ValueError(msg + ", got {}".format(str(alg))) # Add the NS_DUMB option if the locale library is broken. if alg & ns.LOCALEALPHA and natsort.compat.locale.dumb_sort(): alg |= NS_DUMB # Set some variables that will be passed to the factory functions if alg & ns.NUMAFTER: if alg & ns.LOCALEALPHA: sep = natsort.compat.locale.null_string_locale_max else: sep = natsort.compat.locale.null_string_max pre_sep = natsort.compat.locale.null_string_max else: if alg & ns.LOCALEALPHA: sep = natsort.compat.locale.null_string_locale else: sep = natsort.compat.locale.null_string pre_sep = natsort.compat.locale.null_string regex = utils.regex_chooser(alg) # Create the functions that will be used to split strings. input_transform = utils.input_string_transform_factory(alg) component_transform = utils.string_component_transform_factory(alg) final_transform = utils.final_data_transform_factory(alg, sep, pre_sep) # Create the high-level parsing functions for strings, bytes, and numbers. string_func = utils.parse_string_factory( alg, sep, regex.split, input_transform, component_transform, final_transform ) if alg & ns.PATH: string_func = utils.parse_path_factory(string_func) bytes_func = utils.parse_bytes_factory(alg) num_func = utils.parse_number_factory(alg, sep, pre_sep) # Return the natsort key with the parsing path pre-chosen. return partial( utils.natsort_key, key=key, string_func=string_func, bytes_func=bytes_func, num_func=num_func, ) # Exposed for simplicity if one needs the default natsort key. natsort_key = natsort_keygen() natsort_key.__doc__ = """\ natsort_key(val) The default natural sorting key. This is the output of :func:`natsort_keygen` with default values. See Also -------- natsort_keygen """ def natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT): """ Sorts an iterable naturally. Parameters ---------- seq : iterable The input to sort. key : callable, optional A key used to determine how to sort each element of the iterable. It is **not** applied recursively. It should accept a single argument and return a single value. reverse : {{True, False}}, optional Return the list in reversed sorted order. The default is `False`. alg : ns enum, optional This option is used to control which algorithm `natsort` uses when sorting. For details into these options, please see the :class:`ns` class documentation. The default is `ns.INT`. Returns ------- out: list The sorted input. See Also -------- natsort_keygen : Generates the key that makes natural sorting possible. realsorted : A wrapper for ``natsorted(seq, alg=ns.REAL)``. humansorted : A wrapper for ``natsorted(seq, alg=ns.LOCALE)``. index_natsorted : Returns the sorted indexes from `natsorted`. Examples -------- Use `natsorted` just like the builtin `sorted`:: >>> a = ['num3', 'num5', 'num2'] >>> natsorted(a) ['num2', 'num3', 'num5'] """ key = natsort_keygen(key, alg) return sorted(seq, reverse=reverse, key=key) def humansorted(seq, key=None, reverse=False, alg=ns.DEFAULT): """ Convenience function to properly sort non-numeric characters. This is a wrapper around ``natsorted(seq, alg=ns.LOCALE)``. Parameters ---------- seq : iterable The input to sort. key : callable, optional A key used to determine how to sort each element of the sequence. It is **not** applied recursively. It should accept a single argument and return a single value. reverse : {{True, False}}, optional Return the list in reversed sorted order. The default is `False`. alg : ns enum, optional This option is used to control which algorithm `natsort` uses when sorting. For details into these options, please see the :class:`ns` class documentation. The default is `ns.LOCALE`. Returns ------- out : list The sorted input. See Also -------- index_humansorted : Returns the sorted indexes from `humansorted`. Notes ----- Please read :ref:`locale_issues` before using `humansorted`. Examples -------- Use `humansorted` just like the builtin `sorted`:: >>> a = ['Apple', 'Banana', 'apple', 'banana'] >>> natsorted(a) ['Apple', 'Banana', 'apple', 'banana'] >>> humansorted(a) ['apple', 'Apple', 'banana', 'Banana'] """ return natsorted(seq, key, reverse, alg | ns.LOCALE) def realsorted(seq, key=None, reverse=False, alg=ns.DEFAULT): """ Convenience function to properly sort signed floats. A signed float in a string could be "a-5.7". This is a wrapper around ``natsorted(seq, alg=ns.REAL)``. The behavior of :func:`realsorted` for `natsort` version >= 4.0.0 was the default behavior of :func:`natsorted` for `natsort` version < 4.0.0. Parameters ---------- seq : iterable The input to sort. key : callable, optional A key used to determine how to sort each element of the sequence. It is **not** applied recursively. It should accept a single argument and return a single value. reverse : {{True, False}}, optional Return the list in reversed sorted order. The default is `False`. alg : ns enum, optional This option is used to control which algorithm `natsort` uses when sorting. For details into these options, please see the :class:`ns` class documentation. The default is `ns.REAL`. Returns ------- out : list The sorted input. See Also -------- index_realsorted : Returns the sorted indexes from `realsorted`. Examples -------- Use `realsorted` just like the builtin `sorted`:: >>> a = ['num5.10', 'num-3', 'num5.3', 'num2'] >>> natsorted(a) ['num2', 'num5.3', 'num5.10', 'num-3'] >>> realsorted(a) ['num-3', 'num2', 'num5.10', 'num5.3'] """ return natsorted(seq, key, reverse, alg | ns.REAL) def index_natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT): """ Determine the list of the indexes used to sort the input sequence. Sorts a sequence naturally, but returns a list of sorted the indexes and not the sorted list itself. This list of indexes can be used to sort multiple lists by the sorted order of the given sequence. Parameters ---------- seq : iterable The input to sort. key : callable, optional A key used to determine how to sort each element of the sequence. It is **not** applied recursively. It should accept a single argument and return a single value. reverse : {{True, False}}, optional Return the list in reversed sorted order. The default is `False`. alg : ns enum, optional This option is used to control which algorithm `natsort` uses when sorting. For details into these options, please see the :class:`ns` class documentation. The default is `ns.INT`. Returns ------- out : tuple The ordered indexes of the input. See Also -------- natsorted order_by_index Examples -------- Use index_natsorted if you want to sort multiple lists by the sorted order of one list:: >>> a = ['num3', 'num5', 'num2'] >>> b = ['foo', 'bar', 'baz'] >>> index = index_natsorted(a) >>> index [2, 0, 1] >>> # Sort both lists by the sort order of a >>> order_by_index(a, index) ['num2', 'num3', 'num5'] >>> order_by_index(b, index) ['baz', 'foo', 'bar'] """ if key is None: newkey = itemgetter(1) else: def newkey(x): return key(itemgetter(1)(x)) # Pair the index and sequence together, then sort by element index_seq_pair = [(x, y) for x, y in enumerate(seq)] index_seq_pair.sort(reverse=reverse, key=natsort_keygen(newkey, alg)) return [x for x, _ in index_seq_pair] def index_humansorted(seq, key=None, reverse=False, alg=ns.DEFAULT): """ This is a wrapper around ``index_natsorted(seq, alg=ns.LOCALE)``. Parameters ---------- seq: iterable The input to sort. key: callable, optional A key used to determine how to sort each element of the sequence. It is **not** applied recursively. It should accept a single argument and return a single value. reverse : {{True, False}}, optional Return the list in reversed sorted order. The default is `False`. alg : ns enum, optional This option is used to control which algorithm `natsort` uses when sorting. For details into these options, please see the :class:`ns` class documentation. The default is `ns.LOCALE`. Returns ------- out : tuple The ordered indexes of the input. See Also -------- humansorted order_by_index Notes ----- Please read :ref:`locale_issues` before using `humansorted`. Examples -------- Use `index_humansorted` just like the builtin `sorted`:: >>> a = ['Apple', 'Banana', 'apple', 'banana'] >>> index_humansorted(a) [2, 0, 3, 1] """ return index_natsorted(seq, key, reverse, alg | ns.LOCALE) def index_realsorted(seq, key=None, reverse=False, alg=ns.DEFAULT): """ This is a wrapper around ``index_natsorted(seq, alg=ns.REAL)``. Parameters ---------- seq: iterable The input to sort. key: callable, optional A key used to determine how to sort each element of the sequence. It is **not** applied recursively. It should accept a single argument and return a single value. reverse : {{True, False}}, optional Return the list in reversed sorted order. The default is `False`. alg : ns enum, optional This option is used to control which algorithm `natsort` uses when sorting. For details into these options, please see the :class:`ns` class documentation. The default is `ns.REAL`. Returns ------- out : tuple The ordered indexes of the input. See Also -------- realsorted order_by_index Examples -------- Use `index_realsorted` just like the builtin `sorted`:: >>> a = ['num5.10', 'num-3', 'num5.3', 'num2'] >>> index_realsorted(a) [1, 3, 0, 2] """ return index_natsorted(seq, key, reverse, alg | ns.REAL) # noinspection PyShadowingBuiltins,PyUnresolvedReferences def order_by_index(seq, index, iter=False): """ Order a given sequence by an index sequence. The output of `index_natsorted` is a sequence of integers (index) that correspond to how its input sequence **would** be sorted. The idea is that this index can be used to reorder multiple sequences by the sorted order of the first sequence. This function is a convenient wrapper to apply this ordering to a sequence. Parameters ---------- seq : sequence The sequence to order. index : iterable The iterable that indicates how to order `seq`. It should be the same length as `seq` and consist of integers only. iter : {{True, False}}, optional If `True`, the ordered sequence is returned as a iterator; otherwise it is returned as a list. The default is `False`. Returns ------- out : {{list, iterator}} The sequence ordered by `index`, as a `list` or as an iterator (depending on the value of `iter`). See Also -------- index_natsorted index_humansorted index_realsorted Examples -------- `order_by_index` is a convenience function that helps you apply the result of `index_natsorted`:: >>> a = ['num3', 'num5', 'num2'] >>> b = ['foo', 'bar', 'baz'] >>> index = index_natsorted(a) >>> index [2, 0, 1] >>> # Sort both lists by the sort order of a >>> order_by_index(a, index) ['num2', 'num3', 'num5'] >>> order_by_index(b, index) ['baz', 'foo', 'bar'] """ return (seq[i] for i in index) if iter else [seq[i] for i in index] def numeric_regex_chooser(alg): """ Select an appropriate regex for the type of number of interest. Parameters ---------- alg : ns enum Used to indicate the regular expression to select. Returns ------- regex : str Regular expression string that matches the desired number type. """ # Remove the leading and trailing parens return utils.regex_chooser(alg).pattern[1:-1] natsort-7.0.1/natsort/ns_enum.py000066400000000000000000000167121361376133500167400ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ This module defines the "ns" enum for natsort is used to determine what algorithm natsort uses. """ import collections # The below are the base ns options. The values will be stored as powers # of two so bitmasks can be used to extract the user's requested options. enum_options = [ "FLOAT", "SIGNED", "NOEXP", "PATH", "LOCALEALPHA", "LOCALENUM", "IGNORECASE", "LOWERCASEFIRST", "GROUPLETTERS", "UNGROUPLETTERS", "NANLAST", "COMPATIBILITYNORMALIZE", "NUMAFTER", ] # Following were previously options but are now defaults. enum_do_nothing = ["DEFAULT", "INT", "UNSIGNED"] # The following are bitwise-OR combinations of other fields. enum_combos = [("REAL", ("FLOAT", "SIGNED")), ("LOCALE", ("LOCALEALPHA", "LOCALENUM"))] # The following are aliases for other fields. enum_aliases = [ ("I", "INT"), ("U", "UNSIGNED"), ("F", "FLOAT"), ("S", "SIGNED"), ("R", "REAL"), ("N", "NOEXP"), ("P", "PATH"), ("LA", "LOCALEALPHA"), ("LN", "LOCALENUM"), ("L", "LOCALE"), ("IC", "IGNORECASE"), ("LF", "LOWERCASEFIRST"), ("G", "GROUPLETTERS"), ("UG", "UNGROUPLETTERS"), ("C", "UNGROUPLETTERS"), ("CAPITALFIRST", "UNGROUPLETTERS"), ("NL", "NANLAST"), ("CN", "COMPATIBILITYNORMALIZE"), ("NA", "NUMAFTER"), ] # Construct the list of bitwise distinct enums with their fields. enum_fields = collections.OrderedDict( (name, 1 << i) for i, name in enumerate(enum_options) ) enum_fields.update((name, 0) for name in enum_do_nothing) for name, combo in enum_combos: combined_value = enum_fields[combo[0]] for combo_name in combo[1:]: combined_value |= enum_fields[combo_name] enum_fields[name] = combined_value enum_fields.update( (alias, enum_fields[name]) for alias, name in enum_aliases ) # Subclass the namedtuple to improve the docstring. # noinspection PyUnresolvedReferences class _NSEnum(collections.namedtuple("_NSEnum", enum_fields.keys())): """ Enum to control the `natsort` algorithm. This class acts like an enum to control the `natsort` algorithm. The user may select several options simultaneously by or'ing the options together. For example, to choose ``ns.INT``, ``ns.PATH``, and ``ns.LOCALE``, you could do ``ns.INT | ns.LOCALE | ns.PATH``. Each function in the :mod:`natsort` package has an `alg` option that accepts this enum to allow fine control over how your input is sorted. Each option has a shortened 1- or 2-letter form. .. note:: Please read :ref:`locale_issues` before using ``ns.LOCALE``. Attributes ---------- INT, I (default) The default - parse numbers as integers. FLOAT, F Tell `natsort` to parse numbers as floats. UNSIGNED, U (default) Tell `natsort` to ignore any sign (i.e. "-" or "+") to the immediate left of a number. This is the default. SIGNED, S Tell `natsort` to take into account any sign (i.e. "-" or "+") to the immediate left of a number. REAL, R This is a shortcut for ``ns.FLOAT | ns.SIGNED``, which is useful when attempting to sort real numbers. NOEXP, N Tell `natsort` to not search for exponents as part of a float number. For example, with `NOEXP` the number "5.6E5" would be interpreted as `5.6`, `"E"`, and `5` instead of `560000`. NUMAFTER, NA Tell `natsort` to sort numbers after non-numbers. By default numbers will be ordered before non-numbers. PATH, P Tell `natsort` to interpret strings as filesystem paths, so they will be split according to the filesystem separator (i.e. '/' on UNIX, '\\' on Windows), as well as splitting on the file extension, if any. Without this, lists of file paths like ``['Folder/', 'Folder (1)/', 'Folder (10)/']`` will not be sorted properly; 'Folder/' will be placed at the end, not at the front. It is the same as setting the old `as_path` option to `True`. COMPATIBILITYNORMALIZE, CN Use the "NFKD" unicode normalization form on input rather than the default "NFD". This will transform characters such as '⑦' into '7'. Please see https://stackoverflow.com/a/7934397/1399279, https://stackoverflow.com/a/7931547/1399279, and https://unicode.org/reports/tr15/ for full details into unicode normalization. LOCALE, L Tell `natsort` to be locale-aware when sorting. This includes both proper sorting of alphabetical characters as well as proper handling of locale-dependent decimal separators and thousands separators. This is a shortcut for ``ns.LOCALEALPHA | ns.LOCALENUM``. Your sorting results will vary depending on your current locale. LOCALEALPHA, LA Tell `natsort` to be locale-aware when sorting, but only for alphabetical characters. LOCALENUM, LN Tell `natsort` to be locale-aware when sorting, but only for decimal separators and thousands separators. IGNORECASE, IC Tell `natsort` to ignore case when sorting. For example, ``['Banana', 'apple', 'banana', 'Apple']`` would be sorted as ``['apple', 'Apple', 'Banana', 'banana']``. LOWERCASEFIRST, LF Tell `natsort` to put lowercase letters before uppercase letters when sorting. For example, ``['Banana', 'apple', 'banana', 'Apple']`` would be sorted as ``['apple', 'banana', 'Apple', 'Banana']`` (the default order would be ``['Apple', 'Banana', 'apple', 'banana']`` which is the order from a purely ordinal sort). Useless when used with `IGNORECASE`. Please note that if used with ``LOCALE``, this actually has the reverse effect and will put uppercase first (this is because ``LOCALE`` already puts lowercase first); you may use this to your advantage if you need to modify the order returned with ``LOCALE``. GROUPLETTERS, G Tell `natsort` to group lowercase and uppercase letters together when sorting. For example, ``['Banana', 'apple', 'banana', 'Apple']`` would be sorted as ``['Apple', 'apple', 'Banana', 'banana']``. Useless when used with `IGNORECASE`; use with `LOWERCASEFIRST` to reverse the order of upper and lower case. Generally not needed with `LOCALE`. CAPITALFIRST, C Only used when `LOCALE` is enabled. Tell `natsort` to put all capitalized words before non-capitalized words. This is essentially the inverse of `GROUPLETTERS`, and is the default Python sorting behavior without `LOCALE`. UNGROUPLETTERS, UG An alias for `CAPITALFIRST`. NANLAST, NL If an NaN shows up in the input, this instructs `natsort` to treat these as +Infinity and place them after all the other numbers. By default, an NaN be treated as -Infinity and be placed first. Notes ----- If you prefer to use `import natsort as ns` as opposed to `from natsort import natsorted, ns`, the `ns` options are available as top-level imports. >>> import natsort as ns >>> a = ['num5.10', 'num-3', 'num5.3', 'num2'] >>> ns.natsorted(a, alg=ns.REAL) == ns.natsorted(a, alg=ns.ns.REAL) True """ # Here is where the instance of the ns enum that will be exported is created. # It is a poor-man's singleton. ns = _NSEnum(*enum_fields.values()) # The below is private for internal use only. NS_DUMB = 1 << 31 natsort-7.0.1/natsort/unicode_numbers.py000066400000000000000000000023761361376133500204560ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Pre-determine the collection of unicode decimals, digits, and numerals. """ import unicodedata from natsort.unicode_numeric_hex import numeric_hex # Convert each hex into the literal Unicode character. # Stop if a ValueError is raised in case of a narrow Unicode build. # The extra check with unicodedata is in case this Python version # does not support some characters. numeric_chars = [] for a in numeric_hex: try: character = chr(a) except ValueError: # pragma: no cover break if unicodedata.numeric(character, None) is None: continue # pragma: no cover numeric_chars.append(character) # The digit characters are a subset of the numerals. digit_chars = [a for a in numeric_chars if unicodedata.digit(a, None) is not None] # The decimal characters are a subset of the numberals # (probably of the digits, but let's be safe). decimal_chars = [a for a in numeric_chars if unicodedata.decimal(a, None) is not None] # Create a single string with the above data. decimals = "".join(decimal_chars) digits = "".join(digit_chars) numeric = "".join(numeric_chars) digits_no_decimals = "".join([x for x in digits if x not in decimals]) numeric_no_decimals = "".join([x for x in numeric if x not in decimals]) natsort-7.0.1/natsort/unicode_numeric_hex.py000066400000000000000000000555751361376133500213220ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Contains all possible non-ASCII unicode numbers. """ # Rather than determine what unicode characters are numeric on the fly which # would incur a startup runtime penalty, the hex values are hard-coded below. numeric_hex = ( 0xB2, 0xB3, 0xB9, 0xBC, 0xBD, 0xBE, 0x660, 0x661, 0x662, 0x663, 0x664, 0x665, 0x666, 0x667, 0x668, 0x669, 0x6F0, 0x6F1, 0x6F2, 0x6F3, 0x6F4, 0x6F5, 0x6F6, 0x6F7, 0x6F8, 0x6F9, 0x7C0, 0x7C1, 0x7C2, 0x7C3, 0x7C4, 0x7C5, 0x7C6, 0x7C7, 0x7C8, 0x7C9, 0x966, 0x967, 0x968, 0x969, 0x96A, 0x96B, 0x96C, 0x96D, 0x96E, 0x96F, 0x9E6, 0x9E7, 0x9E8, 0x9E9, 0x9EA, 0x9EB, 0x9EC, 0x9ED, 0x9EE, 0x9EF, 0x9F4, 0x9F5, 0x9F6, 0x9F7, 0x9F8, 0x9F9, 0xA66, 0xA67, 0xA68, 0xA69, 0xA6A, 0xA6B, 0xA6C, 0xA6D, 0xA6E, 0xA6F, 0xAE6, 0xAE7, 0xAE8, 0xAE9, 0xAEA, 0xAEB, 0xAEC, 0xAED, 0xAEE, 0xAEF, 0xB66, 0xB67, 0xB68, 0xB69, 0xB6A, 0xB6B, 0xB6C, 0xB6D, 0xB6E, 0xB6F, 0xB72, 0xB73, 0xB74, 0xB75, 0xB76, 0xB77, 0xBE6, 0xBE7, 0xBE8, 0xBE9, 0xBEA, 0xBEB, 0xBEC, 0xBED, 0xBEE, 0xBEF, 0xBF0, 0xBF1, 0xBF2, 0xC66, 0xC67, 0xC68, 0xC69, 0xC6A, 0xC6B, 0xC6C, 0xC6D, 0xC6E, 0xC6F, 0xC78, 0xC79, 0xC7A, 0xC7B, 0xC7C, 0xC7D, 0xC7E, 0xCE6, 0xCE7, 0xCE8, 0xCE9, 0xCEA, 0xCEB, 0xCEC, 0xCED, 0xCEE, 0xCEF, 0xD58, 0xD59, 0xD5A, 0xD5B, 0xD5C, 0xD5D, 0xD5E, 0xD66, 0xD67, 0xD68, 0xD69, 0xD6A, 0xD6B, 0xD6C, 0xD6D, 0xD6E, 0xD6F, 0xD70, 0xD71, 0xD72, 0xD73, 0xD74, 0xD75, 0xD76, 0xD77, 0xD78, 0xDE6, 0xDE7, 0xDE8, 0xDE9, 0xDEA, 0xDEB, 0xDEC, 0xDED, 0xDEE, 0xDEF, 0xE50, 0xE51, 0xE52, 0xE53, 0xE54, 0xE55, 0xE56, 0xE57, 0xE58, 0xE59, 0xED0, 0xED1, 0xED2, 0xED3, 0xED4, 0xED5, 0xED6, 0xED7, 0xED8, 0xED9, 0xF20, 0xF21, 0xF22, 0xF23, 0xF24, 0xF25, 0xF26, 0xF27, 0xF28, 0xF29, 0xF2A, 0xF2B, 0xF2C, 0xF2D, 0xF2E, 0xF2F, 0xF30, 0xF31, 0xF32, 0xF33, 0x1040, 0x1041, 0x1042, 0x1043, 0x1044, 0x1045, 0x1046, 0x1047, 0x1048, 0x1049, 0x1090, 0x1091, 0x1092, 0x1093, 0x1094, 0x1095, 0x1096, 0x1097, 0x1098, 0x1099, 0x1369, 0x136A, 0x136B, 0x136C, 0x136D, 0x136E, 0x136F, 0x1370, 0x1371, 0x1372, 0x1373, 0x1374, 0x1375, 0x1376, 0x1377, 0x1378, 0x1379, 0x137A, 0x137B, 0x137C, 0x16EE, 0x16EF, 0x16F0, 0x17E0, 0x17E1, 0x17E2, 0x17E3, 0x17E4, 0x17E5, 0x17E6, 0x17E7, 0x17E8, 0x17E9, 0x17F0, 0x17F1, 0x17F2, 0x17F3, 0x17F4, 0x17F5, 0x17F6, 0x17F7, 0x17F8, 0x17F9, 0x1810, 0x1811, 0x1812, 0x1813, 0x1814, 0x1815, 0x1816, 0x1817, 0x1818, 0x1819, 0x1946, 0x1947, 0x1948, 0x1949, 0x194A, 0x194B, 0x194C, 0x194D, 0x194E, 0x194F, 0x19D0, 0x19D1, 0x19D2, 0x19D3, 0x19D4, 0x19D5, 0x19D6, 0x19D7, 0x19D8, 0x19D9, 0x19DA, 0x1A80, 0x1A81, 0x1A82, 0x1A83, 0x1A84, 0x1A85, 0x1A86, 0x1A87, 0x1A88, 0x1A89, 0x1A90, 0x1A91, 0x1A92, 0x1A93, 0x1A94, 0x1A95, 0x1A96, 0x1A97, 0x1A98, 0x1A99, 0x1B50, 0x1B51, 0x1B52, 0x1B53, 0x1B54, 0x1B55, 0x1B56, 0x1B57, 0x1B58, 0x1B59, 0x1BB0, 0x1BB1, 0x1BB2, 0x1BB3, 0x1BB4, 0x1BB5, 0x1BB6, 0x1BB7, 0x1BB8, 0x1BB9, 0x1C40, 0x1C41, 0x1C42, 0x1C43, 0x1C44, 0x1C45, 0x1C46, 0x1C47, 0x1C48, 0x1C49, 0x1C50, 0x1C51, 0x1C52, 0x1C53, 0x1C54, 0x1C55, 0x1C56, 0x1C57, 0x1C58, 0x1C59, 0x2070, 0x2074, 0x2075, 0x2076, 0x2077, 0x2078, 0x2079, 0x2080, 0x2081, 0x2082, 0x2083, 0x2084, 0x2085, 0x2086, 0x2087, 0x2088, 0x2089, 0x2150, 0x2151, 0x2152, 0x2153, 0x2154, 0x2155, 0x2156, 0x2157, 0x2158, 0x2159, 0x215A, 0x215B, 0x215C, 0x215D, 0x215E, 0x215F, 0x2160, 0x2161, 0x2162, 0x2163, 0x2164, 0x2165, 0x2166, 0x2167, 0x2168, 0x2169, 0x216A, 0x216B, 0x216C, 0x216D, 0x216E, 0x216F, 0x2170, 0x2171, 0x2172, 0x2173, 0x2174, 0x2175, 0x2176, 0x2177, 0x2178, 0x2179, 0x217A, 0x217B, 0x217C, 0x217D, 0x217E, 0x217F, 0x2180, 0x2181, 0x2182, 0x2185, 0x2186, 0x2187, 0x2188, 0x2189, 0x2460, 0x2461, 0x2462, 0x2463, 0x2464, 0x2465, 0x2466, 0x2467, 0x2468, 0x2469, 0x246A, 0x246B, 0x246C, 0x246D, 0x246E, 0x246F, 0x2470, 0x2471, 0x2472, 0x2473, 0x2474, 0x2475, 0x2476, 0x2477, 0x2478, 0x2479, 0x247A, 0x247B, 0x247C, 0x247D, 0x247E, 0x247F, 0x2480, 0x2481, 0x2482, 0x2483, 0x2484, 0x2485, 0x2486, 0x2487, 0x2488, 0x2489, 0x248A, 0x248B, 0x248C, 0x248D, 0x248E, 0x248F, 0x2490, 0x2491, 0x2492, 0x2493, 0x2494, 0x2495, 0x2496, 0x2497, 0x2498, 0x2499, 0x249A, 0x249B, 0x24EA, 0x24EB, 0x24EC, 0x24ED, 0x24EE, 0x24EF, 0x24F0, 0x24F1, 0x24F2, 0x24F3, 0x24F4, 0x24F5, 0x24F6, 0x24F7, 0x24F8, 0x24F9, 0x24FA, 0x24FB, 0x24FC, 0x24FD, 0x24FE, 0x24FF, 0x2776, 0x2777, 0x2778, 0x2779, 0x277A, 0x277B, 0x277C, 0x277D, 0x277E, 0x277F, 0x2780, 0x2781, 0x2782, 0x2783, 0x2784, 0x2785, 0x2786, 0x2787, 0x2788, 0x2789, 0x278A, 0x278B, 0x278C, 0x278D, 0x278E, 0x278F, 0x2790, 0x2791, 0x2792, 0x2793, 0x2CFD, 0x3007, 0x3021, 0x3022, 0x3023, 0x3024, 0x3025, 0x3026, 0x3027, 0x3028, 0x3029, 0x3038, 0x3039, 0x303A, 0x3192, 0x3193, 0x3194, 0x3195, 0x3220, 0x3221, 0x3222, 0x3223, 0x3224, 0x3225, 0x3226, 0x3227, 0x3228, 0x3229, 0x3248, 0x3249, 0x324A, 0x324B, 0x324C, 0x324D, 0x324E, 0x324F, 0x3251, 0x3252, 0x3253, 0x3254, 0x3255, 0x3256, 0x3257, 0x3258, 0x3259, 0x325A, 0x325B, 0x325C, 0x325D, 0x325E, 0x325F, 0x3280, 0x3281, 0x3282, 0x3283, 0x3284, 0x3285, 0x3286, 0x3287, 0x3288, 0x3289, 0x32B1, 0x32B2, 0x32B3, 0x32B4, 0x32B5, 0x32B6, 0x32B7, 0x32B8, 0x32B9, 0x32BA, 0x32BB, 0x32BC, 0x32BD, 0x32BE, 0x32BF, 0x3405, 0x3483, 0x382A, 0x3B4D, 0x4E00, 0x4E03, 0x4E07, 0x4E09, 0x4E5D, 0x4E8C, 0x4E94, 0x4E96, 0x4EBF, 0x4EC0, 0x4EDF, 0x4EE8, 0x4F0D, 0x4F70, 0x5104, 0x5146, 0x5169, 0x516B, 0x516D, 0x5341, 0x5343, 0x5344, 0x5345, 0x534C, 0x53C1, 0x53C2, 0x53C3, 0x53C4, 0x56DB, 0x58F1, 0x58F9, 0x5E7A, 0x5EFE, 0x5EFF, 0x5F0C, 0x5F0D, 0x5F0E, 0x5F10, 0x62FE, 0x634C, 0x67D2, 0x6F06, 0x7396, 0x767E, 0x8086, 0x842C, 0x8CAE, 0x8CB3, 0x8D30, 0x9621, 0x9646, 0x964C, 0x9678, 0x96F6, 0xA620, 0xA621, 0xA622, 0xA623, 0xA624, 0xA625, 0xA626, 0xA627, 0xA628, 0xA629, 0xA6E6, 0xA6E7, 0xA6E8, 0xA6E9, 0xA6EA, 0xA6EB, 0xA6EC, 0xA6ED, 0xA6EE, 0xA6EF, 0xA830, 0xA831, 0xA832, 0xA833, 0xA834, 0xA835, 0xA8D0, 0xA8D1, 0xA8D2, 0xA8D3, 0xA8D4, 0xA8D5, 0xA8D6, 0xA8D7, 0xA8D8, 0xA8D9, 0xA900, 0xA901, 0xA902, 0xA903, 0xA904, 0xA905, 0xA906, 0xA907, 0xA908, 0xA909, 0xA9D0, 0xA9D1, 0xA9D2, 0xA9D3, 0xA9D4, 0xA9D5, 0xA9D6, 0xA9D7, 0xA9D8, 0xA9D9, 0xA9F0, 0xA9F1, 0xA9F2, 0xA9F3, 0xA9F4, 0xA9F5, 0xA9F6, 0xA9F7, 0xA9F8, 0xA9F9, 0xAA50, 0xAA51, 0xAA52, 0xAA53, 0xAA54, 0xAA55, 0xAA56, 0xAA57, 0xAA58, 0xAA59, 0xABF0, 0xABF1, 0xABF2, 0xABF3, 0xABF4, 0xABF5, 0xABF6, 0xABF7, 0xABF8, 0xABF9, 0xF96B, 0xF973, 0xF978, 0xF9B2, 0xF9D1, 0xF9D3, 0xF9FD, 0xFF10, 0xFF11, 0xFF12, 0xFF13, 0xFF14, 0xFF15, 0xFF16, 0xFF17, 0xFF18, 0xFF19, 0x10107, 0x10108, 0x10109, 0x1010A, 0x1010B, 0x1010C, 0x1010D, 0x1010E, 0x1010F, 0x10110, 0x10111, 0x10112, 0x10113, 0x10114, 0x10115, 0x10116, 0x10117, 0x10118, 0x10119, 0x1011A, 0x1011B, 0x1011C, 0x1011D, 0x1011E, 0x1011F, 0x10120, 0x10121, 0x10122, 0x10123, 0x10124, 0x10125, 0x10126, 0x10127, 0x10128, 0x10129, 0x1012A, 0x1012B, 0x1012C, 0x1012D, 0x1012E, 0x1012F, 0x10130, 0x10131, 0x10132, 0x10133, 0x10140, 0x10141, 0x10142, 0x10143, 0x10144, 0x10145, 0x10146, 0x10147, 0x10148, 0x10149, 0x1014A, 0x1014B, 0x1014C, 0x1014D, 0x1014E, 0x1014F, 0x10150, 0x10151, 0x10152, 0x10153, 0x10154, 0x10155, 0x10156, 0x10157, 0x10158, 0x10159, 0x1015A, 0x1015B, 0x1015C, 0x1015D, 0x1015E, 0x1015F, 0x10160, 0x10161, 0x10162, 0x10163, 0x10164, 0x10165, 0x10166, 0x10167, 0x10168, 0x10169, 0x1016A, 0x1016B, 0x1016C, 0x1016D, 0x1016E, 0x1016F, 0x10170, 0x10171, 0x10172, 0x10173, 0x10174, 0x10175, 0x10176, 0x10177, 0x10178, 0x1018A, 0x1018B, 0x102E1, 0x102E2, 0x102E3, 0x102E4, 0x102E5, 0x102E6, 0x102E7, 0x102E8, 0x102E9, 0x102EA, 0x102EB, 0x102EC, 0x102ED, 0x102EE, 0x102EF, 0x102F0, 0x102F1, 0x102F2, 0x102F3, 0x102F4, 0x102F5, 0x102F6, 0x102F7, 0x102F8, 0x102F9, 0x102FA, 0x102FB, 0x10320, 0x10321, 0x10322, 0x10323, 0x10341, 0x1034A, 0x103D1, 0x103D2, 0x103D3, 0x103D4, 0x103D5, 0x104A0, 0x104A1, 0x104A2, 0x104A3, 0x104A4, 0x104A5, 0x104A6, 0x104A7, 0x104A8, 0x104A9, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10879, 0x1087A, 0x1087B, 0x1087C, 0x1087D, 0x1087E, 0x1087F, 0x108A7, 0x108A8, 0x108A9, 0x108AA, 0x108AB, 0x108AC, 0x108AD, 0x108AE, 0x108AF, 0x108FB, 0x108FC, 0x108FD, 0x108FE, 0x108FF, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x109BC, 0x109BD, 0x109C0, 0x109C1, 0x109C2, 0x109C3, 0x109C4, 0x109C5, 0x109C6, 0x109C7, 0x109C8, 0x109C9, 0x109CA, 0x109CB, 0x109CC, 0x109CD, 0x109CE, 0x109CF, 0x109D2, 0x109D3, 0x109D4, 0x109D5, 0x109D6, 0x109D7, 0x109D8, 0x109D9, 0x109DA, 0x109DB, 0x109DC, 0x109DD, 0x109DE, 0x109DF, 0x109E0, 0x109E1, 0x109E2, 0x109E3, 0x109E4, 0x109E5, 0x109E6, 0x109E7, 0x109E8, 0x109E9, 0x109EA, 0x109EB, 0x109EC, 0x109ED, 0x109EE, 0x109EF, 0x109F0, 0x109F1, 0x109F2, 0x109F3, 0x109F4, 0x109F5, 0x109F6, 0x109F7, 0x109F8, 0x109F9, 0x109FA, 0x109FB, 0x109FC, 0x109FD, 0x109FE, 0x109FF, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A48, 0x10A7D, 0x10A7E, 0x10A9D, 0x10A9E, 0x10A9F, 0x10AEB, 0x10AEC, 0x10AED, 0x10AEE, 0x10AEF, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10BA9, 0x10BAA, 0x10BAB, 0x10BAC, 0x10BAD, 0x10BAE, 0x10BAF, 0x10CFA, 0x10CFB, 0x10CFC, 0x10CFD, 0x10CFE, 0x10CFF, 0x10D30, 0x10D31, 0x10D32, 0x10D33, 0x10D34, 0x10D35, 0x10D36, 0x10D37, 0x10D38, 0x10D39, 0x10E60, 0x10E61, 0x10E62, 0x10E63, 0x10E64, 0x10E65, 0x10E66, 0x10E67, 0x10E68, 0x10E69, 0x10E6A, 0x10E6B, 0x10E6C, 0x10E6D, 0x10E6E, 0x10E6F, 0x10E70, 0x10E71, 0x10E72, 0x10E73, 0x10E74, 0x10E75, 0x10E76, 0x10E77, 0x10E78, 0x10E79, 0x10E7A, 0x10E7B, 0x10E7C, 0x10E7D, 0x10E7E, 0x10F1D, 0x10F1E, 0x10F1F, 0x10F20, 0x10F21, 0x10F22, 0x10F23, 0x10F24, 0x10F25, 0x10F26, 0x10F51, 0x10F52, 0x10F53, 0x10F54, 0x11052, 0x11053, 0x11054, 0x11055, 0x11056, 0x11057, 0x11058, 0x11059, 0x1105A, 0x1105B, 0x1105C, 0x1105D, 0x1105E, 0x1105F, 0x11060, 0x11061, 0x11062, 0x11063, 0x11064, 0x11065, 0x11066, 0x11067, 0x11068, 0x11069, 0x1106A, 0x1106B, 0x1106C, 0x1106D, 0x1106E, 0x1106F, 0x110F0, 0x110F1, 0x110F2, 0x110F3, 0x110F4, 0x110F5, 0x110F6, 0x110F7, 0x110F8, 0x110F9, 0x11136, 0x11137, 0x11138, 0x11139, 0x1113A, 0x1113B, 0x1113C, 0x1113D, 0x1113E, 0x1113F, 0x111D0, 0x111D1, 0x111D2, 0x111D3, 0x111D4, 0x111D5, 0x111D6, 0x111D7, 0x111D8, 0x111D9, 0x111E1, 0x111E2, 0x111E3, 0x111E4, 0x111E5, 0x111E6, 0x111E7, 0x111E8, 0x111E9, 0x111EA, 0x111EB, 0x111EC, 0x111ED, 0x111EE, 0x111EF, 0x111F0, 0x111F1, 0x111F2, 0x111F3, 0x111F4, 0x112F0, 0x112F1, 0x112F2, 0x112F3, 0x112F4, 0x112F5, 0x112F6, 0x112F7, 0x112F8, 0x112F9, 0x11450, 0x11451, 0x11452, 0x11453, 0x11454, 0x11455, 0x11456, 0x11457, 0x11458, 0x11459, 0x114D0, 0x114D1, 0x114D2, 0x114D3, 0x114D4, 0x114D5, 0x114D6, 0x114D7, 0x114D8, 0x114D9, 0x11650, 0x11651, 0x11652, 0x11653, 0x11654, 0x11655, 0x11656, 0x11657, 0x11658, 0x11659, 0x116C0, 0x116C1, 0x116C2, 0x116C3, 0x116C4, 0x116C5, 0x116C6, 0x116C7, 0x116C8, 0x116C9, 0x11730, 0x11731, 0x11732, 0x11733, 0x11734, 0x11735, 0x11736, 0x11737, 0x11738, 0x11739, 0x1173A, 0x1173B, 0x118E0, 0x118E1, 0x118E2, 0x118E3, 0x118E4, 0x118E5, 0x118E6, 0x118E7, 0x118E8, 0x118E9, 0x118EA, 0x118EB, 0x118EC, 0x118ED, 0x118EE, 0x118EF, 0x118F0, 0x118F1, 0x118F2, 0x11C50, 0x11C51, 0x11C52, 0x11C53, 0x11C54, 0x11C55, 0x11C56, 0x11C57, 0x11C58, 0x11C59, 0x11C5A, 0x11C5B, 0x11C5C, 0x11C5D, 0x11C5E, 0x11C5F, 0x11C60, 0x11C61, 0x11C62, 0x11C63, 0x11C64, 0x11C65, 0x11C66, 0x11C67, 0x11C68, 0x11C69, 0x11C6A, 0x11C6B, 0x11C6C, 0x11D50, 0x11D51, 0x11D52, 0x11D53, 0x11D54, 0x11D55, 0x11D56, 0x11D57, 0x11D58, 0x11D59, 0x11DA0, 0x11DA1, 0x11DA2, 0x11DA3, 0x11DA4, 0x11DA5, 0x11DA6, 0x11DA7, 0x11DA8, 0x11DA9, 0x11FC0, 0x11FC1, 0x11FC2, 0x11FC3, 0x11FC4, 0x11FC5, 0x11FC6, 0x11FC7, 0x11FC8, 0x11FC9, 0x11FCA, 0x11FCB, 0x11FCC, 0x11FCD, 0x11FCE, 0x11FCF, 0x11FD0, 0x11FD1, 0x11FD2, 0x11FD3, 0x11FD4, 0x12400, 0x12401, 0x12402, 0x12403, 0x12404, 0x12405, 0x12406, 0x12407, 0x12408, 0x12409, 0x1240A, 0x1240B, 0x1240C, 0x1240D, 0x1240E, 0x1240F, 0x12410, 0x12411, 0x12412, 0x12413, 0x12414, 0x12415, 0x12416, 0x12417, 0x12418, 0x12419, 0x1241A, 0x1241B, 0x1241C, 0x1241D, 0x1241E, 0x1241F, 0x12420, 0x12421, 0x12422, 0x12423, 0x12424, 0x12425, 0x12426, 0x12427, 0x12428, 0x12429, 0x1242A, 0x1242B, 0x1242C, 0x1242D, 0x1242E, 0x1242F, 0x12430, 0x12431, 0x12432, 0x12433, 0x12434, 0x12435, 0x12436, 0x12437, 0x12438, 0x12439, 0x1243A, 0x1243B, 0x1243C, 0x1243D, 0x1243E, 0x1243F, 0x12440, 0x12441, 0x12442, 0x12443, 0x12444, 0x12445, 0x12446, 0x12447, 0x12448, 0x12449, 0x1244A, 0x1244B, 0x1244C, 0x1244D, 0x1244E, 0x1244F, 0x12450, 0x12451, 0x12452, 0x12453, 0x12454, 0x12455, 0x12456, 0x12457, 0x12458, 0x12459, 0x1245A, 0x1245B, 0x1245C, 0x1245D, 0x1245E, 0x1245F, 0x12460, 0x12461, 0x12462, 0x12463, 0x12464, 0x12465, 0x12466, 0x12467, 0x12468, 0x12469, 0x1246A, 0x1246B, 0x1246C, 0x1246D, 0x1246E, 0x16A60, 0x16A61, 0x16A62, 0x16A63, 0x16A64, 0x16A65, 0x16A66, 0x16A67, 0x16A68, 0x16A69, 0x16B50, 0x16B51, 0x16B52, 0x16B53, 0x16B54, 0x16B55, 0x16B56, 0x16B57, 0x16B58, 0x16B59, 0x16B5B, 0x16B5C, 0x16B5D, 0x16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x1ED15, 0x1ED16, 0x1ED17, 0x1ED18, 0x1ED19, 0x1ED1A, 0x1ED1B, 0x1ED1C, 0x1ED1D, 0x1ED1E, 0x1ED1F, 0x1ED20, 0x1ED21, 0x1ED22, 0x1ED23, 0x1ED24, 0x1ED25, 0x1ED26, 0x1ED27, 0x1ED28, 0x1ED29, 0x1ED2A, 0x1ED2B, 0x1ED2C, 0x1ED2D, 0x1ED2F, 0x1ED30, 0x1ED31, 0x1ED32, 0x1ED33, 0x1ED34, 0x1ED35, 0x1ED36, 0x1ED37, 0x1ED38, 0x1ED39, 0x1ED3A, 0x1ED3B, 0x1ED3C, 0x1ED3D, 0x1F100, 0x1F101, 0x1F102, 0x1F103, 0x1F104, 0x1F105, 0x1F106, 0x1F107, 0x1F108, 0x1F109, 0x1F10A, 0x1F10B, 0x1F10C, 0x20001, 0x20064, 0x200E2, 0x20121, 0x2092A, 0x20983, 0x2098C, 0x2099C, 0x20AEA, 0x20AFD, 0x20B19, 0x22390, 0x22998, 0x23B1B, 0x2626D, 0x2F890, ) # Some code that can be used to create the above list of hex numbers. if __name__ == "__main__": import unicodedata hex_chars = [] for i in range(0x110000): try: a = chr(i) except ValueError: break if a in "0123456789": continue if unicodedata.numeric(a, None) is not None: hex_chars.append(i) print(", ".join(["0X{:X}".format(i) for i in hex_chars])) natsort-7.0.1/natsort/utils.py000066400000000000000000000545251361376133500164400ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Utilities and definitions for natsort, mostly all used to define the natsort_key function. SOME CONVENTIONS USED IN THIS FILE. 1 - Factory Functions Most of the logic of natsort revolves around factory functions that create branchless transformation functions. For example, rather than making a string transformation function that has an if statement to determine whether or not to perform .lowercase() at runtime for each element to transform, there is a string transformation factory function that will return a function that either calls .lowercase() or does nothing. In this way, all the branches and decisions are taken care of once, up front. In addition to a slight speed improvement, this provides a more extensible infrastructure. Each of these factory functions will end with the suffix "_factory" to indicate that they themselves return a function. 2 - Keyword Parameters For Local Scope Many of the closures that are created by the factory functions have signatures similar to the following >>> def factory(parameter): ... val = 'yes' if parameter else 'no' ... def closure(x, _val=val): ... return '{} {}'.format(_val, x) ... return closure ... The variable value is passed as the default to a keyword argument. This is a micro-optimization that ensures "val" is a local variable instead of global variable and thus has a slightly improved performance at runtime. """ import re from functools import partial, reduce from itertools import chain as ichain from operator import methodcaller from pathlib import PurePath from unicodedata import normalize from natsort.compat.fastnumbers import fast_float, fast_int from natsort.compat.locale import get_decimal_point, get_strxfrm, get_thousands_sep from natsort.ns_enum import NS_DUMB, ns from natsort.unicode_numbers import digits_no_decimals, numeric_no_decimals class NumericalRegularExpressions: """ Container of regular expressions that match numbers. The numbers also account for unicode non-decimal characters. Not intended to be made an instance - use class methods only. """ # All unicode numeric characters (minus the decimal characters). numeric = numeric_no_decimals # All unicode digit characters (minus the decimal characters). digits = digits_no_decimals # Regular expression to match exponential component of a float. exp = r"(?:[eE][-+]?\d+)?" # Regular expression to match a floating point number. float_num = r"(?:\d+\.?\d*|\.\d+)" @classmethod def _construct_regex(cls, fmt): """Given a format string, construct the regex with class attributes.""" return re.compile(fmt.format(**vars(cls)), flags=re.U) @classmethod def int_sign(cls): """Regular expression to match a signed int.""" return cls._construct_regex(r"([-+]?\d+|[{digits}])") @classmethod def int_nosign(cls): """Regular expression to match an unsigned int.""" return cls._construct_regex(r"(\d+|[{digits}])") @classmethod def float_sign_exp(cls): """Regular expression to match a signed float with exponent.""" return cls._construct_regex(r"([-+]?{float_num}{exp}|[{numeric}])") @classmethod def float_nosign_exp(cls): """Regular expression to match an unsigned float with exponent.""" return cls._construct_regex(r"({float_num}{exp}|[{numeric}])") @classmethod def float_sign_noexp(cls): """Regular expression to match a signed float without exponent.""" return cls._construct_regex(r"([-+]?{float_num}|[{numeric}])") @classmethod def float_nosign_noexp(cls): """Regular expression to match an unsigned float without exponent.""" return cls._construct_regex(r"({float_num}|[{numeric}])") def regex_chooser(alg): """ Select an appropriate regex for the type of number of interest. Parameters ---------- alg : ns enum Used to indicate the regular expression to select. Returns ------- regex : compiled regex object Regular expression object that matches the desired number type. """ if alg & ns.FLOAT: alg &= ns.FLOAT | ns.SIGNED | ns.NOEXP else: alg &= ns.INT | ns.SIGNED return { ns.INT: NumericalRegularExpressions.int_nosign(), ns.FLOAT: NumericalRegularExpressions.float_nosign_exp(), ns.INT | ns.SIGNED: NumericalRegularExpressions.int_sign(), ns.FLOAT | ns.SIGNED: NumericalRegularExpressions.float_sign_exp(), ns.FLOAT | ns.NOEXP: NumericalRegularExpressions.float_nosign_noexp(), ns.FLOAT | ns.SIGNED | ns.NOEXP: NumericalRegularExpressions.float_sign_noexp(), }[alg] def _no_op(x): """A function that does nothing and returns the input as-is.""" return x def _normalize_input_factory(alg): """ Create a function that will normalize unicode input data. Parameters ---------- alg : ns enum Used to indicate how to normalize unicode. Returns ------- func : callable A function that accepts string (unicode) input and returns the the input normalized with the desired normalization scheme. """ normalization_form = "NFKD" if alg & ns.COMPATIBILITYNORMALIZE else "NFD" return partial(normalize, normalization_form) def natsort_key(val, key, string_func, bytes_func, num_func): """ Key to sort strings and numbers naturally. It works by splitting the string into components of strings and numbers, and then converting the numbers into actual ints or floats. Parameters ---------- val : str | unicode | bytes | int | float | iterable key : callable | None A key to apply to the *val* before any other operations are performed. string_func : callable If *val* (or the output of *key* if given) is of type *str*, this function will be applied to it. The function must return a tuple. bytes_func : callable If *val* (or the output of *key* if given) is of type *bytes*, this function will be applied to it. The function must return a tuple. num_func : callable If *val* (or the output of *key* if given) is not of type *bytes*, *str*, nor is iterable, this function will be applied to it. The function must return a tuple. Returns ------- out : tuple The string split into its string and numeric components. It *always* starts with a string, and then alternates between numbers and strings (unless it was applied recursively, in which case it will return tuples of tuples, but the lowest-level tuples will then *always* start with a string etc.). See Also -------- parse_string_factory parse_bytes_factory parse_number_factory """ # Apply key if needed if key is not None: val = key(val) # Assume the input are strings, which is the most common case try: return string_func(val) except (TypeError, AttributeError): # If bytes type, use the bytes_func if type(val) in (bytes,): return bytes_func(val) # Otherwise, assume it is an iterable that must be parsed recursively. # Do not apply the key recursively. try: return tuple( natsort_key(x, None, string_func, bytes_func, num_func) for x in val ) # If that failed, it must be a number. except TypeError: return num_func(val) def parse_bytes_factory(alg): """ Create a function that will format a *bytes* object into a tuple. Parameters ---------- alg : ns enum Indicate how to format the *bytes*. Returns ------- func : callable A function that accepts *bytes* input and returns a tuple with the formatted *bytes*. Intended to be used as the *bytes_func* argument to *natsort_key*. See Also -------- natsort_key """ # We don't worry about ns.UNGROUPLETTERS | ns.LOCALEALPHA because # bytes cannot be compared to strings. if alg & ns.PATH and alg & ns.IGNORECASE: return lambda x: ((x.lower(),),) elif alg & ns.PATH: return lambda x: ((x,),) elif alg & ns.IGNORECASE: return lambda x: (x.lower(),) else: return lambda x: (x,) def parse_number_factory(alg, sep, pre_sep): """ Create a function that will format a number into a tuple. Parameters ---------- alg : ns enum Indicate how to format the *bytes*. sep : str The string character to be inserted before the number in the returned tuple. pre_sep : str In the event that *alg* contains ``UNGROUPLETTERS``, this string will be placed in a single-element tuple at the front of the returned nested tuple. Returns ------- func : callable A function that accepts numeric input (e.g. *int* or *float*) and returns a tuple containing the number with the leading string *sep*. Intended to be used as the *num_func* argument to *natsort_key*. See Also -------- natsort_key """ nan_replace = float("+inf") if alg & ns.NANLAST else float("-inf") def func(val, _nan_replace=nan_replace, _sep=sep): """Given a number, place it in a tuple with a leading null string.""" return _sep, _nan_replace if val != val else val # Return the function, possibly wrapping in tuple if PATH is selected. if alg & ns.PATH and alg & ns.UNGROUPLETTERS and alg & ns.LOCALEALPHA: return lambda x: (((pre_sep,), func(x)),) elif alg & ns.UNGROUPLETTERS and alg & ns.LOCALEALPHA: return lambda x: ((pre_sep,), func(x)) elif alg & ns.PATH: return lambda x: (func(x),) else: return func def parse_string_factory( alg, sep, splitter, input_transform, component_transform, final_transform ): """ Create a function that will split and format a *str* into a tuple. Parameters ---------- alg : ns enum Indicate how to format and split the *str*. sep : str The string character to be inserted between adjacent numeric objects in the returned tuple. splitter : callable A function the will accept a string and returns an iterable of strings where the numbers are separated from the non-numbers. input_transform : callable A function to apply to the string input *before* applying the *splitter* function. Must return a string. component_transform : callable A function that is operated elementwise on the output of *splitter*. It must accept a single string and return either a string or a number. final_transform : callable A function to operate on the return value as a whole. It must accept a tuple and a string argument - the tuple should be the result of applying the above functions, and the string is the original input value. It must return a tuple. Returns ------- func : callable A function that accepts string input and returns a tuple containing the string split into numeric and non-numeric components, where the numeric components are converted into numeric objects. The first element is *always* a string, and then alternates number then string. Intended to be used as the *string_func* argument to *natsort_key*. See Also -------- natsort_key input_string_transform_factory string_component_transform_factory final_data_transform_factory """ # Sometimes we store the "original" input before transformation, # sometimes after. orig_after_xfrm = not (alg & NS_DUMB and alg & ns.LOCALEALPHA) original_func = input_transform if orig_after_xfrm else _no_op normalize_input = _normalize_input_factory(alg) def func(x): # Apply string input transformation function and return to x. # Original function is usually a no-op, but some algorithms require it # to also be the transformation function. x = normalize_input(x) x, original = input_transform(x), original_func(x) x = splitter(x) # Split string into components. x = filter(None, x) # Remove empty strings. x = map(component_transform, x) # Apply transform on components. x = sep_inserter(x, sep) # Insert '' between numbers. return final_transform(x, original) # Apply the final transform. return func def parse_path_factory(str_split): """ Create a function that will properly split and format a path. Parameters ---------- str_split : callable The output of the *parse_string_factory* function. Returns ------- func : callable A function that accepts a string or path-like object and splits it into its path components, then passes each component to *str_split* and returns the result as a nested tuple. Can be used as the *string_func* argument to *natsort_key*. See Also -------- natsort_key parse_string_factory """ return lambda x: tuple(map(str_split, path_splitter(x))) def sep_inserter(iterable, sep): """ Insert '' between numbers in an iterable. Parameters ---------- iterable sep : str The string character to be inserted between adjacent numeric objects. Yields ------ The values of *iterable* in order, with *sep* inserted where adjacent elements are numeric. If the first element in the input is numeric then *sep* will be the first value yielded. """ try: # Get the first element. A StopIteration indicates an empty iterable. # Since we are controlling the types of the input, 'type' is used # instead of 'isinstance' for the small speed advantage it offers. types = (int, float) first = next(iterable) if type(first) in types: yield sep yield first # Now, check if pair of elements are both numbers. If so, add ''. second = next(iterable) if type(first) in types and type(second) in types: yield sep yield second # Now repeat in a loop. for x in iterable: first, second = second, x if type(first) in types and type(second) in types: yield sep yield second except StopIteration: # Catch StopIteration per deprecation in PEP 479: # "Change StopIteration handling inside generators" return def input_string_transform_factory(alg): """ Create a function to transform a string. Parameters ---------- alg : ns enum Indicate how to format the *str*. Returns ------- func : callable A function to be used as the *input_transform* argument to *parse_string_factory*. See Also -------- parse_string_factory """ # Shortcuts. lowfirst = alg & ns.LOWERCASEFIRST dumb = alg & NS_DUMB # Build the chain of functions to execute in order. function_chain = [] if (dumb and not lowfirst) or (lowfirst and not dumb): function_chain.append(methodcaller("swapcase")) if alg & ns.IGNORECASE: function_chain.append(methodcaller("casefold")) if alg & ns.LOCALENUM: # Create a regular expression that will remove thousands separators. strip_thousands = r""" (?<=[0-9]{{1}}) # At least 1 number (?>> groupletters("Apple") 'aAppppllee' """ return "".join(ichain.from_iterable((_low(y), y) for y in x)) def chain_functions(functions): """ Chain a list of single-argument functions together and return. The functions are applied in list order, and the output of the previous functions is passed to the next function. Parameters ---------- functions : list A list of single-argument functions to chain together. Returns ------- func : callable A single argument function. Examples -------- Chain several functions together! >>> funcs = [lambda x: x * 4, len, lambda x: x + 5] >>> func = chain_functions(funcs) >>> func('hey') 17 """ functions = list(functions) if not functions: return _no_op elif len(functions) == 1: return functions[0] else: # See https://stackoverflow.com/a/39123400/1399279 return partial(reduce, lambda res, f: f(res), functions) def do_decoding(s, encoding): """ Helper to decode a *bytes* object, or return the object as-is. Parameters ---------- s : bytes | object encoding : str The encoding to use to decode *s*. Returns ------- decoded *str* if *s* was *bytes* and the decoding was successful. *s* if *s* was not *bytes*. """ try: return s.decode(encoding) except (AttributeError, TypeError): return s # noinspection PyIncorrectDocstring def path_splitter(s, _d_match=re.compile(r"\.\d").match): """ Split a string into its path components. Assumes a string is a path or is path-like. Parameters ---------- s : str | pathlib.Path Returns ------- split : tuple The path split by directory components and extensions. Examples -------- >>> tuple(path_splitter("this/thing.ext")) ('this', 'thing', '.ext') """ if not isinstance(s, PurePath): s = PurePath(s) # Split the path into parts. *path_parts, base = s.parts # Now, split off the file extensions until we reach a decimal number at # the beginning of the suffix or there are no more extensions. suffixes = PurePath(base).suffixes try: digit_index = next(i for i, x in enumerate(reversed(suffixes)) if _d_match(x)) except StopIteration: pass else: digit_index = len(suffixes) - digit_index suffixes = suffixes[digit_index:] base = base.replace("".join(suffixes), "") return filter(None, ichain(path_parts, [base], suffixes)) natsort-7.0.1/setup.cfg000066400000000000000000000030041361376133500150370ustar00rootroot00000000000000[bumpversion] current_version = 7.0.1 commit = True tag = True tag_name = {new_version} [metadata] author = Seth M. Morton author_email = drtuba78@gmail.com url = https://github.com/SethMMorton/natsort description = Simple yet flexible natural sorting in Python. long_description = file: README.rst long_description_content_type = text/x-rst license = MIT license_file = LICENSE classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Science/Research Intended Audience :: System Administrators Intended Audience :: Information Technology Intended Audience :: Financial and Insurance Industry Operating System :: OS Independent License :: OSI Approved :: MIT License Natural Language :: English Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Topic :: Scientific/Engineering :: Information Analysis Topic :: Utilities Topic :: Text Processing [bumpversion:file:setup.py] [bumpversion:file:natsort/__init__.py] [bumpversion:file:docs/conf.py] [bumpversion:file:CHANGELOG.md] search = Unreleased replace = Unreleased --- [{new_version}] - {now:%%Y-%%m-%%d} [flake8] max-line-length = 89 import-order-style = pycharm doctests = True max-complexity = 10 exclude = natsort.egg-info, .tox, .cache, .git, __pycache__, build, dist, docs, .venv natsort-7.0.1/setup.py000066400000000000000000000005431361376133500147350ustar00rootroot00000000000000#! /usr/bin/env python from setuptools import find_packages, setup setup( name='natsort', version='7.0.1', packages=find_packages(), entry_points={'console_scripts': ['natsort = natsort.__main__:main']}, python_requires=">=3.4", extras_require={ 'fast': ["fastnumbers >= 2.0.0"], 'icu': ["PyICU >= 1.0.0"] } ) natsort-7.0.1/tests/000077500000000000000000000000001361376133500143635ustar00rootroot00000000000000natsort-7.0.1/tests/conftest.py000066400000000000000000000023071361376133500165640ustar00rootroot00000000000000""" Fixtures for pytest. """ import locale import hypothesis import pytest # This disables the "too slow" hypothesis heath check globally. # For some reason it thinks that the text/binary generation is too # slow then causes the tests to fail. hypothesis.settings.register_profile( "slow-tests", suppress_health_check=[hypothesis.HealthCheck.too_slow], ) def load_locale(x): """Convenience to load a locale, trying ISO8859-1 first.""" try: locale.setlocale(locale.LC_ALL, str("{}.ISO8859-1".format(x))) except locale.Error: locale.setlocale(locale.LC_ALL, str("{}.UTF-8".format(x))) @pytest.fixture() def with_locale_en_us(): """Convenience to load the en_US locale - reset when complete.""" orig = locale.getlocale() yield load_locale("en_US") locale.setlocale(locale.LC_ALL, orig) @pytest.fixture() def with_locale_de_de(): """ Convenience to load the de_DE locale - reset when complete - skip if missing. """ orig = locale.getlocale() try: load_locale("de_DE") except locale.Error: pytest.skip("requires de_DE locale to be installed") else: yield finally: locale.setlocale(locale.LC_ALL, orig) natsort-7.0.1/tests/profile_natsorted.py000066400000000000000000000035221361376133500204620ustar00rootroot00000000000000# -*- coding: utf-8 -*- """\ This file contains functions to profile natsorted with different inputs and different settings. """ import cProfile import locale import sys try: from natsort import ns, natsort_keygen except ImportError: sys.path.insert(0, ".") from natsort import ns, natsort_keygen locale.setlocale(locale.LC_ALL, "en_US.UTF-8") # Samples to parse number = 14695498 int_string = "43493" float_string = "-434.93e7" plain_string = "hello world" fancy_string = "7abba9342fdab" a_path = "/p/Folder (1)/file (1).tar.gz" some_bytes = b"these are bytes" a_list = ["hello", "goodbye", "74"] basic_key = natsort_keygen() real_key = natsort_keygen(alg=ns.REAL) path_key = natsort_keygen(alg=ns.PATH) locale_key = natsort_keygen(alg=ns.LOCALE) def prof_time_to_generate(): print("*** Generate Plain Key ***") for _ in range(100000): natsort_keygen() cProfile.run("prof_time_to_generate()", sort="time") def prof_parsing(a, msg, key=basic_key): print(msg) for _ in range(100000): key(a) cProfile.run( 'prof_parsing(int_string, "*** Basic Call, Int as String ***")', sort="time" ) cProfile.run( 'prof_parsing(float_string, "*** Basic Call, Float as String ***")', sort="time" ) cProfile.run('prof_parsing(float_string, "*** Real Call ***", real_key)', sort="time") cProfile.run('prof_parsing(number, "*** Basic Call, Number ***")', sort="time") cProfile.run( 'prof_parsing(fancy_string, "*** Basic Call, Mixed String ***")', sort="time" ) cProfile.run('prof_parsing(some_bytes, "*** Basic Call, Byte String ***")', sort="time") cProfile.run('prof_parsing(a_path, "*** Path Call ***", path_key)', sort="time") cProfile.run('prof_parsing(a_list, "*** Basic Call, Recursive ***")', sort="time") cProfile.run( 'prof_parsing("434,930,000 dollars", "*** Locale Call ***", locale_key)', sort="time", ) natsort-7.0.1/tests/test_fake_fastnumbers.py000066400000000000000000000062631361376133500213220ustar00rootroot00000000000000# -*- coding: utf-8 -*- """\ Test the fake fastnumbers module. """ import unicodedata from math import isnan from hypothesis import given from hypothesis.strategies import floats, integers, text from natsort.compat.fake_fastnumbers import fast_float, fast_int def is_float(x): try: float(x) except ValueError: try: unicodedata.numeric(x) except (ValueError, TypeError): return False else: return True else: return True def not_a_float(x): return not is_float(x) def is_int(x): try: return x.is_integer() except AttributeError: try: int(x) except ValueError: try: unicodedata.digit(x) except (ValueError, TypeError): return False else: return True else: return True def not_an_int(x): return not is_int(x) # Each test has an "example" version for demonstrative purposes, # and a test that uses the hypothesis module. def test_fast_float_returns_nan_alternate_if_nan_option_is_given(): assert fast_float("nan", nan=7) == 7 def test_fast_float_converts_float_string_to_float_example(): assert fast_float("45.8") == 45.8 assert fast_float("-45") == -45.0 assert fast_float("45.8e-2", key=len) == 45.8e-2 assert isnan(fast_float("nan")) assert isnan(fast_float("+nan")) assert isnan(fast_float("-NaN")) assert fast_float("۱۲.۱۲") == 12.12 assert fast_float("-۱۲.۱۲") == -12.12 @given(floats(allow_nan=False)) def test_fast_float_converts_float_string_to_float(x): assert fast_float(repr(x)) == x def test_fast_float_leaves_string_as_is_example(): assert fast_float("invalid") == "invalid" @given(text().filter(not_a_float).filter(bool)) def test_fast_float_leaves_string_as_is(x): assert fast_float(x) == x def test_fast_float_with_key_applies_to_string_example(): assert fast_float("invalid", key=len) == len("invalid") @given(text().filter(not_a_float).filter(bool)) def test_fast_float_with_key_applies_to_string(x): assert fast_float(x, key=len) == len(x) def test_fast_int_leaves_float_string_as_is_example(): assert fast_int("45.8") == "45.8" assert fast_int("nan") == "nan" assert fast_int("inf") == "inf" @given(floats().filter(not_an_int)) def test_fast_int_leaves_float_string_as_is(x): assert fast_int(repr(x)) == repr(x) def test_fast_int_converts_int_string_to_int_example(): assert fast_int("-45") == -45 assert fast_int("+45") == 45 assert fast_int("۱۲") == 12 assert fast_int("-۱۲") == -12 @given(integers()) def test_fast_int_converts_int_string_to_int(x): assert fast_int(repr(x)) == x def test_fast_int_leaves_string_as_is_example(): assert fast_int("invalid") == "invalid" @given(text().filter(not_an_int).filter(bool)) def test_fast_int_leaves_string_as_is(x): assert fast_int(x) == x def test_fast_int_with_key_applies_to_string_example(): assert fast_int("invalid", key=len) == len("invalid") @given(text().filter(not_an_int).filter(bool)) def test_fast_int_with_key_applies_to_string(x): assert fast_int(x, key=len) == len(x) natsort-7.0.1/tests/test_final_data_transform_factory.py000066400000000000000000000036161361376133500237060ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" import pytest from hypothesis import example, given from hypothesis.strategies import floats, integers, text from natsort.ns_enum import NS_DUMB, ns from natsort.utils import final_data_transform_factory @pytest.mark.parametrize("alg", [ns.DEFAULT, ns.UNGROUPLETTERS, ns.LOCALE]) @given(x=text(), y=floats(allow_nan=False, allow_infinity=False) | integers()) @pytest.mark.usefixtures("with_locale_en_us") def test_final_data_transform_factory_default(x, y, alg): final_data_transform_func = final_data_transform_factory(alg, "", "::") value = (x, y) original_value = "".join(map(str, value)) result = final_data_transform_func(value, original_value) assert result == value @pytest.mark.parametrize( "alg, func", [ (ns.UNGROUPLETTERS | ns.LOCALE, lambda x: x), (ns.LOCALE | ns.UNGROUPLETTERS | NS_DUMB, lambda x: x), (ns.LOCALE | ns.UNGROUPLETTERS | ns.LOWERCASEFIRST, lambda x: x), ( ns.LOCALE | ns.UNGROUPLETTERS | NS_DUMB | ns.LOWERCASEFIRST, lambda x: x.swapcase(), ), ], ) @given(x=text(), y=floats(allow_nan=False, allow_infinity=False) | integers()) @example(x="İ", y=0) @pytest.mark.usefixtures("with_locale_en_us") def test_final_data_transform_factory_ungroup_and_locale(x, y, alg, func): final_data_transform_func = final_data_transform_factory(alg, "", "::") value = (x, y) original_value = "".join(map(str, value)) result = final_data_transform_func(value, original_value) if x: expected = ((func(original_value[:1]),), value) else: expected = (("::",), value) assert result == expected def test_final_data_transform_factory_ungroup_and_locale_empty_tuple(): final_data_transform_func = final_data_transform_factory(ns.UG | ns.L, "", "::") assert final_data_transform_func((), "") == ((), ()) natsort-7.0.1/tests/test_input_string_transform_factory.py000066400000000000000000000077001361376133500243470ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" import pytest from hypothesis import example, given from hypothesis.strategies import integers, text from natsort.ns_enum import NS_DUMB, ns from natsort.utils import input_string_transform_factory def thousands_separated_int(n): """Insert thousands separators in an int.""" new_int = "" for i, y in enumerate(reversed(n), 1): new_int = y + new_int # For every third digit, insert a thousands separator. if i % 3 == 0 and i != len(n): new_int = "," + new_int return new_int @given(text()) def test_input_string_transform_factory_is_no_op_for_no_alg_options(x): input_string_transform_func = input_string_transform_factory(ns.DEFAULT) assert input_string_transform_func(x) is x @pytest.mark.parametrize( "alg, example_func", [ (ns.IGNORECASE, lambda x: x.casefold()), (NS_DUMB, lambda x: x.swapcase()), (ns.LOWERCASEFIRST, lambda x: x.swapcase()), (NS_DUMB | ns.LOWERCASEFIRST, lambda x: x), # No-op (ns.IGNORECASE | ns.LOWERCASEFIRST, lambda x: x.swapcase().casefold()), ], ) @given(x=text()) def test_input_string_transform_factory(x, alg, example_func): input_string_transform_func = input_string_transform_factory(alg) assert input_string_transform_func(x) == example_func(x) @example(12543642642534980) # 12,543,642,642,534,980 => 12543642642534980 @given(x=integers(min_value=1000)) @pytest.mark.usefixtures("with_locale_en_us") def test_input_string_transform_factory_cleans_thousands(x): int_str = str(x).rstrip("lL") thousands_int_str = thousands_separated_int(int_str) assert thousands_int_str.replace(",", "") != thousands_int_str input_string_transform_func = input_string_transform_factory(ns.LOCALE) assert input_string_transform_func(thousands_int_str) == int_str # Using LOCALEALPHA does not affect numbers. input_string_transform_func_no_op = input_string_transform_factory(ns.LOCALEALPHA) assert input_string_transform_func_no_op(thousands_int_str) == thousands_int_str # These might be too much to test with hypothesis. @pytest.mark.parametrize( "x, expected", [ ("12,543,642642.5345,34980", "12543,642642.5345,34980"), ("12,59443,642,642.53,4534980", "12,59443,642642.53,4534980"), # No change ("12543,642,642.5,34534980", "12543,642642.5,34534980"), ], ) @pytest.mark.usefixtures("with_locale_en_us") def test_input_string_transform_factory_handles_us_locale(x, expected): input_string_transform_func = input_string_transform_factory(ns.LOCALE) assert input_string_transform_func(x) == expected @pytest.mark.parametrize( "x, expected", [ ("12.543.642642,5345.34980", "12543.642642,5345.34980"), ("12.59443.642.642,53.4534980", "12.59443.642642,53.4534980"), # No change ("12543.642.642,5.34534980", "12543.642642,5.34534980"), ], ) @pytest.mark.usefixtures("with_locale_de_de") def test_input_string_transform_factory_handles_de_locale(x, expected): input_string_transform_func = input_string_transform_factory(ns.LOCALE) assert input_string_transform_func(x) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.LOCALE, "1543,753"), # Does nothing without FLOAT (ns.LOCALE | ns.FLOAT, "1543.753"), (ns.LOCALEALPHA, "1543,753"), # LOCALEALPHA won't do anything, need LOCALENUM ], ) @pytest.mark.usefixtures("with_locale_de_de") def test_input_string_transform_factory_handles_german_locale(alg, expected): input_string_transform_func = input_string_transform_factory(alg) assert input_string_transform_func("1543,753") == expected @pytest.mark.usefixtures("with_locale_de_de") def test_input_string_transform_factory_does_nothing_with_non_num_input(): input_string_transform_func = input_string_transform_factory(ns.LOCALE | ns.FLOAT) expected = "154s,t53" assert input_string_transform_func("154s,t53") == expected natsort-7.0.1/tests/test_main.py000066400000000000000000000160131361376133500167210ustar00rootroot00000000000000# -*- coding: utf-8 -*- """\ Test the natsort command-line tool functions. """ import re import sys import pytest from hypothesis import given from hypothesis.strategies import data, floats, integers, lists from natsort.__main__ import ( check_filters, keep_entry_range, keep_entry_value, main, range_check, sort_and_print_entries, ) def test_main_passes_default_arguments_with_no_command_line_options(mocker): p = mocker.patch("natsort.__main__.sort_and_print_entries") main("num-2", "num-6", "num-1") args = p.call_args[0][1] assert not args.paths assert args.filter is None assert args.reverse_filter is None assert args.exclude is None assert not args.reverse assert args.number_type == "int" assert not args.signed assert args.exp assert not args.locale def test_main_passes_arguments_with_all_command_line_options(mocker): arguments = ["--paths", "--reverse", "--locale"] arguments.extend(["--filter", "4", "10"]) arguments.extend(["--reverse-filter", "100", "110"]) arguments.extend(["--number-type", "float"]) arguments.extend(["--noexp", "--sign"]) arguments.extend(["--exclude", "34"]) arguments.extend(["--exclude", "35"]) arguments.extend(["num-2", "num-6", "num-1"]) p = mocker.patch("natsort.__main__.sort_and_print_entries") main(*arguments) args = p.call_args[0][1] assert args.paths assert args.filter == [(4.0, 10.0)] assert args.reverse_filter == [(100.0, 110.0)] assert args.exclude == [34, 35] assert args.reverse assert args.number_type == "float" assert args.signed assert not args.exp assert args.locale class Args: """A dummy class to simulate the argparse Namespace object""" def __init__(self, filt, reverse_filter, exclude, as_path, reverse): self.filter = filt self.reverse_filter = reverse_filter self.exclude = exclude self.reverse = reverse self.number_type = "float" self.signed = True self.exp = True self.paths = as_path self.locale = 0 mock_print = "__builtin__.print" if sys.version[0] == "2" else "builtins.print" entries = [ "tmp/a57/path2", "tmp/a23/path1", "tmp/a1/path1", "tmp/a1 (1)/path1", "tmp/a130/path1", "tmp/a64/path1", "tmp/a64/path2", ] @pytest.mark.parametrize( "options, order", [ # Defaults, all options false # tmp/a1 (1)/path1 # tmp/a1/path1 # tmp/a23/path1 # tmp/a57/path2 # tmp/a64/path1 # tmp/a64/path2 # tmp/a130/path1 ([None, None, False, False, False], [3, 2, 1, 0, 5, 6, 4]), # Path option True # tmp/a1/path1 # tmp/a1 (1)/path1 # tmp/a23/path1 # tmp/a57/path2 # tmp/a64/path1 # tmp/a64/path2 # tmp/a130/path1 ([None, None, False, True, False], [2, 3, 1, 0, 5, 6, 4]), # Filter option keeps only within range # tmp/a23/path1 # tmp/a57/path2 # tmp/a64/path1 # tmp/a64/path2 ([[(20, 100)], None, False, False, False], [1, 0, 5, 6]), # Reverse filter, exclude in range # tmp/a1/path1 # tmp/a1 (1)/path1 # tmp/a130/path1 ([None, [(20, 100)], False, True, False], [2, 3, 4]), # Exclude given values with exclude list # tmp/a1/path1 # tmp/a1 (1)/path1 # tmp/a57/path2 # tmp/a64/path1 # tmp/a64/path2 ([None, None, [23, 130], True, False], [2, 3, 0, 5, 6]), # Reverse order # tmp/a130/path1 # tmp/a64/path2 # tmp/a64/path1 # tmp/a57/path2 # tmp/a23/path1 # tmp/a1 (1)/path1 # tmp/a1/path1 ([None, None, False, True, True], reversed([2, 3, 1, 0, 5, 6, 4])), ], ) def test_sort_and_print_entries(options, order, mocker): p = mocker.patch(mock_print) sort_and_print_entries(entries, Args(*options)) e = [mocker.call(entries[i]) for i in order] p.assert_has_calls(e) # Each test has an "example" version for demonstrative purposes, # and a test that uses the hypothesis module. def test_range_check_returns_range_as_is_but_with_floats_example(): assert range_check(10, 11) == (10.0, 11.0) assert range_check(6.4, 30) == (6.4, 30.0) @given(x=floats(allow_nan=False, min_value=-1E8, max_value=1E8) | integers(), d=data()) def test_range_check_returns_range_as_is_if_first_is_less_than_second(x, d): # Pull data such that the first is less than the second. if isinstance(x, float): y = d.draw(floats(min_value=x + 1.0, max_value=1E9, allow_nan=False)) else: y = d.draw(integers(min_value=x + 1)) assert range_check(x, y) == (x, y) def test_range_check_raises_value_error_if_second_is_less_than_first_example(): with pytest.raises(ValueError, match="low >= high"): range_check(7, 2) @given(x=floats(allow_nan=False), d=data()) def test_range_check_raises_value_error_if_second_is_less_than_first(x, d): # Pull data such that the first is greater than or equal to the second. y = d.draw(floats(max_value=x, allow_nan=False)) with pytest.raises(ValueError, match="low >= high"): range_check(x, y) def test_check_filters_returns_none_if_filter_evaluates_to_false(): assert check_filters(()) is None assert check_filters(False) is None assert check_filters(None) is None def test_check_filters_returns_input_as_is_if_filter_is_valid_example(): assert check_filters([(6, 7)]) == [(6, 7)] assert check_filters([(6, 7), (2, 8)]) == [(6, 7), (2, 8)] @given(x=lists(integers(), min_size=1), d=data()) def test_check_filters_returns_input_as_is_if_filter_is_valid(x, d): # ensure y is element-wise greater than x y = [d.draw(integers(min_value=val + 1)) for val in x] assert check_filters(list(zip(x, y))) == [(i, j) for i, j in zip(x, y)] def test_check_filters_raises_value_error_if_filter_is_invalid_example(): with pytest.raises(ValueError, match="Error in --filter: low >= high"): check_filters([(7, 2)]) @given(x=lists(integers(), min_size=1), d=data()) def test_check_filters_raises_value_error_if_filter_is_invalid(x, d): # ensure y is element-wise less than or equal to x y = [d.draw(integers(max_value=val)) for val in x] with pytest.raises(ValueError, match="Error in --filter: low >= high"): check_filters(list(zip(x, y))) @pytest.mark.parametrize( "lows, highs, truth", # 1. Any portion is between the bounds => True. # 2. Any portion is between any bounds => True. # 3. No portion is between the bounds => False. [([0], [100], True), ([1, 88], [20, 90], True), ([1], [20], False)], ) def test_keep_entry_range(lows, highs, truth): assert keep_entry_range("a56b23c89", lows, highs, int, re.compile(r"\d+")) is truth # 1. Values not in entry => True. 2. Values in entry => False. @pytest.mark.parametrize("values, truth", [([100, 45], True), ([23], False)]) def test_keep_entry_value(values, truth): assert keep_entry_value("a56b23c89", values, int, re.compile(r"\d+")) is truth natsort-7.0.1/tests/test_natsort_key.py000066400000000000000000000022611361376133500203370ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" from hypothesis import given from hypothesis.strategies import binary, floats, integers, lists, text from natsort.utils import natsort_key def str_func(x): if isinstance(x, str): return x else: raise TypeError("Not a str!") def fail(_): raise AssertionError("This should never be reached!") @given(floats(allow_nan=False) | integers()) def test_natsort_key_with_numeric_input_takes_number_path(x): assert natsort_key(x, None, str_func, fail, lambda y: y) is x @given(binary().filter(bool)) def test_natsort_key_with_bytes_input_takes_bytes_path(x): assert natsort_key(x, None, str_func, lambda y: y, fail) is x @given(text()) def test_natsort_key_with_text_input_takes_string_path(x): assert natsort_key(x, None, str_func, fail, fail) is x @given(lists(elements=text(), min_size=1, max_size=10)) def test_natsort_key_with_nested_input_takes_nested_path(x): assert natsort_key(x, None, str_func, fail, fail) == tuple(x) @given(text()) def test_natsort_key_with_key_argument_applies_key_before_processing(x): assert natsort_key(x, len, str_func, fail, lambda y: y) == len(x) natsort-7.0.1/tests/test_natsort_keygen.py000066400000000000000000000123111361376133500210260ustar00rootroot00000000000000# -*- coding: utf-8 -*- """\ Here are a collection of examples of how this module can be used. See the README or the natsort homepage for more details. """ import os import pytest from natsort import natsort_key, natsort_keygen, natsorted, ns from natsort.compat.locale import get_strxfrm, null_string_locale @pytest.fixture def arbitrary_input(): return ["6A-5.034e+1", "/Folder (1)/Foo", 56.7] @pytest.fixture def bytes_input(): return b"6A-5.034e+1" def test_natsort_keygen_demonstration(): original_list = ["a50", "a51.", "a50.31", "a50.4", "a5.034e1", "a50.300"] copy_of_list = original_list[:] original_list.sort(key=natsort_keygen(alg=ns.F)) # natsorted uses the output of natsort_keygen under the hood. assert original_list == natsorted(copy_of_list, alg=ns.F) def test_natsort_key_public(): assert natsort_key("a-5.034e2") == ("a-", 5, ".", 34, "e", 2) def test_natsort_keygen_with_invalid_alg_input_raises_value_error(): # Invalid arguments give the correct response with pytest.raises(ValueError, match="'alg' argument"): natsort_keygen(None, "1") @pytest.mark.parametrize( "alg, expected", [(ns.DEFAULT, ("a-", 5, ".", 34, "e", 1)), (ns.FLOAT | ns.SIGNED, ("a", -50.34))], ) def test_natsort_keygen_returns_natsort_key_that_parses_input(alg, expected): ns_key = natsort_keygen(alg=alg) assert ns_key("a-5.034e1") == expected @pytest.mark.parametrize( "alg, expected", [ ( ns.DEFAULT, (("", 6, "A-", 5, ".", 34, "e+", 1), ("/Folder (", 1, ")/Foo"), ("", 56.7)), ), ( ns.IGNORECASE, (("", 6, "a-", 5, ".", 34, "e+", 1), ("/folder (", 1, ")/foo"), ("", 56.7)), ), (ns.REAL, (("", 6.0, "A", -50.34), ("/Folder (", 1.0, ")/Foo"), ("", 56.7))), ( ns.LOWERCASEFIRST | ns.FLOAT | ns.NOEXP, ( ("", 6.0, "a-", 5.034, "E+", 1.0), ("/fOLDER (", 1.0, ")/fOO"), ("", 56.7), ), ), ( ns.PATH | ns.GROUPLETTERS, ( (("", 6, "aA--", 5, "..", 34, "ee++", 1),), ((2 * os.sep,), ("fFoollddeerr ((", 1, "))"), ("fFoooo",)), (("", 56.7),), ), ), ], ) def test_natsort_keygen_handles_arbitrary_input(arbitrary_input, alg, expected): ns_key = natsort_keygen(alg=alg) assert ns_key(arbitrary_input) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.DEFAULT, (b"6A-5.034e+1",)), (ns.IGNORECASE, (b"6a-5.034e+1",)), (ns.REAL, (b"6A-5.034e+1",)), (ns.LOWERCASEFIRST | ns.FLOAT | ns.NOEXP, (b"6A-5.034e+1",)), (ns.PATH | ns.GROUPLETTERS, ((b"6A-5.034e+1",),)), ], ) def test_natsort_keygen_handles_bytes_input(bytes_input, alg, expected): ns_key = natsort_keygen(alg=alg) assert ns_key(bytes_input) == expected @pytest.mark.parametrize( "alg, expected, is_dumb", [ ( ns.LOCALE, ( (null_string_locale, 6, "A-", 5, ".", 34, "e+", 1), ("/Folder (", 1, ")/Foo"), (null_string_locale, 56.7), ), False, ), ( ns.LOCALE, ( (null_string_locale, 6, "aa--", 5, "..", 34, "eE++", 1), ("//ffoOlLdDeErR ((", 1, "))//ffoOoO"), (null_string_locale, 56.7), ), True, ), ( ns.LOCALE | ns.CAPITALFIRST, ( (("",), (null_string_locale, 6, "A-", 5, ".", 34, "e+", 1)), (("/",), ("/Folder (", 1, ")/Foo")), (("",), (null_string_locale, 56.7)), ), False, ), ], ) @pytest.mark.usefixtures("with_locale_en_us") def test_natsort_keygen_with_locale(mocker, arbitrary_input, alg, expected, is_dumb): # First, apply the correct strxfrm function to the string values. strxfrm = get_strxfrm() expected = [list(sub) for sub in expected] try: for i in (2, 4, 6): expected[0][i] = strxfrm(expected[0][i]) for i in (0, 2): expected[1][i] = strxfrm(expected[1][i]) expected = tuple(tuple(sub) for sub in expected) except IndexError: # ns.LOCALE | ns.CAPITALFIRST expected = [[list(subsub) for subsub in sub] for sub in expected] for i in (2, 4, 6): expected[0][1][i] = strxfrm(expected[0][1][i]) for i in (0, 2): expected[1][1][i] = strxfrm(expected[1][1][i]) expected = tuple(tuple(tuple(subsub) for subsub in sub) for sub in expected) mocker.patch("natsort.compat.locale.dumb_sort", return_value=is_dumb) ns_key = natsort_keygen(alg=alg) assert ns_key(arbitrary_input) == expected @pytest.mark.parametrize( "alg, is_dumb", [(ns.LOCALE, False), (ns.LOCALE, True), (ns.LOCALE | ns.CAPITALFIRST, False)], ) @pytest.mark.usefixtures("with_locale_en_us") def test_natsort_keygen_with_locale_bytes(mocker, bytes_input, alg, is_dumb): expected = (b"6A-5.034e+1",) mocker.patch("natsort.compat.locale.dumb_sort", return_value=is_dumb) ns_key = natsort_keygen(alg=alg) assert ns_key(bytes_input) == expected natsort-7.0.1/tests/test_natsorted.py000066400000000000000000000236201361376133500200020ustar00rootroot00000000000000# -*- coding: utf-8 -*- """\ Here are a collection of examples of how this module can be used. See the README or the natsort homepage for more details. """ from operator import itemgetter import pytest from natsort import as_utf8, natsorted, ns from pytest import raises @pytest.fixture def float_list(): return ["a50", "a51.", "a50.31", "a-50", "a50.4", "a5.034e1", "a50.300"] @pytest.fixture def fruit_list(): return ["Apple", "corn", "Corn", "Banana", "apple", "banana"] @pytest.fixture def mixed_list(): return ["Ä", "0", "ä", 3, "b", 1.5, "2", "Z"] def test_natsorted_numbers_in_ascending_order(): given = ["a2", "a5", "a9", "a1", "a4", "a10", "a6"] expected = ["a1", "a2", "a4", "a5", "a6", "a9", "a10"] assert natsorted(given) == expected def test_natsorted_can_sort_as_signed_floats_with_exponents(float_list): expected = ["a-50", "a50", "a50.300", "a50.31", "a5.034e1", "a50.4", "a51."] assert natsorted(float_list, alg=ns.REAL) == expected @pytest.mark.parametrize( # UNSIGNED is default "alg", [ns.NOEXP | ns.FLOAT | ns.UNSIGNED, ns.NOEXP | ns.FLOAT], ) def test_natsorted_can_sort_as_unsigned_and_ignore_exponents(float_list, alg): expected = ["a5.034e1", "a50", "a50.300", "a50.31", "a50.4", "a51.", "a-50"] assert natsorted(float_list, alg=alg) == expected # DEFAULT and INT are all equivalent. @pytest.mark.parametrize("alg", [ns.DEFAULT, ns.INT]) def test_natsorted_can_sort_as_unsigned_ints_which_is_default(float_list, alg): expected = ["a5.034e1", "a50", "a50.4", "a50.31", "a50.300", "a51.", "a-50"] assert natsorted(float_list, alg=alg) == expected def test_natsorted_can_sort_as_signed_ints(float_list): expected = ["a-50", "a5.034e1", "a50", "a50.4", "a50.31", "a50.300", "a51."] assert natsorted(float_list, alg=ns.SIGNED) == expected @pytest.mark.parametrize( "alg, expected", [(ns.UNSIGNED, ["a7", "a+2", "a-5"]), (ns.SIGNED, ["a-5", "a+2", "a7"])], ) def test_natsorted_can_sort_with_or_without_accounting_for_sign(alg, expected): given = ["a-5", "a7", "a+2"] assert natsorted(given, alg=alg) == expected def test_natsorted_can_sort_as_version_numbers(): given = ["1.9.9a", "1.11", "1.9.9b", "1.11.4", "1.10.1"] expected = ["1.9.9a", "1.9.9b", "1.10.1", "1.11", "1.11.4"] assert natsorted(given) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.DEFAULT, ["0", 1.5, "2", 3, "Ä", "Z", "ä", "b"]), (ns.NUMAFTER, ["Ä", "Z", "ä", "b", "0", 1.5, "2", 3]), ], ) def test_natsorted_handles_mixed_types(mixed_list, alg, expected): assert natsorted(mixed_list, alg=alg) == expected @pytest.mark.parametrize( "alg, expected, slc", [ (ns.DEFAULT, [float("nan"), 5, "25", 1E40], slice(1, None)), (ns.NANLAST, [5, "25", 1E40, float("nan")], slice(None, 3)), ], ) def test_natsorted_handles_nan(alg, expected, slc): given = ["25", 5, float("nan"), 1E40] # The slice is because NaN != NaN # noinspection PyUnresolvedReferences assert natsorted(given, alg=alg)[slc] == expected[slc] def test_natsorted_with_mixed_bytes_and_str_input_raises_type_error(): with raises(TypeError, match="bytes"): natsorted(["ä", b"b"]) # ...unless you use as_utf (or some other decoder). assert natsorted(["ä", b"b"], key=as_utf8) == ["ä", b"b"] def test_natsorted_raises_type_error_for_non_iterable_input(): with raises(TypeError, match="'int' object is not iterable"): natsorted(100) def test_natsorted_recurses_into_nested_lists(): given = [["a1", "a5"], ["a1", "a40"], ["a10", "a1"], ["a2", "a5"]] expected = [["a1", "a5"], ["a1", "a40"], ["a2", "a5"], ["a10", "a1"]] assert natsorted(given) == expected def test_natsorted_applies_key_to_each_list_element_before_sorting_list(): given = [("a", "num3"), ("b", "num5"), ("c", "num2")] expected = [("c", "num2"), ("a", "num3"), ("b", "num5")] assert natsorted(given, key=itemgetter(1)) == expected def test_natsorted_returns_list_in_reversed_order_with_reverse_option(float_list): expected = natsorted(float_list)[::-1] assert natsorted(float_list, reverse=True) == expected def test_natsorted_handles_filesystem_paths(): given = [ "/p/Folder (10)/file.tar.gz", "/p/Folder (1)/file (1).tar.gz", "/p/Folder/file.x1.9.tar.gz", "/p/Folder (1)/file.tar.gz", "/p/Folder/file.x1.10.tar.gz", ] expected_correct = [ "/p/Folder/file.x1.10.tar.gz", "/p/Folder/file.x1.9.tar.gz", "/p/Folder (1)/file.tar.gz", "/p/Folder (1)/file (1).tar.gz", "/p/Folder (10)/file.tar.gz", ] expected_incorrect = [ "/p/Folder (1)/file (1).tar.gz", "/p/Folder (1)/file.tar.gz", "/p/Folder (10)/file.tar.gz", "/p/Folder/file.x1.10.tar.gz", "/p/Folder/file.x1.9.tar.gz", ] # Is incorrect by default. assert natsorted(given, alg=ns.FLOAT) == expected_incorrect # Need ns.PATH to make it correct. assert natsorted(given, alg=ns.FLOAT | ns.PATH) == expected_correct def test_natsorted_handles_numbers_and_filesystem_paths_simultaneously(): # You can sort paths and numbers, not that you'd want to given = ["/Folder (9)/file.exe", 43] expected = [43, "/Folder (9)/file.exe"] assert natsorted(given, alg=ns.PATH) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.DEFAULT, ["Apple", "Banana", "Corn", "apple", "banana", "corn"]), (ns.IGNORECASE, ["Apple", "apple", "Banana", "banana", "corn", "Corn"]), (ns.LOWERCASEFIRST, ["apple", "banana", "corn", "Apple", "Banana", "Corn"]), (ns.GROUPLETTERS, ["Apple", "apple", "Banana", "banana", "Corn", "corn"]), (ns.G | ns.LF, ["apple", "Apple", "banana", "Banana", "corn", "Corn"]), ], ) def test_natsorted_supports_case_handling(alg, expected, fruit_list): assert natsorted(fruit_list, alg=alg) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.DEFAULT, [("A5", "a6"), ("a3", "a1")]), (ns.LOWERCASEFIRST, [("a3", "a1"), ("A5", "a6")]), (ns.IGNORECASE, [("a3", "a1"), ("A5", "a6")]), ], ) def test_natsorted_supports_nested_case_handling(alg, expected): given = [("A5", "a6"), ("a3", "a1")] assert natsorted(given, alg=alg) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.DEFAULT, ["apple", "Apple", "banana", "Banana", "corn", "Corn"]), (ns.CAPITALFIRST, ["Apple", "Banana", "Corn", "apple", "banana", "corn"]), (ns.LOWERCASEFIRST, ["Apple", "apple", "Banana", "banana", "Corn", "corn"]), (ns.C | ns.LF, ["apple", "banana", "corn", "Apple", "Banana", "Corn"]), ], ) @pytest.mark.usefixtures("with_locale_en_us") def test_natsorted_can_sort_using_locale(fruit_list, alg, expected): assert natsorted(fruit_list, alg=ns.LOCALE | alg) == expected @pytest.mark.usefixtures("with_locale_en_us") def test_natsorted_can_sort_locale_specific_numbers_en(): given = ["c", "a5,467.86", "ä", "b", "a5367.86", "a5,6", "a5,50"] expected = ["a5,6", "a5,50", "a5367.86", "a5,467.86", "ä", "b", "c"] assert natsorted(given, alg=ns.LOCALE | ns.F) == expected @pytest.mark.usefixtures("with_locale_de_de") def test_natsorted_can_sort_locale_specific_numbers_de(): given = ["c", "a5.467,86", "ä", "b", "a5367.86", "a5,6", "a5,50"] expected = ["a5,50", "a5,6", "a5367.86", "a5.467,86", "ä", "b", "c"] assert natsorted(given, alg=ns.LOCALE | ns.F) == expected @pytest.mark.usefixtures("with_locale_de_de") def test_natsorted_locale_bug_regression_test_109(): # https://github.com/SethMMorton/natsort/issues/109 given = ["462166", "461761"] expected = ["461761", "462166"] assert natsorted(given, alg=ns.LOCALE) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.DEFAULT, ["0", 1.5, "2", 3, "ä", "Ä", "b", "Z"]), (ns.NUMAFTER, ["ä", "Ä", "b", "Z", "0", 1.5, "2", 3]), (ns.UNGROUPLETTERS, ["0", 1.5, "2", 3, "Ä", "Z", "ä", "b"]), (ns.UG | ns.NA, ["Ä", "Z", "ä", "b", "0", 1.5, "2", 3]), # Adding PATH changes nothing. (ns.PATH, ["0", 1.5, "2", 3, "ä", "Ä", "b", "Z"]), (ns.PATH | ns.NUMAFTER, ["ä", "Ä", "b", "Z", "0", 1.5, "2", 3]), (ns.PATH | ns.UNGROUPLETTERS, ["0", 1.5, "2", 3, "Ä", "Z", "ä", "b"]), (ns.PATH | ns.UG | ns.NA, ["Ä", "Z", "ä", "b", "0", 1.5, "2", 3]), ], ) @pytest.mark.usefixtures("with_locale_en_us") def test_natsorted_handles_mixed_types_with_locale(mixed_list, alg, expected): assert natsorted(mixed_list, alg=ns.LOCALE | alg) == expected @pytest.mark.parametrize( "alg, expected", [ (ns.DEFAULT, ["73", "5039", "Banana", "apple", "corn", "~~~~~~"]), (ns.NUMAFTER, ["Banana", "apple", "corn", "~~~~~~", "73", "5039"]), ], ) def test_natsorted_sorts_an_odd_collection_of_strings(alg, expected): given = ["apple", "Banana", "73", "5039", "corn", "~~~~~~"] assert natsorted(given, alg=alg) == expected def test_natsorted_sorts_mixed_ascii_and_non_ascii_numbers(): given = [ "1st street", "10th street", "2nd street", "2 street", "1 street", "1street", "11 street", "street 2", "street 1", "Street 11", "۲ street", "۱ street", "۱street", "۱۲street", "۱۱ street", "street ۲", "street ۱", "street ۱", "street ۱۲", "street ۱۱", ] expected = [ "1 street", "۱ street", "1st street", "1street", "۱street", "2 street", "۲ street", "2nd street", "10th street", "11 street", "۱۱ street", "۱۲street", "street 1", "street ۱", "street ۱", "street 2", "street ۲", "Street 11", "street ۱۱", "street ۱۲", ] assert natsorted(given, alg=ns.IGNORECASE) == expected natsort-7.0.1/tests/test_natsorted_convenience.py000066400000000000000000000063451361376133500223630ustar00rootroot00000000000000# -*- coding: utf-8 -*- """\ Here are a collection of examples of how this module can be used. See the README or the natsort homepage for more details. """ from operator import itemgetter import pytest from natsort import ( as_ascii, as_utf8, decoder, humansorted, index_humansorted, index_natsorted, index_realsorted, natsorted, ns, order_by_index, realsorted, ) @pytest.fixture def version_list(): return ["1.9.9a", "1.11", "1.9.9b", "1.11.4", "1.10.1"] @pytest.fixture def float_list(): return ["a50", "a51.", "a50.31", "a-50", "a50.4", "a5.034e1", "a50.300"] @pytest.fixture def fruit_list(): return ["Apple", "corn", "Corn", "Banana", "apple", "banana"] def test_decoder_returns_function_that_can_decode_bytes_but_return_non_bytes_as_is(): func = decoder("latin1") str_obj = "bytes" int_obj = 14 assert func(b"bytes") == str_obj assert func(int_obj) is int_obj # returns as-is, same object ID assert ( func(str_obj) is str_obj ) # same object returned b/c only bytes has decode def test_as_ascii_converts_bytes_to_ascii(): assert decoder("ascii")(b"bytes") == as_ascii(b"bytes") def test_as_utf8_converts_bytes_to_utf8(): assert decoder("utf8")(b"bytes") == as_utf8(b"bytes") def test_realsorted_is_identical_to_natsorted_with_real_alg(float_list): assert realsorted(float_list) == natsorted(float_list, alg=ns.REAL) @pytest.mark.usefixtures("with_locale_en_us") def test_humansorted_is_identical_to_natsorted_with_locale_alg(fruit_list): assert humansorted(fruit_list) == natsorted(fruit_list, alg=ns.LOCALE) def test_index_natsorted_returns_integer_list_of_sort_order_for_input_list(): given = ["num3", "num5", "num2"] other = ["foo", "bar", "baz"] index = index_natsorted(given) assert index == [2, 0, 1] assert [given[i] for i in index] == ["num2", "num3", "num5"] assert [other[i] for i in index] == ["baz", "foo", "bar"] def test_index_natsorted_reverse(): given = ["num3", "num5", "num2"] assert index_natsorted(given, reverse=True) == index_natsorted(given)[::-1] def test_index_natsorted_applies_key_function_before_sorting(): given = [("a", "num3"), ("b", "num5"), ("c", "num2")] expected = [2, 0, 1] assert index_natsorted(given, key=itemgetter(1)) == expected def test_index_realsorted_is_identical_to_index_natsorted_with_real_alg(float_list): assert index_realsorted(float_list) == index_natsorted(float_list, alg=ns.REAL) @pytest.mark.usefixtures("with_locale_en_us") def test_index_humansorted_is_identical_to_index_natsorted_with_locale_alg(fruit_list): assert index_humansorted(fruit_list) == index_natsorted(fruit_list, alg=ns.LOCALE) def test_order_by_index_sorts_list_according_to_order_of_integer_list(): given = ["num3", "num5", "num2"] index = [2, 0, 1] expected = [given[i] for i in index] assert expected == ["num2", "num3", "num5"] assert order_by_index(given, index) == expected def test_order_by_index_returns_generator_with_iter_true(): given = ["num3", "num5", "num2"] index = [2, 0, 1] assert order_by_index(given, index, True) != [given[i] for i in index] assert list(order_by_index(given, index, True)) == [given[i] for i in index] natsort-7.0.1/tests/test_ns_enum.py000066400000000000000000000021651361376133500174440ustar00rootroot00000000000000from natsort import ns def test_ns_enum(): enum_name_values = [ ("FLOAT", 0x0001), ("SIGNED", 0x0002), ("NOEXP", 0x0004), ("PATH", 0x0008), ("LOCALEALPHA", 0x0010), ("LOCALENUM", 0x0020), ("IGNORECASE", 0x0040), ("LOWERCASEFIRST", 0x0080), ("GROUPLETTERS", 0x0100), ("UNGROUPLETTERS", 0x0200), ("NANLAST", 0x0400), ("COMPATIBILITYNORMALIZE", 0x0800), ("NUMAFTER", 0x1000), ("DEFAULT", 0x0000), ("INT", 0x0000), ("UNSIGNED", 0x0000), ("REAL", 0x0003), ("LOCALE", 0x0030), ("I", 0x0000), ("U", 0x0000), ("F", 0x0001), ("S", 0x0002), ("R", 0x0003), ("N", 0x0004), ("P", 0x0008), ("LA", 0x0010), ("LN", 0x0020), ("L", 0x0030), ("IC", 0x0040), ("LF", 0x0080), ("G", 0x0100), ("UG", 0x0200), ("C", 0x0200), ("CAPITALFIRST", 0x0200), ("NL", 0x0400), ("CN", 0x0800), ("NA", 0x1000), ] assert list(ns._asdict().items()) == enum_name_values natsort-7.0.1/tests/test_parse_bytes_function.py000066400000000000000000000013361361376133500222240ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" import pytest from hypothesis import given from hypothesis.strategies import binary from natsort.ns_enum import ns from natsort.utils import parse_bytes_factory @pytest.mark.parametrize( "alg, example_func", [ (ns.DEFAULT, lambda x: (x,)), (ns.IGNORECASE, lambda x: (x.lower(),)), # With PATH, it becomes a tested tuple. (ns.PATH, lambda x: ((x,),)), (ns.PATH | ns.IGNORECASE, lambda x: ((x.lower(),),)), ], ) @given(x=binary()) def test_parse_bytest_factory_makes_function_that_returns_tuple(x, alg, example_func): parse_bytes_func = parse_bytes_factory(alg) assert parse_bytes_func(x) == example_func(x) natsort-7.0.1/tests/test_parse_number_function.py000066400000000000000000000023771361376133500223740ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" import pytest from hypothesis import given from hypothesis.strategies import floats, integers from natsort.ns_enum import ns from natsort.utils import parse_number_factory @pytest.mark.usefixtures("with_locale_en_us") @pytest.mark.parametrize( "alg, example_func", [ (ns.DEFAULT, lambda x: ("", x)), (ns.PATH, lambda x: (("", x),)), (ns.UNGROUPLETTERS | ns.LOCALE, lambda x: (("xx",), ("", x))), (ns.PATH | ns.UNGROUPLETTERS | ns.LOCALE, lambda x: ((("xx",), ("", x)),)), ], ) @given(x=floats(allow_nan=False) | integers()) def test_parse_number_factory_makes_function_that_returns_tuple(x, alg, example_func): parse_number_func = parse_number_factory(alg, "", "xx") assert parse_number_func(x) == example_func(x) @pytest.mark.parametrize( "alg, x, result", [ (ns.DEFAULT, 57, ("", 57)), (ns.DEFAULT, float("nan"), ("", float("-inf"))), # NaN transformed to -infinity (ns.NANLAST, float("nan"), ("", float("+inf"))), # NANLAST makes it +infinity ], ) def test_parse_number_factory_treats_nan_special(alg, x, result): parse_number_func = parse_number_factory(alg, "", "xx") assert parse_number_func(x) == result natsort-7.0.1/tests/test_parse_string_function.py000066400000000000000000000055611361376133500224100ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" import unicodedata import pytest from hypothesis import given from hypothesis.strategies import floats, integers, lists, text from natsort.compat.fastnumbers import fast_float from natsort.ns_enum import NS_DUMB, ns from natsort.utils import NumericalRegularExpressions as NumRegex from natsort.utils import parse_string_factory class CustomTuple(tuple): """Used to ensure what is given during testing is what is returned.""" original = None def input_transform(x): """Make uppercase.""" try: return x.upper() except AttributeError: return x def final_transform(x, original): """Make the input a CustomTuple.""" t = CustomTuple(x) t.original = original return t @pytest.fixture def parse_string_func(request): """A parse_string_factory result with sample arguments.""" sep = "" return parse_string_factory( request.param, # algorirhm sep, NumRegex.int_nosign().split, input_transform, fast_float, final_transform, ) @pytest.mark.parametrize("parse_string_func", [ns.DEFAULT], indirect=True) @given(x=floats() | integers()) def test_parse_string_factory_raises_type_error_if_given_number(x, parse_string_func): with pytest.raises(TypeError): assert parse_string_func(x) # noinspection PyCallingNonCallable @pytest.mark.parametrize( "parse_string_func, orig_func", [ (ns.DEFAULT, lambda x: x.upper()), (ns.LOCALE, lambda x: x.upper()), (ns.LOCALE | NS_DUMB, lambda x: x), # This changes the "original" handling. ], indirect=["parse_string_func"], ) @given( x=lists( elements=floats(allow_nan=False) | text() | integers(), min_size=1, max_size=10 ) ) @pytest.mark.usefixtures("with_locale_en_us") def test_parse_string_factory_invariance(x, parse_string_func, orig_func): # parse_string_factory is the high-level combination of several dedicated # functions involved in splitting and manipulating a string. The details of # what those functions do is not relevant to testing parse_string_factory. # What is relevant is that the form of the output matches the invariant # that even elements are string and odd are numerical. That each component # function is doing what it should is tested elsewhere. value = "".join(map(str, x)) # Convert the input to a single string. result = parse_string_func(value) result_types = list(map(type, result)) expected_types = [str if i % 2 == 0 else float for i in range(len(result))] assert result_types == expected_types # The result is in our CustomTuple. assert isinstance(result, CustomTuple) # Original should have gone through the "input_transform" # which is uppercase in these tests. assert result.original == orig_func(unicodedata.normalize("NFD", value)) natsort-7.0.1/tests/test_regex.py000066400000000000000000000115001361376133500171030ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the splitting regular expressions.""" import pytest from natsort import ns, numeric_regex_chooser from natsort.utils import NumericalRegularExpressions as NumRegex regex_names = { NumRegex.int_nosign(): "int_nosign", NumRegex.int_sign(): "int_sign", NumRegex.float_nosign_noexp(): "float_nosign_noexp", NumRegex.float_sign_noexp(): "float_sign_noexp", NumRegex.float_nosign_exp(): "float_nosign_exp", NumRegex.float_sign_exp(): "float_sign_exp", } # Regex Aliases (so lines stay a reasonable length. i_u = NumRegex.int_nosign() i_s = NumRegex.int_sign() f_u = NumRegex.float_nosign_noexp() f_s = NumRegex.float_sign_noexp() f_ue = NumRegex.float_nosign_exp() f_se = NumRegex.float_sign_exp() # Assemble a test suite of regular strings and their regular expression # splitting result. Organize by the input string. regex_tests = { "-123.45e+67": { i_u: ["-", "123", ".", "45", "e+", "67", ""], i_s: ["", "-123", ".", "45", "e", "+67", ""], f_u: ["-", "123.45", "e+", "67", ""], f_s: ["", "-123.45", "e", "+67", ""], f_ue: ["-", "123.45e+67", ""], f_se: ["", "-123.45e+67", ""], }, "a-123.45e+67b": { i_u: ["a-", "123", ".", "45", "e+", "67", "b"], i_s: ["a", "-123", ".", "45", "e", "+67", "b"], f_u: ["a-", "123.45", "e+", "67", "b"], f_s: ["a", "-123.45", "e", "+67", "b"], f_ue: ["a-", "123.45e+67", "b"], f_se: ["a", "-123.45e+67", "b"], }, "hello": { i_u: ["hello"], i_s: ["hello"], f_u: ["hello"], f_s: ["hello"], f_ue: ["hello"], f_se: ["hello"], }, "abc12.34.56-7def": { i_u: ["abc", "12", ".", "34", ".", "56", "-", "7", "def"], i_s: ["abc", "12", ".", "34", ".", "56", "", "-7", "def"], f_u: ["abc", "12.34", "", ".56", "-", "7", "def"], f_s: ["abc", "12.34", "", ".56", "", "-7", "def"], f_ue: ["abc", "12.34", "", ".56", "-", "7", "def"], f_se: ["abc", "12.34", "", ".56", "", "-7", "def"], }, "a1b2c3d4e5e6": { i_u: ["a", "1", "b", "2", "c", "3", "d", "4", "e", "5", "e", "6", ""], i_s: ["a", "1", "b", "2", "c", "3", "d", "4", "e", "5", "e", "6", ""], f_u: ["a", "1", "b", "2", "c", "3", "d", "4", "e", "5", "e", "6", ""], f_s: ["a", "1", "b", "2", "c", "3", "d", "4", "e", "5", "e", "6", ""], f_ue: ["a", "1", "b", "2", "c", "3", "d", "4e5", "e", "6", ""], f_se: ["a", "1", "b", "2", "c", "3", "d", "4e5", "e", "6", ""], }, "eleven۱۱eleven11eleven১১": { # All of these are the decimal 11 i_u: ["eleven", "۱۱", "eleven", "11", "eleven", "১১", ""], i_s: ["eleven", "۱۱", "eleven", "11", "eleven", "১১", ""], f_u: ["eleven", "۱۱", "eleven", "11", "eleven", "১১", ""], f_s: ["eleven", "۱۱", "eleven", "11", "eleven", "১১", ""], f_ue: ["eleven", "۱۱", "eleven", "11", "eleven", "১১", ""], f_se: ["eleven", "۱۱", "eleven", "11", "eleven", "১১", ""], }, "12①②ⅠⅡ⅓": { # Two decimals, Two digits, Two numerals, fraction i_u: ["", "12", "", "①", "", "②", "ⅠⅡ⅓"], i_s: ["", "12", "", "①", "", "②", "ⅠⅡ⅓"], f_u: ["", "12", "", "①", "", "②", "", "Ⅰ", "", "Ⅱ", "", "⅓", ""], f_s: ["", "12", "", "①", "", "②", "", "Ⅰ", "", "Ⅱ", "", "⅓", ""], f_ue: ["", "12", "", "①", "", "②", "", "Ⅰ", "", "Ⅱ", "", "⅓", ""], f_se: ["", "12", "", "①", "", "②", "", "Ⅰ", "", "Ⅱ", "", "⅓", ""], } } # From the above collections, create the parametrized tests and labels. regex_params = [ (given, expected, regex) for given, values in regex_tests.items() for regex, expected in values.items() ] labels = ["{}-{}".format(given, regex_names[regex]) for given, _, regex in regex_params] @pytest.mark.parametrize("x, expected, regex", regex_params, ids=labels) def test_regex_splits_correctly(x, expected, regex): # noinspection PyUnresolvedReferences assert regex.split(x) == expected @pytest.mark.parametrize( "given, expected", [ (ns.INT, NumRegex.int_nosign()), (ns.INT | ns.UNSIGNED, NumRegex.int_nosign()), (ns.INT | ns.SIGNED, NumRegex.int_sign()), (ns.INT | ns.NOEXP, NumRegex.int_nosign()), (ns.FLOAT, NumRegex.float_nosign_exp()), (ns.FLOAT | ns.UNSIGNED, NumRegex.float_nosign_exp()), (ns.FLOAT | ns.SIGNED, NumRegex.float_sign_exp()), (ns.FLOAT | ns.NOEXP, NumRegex.float_nosign_noexp()), (ns.FLOAT | ns.SIGNED | ns.NOEXP, NumRegex.float_sign_noexp()), (ns.FLOAT | ns.UNSIGNED | ns.NOEXP, NumRegex.float_nosign_noexp()), ], ) def test_regex_chooser(given, expected): assert numeric_regex_chooser(given) == expected.pattern[1:-1] # remove parens natsort-7.0.1/tests/test_string_component_transform_factory.py000066400000000000000000000047471361376133500252220ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" from functools import partial import pytest from hypothesis import example, given from hypothesis.strategies import floats, integers, text from natsort.compat.fastnumbers import fast_float, fast_int from natsort.compat.locale import get_strxfrm from natsort.ns_enum import NS_DUMB, ns from natsort.utils import groupletters, string_component_transform_factory # There are some unicode values that are known failures with the builtin locale # library on BSD systems that has nothing to do with natsort (a ValueError is # raised by strxfrm). Let's filter them out. try: bad_uni_chars = frozenset( chr(x) for x in range(0X10fefd, 0X10ffff + 1) ) except ValueError: # Narrow unicode build... no worries. bad_uni_chars = frozenset() def no_bad_uni_chars(x, _bad_chars=bad_uni_chars): """Ensure text does not contain bad unicode characters""" return not any(y in _bad_chars for y in x) def no_null(x): """Ensure text does not contain a null character.""" return "\0" not in x @pytest.mark.parametrize( "alg, example_func", [ (ns.INT, fast_int), (ns.DEFAULT, fast_int), (ns.FLOAT, partial(fast_float, nan=float("-inf"))), (ns.FLOAT | ns.NANLAST, partial(fast_float, nan=float("+inf"))), (ns.GROUPLETTERS, partial(fast_int, key=groupletters)), (ns.LOCALE, partial(fast_int, key=lambda x: get_strxfrm()(x))), ( ns.GROUPLETTERS | ns.LOCALE, partial(fast_int, key=lambda x: get_strxfrm()(groupletters(x))), ), ( NS_DUMB | ns.LOCALE, partial(fast_int, key=lambda x: get_strxfrm()(groupletters(x))), ), ( ns.GROUPLETTERS | ns.LOCALE | ns.FLOAT | ns.NANLAST, partial( fast_float, key=lambda x: get_strxfrm()(groupletters(x)), nan=float("+inf"), ), ), ], ) @example(x=float("nan")) @given( x=integers() | floats() | text().filter(bool).filter(no_bad_uni_chars).filter(no_null) ) @pytest.mark.usefixtures("with_locale_en_us") def test_string_component_transform_factory(x, alg, example_func): string_component_transform_func = string_component_transform_factory(alg) try: assert string_component_transform_func(str(x)) == example_func(str(x)) except ValueError as e: # handle broken locale lib on BSD. if "is not in range" not in str(e): raise natsort-7.0.1/tests/test_unicode_numbers.py000066400000000000000000000037241361376133500211630ustar00rootroot00000000000000# -*- coding: utf-8 -*- """\ Test the Unicode numbers module. """ import unicodedata from natsort.unicode_numbers import ( decimal_chars, decimals, digit_chars, digits, digits_no_decimals, numeric, numeric_chars, numeric_hex, numeric_no_decimals, ) def test_numeric_chars_contains_only_valid_unicode_numeric_characters(): for a in numeric_chars: assert unicodedata.numeric(a, None) is not None def test_digit_chars_contains_only_valid_unicode_digit_characters(): for a in digit_chars: assert unicodedata.digit(a, None) is not None def test_decimal_chars_contains_only_valid_unicode_decimal_characters(): for a in decimal_chars: assert unicodedata.decimal(a, None) is not None def test_numeric_chars_contains_all_valid_unicode_numeric_and_digit_characters(): set_numeric_hex = set(numeric_hex) set_numeric_chars = set(numeric_chars) set_digit_chars = set(digit_chars) set_decimal_chars = set(decimal_chars) for i in range(0X110000): try: a = chr(i) except ValueError: break if a in "0123456789": continue if unicodedata.numeric(a, None) is not None: assert i in set_numeric_hex assert a in set_numeric_chars if unicodedata.digit(a, None) is not None: assert i in set_numeric_hex assert a in set_digit_chars if unicodedata.decimal(a, None) is not None: assert i in set_numeric_hex assert a in set_decimal_chars assert set_decimal_chars.isdisjoint(digits_no_decimals) assert set_digit_chars.issuperset(digits_no_decimals) assert set_decimal_chars.isdisjoint(numeric_no_decimals) assert set_numeric_chars.issuperset(numeric_no_decimals) def test_combined_string_contains_all_characters_in_list(): assert numeric == "".join(numeric_chars) assert digits == "".join(digit_chars) assert decimals == "".join(decimal_chars) natsort-7.0.1/tests/test_utils.py000066400000000000000000000125161361376133500171410ustar00rootroot00000000000000# -*- coding: utf-8 -*- """These test the utils.py functions.""" import os import pathlib import string from itertools import chain from operator import neg as op_neg import pytest from hypothesis import given from hypothesis.strategies import integers, lists, sampled_from, text from natsort import utils from natsort.ns_enum import ns def test_do_decoding_decodes_bytes_string_to_unicode(): assert type(utils.do_decoding(b"bytes", "ascii")) is str assert utils.do_decoding(b"bytes", "ascii") == "bytes" assert utils.do_decoding(b"bytes", "ascii") == b"bytes".decode("ascii") @pytest.mark.parametrize( "alg, expected", [ (ns.I, utils.NumericalRegularExpressions.int_nosign()), (ns.I | ns.N, utils.NumericalRegularExpressions.int_nosign()), (ns.I | ns.S, utils.NumericalRegularExpressions.int_sign()), (ns.I | ns.S | ns.N, utils.NumericalRegularExpressions.int_sign()), (ns.F, utils.NumericalRegularExpressions.float_nosign_exp()), (ns.F | ns.N, utils.NumericalRegularExpressions.float_nosign_noexp()), (ns.F | ns.S, utils.NumericalRegularExpressions.float_sign_exp()), (ns.F | ns.S | ns.N, utils.NumericalRegularExpressions.float_sign_noexp()), ], ) def test_regex_chooser_returns_correct_regular_expression_object(alg, expected): assert utils.regex_chooser(alg).pattern == expected.pattern @pytest.mark.parametrize( "alg, value_or_alias", [ # Defaults (ns.DEFAULT, 0), (ns.INT, 0), (ns.UNSIGNED, 0), # Aliases (ns.INT, ns.I), (ns.UNSIGNED, ns.U), (ns.FLOAT, ns.F), (ns.SIGNED, ns.S), (ns.NOEXP, ns.N), (ns.PATH, ns.P), (ns.LOCALEALPHA, ns.LA), (ns.LOCALENUM, ns.LN), (ns.LOCALE, ns.L), (ns.IGNORECASE, ns.IC), (ns.LOWERCASEFIRST, ns.LF), (ns.GROUPLETTERS, ns.G), (ns.UNGROUPLETTERS, ns.UG), (ns.CAPITALFIRST, ns.C), (ns.UNGROUPLETTERS, ns.CAPITALFIRST), (ns.NANLAST, ns.NL), (ns.COMPATIBILITYNORMALIZE, ns.CN), (ns.NUMAFTER, ns.NA), # Convenience (ns.LOCALE, ns.LOCALEALPHA | ns.LOCALENUM), (ns.REAL, ns.FLOAT | ns.SIGNED), ], ) def test_ns_enum_values_and_aliases(alg, value_or_alias): assert alg == value_or_alias def test_chain_functions_is_a_no_op_if_no_functions_are_given(): x = 2345 assert utils.chain_functions([])(x) is x def test_chain_functions_does_one_function_if_one_function_is_given(): x = "2345" assert utils.chain_functions([len])(x) == 4 def test_chain_functions_combines_functions_in_given_order(): x = 2345 assert utils.chain_functions([str, len, op_neg])(x) == -len(str(x)) # Each test has an "example" version for demonstrative purposes, # and a test that uses the hypothesis module. def test_groupletters_returns_letters_with_lowercase_transform_of_letter_example(): assert utils.groupletters("HELLO") == "hHeElLlLoO" assert utils.groupletters("hello") == "hheelllloo" @given(text().filter(bool)) def test_groupletters_returns_letters_with_lowercase_transform_of_letter(x): assert utils.groupletters(x) == "".join( chain.from_iterable([y.casefold(), y] for y in x) ) def test_sep_inserter_does_nothing_if_no_numbers_example(): assert list(utils.sep_inserter(iter(["a", "b", "c"]), "")) == ["a", "b", "c"] assert list(utils.sep_inserter(iter(["a"]), "")) == ["a"] def test_sep_inserter_does_nothing_if_only_one_number_example(): assert list(utils.sep_inserter(iter(["a", 5]), "")) == ["a", 5] def test_sep_inserter_inserts_separator_string_between_two_numbers_example(): assert list(utils.sep_inserter(iter([5, 9]), "")) == ["", 5, "", 9] @given(lists(elements=text().filter(bool) | integers(), min_size=3)) def test_sep_inserter_inserts_separator_between_two_numbers(x): # Rather than just replicating the results in a different algorithm, # validate that the "shape" of the output is as expected. result = list(utils.sep_inserter(iter(x), "")) for i, pos in enumerate(result[1:-1], 1): if pos == "": assert isinstance(result[i - 1], int) assert isinstance(result[i + 1], int) def test_path_splitter_splits_path_string_by_separator_example(): given = "/this/is/a/path" expected = (os.sep, "this", "is", "a", "path") assert tuple(utils.path_splitter(given)) == tuple(expected) given = pathlib.Path(given) assert tuple(utils.path_splitter(given)) == tuple(expected) @given(lists(sampled_from(string.ascii_letters), min_size=2).filter(all)) def test_path_splitter_splits_path_string_by_separator(x): z = str(pathlib.Path(*x)) assert tuple(utils.path_splitter(z)) == tuple(pathlib.Path(z).parts) def test_path_splitter_splits_path_string_by_separator_and_removes_extension_example(): given = "/this/is/a/path/file.x1.10.tar.gz" expected = (os.sep, "this", "is", "a", "path", "file.x1.10", ".tar", ".gz") assert tuple(utils.path_splitter(given)) == tuple(expected) @given(lists(sampled_from(string.ascii_letters), min_size=3).filter(all)) def test_path_splitter_splits_path_string_by_separator_and_removes_extension(x): z = str(pathlib.Path(*x[:-2])) + "." + x[-1] y = tuple(pathlib.Path(z).parts) assert tuple(utils.path_splitter(z)) == y[:-1] + ( pathlib.Path(z).stem, pathlib.Path(z).suffix, ) natsort-7.0.1/tox.ini000066400000000000000000000037401361376133500145400ustar00rootroot00000000000000# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = flake8, py35, py36, py37, py38 # Other valid evironments are: # docs # release # clean # bump # Don't error out if a user hasn't installed all python versions. skip_missing_interpreters = true [testenv] passenv = WITH_EXTRAS deps = -r dev/requirements.txt extras = {env:WITH_EXTRAS:} commands = # Doctests {envpython} -m doctest -o IGNORE_EXCEPTION_DETAIL docs/howitworks.rst pytest README.rst docs/examples.rst pytest --doctest-modules {envsitepackagesdir}/natsort # Full test suite. Allow the user to pass command-line objects. pytest --hypothesis-profile=slow-tests --tb=short --cov {envsitepackagesdir}/natsort --cov-report term-missing {posargs:} # Check code quality. [testenv:flake8] deps = flake8 flake8-import-order flake8-bugbear pep8-naming check-manifest twine commands = {envpython} setup.py sdist bdist_wheel flake8 check-manifest --ignore ".github*,*.md,.coveragerc" twine check dist/* skip_install = true # Build documentation. # sphinx and sphinx_rtd_theme not in docs/requirements.txt because they # will already be installed on readthedocs. [testenv:docs] deps = sphinx sphinx_rtd_theme -r docs/requirements.txt commands = {envpython} setup.py build_sphinx skip_install = true # Bump version [testenv:bump] passenv = HOME deps = bump2version commands = {envpython} dev/bump.py {posargs:} skip_install = true # Release the code to PyPI [testenv:release] deps = twine commands = {envpython} setup.py sdist --format=gztar bdist_wheel twine upload --skip-existing dist/* skip_install = true # Clean up the working directory [testenv:clean] deps = commands = {envpython} dev/clean.py skip_install = true