Upload folder using huggingface_hub (part 11)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/PKG-INFOAdded+140
- .conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/SOURCES.txtAdded+518
- .conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/dependency_links.txtAdded+1
- .conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/entry_points.txtAdded+51
- .conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/requires.txtAdded+84
- .conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/top_level.txtAdded+2
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLERAdded+1
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATAAdded+133
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORDAdded+21
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTEDAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEELAdded+5
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSEAdded+73
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txtAdded+1
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_typing.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_adapters.pyAdded+136
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.pyAdded+34
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_compat.pyAdded+56
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_functools.pyAdded+135
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_itertools.pyAdded+171
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_meta.pyAdded+71
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_text.pyAdded+99
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_typing.pyAdded+15
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.pyAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.pyAdded+22
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.pyAdded+42
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/diagnose.pyAdded+21
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/py.typedAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLERAdded+1
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSEAdded+17
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATAAdded+96
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORDAdded+14
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTEDAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEELAdded+5
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txtAdded+1
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/context/__init__.pyAdded+367
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/context/__pycache__/__init__.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/context/py.typedAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyAdded+722
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyiAdded+123
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/py.typedAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txtAdded+2
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/__init__.pyAdded+647
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-311.pycAdded
- .conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-311.pycAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140Metadata-Version: 2.4Name: setuptoolsVersion: 84.0.0Summary: Most extensible Python build backend with support for C/C++ extension modulesAuthor-email: Python Packaging Authority <distutils-sig@python.org>License-Expression: MITProject-URL: Source, https://github.com/pypa/setuptoolsProject-URL: Documentation, https://setuptools.pypa.io/Project-URL: Changelog, https://setuptools.pypa.io/en/stable/history.htmlKeywords: CPAN PyPI distutils eggs package managementClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: System :: Archiving :: PackagingClassifier: Topic :: System :: Systems AdministrationClassifier: Topic :: UtilitiesRequires-Python: >=3.10Description-Content-Type: text/x-rstLicense-File: LICENSEProvides-Extra: testRequires-Dist: pytest!=8.1.*,>=6; extra == "test"Requires-Dist: virtualenv>=13.0.0; extra == "test"Requires-Dist: wheel>=0.44.0; extra == "test"Requires-Dist: pip>=19.1; extra == "test"Requires-Dist: packaging>=24.2; extra == "test"Requires-Dist: jaraco.envs>=2.2; extra == "test"Requires-Dist: pytest-xdist>=3; extra == "test"Requires-Dist: jaraco.path>=3.7.2; extra == "test"Requires-Dist: build[virtualenv]>=1.0.3; extra == "test"Requires-Dist: filelock>=3.4.0; extra == "test"Requires-Dist: ini2toml[lite]>=0.14; extra == "test"Requires-Dist: tomli-w>=1.0.0; extra == "test"Requires-Dist: pytest-timeout; extra == "test"Requires-Dist: pytest-perf; sys_platform != "cygwin" and extra == "test"Requires-Dist: jaraco.develop>=7.21; (python_version >= "3.9" and sys_platform != "cygwin") and extra == "test"Requires-Dist: pytest-home>=0.5; extra == "test"Requires-Dist: pytest-subprocess; extra == "test"Requires-Dist: pyproject-hooks!=1.1; extra == "test"Requires-Dist: jaraco.test>=5.5; extra == "test"Provides-Extra: docRequires-Dist: sphinx>=3.5; extra == "doc"Requires-Dist: jaraco.packaging>=9.3; extra == "doc"Requires-Dist: rst.linker>=1.9; extra == "doc"Requires-Dist: furo; extra == "doc"Requires-Dist: sphinx-lint; extra == "doc"Requires-Dist: jaraco.tidelift>=1.4; extra == "doc"Requires-Dist: pygments-github-lexers==0.0.5; extra == "doc"Requires-Dist: sphinx-favicon; extra == "doc"Requires-Dist: sphinx-inline-tabs; extra == "doc"Requires-Dist: sphinx-reredirects; extra == "doc"Requires-Dist: sphinxcontrib-towncrier; extra == "doc"Requires-Dist: sphinx-notfound-page<2,>=1; extra == "doc"Requires-Dist: pyproject-hooks!=1.1; extra == "doc"Requires-Dist: towncrier<24.7; extra == "doc"Provides-Extra: sslProvides-Extra: certsProvides-Extra: coreRequires-Dist: packaging>=24.2; extra == "core"Requires-Dist: more_itertools>=8.8; extra == "core"Requires-Dist: jaraco.text>=3.7; extra == "core"Requires-Dist: importlib_metadata>=6; python_version < "3.10" and extra == "core"Requires-Dist: tomli>=2.0.1; python_version < "3.11" and extra == "core"Requires-Dist: wheel>=0.43.0; extra == "core"Requires-Dist: jaraco.functools>=4; extra == "core"Requires-Dist: more_itertools; extra == "core"Provides-Extra: checkRequires-Dist: pytest-checkdocs>=2.14; extra == "check"Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check"Requires-Dist: ruff>=0.13.0; sys_platform != "cygwin" and extra == "check"Provides-Extra: coverRequires-Dist: pytest-cov; extra == "cover"Provides-Extra: enablerRequires-Dist: pytest-enabler>=3.4; extra == "enabler"Provides-Extra: typeRequires-Dist: pytest-mypy>=1.0.1; platform_python_implementation != "PyPy" and extra == "type"Requires-Dist: mypy==1.18.*; extra == "type"Requires-Dist: importlib_metadata>=7.0.2; python_version < "3.10" and extra == "type"Requires-Dist: jaraco.develop>=7.21; sys_platform != "cygwin" and extra == "type"Dynamic: license-file
.. |pypi-version| image:: https://img.shields.io/pypi/v/setuptools.svg :target: https://pypi.org/project/setuptools
.. |py-version| image:: https://img.shields.io/pypi/pyversions/setuptools.svg
.. |test-badge| image:: https://github.com/pypa/setuptools/actions/workflows/main.yml/badge.svg :target: https://github.com/pypa/setuptools/actions?query=workflow%3A%22tests%22 :alt: tests
.. |ruff-badge| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json :target: https://github.com/astral-sh/ruff :alt: Ruff
.. |docs-badge| image:: https://img.shields.io/readthedocs/setuptools/latest.svg :target: https://setuptools.pypa.io
.. |skeleton-badge| image:: https://img.shields.io/badge/skeleton-2026-informational :target: https://blog.jaraco.com/skeleton
.. |codecov-badge| image:: https://img.shields.io/codecov/c/github/pypa/setuptools/master.svg?logo=codecov&logoColor=white :target: https://codecov.io/gh/pypa/setuptools
.. |tidelift-badge| image:: https://tidelift.com/badges/github/pypa/setuptools?style=flat :target: https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=readme
.. |discord-badge| image:: https://img.shields.io/discord/803025117553754132 :target: https://discord.com/channels/803025117553754132/815945031150993468 :alt: Discord
|pypi-version| |py-version| |test-badge| |ruff-badge| |docs-badge| |skeleton-badge| |codecov-badge| |discord-badge|
See the `Quickstart <https://setuptools.pypa.io/en/latest/userguide/quickstart.html>`_and the `User's Guide <https://setuptools.pypa.io/en/latest/userguide/>`_ forinstructions on how to use Setuptools.
Questions and comments should be directed to `GitHub Discussions<https://github.com/pypa/setuptools/discussions>`_.Bug reports and especially tested patches may besubmitted directly to the `bug tracker<https://github.com/pypa/setuptools/issues>`_.
Code of Conduct===============
Everyone interacting in the setuptools project's codebases, issue trackers,chat rooms, and fora is expected to follow the`PSF Code of Conduct <https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md>`_.
For Enterprise==============
Available as part of the Tidelift Subscription.
Setuptools and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
`Learn more <https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=referral&utm_campaign=github>`_.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518LICENSEMANIFEST.inNEWS.rstREADME.rstconftest.pyexercises.pylauncher.cmypy.inipyproject.tomlpytest.inisetup.cfgsetup.pytox.ini_distutils_hack/__init__.py_distutils_hack/override.pydocs/artwork.rstdocs/build_meta.rstdocs/conf.pydocs/history.rstdocs/index.rstdocs/python 2 sunset.rstdocs/roadmap.rstdocs/setuptools.rstdocs/deprecated/changed_keywords.rstdocs/deprecated/commands.rstdocs/deprecated/dependency_links.rstdocs/deprecated/distutils-legacy.rstdocs/deprecated/easy_install.rstdocs/deprecated/functionalities.rstdocs/deprecated/index.rstdocs/deprecated/pkg_resources.rstdocs/deprecated/python_eggs.rstdocs/deprecated/resource_extraction.rstdocs/deprecated/sdist-reproducibility.rstdocs/deprecated/zip_safe.rstdocs/deprecated/distutils/_setuptools_disclaimer.rstdocs/deprecated/distutils/apiref.rstdocs/deprecated/distutils/builtdist.rstdocs/deprecated/distutils/commandref.rstdocs/deprecated/distutils/configfile.rstdocs/deprecated/distutils/examples.rstdocs/deprecated/distutils/extending.rstdocs/deprecated/distutils/index.rstdocs/deprecated/distutils/introduction.rstdocs/deprecated/distutils/packageindex.rstdocs/deprecated/distutils/setupscript.rstdocs/deprecated/distutils/sourcedist.rstdocs/deprecated/distutils/uploading.rstdocs/development/developer-guide.rstdocs/development/index.rstdocs/development/releases.rstdocs/references/keywords.rstdocs/userguide/datafiles.rstdocs/userguide/declarative_config.rstdocs/userguide/dependency_management.rstdocs/userguide/development_mode.rstdocs/userguide/distribution.rstdocs/userguide/entry_point.rstdocs/userguide/ext_modules.rstdocs/userguide/extension.rstdocs/userguide/index.rstdocs/userguide/interfaces.rstdocs/userguide/license_migration.rstdocs/userguide/miscellaneous.rstdocs/userguide/package_discovery.rstdocs/userguide/pyproject_config.rstdocs/userguide/quickstart.rstnewsfragments/.gitignorenewsfragments/README.rstsetuptools/__init__.pysetuptools/_core_metadata.pysetuptools/_discovery.pysetuptools/_entry_points.pysetuptools/_imp.pysetuptools/_importlib.pysetuptools/_itertools.pysetuptools/_normalization.pysetuptools/_path.pysetuptools/_reqs.pysetuptools/_scripts.pysetuptools/_shutil.pysetuptools/_static.pysetuptools/archive_util.pysetuptools/build_meta.pysetuptools/cli-32.exesetuptools/cli-64.exesetuptools/cli-arm64.exesetuptools/cli.exesetuptools/depends.pysetuptools/discovery.pysetuptools/dist.pysetuptools/errors.pysetuptools/extension.pysetuptools/glob.pysetuptools/gui-32.exesetuptools/gui-64.exesetuptools/gui-arm64.exesetuptools/gui.exesetuptools/installer.pysetuptools/launch.pysetuptools/launcher manifest.xmlsetuptools/logging.pysetuptools/modified.pysetuptools/monkey.pysetuptools/msvc.pysetuptools/namespaces.pysetuptools/script (dev).tmplsetuptools/script.tmplsetuptools/unicode_utils.pysetuptools/version.pysetuptools/warnings.pysetuptools/wheel.pysetuptools/windows_support.pysetuptools.egg-info/PKG-INFOsetuptools.egg-info/SOURCES.txtsetuptools.egg-info/dependency_links.txtsetuptools.egg-info/entry_points.txtsetuptools.egg-info/requires.txtsetuptools.egg-info/top_level.txtsetuptools/_distutils/__init__.pysetuptools/_distutils/_dataclass.pysetuptools/_distutils/_log.pysetuptools/_distutils/_macos_compat.pysetuptools/_distutils/_modified.pysetuptools/_distutils/_msvccompiler.pysetuptools/_distutils/archive_util.pysetuptools/_distutils/ccompiler.pysetuptools/_distutils/cmd.pysetuptools/_distutils/core.pysetuptools/_distutils/cygwinccompiler.pysetuptools/_distutils/debug.pysetuptools/_distutils/dep_util.pysetuptools/_distutils/dir_util.pysetuptools/_distutils/dist.pysetuptools/_distutils/errors.pysetuptools/_distutils/extension.pysetuptools/_distutils/fancy_getopt.pysetuptools/_distutils/file_util.pysetuptools/_distutils/filelist.pysetuptools/_distutils/log.pysetuptools/_distutils/py.typedsetuptools/_distutils/spawn.pysetuptools/_distutils/sysconfig.pysetuptools/_distutils/text_file.pysetuptools/_distutils/unixccompiler.pysetuptools/_distutils/util.pysetuptools/_distutils/version.pysetuptools/_distutils/versionpredicate.pysetuptools/_distutils/zosccompiler.pysetuptools/_distutils/command/__init__.pysetuptools/_distutils/command/_framework_compat.pysetuptools/_distutils/command/bdist.pysetuptools/_distutils/command/bdist_dumb.pysetuptools/_distutils/command/bdist_rpm.pysetuptools/_distutils/command/build.pysetuptools/_distutils/command/build_clib.pysetuptools/_distutils/command/build_ext.pysetuptools/_distutils/command/build_py.pysetuptools/_distutils/command/build_scripts.pysetuptools/_distutils/command/check.pysetuptools/_distutils/command/clean.pysetuptools/_distutils/command/config.pysetuptools/_distutils/command/install.pysetuptools/_distutils/command/install_data.pysetuptools/_distutils/command/install_egg_info.pysetuptools/_distutils/command/install_headers.pysetuptools/_distutils/command/install_lib.pysetuptools/_distutils/command/install_scripts.pysetuptools/_distutils/command/sdist.pysetuptools/_distutils/compat/__init__.pysetuptools/_distutils/compat/numpy.pysetuptools/_distutils/compat/py310.pysetuptools/_distutils/compilers/_modified.pysetuptools/_distutils/compilers/_util.pysetuptools/_distutils/compilers/errors.pysetuptools/_distutils/compilers/logging.pysetuptools/_distutils/compilers/C/base.pysetuptools/_distutils/compilers/C/cygwin.pysetuptools/_distutils/compilers/C/errors.pysetuptools/_distutils/compilers/C/msvc.pysetuptools/_distutils/compilers/C/py.typedsetuptools/_distutils/compilers/C/unix.pysetuptools/_distutils/compilers/C/zos.pysetuptools/_distutils/compilers/C/tests/conftest.pysetuptools/_distutils/compilers/C/tests/test_base.pysetuptools/_distutils/compilers/C/tests/test_cygwin.pysetuptools/_distutils/compilers/C/tests/test_mingw.pysetuptools/_distutils/compilers/C/tests/test_msvc.pysetuptools/_distutils/compilers/C/tests/test_unix.pysetuptools/_distutils/compilers/platform/detect.pysetuptools/_distutils/compilers/platform/macos.pysetuptools/_distutils/tests/__init__.pysetuptools/_distutils/tests/support.pysetuptools/_distutils/tests/test_archive_util.pysetuptools/_distutils/tests/test_bdist.pysetuptools/_distutils/tests/test_bdist_dumb.pysetuptools/_distutils/tests/test_bdist_rpm.pysetuptools/_distutils/tests/test_build.pysetuptools/_distutils/tests/test_build_clib.pysetuptools/_distutils/tests/test_build_ext.pysetuptools/_distutils/tests/test_build_py.pysetuptools/_distutils/tests/test_build_scripts.pysetuptools/_distutils/tests/test_check.pysetuptools/_distutils/tests/test_clean.pysetuptools/_distutils/tests/test_cmd.pysetuptools/_distutils/tests/test_config_cmd.pysetuptools/_distutils/tests/test_core.pysetuptools/_distutils/tests/test_dir_util.pysetuptools/_distutils/tests/test_dist.pysetuptools/_distutils/tests/test_extension.pysetuptools/_distutils/tests/test_file_util.pysetuptools/_distutils/tests/test_filelist.pysetuptools/_distutils/tests/test_install.pysetuptools/_distutils/tests/test_install_data.pysetuptools/_distutils/tests/test_install_headers.pysetuptools/_distutils/tests/test_install_lib.pysetuptools/_distutils/tests/test_install_scripts.pysetuptools/_distutils/tests/test_log.pysetuptools/_distutils/tests/test_modified.pysetuptools/_distutils/tests/test_sdist.pysetuptools/_distutils/tests/test_spawn.pysetuptools/_distutils/tests/test_sysconfig.pysetuptools/_distutils/tests/test_text_file.pysetuptools/_distutils/tests/test_util.pysetuptools/_distutils/tests/test_version.pysetuptools/_distutils/tests/test_versionpredicate.pysetuptools/_distutils/tests/unix_compat.pysetuptools/_distutils/tests/compat/__init__.pysetuptools/_vendor/.locksetuptools/_vendor/ruff.tomlsetuptools/_vendor/autocommand/__init__.pysetuptools/_vendor/autocommand/autoasync.pysetuptools/_vendor/autocommand/autocommand.pysetuptools/_vendor/autocommand/automain.pysetuptools/_vendor/autocommand/autoparse.pysetuptools/_vendor/autocommand/errors.pysetuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLERsetuptools/_vendor/autocommand-2.2.2.dist-info/LICENSEsetuptools/_vendor/autocommand-2.2.2.dist-info/METADATAsetuptools/_vendor/autocommand-2.2.2.dist-info/RECORDsetuptools/_vendor/autocommand-2.2.2.dist-info/REQUESTEDsetuptools/_vendor/autocommand-2.2.2.dist-info/WHEELsetuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txtsetuptools/_vendor/backports/__init__.pysetuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLERsetuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSEsetuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATAsetuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORDsetuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTEDsetuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEELsetuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txtsetuptools/_vendor/backports/tarfile/__init__.pysetuptools/_vendor/backports/tarfile/__main__.pysetuptools/_vendor/backports/tarfile/compat/__init__.pysetuptools/_vendor/backports/tarfile/compat/py38.pysetuptools/_vendor/importlib_metadata/__init__.pysetuptools/_vendor/importlib_metadata/_adapters.pysetuptools/_vendor/importlib_metadata/_collections.pysetuptools/_vendor/importlib_metadata/_compat.pysetuptools/_vendor/importlib_metadata/_functools.pysetuptools/_vendor/importlib_metadata/_itertools.pysetuptools/_vendor/importlib_metadata/_meta.pysetuptools/_vendor/importlib_metadata/_text.pysetuptools/_vendor/importlib_metadata/_typing.pysetuptools/_vendor/importlib_metadata/diagnose.pysetuptools/_vendor/importlib_metadata/py.typedsetuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLERsetuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATAsetuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORDsetuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTEDsetuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEELsetuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txtsetuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSEsetuptools/_vendor/importlib_metadata/compat/__init__.pysetuptools/_vendor/importlib_metadata/compat/py311.pysetuptools/_vendor/importlib_metadata/compat/py39.pysetuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLERsetuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSEsetuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATAsetuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORDsetuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTEDsetuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEELsetuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txtsetuptools/_vendor/jaraco/context/__init__.pysetuptools/_vendor/jaraco/context/py.typedsetuptools/_vendor/jaraco/functools/__init__.pysetuptools/_vendor/jaraco/functools/__init__.pyisetuptools/_vendor/jaraco/functools/py.typedsetuptools/_vendor/jaraco/text/Lorem ipsum.txtsetuptools/_vendor/jaraco/text/__init__.pysetuptools/_vendor/jaraco/text/layouts.pysetuptools/_vendor/jaraco/text/show-newlines.pysetuptools/_vendor/jaraco/text/strip-prefix.pysetuptools/_vendor/jaraco/text/to-dvorak.pysetuptools/_vendor/jaraco/text/to-qwerty.pysetuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLERsetuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATAsetuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORDsetuptools/_vendor/jaraco_context-6.1.0.dist-info/REQUESTEDsetuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEELsetuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txtsetuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSEsetuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLERsetuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATAsetuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORDsetuptools/_vendor/jaraco_functools-4.4.0.dist-info/REQUESTEDsetuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEELsetuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txtsetuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSEsetuptools/_vendor/more_itertools/__init__.pysetuptools/_vendor/more_itertools/__init__.pyisetuptools/_vendor/more_itertools/more.pysetuptools/_vendor/more_itertools/more.pyisetuptools/_vendor/more_itertools/py.typedsetuptools/_vendor/more_itertools/recipes.pysetuptools/_vendor/more_itertools/recipes.pyisetuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLERsetuptools/_vendor/more_itertools-10.8.0.dist-info/METADATAsetuptools/_vendor/more_itertools-10.8.0.dist-info/RECORDsetuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTEDsetuptools/_vendor/more_itertools-10.8.0.dist-info/WHEELsetuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/LICENSEsetuptools/_vendor/packaging/__init__.pysetuptools/_vendor/packaging/_elffile.pysetuptools/_vendor/packaging/_manylinux.pysetuptools/_vendor/packaging/_musllinux.pysetuptools/_vendor/packaging/_parser.pysetuptools/_vendor/packaging/_structures.pysetuptools/_vendor/packaging/_tokenizer.pysetuptools/_vendor/packaging/markers.pysetuptools/_vendor/packaging/metadata.pysetuptools/_vendor/packaging/py.typedsetuptools/_vendor/packaging/pylock.pysetuptools/_vendor/packaging/requirements.pysetuptools/_vendor/packaging/specifiers.pysetuptools/_vendor/packaging/tags.pysetuptools/_vendor/packaging/utils.pysetuptools/_vendor/packaging/version.pysetuptools/_vendor/packaging-26.0.dist-info/INSTALLERsetuptools/_vendor/packaging-26.0.dist-info/METADATAsetuptools/_vendor/packaging-26.0.dist-info/RECORDsetuptools/_vendor/packaging-26.0.dist-info/REQUESTEDsetuptools/_vendor/packaging-26.0.dist-info/WHEELsetuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSEsetuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.APACHEsetuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.BSDsetuptools/_vendor/packaging/licenses/__init__.pysetuptools/_vendor/packaging/licenses/_spdx.pysetuptools/_vendor/platformdirs/__init__.pysetuptools/_vendor/platformdirs/__main__.pysetuptools/_vendor/platformdirs/android.pysetuptools/_vendor/platformdirs/api.pysetuptools/_vendor/platformdirs/macos.pysetuptools/_vendor/platformdirs/py.typedsetuptools/_vendor/platformdirs/unix.pysetuptools/_vendor/platformdirs/version.pysetuptools/_vendor/platformdirs/windows.pysetuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLERsetuptools/_vendor/platformdirs-4.4.0.dist-info/METADATAsetuptools/_vendor/platformdirs-4.4.0.dist-info/RECORDsetuptools/_vendor/platformdirs-4.4.0.dist-info/REQUESTEDsetuptools/_vendor/platformdirs-4.4.0.dist-info/WHEELsetuptools/_vendor/platformdirs-4.4.0.dist-info/licenses/LICENSEsetuptools/_vendor/tomli/__init__.pysetuptools/_vendor/tomli/_parser.pysetuptools/_vendor/tomli/_re.pysetuptools/_vendor/tomli/_types.pysetuptools/_vendor/tomli/py.typedsetuptools/_vendor/tomli-2.4.0.dist-info/INSTALLERsetuptools/_vendor/tomli-2.4.0.dist-info/METADATAsetuptools/_vendor/tomli-2.4.0.dist-info/RECORDsetuptools/_vendor/tomli-2.4.0.dist-info/REQUESTEDsetuptools/_vendor/tomli-2.4.0.dist-info/WHEELsetuptools/_vendor/tomli-2.4.0.dist-info/licenses/LICENSEsetuptools/_vendor/wheel/__init__.pysetuptools/_vendor/wheel/__main__.pysetuptools/_vendor/wheel/_bdist_wheel.pysetuptools/_vendor/wheel/_metadata.pysetuptools/_vendor/wheel/_setuptools_logging.pysetuptools/_vendor/wheel/bdist_wheel.pysetuptools/_vendor/wheel/macosx_libfile.pysetuptools/_vendor/wheel/metadata.pysetuptools/_vendor/wheel/wheelfile.pysetuptools/_vendor/wheel-0.46.3.dist-info/INSTALLERsetuptools/_vendor/wheel-0.46.3.dist-info/METADATAsetuptools/_vendor/wheel-0.46.3.dist-info/RECORDsetuptools/_vendor/wheel-0.46.3.dist-info/REQUESTEDsetuptools/_vendor/wheel-0.46.3.dist-info/WHEELsetuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txtsetuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txtsetuptools/_vendor/wheel/_commands/__init__.pysetuptools/_vendor/wheel/_commands/convert.pysetuptools/_vendor/wheel/_commands/pack.pysetuptools/_vendor/wheel/_commands/tags.pysetuptools/_vendor/wheel/_commands/unpack.pysetuptools/_vendor/zipp/__init__.pysetuptools/_vendor/zipp/_functools.pysetuptools/_vendor/zipp/glob.pysetuptools/_vendor/zipp-3.23.0.dist-info/INSTALLERsetuptools/_vendor/zipp-3.23.0.dist-info/METADATAsetuptools/_vendor/zipp-3.23.0.dist-info/RECORDsetuptools/_vendor/zipp-3.23.0.dist-info/REQUESTEDsetuptools/_vendor/zipp-3.23.0.dist-info/WHEELsetuptools/_vendor/zipp-3.23.0.dist-info/top_level.txtsetuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSEsetuptools/_vendor/zipp/compat/__init__.pysetuptools/_vendor/zipp/compat/overlay.pysetuptools/_vendor/zipp/compat/py310.pysetuptools/_vendor/zipp/compat/py313.pysetuptools/command/__init__.pysetuptools/command/_requirestxt.pysetuptools/command/alias.pysetuptools/command/bdist_egg.pysetuptools/command/bdist_rpm.pysetuptools/command/bdist_wheel.pysetuptools/command/build.pysetuptools/command/build_clib.pysetuptools/command/build_ext.pysetuptools/command/build_py.pysetuptools/command/develop.pysetuptools/command/dist_info.pysetuptools/command/easy_install.pysetuptools/command/editable_wheel.pysetuptools/command/egg_info.pysetuptools/command/install.pysetuptools/command/install_egg_info.pysetuptools/command/install_lib.pysetuptools/command/install_scripts.pysetuptools/command/rotate.pysetuptools/command/saveopts.pysetuptools/command/sdist.pysetuptools/command/setopt.pysetuptools/command/test.pysetuptools/compat/__init__.pysetuptools/compat/py310.pysetuptools/compat/py311.pysetuptools/compat/py312.pysetuptools/compat/py39.pysetuptools/config/NOTICEsetuptools/config/__init__.pysetuptools/config/_apply_pyprojecttoml.pysetuptools/config/distutils.schema.jsonsetuptools/config/expand.pysetuptools/config/pyprojecttoml.pysetuptools/config/setupcfg.pysetuptools/config/setuptools.schema.jsonsetuptools/config/_validate_pyproject/NOTICEsetuptools/config/_validate_pyproject/__init__.pysetuptools/config/_validate_pyproject/error_reporting.pysetuptools/config/_validate_pyproject/extra_validations.pysetuptools/config/_validate_pyproject/fastjsonschema_exceptions.pysetuptools/config/_validate_pyproject/fastjsonschema_validations.pysetuptools/config/_validate_pyproject/formats.pysetuptools/tests/__init__.pysetuptools/tests/contexts.pysetuptools/tests/environment.pysetuptools/tests/fixtures.pysetuptools/tests/mod_with_constant.pysetuptools/tests/namespaces.pysetuptools/tests/test_archive_util.pysetuptools/tests/test_bdist_deprecations.pysetuptools/tests/test_bdist_egg.pysetuptools/tests/test_bdist_wheel.pysetuptools/tests/test_build.pysetuptools/tests/test_build_clib.pysetuptools/tests/test_build_ext.pysetuptools/tests/test_build_meta.pysetuptools/tests/test_build_py.pysetuptools/tests/test_config_discovery.pysetuptools/tests/test_core_metadata.pysetuptools/tests/test_depends.pysetuptools/tests/test_develop.pysetuptools/tests/test_dist.pysetuptools/tests/test_dist_info.pysetuptools/tests/test_distutils_adoption.pysetuptools/tests/test_editable_install.pysetuptools/tests/test_egg_info.pysetuptools/tests/test_extern.pysetuptools/tests/test_find_packages.pysetuptools/tests/test_find_py_modules.pysetuptools/tests/test_glob.pysetuptools/tests/test_install_scripts.pysetuptools/tests/test_logging.pysetuptools/tests/test_manifest.pysetuptools/tests/test_namespaces.pysetuptools/tests/test_scripts.pysetuptools/tests/test_sdist.pysetuptools/tests/test_setopt.pysetuptools/tests/test_setuptools.pysetuptools/tests/test_shutil_wrapper.pysetuptools/tests/test_unicode_utils.pysetuptools/tests/test_virtualenv.pysetuptools/tests/test_warnings.pysetuptools/tests/test_wheel.pysetuptools/tests/test_windows_wrappers.pysetuptools/tests/text.pysetuptools/tests/textwrap.pysetuptools/tests/compat/__init__.pysetuptools/tests/compat/py39.pysetuptools/tests/config/__init__.pysetuptools/tests/config/setupcfg_examples.txtsetuptools/tests/config/test_apply_pyprojecttoml.pysetuptools/tests/config/test_expand.pysetuptools/tests/config/test_pyprojecttoml.pysetuptools/tests/config/test_pyprojecttoml_dynamic_deps.pysetuptools/tests/config/test_setupcfg.pysetuptools/tests/config/downloads/__init__.pysetuptools/tests/config/downloads/preload.pysetuptools/tests/indexes/test_links_priority/external.htmlsetuptools/tests/indexes/test_links_priority/simple/foobar/index.htmlsetuptools/tests/integration/__init__.pysetuptools/tests/integration/helpers.pysetuptools/tests/integration/test_pbr.pysetuptools/tests/integration/test_pip_install_sdist.pytools/build_launchers.pytools/finalize.pytools/generate_validation_code.pytools/vendored.py1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051[distutils.commands]alias = setuptools.command.alias:aliasbdist_egg = setuptools.command.bdist_egg:bdist_eggbdist_rpm = setuptools.command.bdist_rpm:bdist_rpmbdist_wheel = setuptools.command.bdist_wheel:bdist_wheelbuild = setuptools.command.build:buildbuild_clib = setuptools.command.build_clib:build_clibbuild_ext = setuptools.command.build_ext:build_extbuild_py = setuptools.command.build_py:build_pydevelop = setuptools.command.develop:developdist_info = setuptools.command.dist_info:dist_infoeasy_install = setuptools.command.easy_install:easy_installeditable_wheel = setuptools.command.editable_wheel:editable_wheelegg_info = setuptools.command.egg_info:egg_infoinstall = setuptools.command.install:installinstall_egg_info = setuptools.command.install_egg_info:install_egg_infoinstall_lib = setuptools.command.install_lib:install_libinstall_scripts = setuptools.command.install_scripts:install_scriptsrotate = setuptools.command.rotate:rotatesaveopts = setuptools.command.saveopts:saveoptssdist = setuptools.command.sdist:sdistsetopt = setuptools.command.setopt:setopt
[distutils.setup_keywords]dependency_links = setuptools.dist:assert_string_listeager_resources = setuptools.dist:assert_string_listentry_points = setuptools.dist:check_entry_pointsexclude_package_data = setuptools.dist:check_package_dataextras_require = setuptools.dist:check_extrasinclude_package_data = setuptools.dist:assert_boolinstall_requires = setuptools.dist:check_requirementsnamespace_packages = setuptools.dist:check_nsppackage_data = setuptools.dist:check_package_datapackages = setuptools.dist:check_packagespython_requires = setuptools.dist:check_specifiersetup_requires = setuptools.dist:check_requirementsuse_2to3 = setuptools.dist:invalid_unless_falsezip_safe = setuptools.dist:assert_bool
[egg_info.writers]PKG-INFO = setuptools.command.egg_info:write_pkg_infodependency_links.txt = setuptools.command.egg_info:overwrite_argeager_resources.txt = setuptools.command.egg_info:overwrite_argentry_points.txt = setuptools.command.egg_info:write_entriesnamespace_packages.txt = setuptools.command.egg_info:overwrite_argrequires.txt = setuptools.command.egg_info:write_requirementstop_level.txt = setuptools.command.egg_info:write_toplevel_names
[setuptools.finalize_distribution_options]keywords = setuptools.dist:Distribution._finalize_setup_keywordsparent_finalize = setuptools.dist:_Distribution.finalize_options123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
[certs]
[check]pytest-checkdocs>=2.14
[check:sys_platform != "cygwin"]pytest-ruff>=0.2.1ruff>=0.13.0
[core]packaging>=24.2more_itertools>=8.8jaraco.text>=3.7wheel>=0.43.0jaraco.functools>=4more_itertools
[core:python_version < "3.10"]importlib_metadata>=6
[core:python_version < "3.11"]tomli>=2.0.1
[cover]pytest-cov
[doc]sphinx>=3.5jaraco.packaging>=9.3rst.linker>=1.9furosphinx-lintjaraco.tidelift>=1.4pygments-github-lexers==0.0.5sphinx-faviconsphinx-inline-tabssphinx-reredirectssphinxcontrib-towncriersphinx-notfound-page<2,>=1pyproject-hooks!=1.1towncrier<24.7
[enabler]pytest-enabler>=3.4
[ssl]
[test]pytest!=8.1.*,>=6virtualenv>=13.0.0wheel>=0.44.0pip>=19.1packaging>=24.2jaraco.envs>=2.2pytest-xdist>=3jaraco.path>=3.7.2build[virtualenv]>=1.0.3filelock>=3.4.0ini2toml[lite]>=0.14tomli-w>=1.0.0pytest-timeoutpytest-home>=0.5pytest-subprocesspyproject-hooks!=1.1jaraco.test>=5.5
[test:python_version >= "3.9" and sys_platform != "cygwin"]jaraco.develop>=7.21
[test:sys_platform != "cygwin"]pytest-perf
[type]mypy==1.18.*
[type:platform_python_implementation != "PyPy"]pytest-mypy>=1.0.1
[type:python_version < "3.10"]importlib_metadata>=7.0.2
[type:sys_platform != "cygwin"]jaraco.develop>=7.2112_distutils_hacksetuptools1conda123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133Metadata-Version: 2.4Name: importlib_metadataVersion: 8.7.1Summary: Read metadata from Python packagesAuthor-email: "Jason R. Coombs" <jaraco@jaraco.com>License-Expression: Apache-2.0Project-URL: Source, https://github.com/python/importlib_metadataClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyRequires-Python: >=3.9Description-Content-Type: text/x-rstLicense-File: LICENSERequires-Dist: zipp>=3.20Provides-Extra: testRequires-Dist: pytest!=8.1.*,>=6; extra == "test"Requires-Dist: packaging; extra == "test"Requires-Dist: pyfakefs; extra == "test"Requires-Dist: flufl.flake8; extra == "test"Requires-Dist: pytest-perf>=0.9.2; extra == "test"Requires-Dist: jaraco.test>=5.4; extra == "test"Provides-Extra: docRequires-Dist: sphinx>=3.5; extra == "doc"Requires-Dist: jaraco.packaging>=9.3; extra == "doc"Requires-Dist: rst.linker>=1.9; extra == "doc"Requires-Dist: furo; extra == "doc"Requires-Dist: sphinx-lint; extra == "doc"Requires-Dist: jaraco.tidelift>=1.4; extra == "doc"Provides-Extra: perfRequires-Dist: ipython; extra == "perf"Provides-Extra: checkRequires-Dist: pytest-checkdocs>=2.4; extra == "check"Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check"Provides-Extra: coverRequires-Dist: pytest-cov; extra == "cover"Provides-Extra: enablerRequires-Dist: pytest-enabler>=3.4; extra == "enabler"Provides-Extra: typeRequires-Dist: pytest-mypy>=1.0.1; extra == "type"Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type"Dynamic: license-file
.. image:: https://img.shields.io/pypi/v/importlib_metadata.svg :target: https://pypi.org/project/importlib_metadata
.. image:: https://img.shields.io/pypi/pyversions/importlib_metadata.svg
.. image:: https://github.com/python/importlib_metadata/actions/workflows/main.yml/badge.svg :target: https://github.com/python/importlib_metadata/actions?query=workflow%3A%22tests%22 :alt: tests
.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json :target: https://github.com/astral-sh/ruff :alt: Ruff
.. image:: https://readthedocs.org/projects/importlib-metadata/badge/?version=latest :target: https://importlib-metadata.readthedocs.io/en/latest/?badge=latest
.. image:: https://img.shields.io/badge/skeleton-2025-informational :target: https://blog.jaraco.com/skeleton
.. image:: https://tidelift.com/badges/package/pypi/importlib-metadata :target: https://tidelift.com/subscription/pkg/pypi-importlib-metadata?utm_source=pypi-importlib-metadata&utm_medium=readme
Library to access the metadata for a Python package.
This package supplies third-party access to the functionality of`importlib.metadata <https://docs.python.org/3/library/importlib.metadata.html>`_including improvements added to subsequent Python versions.
Compatibility=============
New features are introduced in this third-party library and later mergedinto CPython. The following table indicates which versions of this librarywere contributed to different versions in the standard library:
.. list-table:: :header-rows: 1
* - importlib_metadata - stdlib * - 7.0 - 3.13 * - 6.5 - 3.12 * - 4.13 - 3.11 * - 4.6 - 3.10 * - 1.4 - 3.8
Usage=====
See the `online documentation <https://importlib-metadata.readthedocs.io/>`_for usage details.
`Finder authors<https://docs.python.org/3/reference/import.html#finders-and-loaders>`_ canalso add support for custom package installers. See the above documentationfor details.
Caveats=======
This project primarily supports third-party packages installed by PyPAtools (or other conforming packages). It does not support:
- Packages in the stdlib.- Packages installed without metadata.
Project details===============
* Project home: https://github.com/python/importlib_metadata * Report bugs at: https://github.com/python/importlib_metadata/issues * Code hosting: https://github.com/python/importlib_metadata * Documentation: https://importlib-metadata.readthedocs.io/
For Enterprise==============
Available as part of the Tidelift Subscription.
This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
`Learn more <https://tidelift.com/subscription/pkg/pypi-importlib-metadata?utm_source=pypi-importlib-metadata&utm_medium=referral&utm_campaign=github>`_.123456789101112131415161718192021importlib_metadata-8.7.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2importlib_metadata-8.7.1.dist-info/METADATA,sha256=o-OLnuQyYonUhkcE8w4pnudp4jCc6fSnXw3hpQrQo1Y,4670importlib_metadata-8.7.1.dist-info/RECORD,,importlib_metadata-8.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0importlib_metadata-8.7.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91importlib_metadata-8.7.1.dist-info/licenses/LICENSE,sha256=RYUC4S2Xu_ZEOGBqIARKqF6wX7CoqAe7NdvsJT_R_AQ,10278importlib_metadata-8.7.1.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19importlib_metadata/__init__.py,sha256=u7Ew4-UkpzNY-ka6k-WRkDhQZS1akkLMfWs2eEnUmGo,37734importlib_metadata/_adapters.py,sha256=r5i8XLrKT6xmrpoREZhZrfczOYDmrVZeJBW5u0HzIGU,3797importlib_metadata/_collections.py,sha256=CxAhzlF3g1rwu_fMiB53JtRQiUFh0RgiMpoOvmK_ocg,760importlib_metadata/_compat.py,sha256=VC5ZDLlT-BcshauCShdFJvMNLntJJfZzNK1meGa-enw,1313importlib_metadata/_functools.py,sha256=0pA2OoiVK6wnsGq8HvVIzgdkvLiZ0nfnfw7IsndjoHk,3510importlib_metadata/_itertools.py,sha256=nMvp9SfHAQ_JYwK4L2i64lr3GRXGlYlikGTVzWbys_E,5351importlib_metadata/_meta.py,sha256=EtHyiJ5kGzWFDfKyQ2XQp6Vu113CeadKW1Vf6aGc1B4,1765importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166importlib_metadata/_typing.py,sha256=EQKhhsEgz_Sa-FnePI-faC72rNOOQwopjA1i5pG8FDU,367importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608importlib_metadata/compat/py39.py,sha256=J3W7PUVRPNYMmcvT12RF8ndBU9e8_T0Ac4U87Bsrq70,1187importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,012345Wheel-Version: 1.0Generator: setuptools (80.9.0)Root-Is-Purelib: trueTag: py3-none-any
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273Apache LicenseVersion 2.0, January 2004http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2025 [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.1importlib_metadata123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import email.messageimport email.policyimport reimport textwrap
from ._text import FoldedCase
class RawPolicy(email.policy.EmailPolicy): def fold(self, name, value): folded = self.linesep.join( textwrap .indent(value, prefix=' ' * 8, predicate=lambda line: True) .lstrip() .splitlines() ) return f'{name}: {folded}{self.linesep}'
class Message(email.message.Message): r""" Specialized Message subclass to handle metadata naturally.
Reads values that may have newlines in them and converts the payload to the Description.
>>> msg_text = textwrap.dedent(''' ... Name: Foo ... Version: 3.0 ... License: blah ... de-blah ... <BLANKLINE> ... First line of description. ... Second line of description. ... <BLANKLINE> ... Fourth line! ... ''').lstrip().replace('<BLANKLINE>', '') >>> msg = Message(email.message_from_string(msg_text)) >>> msg['Description'] 'First line of description.\nSecond line of description.\n\nFourth line!\n'
Message should render even if values contain newlines.
>>> print(msg) Name: Foo Version: 3.0 License: blah de-blah Description: First line of description. Second line of description. <BLANKLINE> Fourth line! <BLANKLINE> <BLANKLINE> """
multiple_use_keys = set( map( FoldedCase, [ 'Classifier', 'Obsoletes-Dist', 'Platform', 'Project-URL', 'Provides-Dist', 'Provides-Extra', 'Requires-Dist', 'Requires-External', 'Supported-Platform', 'Dynamic', ], ) ) """ Keys that may be indicated multiple times per PEP 566. """
def __new__(cls, orig: email.message.Message): res = super().__new__(cls) vars(res).update(vars(orig)) return res
def __init__(self, *args, **kwargs): self._headers = self._repair_headers()
# suppress spurious error from mypy def __iter__(self): return super().__iter__()
def __getitem__(self, item): """ Override parent behavior to typical dict behavior.
``email.message.Message`` will emit None values for missing keys. Typical mappings, including this ``Message``, will raise a key error for missing keys.
Ref python/importlib_metadata#371. """ res = super().__getitem__(item) if res is None: raise KeyError(item) return res
def _repair_headers(self): def redent(value): "Correct for RFC822 indentation" indent = ' ' * 8 if not value or '\n' + indent not in value: return value return textwrap.dedent(indent + value)
headers = [(key, redent(value)) for key, value in vars(self)['_headers']] if self._payload: headers.append(('Description', self.get_payload())) self.set_payload('') return headers
def as_string(self): return super().as_string(policy=RawPolicy())
@property def json(self): """ Convert PackageMetadata to a JSON-compatible format per PEP 0566. """
def transform(key): value = self.get_all(key) if key in self.multiple_use_keys else self[key] if key == 'Keywords': value = re.split(r'\s+', value) tk = key.lower().replace('-', '_') return tk, value
return dict(map(transform, map(FoldedCase, self)))12345678910111213141516171819202122232425262728293031323334import collectionsimport typing
# from jaraco.collections 3.3class FreezableDefaultDict(collections.defaultdict): """ Often it is desirable to prevent the mutation of a default dict after its initial construction, such as to prevent mutation during iteration.
>>> dd = FreezableDefaultDict(list) >>> dd[0].append('1') >>> dd.freeze() >>> dd[1] [] >>> len(dd) 1 """
def __missing__(self, key): return getattr(self, '_frozen', super().__missing__)(key)
def freeze(self): self._frozen = lambda key: self.default_factory()
class Pair(typing.NamedTuple): name: str value: str
@classmethod def parse(cls, text): return cls(*map(str.strip, text.split("=", 1)))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import platformimport sys
__all__ = ['install', 'NullFinder']
def install(cls): """ Class decorator for installation on sys.meta_path.
Adds the backport DistributionFinder to sys.meta_path and attempts to disable the finder functionality of the stdlib DistributionFinder. """ sys.meta_path.append(cls()) disable_stdlib_finder() return cls
def disable_stdlib_finder(): """ Give the backport primacy for discovering path-based distributions by monkey-patching the stdlib O_O.
See #91 for more background for rationale on this sketchy behavior. """
def matches(finder): return getattr( finder, '__module__', None ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions')
for finder in filter(matches, sys.meta_path): # pragma: nocover del finder.find_distributions
class NullFinder: """ A "Finder" (aka "MetaPathFinder") that never finds any modules, but may find distributions. """
@staticmethod def find_spec(*args, **kwargs): return None
def pypy_partial(val): """ Adjust for variable stacklevel on partial under PyPy.
Workaround for #327. """ is_pypy = platform.python_implementation() == 'PyPy' return val + is_pypy123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135import functoolsimport typesfrom typing import Callable, TypeVar
# from jaraco.functools 3.3def method_cache(method, cache_wrapper=None): """ Wrap lru_cache to support storing the cache data in the object instances.
Abstracts the common paradigm where the method explicitly saves an underscore-prefixed protected property on first call and returns that subsequently.
>>> class MyClass: ... calls = 0 ... ... @method_cache ... def method(self, value): ... self.calls += 1 ... return value
>>> a = MyClass() >>> a.method(3) 3 >>> for x in range(75): ... res = a.method(x) >>> a.calls 75
Note that the apparent behavior will be exactly like that of lru_cache except that the cache is stored on each instance, so values in one instance will not flush values from another, and when an instance is deleted, so are the cached values for that instance.
>>> b = MyClass() >>> for x in range(35): ... res = b.method(x) >>> b.calls 35 >>> a.method(0) 0 >>> a.calls 75
Note that if method had been decorated with ``functools.lru_cache()``, a.calls would have been 76 (due to the cached value of 0 having been flushed by the 'b' instance).
Clear the cache with ``.cache_clear()``
>>> a.method.cache_clear()
Same for a method that hasn't yet been called.
>>> c = MyClass() >>> c.method.cache_clear()
Another cache wrapper may be supplied:
>>> cache = functools.lru_cache(maxsize=2) >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) >>> a = MyClass() >>> a.method2() 3
Caution - do not subsequently wrap the method with another decorator, such as ``@property``, which changes the semantics of the function.
See also http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ for another implementation and additional justification. """ cache_wrapper = cache_wrapper or functools.lru_cache()
def wrapper(self, *args, **kwargs): # it's the first call, replace the method with a cached, bound method bound_method = types.MethodType(method, self) cached_method = cache_wrapper(bound_method) setattr(self, method.__name__, cached_method) return cached_method(*args, **kwargs)
# Support cache clear even before cache has been created. wrapper.cache_clear = lambda: None
return wrapper
# From jaraco.functools 3.3def pass_none(func): """ Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) """
@functools.wraps(func) def wrapper(param, *args, **kwargs): if param is not None: return func(param, *args, **kwargs)
return wrapper
# From jaraco.functools 4.4def noop(*args, **kwargs): """ A no-operation function that does nothing.
>>> noop(1, 2, three=3) """
_T = TypeVar('_T')
# From jaraco.functools 4.4def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]: """ Wrap the function to always return the first parameter.
>>> passthrough(print)('3') 3 '3' """
@functools.wraps(func) def wrapper(first: _T, *args, **kwargs) -> _T: func(first, *args, **kwargs) return first
return wrapper # type: ignore[return-value]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171from collections import defaultdict, dequefrom itertools import filterfalse
def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element
# copied from more_itertools 8.8def always_iterable(obj, base_type=(str, bytes)): """If *obj* is iterable, return an iterator over its items::
>>> obj = (1, 2, 3) >>> list(always_iterable(obj)) [1, 2, 3]
If *obj* is not iterable, return a one-item iterable containing *obj*::
>>> obj = 1 >>> list(always_iterable(obj)) [1]
If *obj* is ``None``, return an empty iterable:
>>> obj = None >>> list(always_iterable(None)) []
By default, binary and text strings are not considered iterable::
>>> obj = 'foo' >>> list(always_iterable(obj)) ['foo']
If *base_type* is set, objects for which ``isinstance(obj, base_type)`` returns ``True`` won't be considered iterable.
>>> obj = {'a': 1} >>> list(always_iterable(obj)) # Iterate over the dict's keys ['a'] >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit [{'a': 1}]
Set *base_type* to ``None`` to avoid any special handling and treat objects Python considers iterable as iterable:
>>> obj = 'foo' >>> list(always_iterable(obj, base_type=None)) ['f', 'o', 'o'] """ if obj is None: return iter(())
if (base_type is not None) and isinstance(obj, base_type): return iter((obj,))
try: return iter(obj) except TypeError: return iter((obj,))
# Copied from more_itertools 10.3class bucket: """Wrap *iterable* and return an object that buckets the iterable into child iterables based on a *key* function.
>>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character >>> sorted(list(s)) # Get the keys ['a', 'b', 'c'] >>> a_iterable = s['a'] >>> next(a_iterable) 'a1' >>> next(a_iterable) 'a2' >>> list(s['b']) ['b1', 'b2', 'b3']
The original iterable will be advanced and its items will be cached until they are used by the child iterables. This may require significant storage.
By default, attempting to select a bucket to which no items belong will exhaust the iterable and cache all values. If you specify a *validator* function, selected buckets will instead be checked against it.
>>> from itertools import count >>> it = count(1, 2) # Infinite sequence of odd numbers >>> key = lambda x: x % 10 # Bucket by last digit >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only >>> s = bucket(it, key=key, validator=validator) >>> 2 in s False >>> list(s[2]) []
"""
def __init__(self, iterable, key, validator=None): self._it = iter(iterable) self._key = key self._cache = defaultdict(deque) self._validator = validator or (lambda x: True)
def __contains__(self, value): if not self._validator(value): return False
try: item = next(self[value]) except StopIteration: return False else: self._cache[value].appendleft(item)
return True
def _get_values(self, value): """ Helper to yield items from the parent iterator that match *value*. Items that don't match are stored in the local cache as they are encountered. """ while True: # If we've cached some items that match the target value, emit # the first one and evict it from the cache. if self._cache[value]: yield self._cache[value].popleft() # Otherwise we need to advance the parent iterator to search for # a matching item, caching the rest. else: while True: try: item = next(self._it) except StopIteration: return item_value = self._key(item) if item_value == value: yield item break elif self._validator(item_value): self._cache[item_value].append(item)
def __iter__(self): for item in self._it: item_value = self._key(item) if self._validator(item_value): self._cache[item_value].append(item)
yield from self._cache.keys()
def __getitem__(self, value): if not self._validator(value): return iter(())
return self._get_values(value)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071from __future__ import annotations
import osfrom collections.abc import Iteratorfrom typing import ( Any, Protocol, TypeVar, overload,)
_T = TypeVar("_T")
class PackageMetadata(Protocol): def __len__(self) -> int: ... # pragma: no cover
def __contains__(self, item: str) -> bool: ... # pragma: no cover
def __getitem__(self, key: str) -> str: ... # pragma: no cover
def __iter__(self) -> Iterator[str]: ... # pragma: no cover
@overload def get( self, name: str, failobj: None = None ) -> str | None: ... # pragma: no cover
@overload def get(self, name: str, failobj: _T) -> str | _T: ... # pragma: no cover
# overload per python/importlib_metadata#435 @overload def get_all( self, name: str, failobj: None = None ) -> list[Any] | None: ... # pragma: no cover
@overload def get_all(self, name: str, failobj: _T) -> list[Any] | _T: """ Return all values associated with a possibly multi-valued key. """
@property def json(self) -> dict[str, str | list[str]]: """ A JSON-compatible form of the metadata. """
class SimplePath(Protocol): """ A minimal subset of pathlib.Path required by Distribution. """
def joinpath( self, other: str | os.PathLike[str] ) -> SimplePath: ... # pragma: no cover
def __truediv__( self, other: str | os.PathLike[str] ) -> SimplePath: ... # pragma: no cover
@property def parent(self) -> SimplePath: ... # pragma: no cover
def read_text(self, encoding=None) -> str: ... # pragma: no cover
def read_bytes(self) -> bytes: ... # pragma: no cover
def exists(self) -> bool: ... # pragma: no cover123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import re
from ._functools import method_cache
# from jaraco.text 3.5class FoldedCase(str): """ A case insensitive string class; behaves just like str except compares equal when the only variation is case.
>>> s = FoldedCase('hello world')
>>> s == 'Hello World' True
>>> 'Hello World' == s True
>>> s != 'Hello World' False
>>> s.index('O') 4
>>> s.split('O') ['hell', ' w', 'rld']
>>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) ['alpha', 'Beta', 'GAMMA']
Sequence membership is straightforward.
>>> "Hello World" in [s] True >>> s in ["Hello World"] True
You may test for set inclusion, but candidate and elements must both be folded.
>>> FoldedCase("Hello World") in {s} True >>> s in {FoldedCase("Hello World")} True
String inclusion works as long as the FoldedCase object is on the right.
>>> "hello" in FoldedCase("Hello World") True
But not if the FoldedCase object is on the left:
>>> FoldedCase('hello') in 'Hello World' False
In that case, use in_:
>>> FoldedCase('hello').in_('Hello World') True
>>> FoldedCase('hello') > FoldedCase('Hello') False """
def __lt__(self, other): return self.lower() < other.lower()
def __gt__(self, other): return self.lower() > other.lower()
def __eq__(self, other): return self.lower() == other.lower()
def __ne__(self, other): return self.lower() != other.lower()
def __hash__(self): return hash(self.lower())
def __contains__(self, other): return super().lower().__contains__(other.lower())
def in_(self, other): "Does self appear in other?" return self in FoldedCase(other)
# cache lower since it's likely to be called frequently. @method_cache def lower(self): return super().lower()
def index(self, sub): return self.lower().index(sub.lower())
def split(self, splitter=' ', maxsplit=0): pattern = re.compile(re.escape(splitter), re.I) return pattern.split(self, maxsplit)123456789101112131415import functoolsimport typing
from ._meta import PackageMetadata
md_none = functools.partial(typing.cast, PackageMetadata)"""Suppress type errors for optional metadata.
Although Distribution.metadata can return None when metadata is corruptand thus None, allow callers to assume it's not None and crash ifthat's the case.
# python/importlib_metadata#493"""12345678910111213141516171819202122import osimport pathlibimport sysimport types
def wrap(path): # pragma: no cover """ Workaround for https://github.com/python/cpython/issues/84538 to add backward compatibility for walk_up=True. An example affected package is dask-labextension, which uses jupyter-packaging to install JupyterLab javascript files outside of site-packages. """
def relative_to(root, *, walk_up=False): return pathlib.Path(os.path.relpath(path, root))
return types.SimpleNamespace(relative_to=relative_to)
relative_fix = wrap if sys.version_info < (3, 12) else lambda x: x123456789101112131415161718192021222324252627282930313233343536373839404142"""Compatibility layer with Python 3.8/3.9"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING: # pragma: no cover # Prevent circular imports on runtime. from .. import Distribution, EntryPointelse: Distribution = EntryPoint = Any
from .._typing import md_none
def normalized_name(dist: Distribution) -> str | None: """ Honor name normalization for distributions that don't provide ``_normalized_name``. """ try: return dist._normalized_name except AttributeError: from .. import Prepared # -> delay to prevent circular imports.
return Prepared.normalize( getattr(dist, "name", None) or md_none(dist.metadata)['Name'] )
def ep_matches(ep: EntryPoint, **params) -> bool: """ Workaround for ``EntryPoint`` objects without the ``matches`` method. """ try: return ep.matches(**params) except AttributeError: from .. import EntryPoint # -> delay to prevent circular imports.
# Reconstruct the EntryPoint object to make sure it is compatible. return EntryPoint(ep.name, ep.value, ep.group).matches(**params)123456789101112131415161718192021import sys
from . import Distribution
def inspect(path): print("Inspecting", path) dists = list(Distribution.discover(path=[path])) if not dists: return print("Found", len(dists), "packages:", end=' ') print(', '.join(dist.name for dist in dists))
def run(): for path in sys.path: inspect(path)
if __name__ == '__main__': run()1conda1234567891011121314151617Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), todeal in the Software without restriction, including without limitation therights to use, copy, modify, merge, publish, distribute, sublicense, and/orsell copies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGSIN THE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596Metadata-Version: 2.1Name: jaraco.textVersion: 4.0.0Summary: Module for text manipulationAuthor-email: "Jason R. Coombs" <jaraco@jaraco.com>Project-URL: Source, https://github.com/jaraco/jaraco.textClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyRequires-Python: >=3.8Description-Content-Type: text/x-rstLicense-File: LICENSERequires-Dist: jaraco.functoolsRequires-Dist: jaraco.context >=4.1Requires-Dist: autocommandRequires-Dist: more-itertoolsRequires-Dist: importlib-resources ; python_version < "3.9"Provides-Extra: docRequires-Dist: sphinx >=3.5 ; extra == 'doc'Requires-Dist: jaraco.packaging >=9.3 ; extra == 'doc'Requires-Dist: rst.linker >=1.9 ; extra == 'doc'Requires-Dist: furo ; extra == 'doc'Requires-Dist: sphinx-lint ; extra == 'doc'Requires-Dist: jaraco.tidelift >=1.4 ; extra == 'doc'Provides-Extra: inflectRequires-Dist: inflect ; extra == 'inflect'Provides-Extra: testRequires-Dist: pytest !=8.1.*,>=6 ; extra == 'test'Requires-Dist: pytest-checkdocs >=2.4 ; extra == 'test'Requires-Dist: pytest-cov ; extra == 'test'Requires-Dist: pytest-mypy ; extra == 'test'Requires-Dist: pytest-enabler >=2.2 ; extra == 'test'Requires-Dist: pathlib2 ; (python_version < "3.10") and extra == 'test'Requires-Dist: pytest-ruff >=0.2.1 ; (sys_platform != "cygwin") and extra == 'test'
.. image:: https://img.shields.io/pypi/v/jaraco.text.svg :target: https://pypi.org/project/jaraco.text
.. image:: https://img.shields.io/pypi/pyversions/jaraco.text.svg
.. image:: https://github.com/jaraco/jaraco.text/actions/workflows/main.yml/badge.svg :target: https://github.com/jaraco/jaraco.text/actions?query=workflow%3A%22tests%22 :alt: tests
.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json :target: https://github.com/astral-sh/ruff :alt: Ruff
.. image:: https://readthedocs.org/projects/jaracotext/badge/?version=latest :target: https://jaracotext.readthedocs.io/en/latest/?badge=latest
.. image:: https://img.shields.io/badge/skeleton-2024-informational :target: https://blog.jaraco.com/skeleton
.. image:: https://tidelift.com/badges/package/pypi/jaraco.text :target: https://tidelift.com/subscription/pkg/pypi-jaraco.text?utm_source=pypi-jaraco.text&utm_medium=readme
This package provides handy routines for dealing with text, such aswrapping, substitution, trimming, stripping, prefix and suffix removal,line continuation, indentation, comment processing, identifier processing,values parsing, case insensitive comparison, and more. See the docs(linked in the badge above) for the detailed documentation and examples.
Layouts=======
One of the features of this package is the layouts module, whichprovides a simple example of translating keystrokes from one keyboardlayout to another::
echo qwerty | python -m jaraco.text.to-dvorak ',.pyf echo "',.pyf" | python -m jaraco.text.to-qwerty qwerty
Newline Reporting=================
Need to know what newlines appear in a file?
::
$ python -m jaraco.text.show-newlines README.rst newline is '\n'
For Enterprise==============
Available as part of the Tidelift Subscription.
This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
`Learn more <https://tidelift.com/subscription/pkg/pypi-jaraco.text?utm_source=pypi-jaraco.text&utm_medium=referral&utm_campaign=github>`_.1234567891011121314jaraco.text-4.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2jaraco.text-4.0.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023jaraco.text-4.0.0.dist-info/METADATA,sha256=XC_QkBLJVPE5sQYkl41TNaZUw0AUzQb29GbKaD28nFY,3731jaraco.text-4.0.0.dist-info/RECORD,,jaraco.text-4.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0jaraco.text-4.0.0.dist-info/WHEEL,sha256=Wyh-_nZ0DJYolHNn1_hMa4lM7uDedD_RGVwbmTjyItk,91jaraco.text-4.0.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7jaraco/text/Lorem ipsum.txt,sha256=N_7c_79zxOufBY9HZ3yzMgOkNv-TkOTTio4BydrSjgs,1335jaraco/text/__init__.py,sha256=lazNYXo8IhOR1bFigLAyGiiQao6jtO3KGWh8bZZPx3c,16762jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643jaraco/text/show-newlines.py,sha256=jT0vp4gLhG20hX2lTB-zKo_i3NgKzj79yRAdz4eMzIM,903jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412jaraco/text/to-dvorak.py,sha256=36nPPsiifwv6RfpAb--3zpgbIx8ohnnI1aR29IJTO9s,118jaraco/text/to-qwerty.py,sha256=IQoFY9v7vLTEybcput4KBYm_5GR35pmtgZ_xyrmdTgI,11812345Wheel-Version: 1.0Generator: setuptools (71.1.0)Root-Is-Purelib: trueTag: py3-none-any
1jaraco123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367from __future__ import annotations
import contextlibimport errnoimport functoolsimport operatorimport osimport platformimport shutilimport statimport subprocessimport sysimport tempfileimport urllib.requestfrom collections.abc import Iterator
if sys.version_info < (3, 12): from backports import tarfileelse: import tarfile
@contextlib.contextmanagerdef pushd(dir: str | os.PathLike) -> Iterator[str | os.PathLike]: """ >>> tmp_path = getfixture('tmp_path') >>> with pushd(tmp_path): ... assert os.getcwd() == os.fspath(tmp_path) >>> assert os.getcwd() != os.fspath(tmp_path) """
orig = os.getcwd() os.chdir(dir) try: yield dir finally: os.chdir(orig)
@contextlib.contextmanagerdef tarball( url, target_dir: str | os.PathLike | None = None) -> Iterator[str | os.PathLike]: """ Get a URL to a tarball, download, extract, yield, then clean up.
Assumes everything in the tarball is prefixed with a common directory. That common path is stripped and the contents are extracted to ``target_dir``, similar to passing ``-C {target} --strip-components 1`` to the ``tar`` command.
Uses the streaming protocol to extract the contents from a stream in a single pass without loading the whole file into memory.
>>> import urllib.request >>> url = getfixture('tarfile_served') >>> target = getfixture('tmp_path') / 'out' >>> tb = tarball(url, target_dir=target) >>> import pathlib >>> with tb as extracted: ... contents = pathlib.Path(extracted, 'contents.txt').read_text(encoding='utf-8') >>> assert not os.path.exists(extracted)
If the target is not specified, contents are extracted to a directory relative to the current working directory named after the name of the file as extracted from the URL.
>>> target = getfixture('tmp_path') >>> with pushd(target), tarball(url): ... target.joinpath('served').is_dir() True """ if target_dir is None: target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '') os.mkdir(target_dir) try: req = urllib.request.urlopen(url) with tarfile.open(fileobj=req, mode='r|*') as tf: tf.extractall(path=target_dir, filter=_default_filter) yield target_dir finally: shutil.rmtree(target_dir)
def _compose_tarfile_filters(*filters): def compose_two(f1, f2): return lambda member, path: f1(f2(member, path), path)
return functools.reduce(compose_two, filters, lambda member, path: member)
def strip_first_component( member: tarfile.TarInfo, path,) -> tarfile.TarInfo: _, member.name = member.name.split('/', 1) return member
_default_filter = _compose_tarfile_filters(tarfile.data_filter, strip_first_component)
def _compose(*cmgrs): """ Compose any number of dependent context managers into a single one.
The last, innermost context manager may take arbitrary arguments, but each successive context manager should accept the result from the previous as a single parameter.
Like :func:`jaraco.functools.compose`, behavior works from right to left, so the context manager should be indicated from outermost to innermost.
Example, to create a context manager to change to a temporary directory:
>>> temp_dir_as_cwd = _compose(pushd, temp_dir) >>> with temp_dir_as_cwd() as dir: ... assert os.path.samefile(os.getcwd(), dir) """
def compose_two(inner, outer): def composed(*args, **kwargs): with inner(*args, **kwargs) as saved, outer(saved) as res: yield res
return contextlib.contextmanager(composed)
return functools.reduce(compose_two, reversed(cmgrs))
tarball_cwd = _compose(pushd, tarball)"""A tarball context with the current working directory pointing to the contents."""
def remove_readonly(func, path, exc_info): """ Add support for removing read-only files on Windows. """ _, exc, _ = exc_info if func in (os.rmdir, os.remove, os.unlink) and exc.errno == errno.EACCES: # change the file to be readable,writable,executable: 0777 os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # retry func(path) else: raise
def robust_remover(): return ( functools.partial(shutil.rmtree, onerror=remove_readonly) if platform.system() == 'Windows' else shutil.rmtree )
@contextlib.contextmanagerdef temp_dir(remover=shutil.rmtree): """ Create a temporary directory context. Pass a custom remover to override the removal behavior.
>>> import pathlib >>> with temp_dir() as the_dir: ... assert os.path.isdir(the_dir) >>> assert not os.path.exists(the_dir) """ temp_dir = tempfile.mkdtemp() try: yield temp_dir finally: remover(temp_dir)
robust_temp_dir = functools.partial(temp_dir, remover=robust_remover())
@contextlib.contextmanagerdef repo_context( url, branch: str | None = None, quiet: bool = True, dest_ctx=robust_temp_dir): """ Check out the repo indicated by url.
If dest_ctx is supplied, it should be a context manager to yield the target directory for the check out.
>>> getfixture('ensure_git') >>> getfixture('needs_internet') >>> repo = repo_context('https://github.com/jaraco/jaraco.context') >>> with repo as dest: ... listing = os.listdir(dest) >>> 'README.rst' in listing True """ exe = 'git' if 'git' in url else 'hg' with dest_ctx() as repo_dir: cmd = [exe, 'clone', url, repo_dir] cmd.extend(['--branch', branch] * bool(branch)) stream = subprocess.DEVNULL if quiet else None subprocess.check_call(cmd, stdout=stream, stderr=stream) yield repo_dir
class ExceptionTrap: """ A context manager that will catch certain exceptions and provide an indication they occurred.
>>> with ExceptionTrap() as trap: ... raise Exception() >>> bool(trap) True
>>> with ExceptionTrap() as trap: ... pass >>> bool(trap) False
>>> with ExceptionTrap(ValueError) as trap: ... raise ValueError("1 + 1 is not 3") >>> bool(trap) True >>> trap.value ValueError('1 + 1 is not 3') >>> trap.tb <traceback object at ...>
>>> with ExceptionTrap(ValueError) as trap: ... raise Exception() Traceback (most recent call last): ... Exception
>>> bool(trap) False """
exc_info = None, None, None
def __init__(self, exceptions=(Exception,)): self.exceptions = exceptions
def __enter__(self): return self
@property def type(self): return self.exc_info[0]
@property def value(self): return self.exc_info[1]
@property def tb(self): return self.exc_info[2]
def __exit__(self, *exc_info): type = exc_info[0] matches = type and issubclass(type, self.exceptions) if matches: self.exc_info = exc_info return matches
def __bool__(self): return bool(self.type)
def raises(self, func, *, _test=bool): """ Wrap func and replace the result with the truth value of the trap (True if an exception occurred).
First, give the decorator an alias to support Python 3.8 Syntax.
>>> raises = ExceptionTrap(ValueError).raises
Now decorate a function that always fails.
>>> @raises ... def fail(): ... raise ValueError('failed') >>> fail() True """
@functools.wraps(func) def wrapper(*args, **kwargs): with ExceptionTrap(self.exceptions) as trap: func(*args, **kwargs) return _test(trap)
return wrapper
def passes(self, func): """ Wrap func and replace the result with the truth value of the trap (True if no exception).
First, give the decorator an alias to support Python 3.8 Syntax.
>>> passes = ExceptionTrap(ValueError).passes
Now decorate a function that always fails.
>>> @passes ... def fail(): ... raise ValueError('failed')
>>> fail() False """ return self.raises(func, _test=operator.not_)
class suppress(contextlib.suppress, contextlib.ContextDecorator): """ A version of contextlib.suppress with decorator support.
>>> @suppress(KeyError) ... def key_error(): ... {}[''] >>> key_error() """
class on_interrupt(contextlib.ContextDecorator): """ Replace a KeyboardInterrupt with SystemExit(1).
Useful in conjunction with console entry point functions.
>>> def do_interrupt(): ... raise KeyboardInterrupt() >>> on_interrupt('error')(do_interrupt)() Traceback (most recent call last): ... SystemExit: 1 >>> on_interrupt('error', code=255)(do_interrupt)() Traceback (most recent call last): ... SystemExit: 255 >>> on_interrupt('suppress')(do_interrupt)() >>> with __import__('pytest').raises(KeyboardInterrupt): ... on_interrupt('ignore')(do_interrupt)() """
def __init__(self, action='error', /, code=1): self.action = action self.code = code
def __enter__(self): return self
def __exit__(self, exctype, excinst, exctb): if exctype is not KeyboardInterrupt or self.action == 'ignore': return elif self.action == 'error': raise SystemExit(self.code) from excinst return self.action == 'suppress'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722from __future__ import annotations
import collections.abcimport functoolsimport inspectimport itertoolsimport operatorimport timeimport typesimport warningsfrom typing import Callable, TypeVar
import more_itertools
def compose(*funcs): """ Compose any number of unary functions into a single unary function.
Comparable to `function composition <https://en.wikipedia.org/wiki/Function_composition>`_ in mathematics:
``h = g ∘ f`` implies ``h(x) = g(f(x))``.
In Python, ``h = compose(g, f)``.
>>> import textwrap >>> expected = str.strip(textwrap.dedent(compose.__doc__)) >>> strip_and_dedent = compose(str.strip, textwrap.dedent) >>> strip_and_dedent(compose.__doc__) == expected True
Compose also allows the innermost function to take arbitrary arguments.
>>> round_three = lambda x: round(x, ndigits=3) >>> f = compose(round_three, int.__truediv__) >>> [f(3*x, x+1) for x in range(1,10)] [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7] """
def compose_two(f1, f2): return lambda *args, **kwargs: f1(f2(*args, **kwargs))
return functools.reduce(compose_two, funcs)
def once(func): """ Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function will not be expensive on subsequent calls and is idempotent.
>>> add_three = once(lambda a: a+3) >>> add_three(3) 6 >>> add_three(9) 6 >>> add_three('12') 6
To reset the stored value, simply clear the property ``saved_result``.
>>> del add_three.saved_result >>> add_three(9) 12 >>> add_three(8) 12
Or invoke 'reset()' on it.
>>> add_three.reset() >>> add_three(-3) 0 >>> add_three(0) 0 """
@functools.wraps(func) def wrapper(*args, **kwargs): if not hasattr(wrapper, 'saved_result'): wrapper.saved_result = func(*args, **kwargs) return wrapper.saved_result
wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result') return wrapper
def method_cache(method, cache_wrapper=functools.lru_cache()): """ Wrap lru_cache to support storing the cache data in the object instances.
Abstracts the common paradigm where the method explicitly saves an underscore-prefixed protected property on first call and returns that subsequently.
>>> class MyClass: ... calls = 0 ... ... @method_cache ... def method(self, value): ... self.calls += 1 ... return value
>>> a = MyClass() >>> a.method(3) 3 >>> for x in range(75): ... res = a.method(x) >>> a.calls 75
Note that the apparent behavior will be exactly like that of lru_cache except that the cache is stored on each instance, so values in one instance will not flush values from another, and when an instance is deleted, so are the cached values for that instance.
>>> b = MyClass() >>> for x in range(35): ... res = b.method(x) >>> b.calls 35 >>> a.method(0) 0 >>> a.calls 75
Note that if method had been decorated with ``functools.lru_cache()``, a.calls would have been 76 (due to the cached value of 0 having been flushed by the 'b' instance).
Clear the cache with ``.cache_clear()``
>>> a.method.cache_clear()
Same for a method that hasn't yet been called.
>>> c = MyClass() >>> c.method.cache_clear()
Another cache wrapper may be supplied:
>>> cache = functools.lru_cache(maxsize=2) >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) >>> a = MyClass() >>> a.method2() 3
Caution - do not subsequently wrap the method with another decorator, such as ``@property``, which changes the semantics of the function.
See also http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ for another implementation and additional justification. """
def wrapper(self, *args, **kwargs): # it's the first call, replace the method with a cached, bound method bound_method = types.MethodType(method, self) cached_method = cache_wrapper(bound_method) setattr(self, method.__name__, cached_method) return cached_method(*args, **kwargs)
# Support cache clear even before cache has been created. wrapper.cache_clear = lambda: None
return _special_method_cache(method, cache_wrapper) or wrapper
def _special_method_cache(method, cache_wrapper): """ Because Python treats special methods differently, it's not possible to use instance attributes to implement the cached methods.
Instead, install the wrapper method under a different name and return a simple proxy to that wrapper.
https://github.com/jaraco/jaraco.functools/issues/5 """ name = method.__name__ special_names = '__getattr__', '__getitem__'
if name not in special_names: return None
wrapper_name = '__cached' + name
def proxy(self, /, *args, **kwargs): if wrapper_name not in vars(self): bound = types.MethodType(method, self) cache = cache_wrapper(bound) setattr(self, wrapper_name, cache) else: cache = getattr(self, wrapper_name) return cache(*args, **kwargs)
return proxy
def apply(transform): """ Decorate a function with a transform function that is invoked on results returned from the decorated function.
>>> @apply(reversed) ... def get_numbers(start): ... "doc for get_numbers" ... return range(start, start+3) >>> list(get_numbers(4)) [6, 5, 4] >>> get_numbers.__doc__ 'doc for get_numbers' """
def wrap(func): return functools.wraps(func)(compose(transform, func))
return wrap
def result_invoke(action): r""" Decorate a function with an action function that is invoked on the results returned from the decorated function (for its side effect), then return the original result.
>>> @result_invoke(print) ... def add_two(a, b): ... return a + b >>> x = add_two(2, 3) 5 >>> x 5 """
def wrap(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) action(result) return result
return wrapper
return wrap
def invoke(f, /, *args, **kwargs): """ Call a function for its side effect after initialization.
The benefit of using the decorator instead of simply invoking a function after defining it is that it makes explicit the author's intent for the function to be called immediately. Whereas if one simply calls the function immediately, it's less obvious if that was intentional or incidental. It also avoids repeating the name - the two actions, defining the function and calling it immediately are modeled separately, but linked by the decorator construct.
The benefit of having a function construct (opposed to just invoking some behavior inline) is to serve as a scope in which the behavior occurs. It avoids polluting the global namespace with local variables, provides an anchor on which to attach documentation (docstring), keeps the behavior logically separated (instead of conceptually separated or not separated at all), and provides potential to re-use the behavior for testing or other purposes.
This function is named as a pithy way to communicate, "call this function primarily for its side effect", or "while defining this function, also take it aside and call it". It exists because there's no Python construct for "define and call" (nor should there be, as decorators serve this need just fine). The behavior happens immediately and synchronously.
>>> @invoke ... def func(): print("called") called >>> func() called
Use functools.partial to pass parameters to the initial call
>>> @functools.partial(invoke, name='bingo') ... def func(name): print('called with', name) called with bingo """ f(*args, **kwargs) return f
_T = TypeVar('_T')
def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]: """ Wrap the function to always return the first parameter.
>>> passthrough(print)('3') 3 '3' """
@functools.wraps(func) def wrapper(first: _T, *args, **kwargs) -> _T: func(first, *args, **kwargs) return first
return wrapper
class Throttler: """Rate-limit a function (or other callable)."""
def __init__(self, func, max_rate=float('Inf')): if isinstance(func, Throttler): func = func.func self.func = func self.max_rate = max_rate self.reset()
def reset(self): self.last_called = 0
def __call__(self, *args, **kwargs): self._wait() return self.func(*args, **kwargs)
def _wait(self): """Ensure at least 1/max_rate seconds from last call.""" elapsed = time.time() - self.last_called must_wait = 1 / self.max_rate - elapsed time.sleep(max(0, must_wait)) self.last_called = time.time()
def __get__(self, obj, owner=None): return first_invoke(self._wait, functools.partial(self.func, obj))
def first_invoke(func1, func2): """ Return a function that when invoked will invoke func1 without any parameters (for its side effect) and then invoke func2 with whatever parameters were passed, returning its result. """
def wrapper(*args, **kwargs): func1() return func2(*args, **kwargs)
return wrapper
method_caller = first_invoke( lambda: warnings.warn( '`jaraco.functools.method_caller` is deprecated, ' 'use `operator.methodcaller` instead', DeprecationWarning, stacklevel=3, ), operator.methodcaller,)
def retry_call(func, cleanup=lambda: None, retries=0, trap=()): """ Given a callable func, trap the indicated exceptions for up to 'retries' times, invoking cleanup on the exception. On the final attempt, allow any exceptions to propagate. """ attempts = itertools.count() if retries == float('inf') else range(retries) for _ in attempts: try: return func() except trap: cleanup()
return func()
def retry(*r_args, **r_kwargs): """ Decorator wrapper for retry_call. Accepts arguments to retry_call except func and then returns a decorator for the decorated function.
Ex:
>>> @retry(retries=3) ... def my_func(a, b): ... "this is my funk" ... print(a, b) >>> my_func.__doc__ 'this is my funk' """
def decorate(func): @functools.wraps(func) def wrapper(*f_args, **f_kwargs): bound = functools.partial(func, *f_args, **f_kwargs) return retry_call(bound, *r_args, **r_kwargs)
return wrapper
return decorate
def print_yielded(func): """ Convert a generator into a function that prints all yielded elements.
>>> @print_yielded ... def x(): ... yield 3; yield None >>> x() 3 None """ print_all = functools.partial(map, print) print_results = compose(more_itertools.consume, print_all, func) return functools.wraps(func)(print_results)
def pass_none(func): """ Wrap func so it's not called if its first param is None.
>>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) """
@functools.wraps(func) def wrapper(param, /, *args, **kwargs): if param is not None: return func(param, *args, **kwargs) return None
return wrapper
def none_as(value, replacement=None): """ >>> none_as(None, 'foo') 'foo' >>> none_as('bar', 'foo') 'bar' """ return replacement if value is None else value
def assign_params(func, namespace): """ Assign parameters from namespace where func solicits.
>>> def func(x, y=3): ... print(x, y) >>> assigned = assign_params(func, dict(x=2, z=4)) >>> assigned() 2 3
The usual errors are raised if a function doesn't receive its required parameters:
>>> assigned = assign_params(func, dict(y=3, z=4)) >>> assigned() Traceback (most recent call last): TypeError: func() ...argument...
It even works on methods:
>>> class Handler: ... def meth(self, arg): ... print(arg) >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))() crystal """ sig = inspect.signature(func) params = sig.parameters.keys() call_ns = {k: namespace[k] for k in params if k in namespace} return functools.partial(func, **call_ns)
def save_method_args(method): """ Wrap a method such that when it is called, the args and kwargs are saved on the method.
>>> class MyClass: ... @save_method_args ... def method(self, a, b): ... print(a, b) >>> my_ob = MyClass() >>> my_ob.method(1, 2) 1 2 >>> my_ob._saved_method.args (1, 2) >>> my_ob._saved_method.kwargs {} >>> my_ob.method(a=3, b='foo') 3 foo >>> my_ob._saved_method.args () >>> my_ob._saved_method.kwargs == dict(a=3, b='foo') True
The arguments are stored on the instance, allowing for different instance to save different args.
>>> your_ob = MyClass() >>> your_ob.method({str('x'): 3}, b=[4]) {'x': 3} [4] >>> your_ob._saved_method.args ({'x': 3},) >>> my_ob._saved_method.args () """ args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') # noqa: PYI024 # Internal; stubs used for typing
@functools.wraps(method) def wrapper(self, /, *args, **kwargs): attr_name = '_saved_' + method.__name__ attr = args_and_kwargs(args, kwargs) setattr(self, attr_name, attr) return method(self, *args, **kwargs)
return wrapper
def except_(*exceptions, replace=None, use=None): """ Replace the indicated exceptions, if raised, with the indicated literal replacement or evaluated expression (if present).
>>> safe_int = except_(ValueError)(int) >>> safe_int('five') >>> safe_int('5') 5
Specify a literal replacement with ``replace``.
>>> safe_int_r = except_(ValueError, replace=0)(int) >>> safe_int_r('five') 0
Provide an expression to ``use`` to pass through particular parameters.
>>> safe_int_pt = except_(ValueError, use='args[0]')(int) >>> safe_int_pt('five') 'five'
"""
def decorate(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions: try: return eval(use) except TypeError: return replace
return wrapper
return decorate
def identity(x): """ Return the argument.
>>> o = object() >>> identity(o) is o True """ return x
def bypass_when(check, *, _op=identity): """ Decorate a function to return its parameter when ``check``.
>>> bypassed = [] # False
>>> @bypass_when(bypassed) ... def double(x): ... return x * 2 >>> double(2) 4 >>> bypassed[:] = [object()] # True >>> double(2) 2 """
def decorate(func): @functools.wraps(func) def wrapper(param, /): return param if _op(check) else func(param)
return wrapper
return decorate
def bypass_unless(check): """ Decorate a function to return its parameter unless ``check``.
>>> enabled = [object()] # True
>>> @bypass_unless(enabled) ... def double(x): ... return x * 2 >>> double(2) 4 >>> del enabled[:] # False >>> double(2) 2 """ return bypass_when(check, _op=operator.not_)
@functools.singledispatchdef _splat_inner(args, func): """Splat args to func.""" return func(*args)
@_splat_inner.registerdef _(args: collections.abc.Mapping, func): """Splat kargs to func as kwargs.""" return func(**args)
def splat(func): """ Wrap func to expect its parameters to be passed positionally in a tuple.
Has a similar effect to that of ``itertools.starmap`` over simple ``map``.
>>> pairs = [(-1, 1), (0, 2)] >>> more_itertools.consume(itertools.starmap(print, pairs)) -1 1 0 2 >>> more_itertools.consume(map(splat(print), pairs)) -1 1 0 2
The approach generalizes to other iterators that don't have a "star" equivalent, such as a "starfilter".
>>> list(filter(splat(operator.add), pairs)) [(0, 2)]
Splat also accepts a mapping argument.
>>> def is_nice(msg, code): ... return "smile" in msg or code == 0 >>> msgs = [ ... dict(msg='smile!', code=20), ... dict(msg='error :(', code=1), ... dict(msg='unknown', code=0), ... ] >>> for msg in filter(splat(is_nice), msgs): ... print(msg) {'msg': 'smile!', 'code': 20} {'msg': 'unknown', 'code': 0} """ return functools.wraps(func)(functools.partial(_splat_inner, func=func))
_T = TypeVar('_T')
def chainable(method: Callable[[_T, ...], None]) -> Callable[[_T, ...], _T]: """ Wrap an instance method to always return self.
>>> class Dingus: ... @chainable ... def set_attr(self, name, val): ... setattr(self, name, val) >>> d = Dingus().set_attr('a', 'eh!') >>> d.a 'eh!' >>> d2 = Dingus().set_attr('a', 'eh!').set_attr('b', 'bee!') >>> d2.a + d2.b 'eh!bee!'
Enforces that the return value is null.
>>> class BorkedDingus: ... @chainable ... def set_attr(self, name, val): ... setattr(self, name, val) ... return len(name) >>> BorkedDingus().set_attr('a', 'eh!') Traceback (most recent call last): ... AssertionError """
@functools.wraps(method) def wrapper(self, *args, **kwargs): assert method(self, *args, **kwargs) is None return self
return wrapper
def noop(*args, **kwargs): """ A no-operation function that does nothing.
>>> noop(1, 2, three=3) """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123from collections.abc import Callable, Hashable, Iteratorfrom functools import partialfrom operator import methodcallerfrom typing import ( Any, Generic, Protocol, TypeVar, overload,)
from typing_extensions import Concatenate, ParamSpec, TypeVarTuple, Unpack
_P = ParamSpec('_P')_R = TypeVar('_R')_T = TypeVar('_T')_Ts = TypeVarTuple('_Ts')_R1 = TypeVar('_R1')_R2 = TypeVar('_R2')_V = TypeVar('_V')_S = TypeVar('_S')_R_co = TypeVar('_R_co', covariant=True)
class _OnceCallable(Protocol[_P, _R]): saved_result: _R reset: Callable[[], None] def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...
class _ProxyMethodCacheWrapper(Protocol[_R_co]): cache_clear: Callable[[], None] def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ...
class _MethodCacheWrapper(Protocol[_R_co]): def cache_clear(self) -> None: ... def __call__(self, *args: Hashable, **kwargs: Hashable) -> _R_co: ...
# `compose()` overloads below will cover most use cases.
@overloaddef compose( __func1: Callable[[_R], _T], __func2: Callable[_P, _R], /,) -> Callable[_P, _T]: ...@overloaddef compose( __func1: Callable[[_R], _T], __func2: Callable[[_R1], _R], __func3: Callable[_P, _R1], /,) -> Callable[_P, _T]: ...@overloaddef compose( __func1: Callable[[_R], _T], __func2: Callable[[_R2], _R], __func3: Callable[[_R1], _R2], __func4: Callable[_P, _R1], /,) -> Callable[_P, _T]: ...def once(func: Callable[_P, _R]) -> _OnceCallable[_P, _R]: ...def method_cache( method: Callable[..., _R], cache_wrapper: Callable[[Callable[..., _R]], _MethodCacheWrapper[_R]] = ...,) -> _MethodCacheWrapper[_R] | _ProxyMethodCacheWrapper[_R]: ...def apply( transform: Callable[[_R], _T],) -> Callable[[Callable[_P, _R]], Callable[_P, _T]]: ...def result_invoke( action: Callable[[_R], Any],) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...def invoke( f: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _R]: ...
class Throttler(Generic[_R]): last_called: float func: Callable[..., _R] max_rate: float def __init__( self, func: Callable[..., _R] | Throttler[_R], max_rate: float = ... ) -> None: ... def reset(self) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _R: ... def __get__(self, obj: Any, owner: type[Any] | None = ...) -> Callable[..., _R]: ...
def first_invoke( func1: Callable[..., Any], func2: Callable[_P, _R]) -> Callable[_P, _R]: ...
method_caller: Callable[..., methodcaller]
def retry_call( func: Callable[..., _R], cleanup: Callable[..., None] = ..., retries: float = ..., trap: type[BaseException] | tuple[type[BaseException], ...] = ...,) -> _R: ...def retry( cleanup: Callable[..., None] = ..., retries: float = ..., trap: type[BaseException] | tuple[type[BaseException], ...] = ...,) -> Callable[[Callable[..., _R]], Callable[..., _R]]: ...def print_yielded(func: Callable[_P, Iterator[Any]]) -> Callable[_P, None]: ...def pass_none( func: Callable[Concatenate[_T, _P], _R],) -> Callable[Concatenate[_T, _P], _R]: ...def assign_params( func: Callable[..., _R], namespace: dict[str, Any]) -> partial[_R]: ...def save_method_args( method: Callable[Concatenate[_S, _P], _R],) -> Callable[Concatenate[_S, _P], _R]: ...def except_( *exceptions: type[BaseException], replace: Any = ..., use: Any = ...) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]: ...def identity(x: _T) -> _T: ...def bypass_when( check: _V, *, _op: Callable[[_V], Any] = ...) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ...def bypass_unless( check: Any,) -> Callable[[Callable[[_T], _R]], Callable[[_T], _T | _R]]: ...def splat(func: Callable[[Unpack[_Ts]], _R]) -> Callable[[tuple[Unpack[_Ts]]], _R]: ...12Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647import functoolsimport itertoolsimport reimport textwrap
from typing import Iterable
try: from importlib.resources import files # type: ignoreexcept ImportError: # pragma: nocover from importlib_resources import files # type: ignore
from jaraco.context import ExceptionTrapfrom jaraco.functools import compose, method_cache
def substitution(old, new): """ Return a function that will perform a substitution on a string """ return lambda s: s.replace(old, new)
def multi_substitution(*substitutions): """ Take a sequence of pairs specifying substitutions, and create a function that performs those substitutions.
>>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo') 'baz' """ substitutions = itertools.starmap(substitution, substitutions) # compose function applies last function first, so reverse the # substitutions to get the expected order. substitutions = reversed(tuple(substitutions)) return compose(*substitutions)
class FoldedCase(str): """ A case insensitive string class; behaves just like str except compares equal when the only variation is case.
>>> s = FoldedCase('hello world')
>>> s == 'Hello World' True
>>> 'Hello World' == s True
>>> s != 'Hello World' False
>>> s.index('O') 4
>>> s.split('O') ['hell', ' w', 'rld']
>>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) ['alpha', 'Beta', 'GAMMA']
Sequence membership is straightforward.
>>> "Hello World" in [s] True >>> s in ["Hello World"] True
Allows testing for set inclusion, but candidate and elements must both be folded.
>>> FoldedCase("Hello World") in {s} True >>> s in {FoldedCase("Hello World")} True
String inclusion works as long as the FoldedCase object is on the right.
>>> "hello" in FoldedCase("Hello World") True
But not if the FoldedCase object is on the left:
>>> FoldedCase('hello') in 'Hello World' False
In that case, use ``in_``:
>>> FoldedCase('hello').in_('Hello World') True
>>> FoldedCase('hello') > FoldedCase('Hello') False
>>> FoldedCase('ß') == FoldedCase('ss') True """
def __lt__(self, other): return self.casefold() < other.casefold()
def __gt__(self, other): return self.casefold() > other.casefold()
def __eq__(self, other): return self.casefold() == other.casefold()
def __ne__(self, other): return self.casefold() != other.casefold()
def __hash__(self): return hash(self.casefold())
def __contains__(self, other): return super().casefold().__contains__(other.casefold())
def in_(self, other): "Does self appear in other?" return self in FoldedCase(other)
# cache casefold since it's likely to be called frequently. @method_cache def casefold(self): return super().casefold()
def index(self, sub): return self.casefold().index(sub.casefold())
def split(self, splitter=' ', maxsplit=0): pattern = re.compile(re.escape(splitter), re.I) return pattern.split(self, maxsplit)
# Python 3.8 compatibility_unicode_trap = ExceptionTrap(UnicodeDecodeError)
@_unicode_trap.passesdef is_decodable(value): r""" Return True if the supplied value is decodable (using the default encoding).
>>> is_decodable(b'\xff') False >>> is_decodable(b'\x32') True """ value.decode()
def is_binary(value): r""" Return True if the value appears to be binary (that is, it's a byte string and isn't decodable).
>>> is_binary(b'\xff') True >>> is_binary('\xff') False """ return isinstance(value, bytes) and not is_decodable(value)
def trim(s): r""" Trim something like a docstring to remove the whitespace that is common due to indentation and formatting.
>>> trim("\n\tfoo = bar\n\t\tbar = baz\n") 'foo = bar\n\tbar = baz' """ return textwrap.dedent(s).strip()
def wrap(s): """ Wrap lines of text, retaining existing newlines as paragraph markers.
>>> print(wrap(lorem_ipsum)) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <BLANKLINE> Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst. """ paragraphs = s.splitlines() wrapped = ('\n'.join(textwrap.wrap(para)) for para in paragraphs) return '\n\n'.join(wrapped)
def unwrap(s): r""" Given a multi-line string, return an unwrapped version.
>>> wrapped = wrap(lorem_ipsum) >>> wrapped.count('\n') 20 >>> unwrapped = unwrap(wrapped) >>> unwrapped.count('\n') 1 >>> print(unwrapped) Lorem ipsum dolor sit amet, consectetur adipiscing ... Curabitur pretium tincidunt lacus. Nulla gravida orci ...
""" paragraphs = re.split(r'\n\n+', s) cleaned = (para.replace('\n', ' ') for para in paragraphs) return '\n'.join(cleaned)
lorem_ipsum: str = ( files(__name__).joinpath('Lorem ipsum.txt').read_text(encoding='utf-8'))
class Splitter: """object that will split a string with the given arguments for each call
>>> s = Splitter(',') >>> s('hello, world, this is your, master calling') ['hello', ' world', ' this is your', ' master calling'] """
def __init__(self, *args): self.args = args
def __call__(self, s): return s.split(*self.args)
def indent(string, prefix=' ' * 4): """ >>> indent('foo') ' foo' """ return prefix + string
class WordSet(tuple): """ Given an identifier, return the words that identifier represents, whether in camel case, underscore-separated, etc.
>>> WordSet.parse("camelCase") ('camel', 'Case')
>>> WordSet.parse("under_sep") ('under', 'sep')
Acronyms should be retained
>>> WordSet.parse("firstSNL") ('first', 'SNL')
>>> WordSet.parse("you_and_I") ('you', 'and', 'I')
>>> WordSet.parse("A simple test") ('A', 'simple', 'test')
Multiple caps should not interfere with the first cap of another word.
>>> WordSet.parse("myABCClass") ('my', 'ABC', 'Class')
The result is a WordSet, providing access to other forms.
>>> WordSet.parse("myABCClass").underscore_separated() 'my_ABC_Class'
>>> WordSet.parse('a-command').camel_case() 'ACommand'
>>> WordSet.parse('someIdentifier').lowered().space_separated() 'some identifier'
Slices of the result should return another WordSet.
>>> WordSet.parse('taken-out-of-context')[1:].underscore_separated() 'out_of_context'
>>> WordSet.from_class_name(WordSet()).lowered().space_separated() 'word set'
>>> example = WordSet.parse('figured it out') >>> example.headless_camel_case() 'figuredItOut' >>> example.dash_separated() 'figured-it-out'
"""
_pattern = re.compile('([A-Z]?[a-z]+)|([A-Z]+(?![a-z]))')
def capitalized(self): return WordSet(word.capitalize() for word in self)
def lowered(self): return WordSet(word.lower() for word in self)
def camel_case(self): return ''.join(self.capitalized())
def headless_camel_case(self): words = iter(self) first = next(words).lower() new_words = itertools.chain((first,), WordSet(words).camel_case()) return ''.join(new_words)
def underscore_separated(self): return '_'.join(self)
def dash_separated(self): return '-'.join(self)
def space_separated(self): return ' '.join(self)
def trim_right(self, item): """ Remove the item from the end of the set.
>>> WordSet.parse('foo bar').trim_right('foo') ('foo', 'bar') >>> WordSet.parse('foo bar').trim_right('bar') ('foo',) >>> WordSet.parse('').trim_right('bar') () """ return self[:-1] if self and self[-1] == item else self
def trim_left(self, item): """ Remove the item from the beginning of the set.
>>> WordSet.parse('foo bar').trim_left('foo') ('bar',) >>> WordSet.parse('foo bar').trim_left('bar') ('foo', 'bar') >>> WordSet.parse('').trim_left('bar') () """ return self[1:] if self and self[0] == item else self
def trim(self, item): """ >>> WordSet.parse('foo bar').trim('foo') ('bar',) """ return self.trim_left(item).trim_right(item)
def __getitem__(self, item): result = super().__getitem__(item) if isinstance(item, slice): result = WordSet(result) return result
@classmethod def parse(cls, identifier): matches = cls._pattern.finditer(identifier) return WordSet(match.group(0) for match in matches)
@classmethod def from_class_name(cls, subject): return cls.parse(subject.__class__.__name__)
# for backward compatibilitywords = WordSet.parse
def simple_html_strip(s): r""" Remove HTML from the string `s`.
>>> str(simple_html_strip('')) ''
>>> print(simple_html_strip('A <bold>stormy</bold> day in paradise')) A stormy day in paradise
>>> print(simple_html_strip('Somebody <!-- do not --> tell the truth.')) Somebody tell the truth.
>>> print(simple_html_strip('What about<br/>\nmultiple lines?')) What about multiple lines? """ html_stripper = re.compile('(<!--.*?-->)|(<[^>]*>)|([^<]+)', re.DOTALL) texts = (match.group(3) or '' for match in html_stripper.finditer(s)) return ''.join(texts)
class SeparatedValues(str): """ A string separated by a separator. Overrides __iter__ for getting the values.
>>> list(SeparatedValues('a,b,c')) ['a', 'b', 'c']
Whitespace is stripped and empty values are discarded.
>>> list(SeparatedValues(' a, b , c, ')) ['a', 'b', 'c'] """
separator = ','
def __iter__(self): parts = self.split(self.separator) return filter(None, (part.strip() for part in parts))
class Stripper: r""" Given a series of lines, find the common prefix and strip it from them.
>>> lines = [ ... 'abcdefg\n', ... 'abc\n', ... 'abcde\n', ... ] >>> res = Stripper.strip_prefix(lines) >>> res.prefix 'abc' >>> list(res.lines) ['defg\n', '\n', 'de\n']
If no prefix is common, nothing should be stripped.
>>> lines = [ ... 'abcd\n', ... '1234\n', ... ] >>> res = Stripper.strip_prefix(lines) >>> res.prefix = '' >>> list(res.lines) ['abcd\n', '1234\n'] """
def __init__(self, prefix, lines): self.prefix = prefix self.lines = map(self, lines)
@classmethod def strip_prefix(cls, lines): prefix_lines, lines = itertools.tee(lines) prefix = functools.reduce(cls.common_prefix, prefix_lines) return cls(prefix, lines)
def __call__(self, line): if not self.prefix: return line null, prefix, rest = line.partition(self.prefix) return rest
@staticmethod def common_prefix(s1, s2): """ Return the common prefix of two lines. """ index = min(len(s1), len(s2)) while s1[:index] != s2[:index]: index -= 1 return s1[:index]
def remove_prefix(text, prefix): """ Remove the prefix from the text if it exists.
>>> remove_prefix('underwhelming performance', 'underwhelming ') 'performance'
>>> remove_prefix('something special', 'sample') 'something special' """ null, prefix, rest = text.rpartition(prefix) return rest
def remove_suffix(text, suffix): """ Remove the suffix from the text if it exists.
>>> remove_suffix('name.git', '.git') 'name'
>>> remove_suffix('something special', 'sample') 'something special' """ rest, suffix, null = text.partition(suffix) return rest
def normalize_newlines(text): r""" Replace alternate newlines with the canonical newline.
>>> normalize_newlines('Lorem Ipsum\u2029') 'Lorem Ipsum\n' >>> normalize_newlines('Lorem Ipsum\r\n') 'Lorem Ipsum\n' >>> normalize_newlines('Lorem Ipsum\x85') 'Lorem Ipsum\n' """ newlines = ['\r\n', '\r', '\n', '\u0085', '\u2028', '\u2029'] pattern = '|'.join(newlines) return re.sub(pattern, '\n', text)
def _nonblank(str): return str and not str.startswith('#')
@functools.singledispatchdef yield_lines(iterable): r""" Yield valid lines of a string or iterable.
>>> list(yield_lines('')) [] >>> list(yield_lines(['foo', 'bar'])) ['foo', 'bar'] >>> list(yield_lines('foo\nbar')) ['foo', 'bar'] >>> list(yield_lines('\nfoo\n#bar\nbaz #comment')) ['foo', 'baz #comment'] >>> list(yield_lines(['foo\nbar', 'baz', 'bing\n\n\n'])) ['foo', 'bar', 'baz', 'bing'] """ return itertools.chain.from_iterable(map(yield_lines, iterable))
@yield_lines.register(str)def _(text): return clean(text.splitlines())
def clean(lines: Iterable[str]): """ Yield non-blank, non-comment elements from lines. """ return filter(_nonblank, map(str.strip, lines))
def drop_comment(line): """ Drop comments.
>>> drop_comment('foo # bar') 'foo'
A hash without a space may be in a URL.
>>> drop_comment('http://example.com/foo#bar') 'http://example.com/foo#bar' """ return line.partition(' #')[0]
def join_continuation(lines): r""" Join lines continued by a trailing backslash.
>>> list(join_continuation(['foo \\', 'bar', 'baz'])) ['foobar', 'baz'] >>> list(join_continuation(['foo \\', 'bar', 'baz'])) ['foobar', 'baz'] >>> list(join_continuation(['foo \\', 'bar \\', 'baz'])) ['foobarbaz']
Not sure why, but... The character preceding the backslash is also elided.
>>> list(join_continuation(['goo\\', 'dly'])) ['godly']
A terrible idea, but... If no line is available to continue, suppress the lines.
>>> list(join_continuation(['foo', 'bar\\', 'baz\\'])) ['foo'] """ lines = iter(lines) for item in lines: while item.endswith('\\'): try: item = item[:-2].strip() + next(lines) except StopIteration: return yield item
def read_newlines(filename, limit=1024): r""" >>> tmp_path = getfixture('tmp_path') >>> filename = tmp_path / 'out.txt' >>> _ = filename.write_text('foo\n', newline='', encoding='utf-8') >>> read_newlines(filename) '\n' >>> _ = filename.write_text('foo\r\n', newline='', encoding='utf-8') >>> read_newlines(filename) '\r\n' >>> _ = filename.write_text('foo\r\nbar\nbing\r', newline='', encoding='utf-8') >>> read_newlines(filename) ('\r', '\n', '\r\n') """ with open(filename, encoding='utf-8') as fp: fp.read(limit) return fp.newlines
def lines_from(input): """ Generate lines from a :class:`importlib.resources.abc.Traversable` path.
>>> lines = lines_from(files(__name__).joinpath('Lorem ipsum.txt')) >>> next(lines) 'Lorem ipsum...' >>> next(lines) 'Curabitur pretium...' """ with input.open(encoding='utf-8') as stream: yield from stream.conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/PKG-INFOAdded+140
.conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/SOURCES.txtAdded+518
.conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/dependency_links.txtAdded+1
.conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/entry_points.txtAdded+51
.conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/requires.txtAdded+84
.conda-env/lib/python3.11/site-packages/setuptools-84.0.0-py3.11.egg-info/top_level.txtAdded+2
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLERAdded+1
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATAAdded+133
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORDAdded+21
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTEDAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEELAdded+5
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSEAdded+73
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txtAdded+1
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_typing.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_adapters.pyAdded+136
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.pyAdded+34
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_compat.pyAdded+56
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_functools.pyAdded+135
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_itertools.pyAdded+171
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_meta.pyAdded+71
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_text.pyAdded+99
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_typing.pyAdded+15
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.pyAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.pyAdded+22
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.pyAdded+42
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/diagnose.pyAdded+21
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/importlib_metadata/py.typedAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLERAdded+1
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSEAdded+17
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATAAdded+96
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORDAdded+14
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTEDAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEELAdded+5
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txtAdded+1
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/context/__init__.pyAdded+367
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/context/__pycache__/__init__.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/context/py.typedAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyAdded+722
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyiAdded+123
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/functools/py.typedAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txtAdded+2
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/__init__.pyAdded+647
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-311.pycAdded
.conda-env/lib/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-311.pycAdded