Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/METADATA +105 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/RECORD +21 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/REQUESTED +0 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/WHEEL +5 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/direct_url.json +1 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/licenses/LICENSE +3 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/licenses/LICENSE.APACHE2 +202 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/licenses/LICENSE.MIT +20 -0
- miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/top_level.txt +1 -0
- miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.bat +5 -0
- miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.sh +2 -0
- miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.bat +2 -0
- miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.sh +2 -0
- miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/INSTALLER +1 -0
- miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/METADATA +270 -0
- miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/RECORD +16 -0
- miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/REQUESTED +0 -0
- miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/WHEEL +4 -0
- miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/direct_url.json +1 -0
- miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/licenses/LICENSE +21 -0
- miniconda3/lib/python3.13/site-packages/tomli/__init__.py +8 -0
- miniconda3/lib/python3.13/site-packages/tomli/_parser.py +782 -0
- miniconda3/lib/python3.13/site-packages/tomli/_re.py +119 -0
- miniconda3/lib/python3.13/site-packages/tomli/_types.py +10 -0
- miniconda3/lib/python3.13/site-packages/tomli/py.typed +1 -0
- miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/INSTALLER +1 -0
- miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/METADATA +78 -0
- miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/RECORD +34 -0
- miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/REQUESTED +0 -0
- miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/WHEEL +4 -0
- miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/direct_url.json +1 -0
- miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/licenses/LICENSE +20 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/__init__.py +59 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/_compat.py +22 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/_types.py +82 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/_utils.py +158 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/api.py +312 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/container.py +946 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/exceptions.py +234 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/items.py +2013 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/parser.py +1140 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/py.typed +0 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/source.py +180 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/toml_char.py +52 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/toml_document.py +7 -0
- miniconda3/lib/python3.13/site-packages/tomlkit/toml_file.py +59 -0
- miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/INSTALLER +1 -0
- miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/METADATA +1595 -0
- miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/RECORD +74 -0
- miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/REQUESTED +0 -0
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: sniffio
|
| 3 |
+
Version: 1.3.1
|
| 4 |
+
Summary: Sniff out which async library your code is running under
|
| 5 |
+
Author-email: "Nathaniel J. Smith" <njs@pobox.com>
|
| 6 |
+
License: MIT OR Apache-2.0
|
| 7 |
+
Project-URL: Homepage, https://github.com/python-trio/sniffio
|
| 8 |
+
Project-URL: Documentation, https://sniffio.readthedocs.io/
|
| 9 |
+
Project-URL: Changelog, https://sniffio.readthedocs.io/en/latest/history.html
|
| 10 |
+
Keywords: async,trio,asyncio
|
| 11 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 12 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 13 |
+
Classifier: Framework :: Trio
|
| 14 |
+
Classifier: Framework :: AsyncIO
|
| 15 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 16 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
| 17 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 18 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 19 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 20 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 21 |
+
Classifier: Intended Audience :: Developers
|
| 22 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 23 |
+
Requires-Python: >=3.7
|
| 24 |
+
Description-Content-Type: text/x-rst
|
| 25 |
+
License-File: LICENSE
|
| 26 |
+
License-File: LICENSE.APACHE2
|
| 27 |
+
License-File: LICENSE.MIT
|
| 28 |
+
Dynamic: license-file
|
| 29 |
+
|
| 30 |
+
.. image:: https://img.shields.io/badge/chat-join%20now-blue.svg
|
| 31 |
+
:target: https://gitter.im/python-trio/general
|
| 32 |
+
:alt: Join chatroom
|
| 33 |
+
|
| 34 |
+
.. image:: https://img.shields.io/badge/docs-read%20now-blue.svg
|
| 35 |
+
:target: https://sniffio.readthedocs.io/en/latest/?badge=latest
|
| 36 |
+
:alt: Documentation Status
|
| 37 |
+
|
| 38 |
+
.. image:: https://img.shields.io/pypi/v/sniffio.svg
|
| 39 |
+
:target: https://pypi.org/project/sniffio
|
| 40 |
+
:alt: Latest PyPi version
|
| 41 |
+
|
| 42 |
+
.. image:: https://img.shields.io/conda/vn/conda-forge/sniffio.svg
|
| 43 |
+
:target: https://anaconda.org/conda-forge/sniffio
|
| 44 |
+
:alt: Latest conda-forge version
|
| 45 |
+
|
| 46 |
+
.. image:: https://travis-ci.org/python-trio/sniffio.svg?branch=master
|
| 47 |
+
:target: https://travis-ci.org/python-trio/sniffio
|
| 48 |
+
:alt: Automated test status
|
| 49 |
+
|
| 50 |
+
.. image:: https://codecov.io/gh/python-trio/sniffio/branch/master/graph/badge.svg
|
| 51 |
+
:target: https://codecov.io/gh/python-trio/sniffio
|
| 52 |
+
:alt: Test coverage
|
| 53 |
+
|
| 54 |
+
=================================================================
|
| 55 |
+
sniffio: Sniff out which async library your code is running under
|
| 56 |
+
=================================================================
|
| 57 |
+
|
| 58 |
+
You're writing a library. You've decided to be ambitious, and support
|
| 59 |
+
multiple async I/O packages, like `Trio
|
| 60 |
+
<https://trio.readthedocs.io>`__, and `asyncio
|
| 61 |
+
<https://docs.python.org/3/library/asyncio.html>`__, and ... You've
|
| 62 |
+
written a bunch of clever code to handle all the differences. But...
|
| 63 |
+
how do you know *which* piece of clever code to run?
|
| 64 |
+
|
| 65 |
+
This is a tiny package whose only purpose is to let you detect which
|
| 66 |
+
async library your code is running under.
|
| 67 |
+
|
| 68 |
+
* Documentation: https://sniffio.readthedocs.io
|
| 69 |
+
|
| 70 |
+
* Bug tracker and source code: https://github.com/python-trio/sniffio
|
| 71 |
+
|
| 72 |
+
* License: MIT or Apache License 2.0, your choice
|
| 73 |
+
|
| 74 |
+
* Contributor guide: https://trio.readthedocs.io/en/latest/contributing.html
|
| 75 |
+
|
| 76 |
+
* Code of conduct: Contributors are requested to follow our `code of
|
| 77 |
+
conduct
|
| 78 |
+
<https://trio.readthedocs.io/en/latest/code-of-conduct.html>`_
|
| 79 |
+
in all project spaces.
|
| 80 |
+
|
| 81 |
+
This library is maintained by the Trio project, as a service to the
|
| 82 |
+
async Python community as a whole.
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
Quickstart
|
| 86 |
+
----------
|
| 87 |
+
|
| 88 |
+
.. code-block:: python3
|
| 89 |
+
|
| 90 |
+
from sniffio import current_async_library
|
| 91 |
+
import trio
|
| 92 |
+
import asyncio
|
| 93 |
+
|
| 94 |
+
async def print_library():
|
| 95 |
+
library = current_async_library()
|
| 96 |
+
print("This is:", library)
|
| 97 |
+
|
| 98 |
+
# Prints "This is trio"
|
| 99 |
+
trio.run(print_library)
|
| 100 |
+
|
| 101 |
+
# Prints "This is asyncio"
|
| 102 |
+
asyncio.run(print_library())
|
| 103 |
+
|
| 104 |
+
For more details, including how to add support to new async libraries,
|
| 105 |
+
`please peruse our fine manual <https://sniffio.readthedocs.io>`__.
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
sniffio-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
sniffio-1.3.1.dist-info/METADATA,sha256=iBHZyTWv8VlfclyAh1YCAYAuC_9f-RIosA6NxaMeABU,3793
|
| 3 |
+
sniffio-1.3.1.dist-info/RECORD,,
|
| 4 |
+
sniffio-1.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
sniffio-1.3.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
| 6 |
+
sniffio-1.3.1.dist-info/direct_url.json,sha256=h4EYYmq5gkCXVmSjI4CiGYw50Tq7AXwPo3QAVDQSBkU,97
|
| 7 |
+
sniffio-1.3.1.dist-info/licenses/LICENSE,sha256=ZSyHhIjRRWNh4Iw_hgf9e6WYkqFBA9Fczk_5PIW1zIs,185
|
| 8 |
+
sniffio-1.3.1.dist-info/licenses/LICENSE.APACHE2,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
| 9 |
+
sniffio-1.3.1.dist-info/licenses/LICENSE.MIT,sha256=Pm2uVV65J4f8gtHUg1Vnf0VMf2Wus40_nnK_mj2vA0s,1046
|
| 10 |
+
sniffio-1.3.1.dist-info/top_level.txt,sha256=v9UJXGs5CyddCVeAqXkQiWOrpp6Wtx6GeRrPt9-jjHg,8
|
| 11 |
+
sniffio/__init__.py,sha256=9WJEJlXu7yluP0YtI5SQ9M9OTQfbNHkadarK1vXGDPM,335
|
| 12 |
+
sniffio/__pycache__/__init__.cpython-313.pyc,,
|
| 13 |
+
sniffio/__pycache__/_impl.cpython-313.pyc,,
|
| 14 |
+
sniffio/__pycache__/_version.cpython-313.pyc,,
|
| 15 |
+
sniffio/_impl.py,sha256=UmUFMZpiuOrcjnuHhuYiYMxeCNWfqu9kBlaPf0xk6X8,2843
|
| 16 |
+
sniffio/_tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 17 |
+
sniffio/_tests/__pycache__/__init__.cpython-313.pyc,,
|
| 18 |
+
sniffio/_tests/__pycache__/test_sniffio.cpython-313.pyc,,
|
| 19 |
+
sniffio/_tests/test_sniffio.py,sha256=MMJZZJjQrUi95RANNM-a_55BZquA_gv4rHU1pevcTCM,2058
|
| 20 |
+
sniffio/_version.py,sha256=iVes5xwsHeRzQDexBaAhyx_taNt2ucfA7CWAo4QDt6Q,89
|
| 21 |
+
sniffio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///home/task_176432917442011/conda-bld/sniffio_1764329188237/work"}
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This software is made available under the terms of *either* of the
|
| 2 |
+
licenses found in LICENSE.APACHE2 or LICENSE.MIT. Contributions to are
|
| 3 |
+
made under the terms of *both* these licenses.
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/licenses/LICENSE.APACHE2
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/licenses/LICENSE.MIT
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 4 |
+
a copy of this software and associated documentation files (the
|
| 5 |
+
"Software"), to deal in the Software without restriction, including
|
| 6 |
+
without limitation the rights to use, copy, modify, merge, publish,
|
| 7 |
+
distribute, sublicense, and/or sell copies of the Software, and to
|
| 8 |
+
permit persons to whom the Software is furnished to do so, subject to
|
| 9 |
+
the following conditions:
|
| 10 |
+
|
| 11 |
+
The above copyright notice and this permission notice shall be
|
| 12 |
+
included in all copies or substantial portions of the Software.
|
| 13 |
+
|
| 14 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 15 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 16 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 17 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
| 18 |
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
| 19 |
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
| 20 |
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
miniconda3/lib/python3.13/site-packages/sniffio-1.3.1.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
sniffio
|
miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.bat
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@ECHO OFF
|
| 2 |
+
set TEST=teststringfromactivate
|
| 3 |
+
|
| 4 |
+
set PATH_PRE_ACTIVATE_DEACTIVATE=%PATH%
|
| 5 |
+
set PATH=%TEST%/bin/test;%PATH%
|
miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.sh
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export TEST=teststringfromactivate
|
| 2 |
+
export PATH="${TEST}/bin/test:${PATH}"
|
miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.bat
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@ECHO OFF
|
| 2 |
+
set PATH=%PATH_PRE_ACTIVATE_DEACTIVATE%
|
miniconda3/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.sh
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export TEST=teststringfromactivate
|
| 2 |
+
export PATH=`echo $PATH | sed "s|${TEST}/bin/test:||"`
|
miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: tomli
|
| 3 |
+
Version: 2.4.0
|
| 4 |
+
Summary: A lil' TOML parser
|
| 5 |
+
Keywords: toml
|
| 6 |
+
Author-email: Taneli Hukkinen <hukkin@users.noreply.github.com>
|
| 7 |
+
Requires-Python: >=3.8
|
| 8 |
+
Description-Content-Type: text/markdown
|
| 9 |
+
License-Expression: MIT
|
| 10 |
+
Classifier: Operating System :: MacOS
|
| 11 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 12 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 13 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 14 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 15 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 16 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 17 |
+
Classifier: Typing :: Typed
|
| 18 |
+
License-File: LICENSE
|
| 19 |
+
Project-URL: Changelog, https://github.com/hukkin/tomli/blob/master/CHANGELOG.md
|
| 20 |
+
Project-URL: Homepage, https://github.com/hukkin/tomli
|
| 21 |
+
|
| 22 |
+
[](https://github.com/hukkin/tomli/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush)
|
| 23 |
+
[](https://codecov.io/gh/hukkin/tomli)
|
| 24 |
+
[](https://pypi.org/project/tomli)
|
| 25 |
+
|
| 26 |
+
# Tomli
|
| 27 |
+
|
| 28 |
+
> A lil' TOML parser
|
| 29 |
+
|
| 30 |
+
**Table of Contents** *generated with [mdformat-toc](https://github.com/hukkin/mdformat-toc)*
|
| 31 |
+
|
| 32 |
+
<!-- mdformat-toc start --slug=github --maxlevel=6 --minlevel=2 -->
|
| 33 |
+
|
| 34 |
+
- [Intro](#intro)
|
| 35 |
+
- [Installation](#installation)
|
| 36 |
+
- [Usage](#usage)
|
| 37 |
+
- [Parse a TOML string](#parse-a-toml-string)
|
| 38 |
+
- [Parse a TOML file](#parse-a-toml-file)
|
| 39 |
+
- [Handle invalid TOML](#handle-invalid-toml)
|
| 40 |
+
- [Construct `decimal.Decimal`s from TOML floats](#construct-decimaldecimals-from-toml-floats)
|
| 41 |
+
- [Building a `tomli`/`tomllib` compatibility layer](#building-a-tomlitomllib-compatibility-layer)
|
| 42 |
+
- [FAQ](#faq)
|
| 43 |
+
- [Why this parser?](#why-this-parser)
|
| 44 |
+
- [Is comment preserving round-trip parsing supported?](#is-comment-preserving-round-trip-parsing-supported)
|
| 45 |
+
- [Is there a `dumps`, `write` or `encode` function?](#is-there-a-dumps-write-or-encode-function)
|
| 46 |
+
- [How do TOML types map into Python types?](#how-do-toml-types-map-into-python-types)
|
| 47 |
+
- [Performance](#performance)
|
| 48 |
+
- [Pure Python](#pure-python)
|
| 49 |
+
- [Mypyc generated wheel](#mypyc-generated-wheel)
|
| 50 |
+
|
| 51 |
+
<!-- mdformat-toc end -->
|
| 52 |
+
|
| 53 |
+
## Intro<a name="intro"></a>
|
| 54 |
+
|
| 55 |
+
Tomli is a Python library for parsing [TOML](https://toml.io).
|
| 56 |
+
Version 2.4.0 and later are compatible with [TOML v1.1.0](https://toml.io/en/v1.1.0).
|
| 57 |
+
Older versions are [TOML v1.0.0](https://toml.io/en/v1.0.0) compatible.
|
| 58 |
+
|
| 59 |
+
A version of Tomli, the `tomllib` module,
|
| 60 |
+
was added to the standard library in Python 3.11
|
| 61 |
+
via [PEP 680](https://www.python.org/dev/peps/pep-0680/).
|
| 62 |
+
Tomli continues to provide a backport on PyPI for Python versions
|
| 63 |
+
where the standard library module is not available
|
| 64 |
+
and that have not yet reached their end-of-life.
|
| 65 |
+
|
| 66 |
+
Tomli uses [mypyc](https://github.com/mypyc/mypyc)
|
| 67 |
+
to generate binary wheels for most of the widely used platforms,
|
| 68 |
+
so Python 3.11+ users may prefer it over `tomllib` for improved performance.
|
| 69 |
+
Pure Python wheels are available on any platform and should perform the same as `tomllib`.
|
| 70 |
+
|
| 71 |
+
## Installation<a name="installation"></a>
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
pip install tomli
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
## Usage<a name="usage"></a>
|
| 78 |
+
|
| 79 |
+
### Parse a TOML string<a name="parse-a-toml-string"></a>
|
| 80 |
+
|
| 81 |
+
```python
|
| 82 |
+
import tomli
|
| 83 |
+
|
| 84 |
+
toml_str = """
|
| 85 |
+
[[players]]
|
| 86 |
+
name = "Lehtinen"
|
| 87 |
+
number = 26
|
| 88 |
+
|
| 89 |
+
[[players]]
|
| 90 |
+
name = "Numminen"
|
| 91 |
+
number = 27
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
toml_dict = tomli.loads(toml_str)
|
| 95 |
+
assert toml_dict == {
|
| 96 |
+
"players": [{"name": "Lehtinen", "number": 26}, {"name": "Numminen", "number": 27}]
|
| 97 |
+
}
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
### Parse a TOML file<a name="parse-a-toml-file"></a>
|
| 101 |
+
|
| 102 |
+
```python
|
| 103 |
+
import tomli
|
| 104 |
+
|
| 105 |
+
with open("path_to_file/conf.toml", "rb") as f:
|
| 106 |
+
toml_dict = tomli.load(f)
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
The file must be opened in binary mode (with the `"rb"` flag).
|
| 110 |
+
Binary mode will enforce decoding the file as UTF-8 with universal newlines disabled,
|
| 111 |
+
both of which are required to correctly parse TOML.
|
| 112 |
+
|
| 113 |
+
### Handle invalid TOML<a name="handle-invalid-toml"></a>
|
| 114 |
+
|
| 115 |
+
```python
|
| 116 |
+
import tomli
|
| 117 |
+
|
| 118 |
+
try:
|
| 119 |
+
toml_dict = tomli.loads("]] this is invalid TOML [[")
|
| 120 |
+
except tomli.TOMLDecodeError:
|
| 121 |
+
print("Yep, definitely not valid.")
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Note that error messages are considered informational only.
|
| 125 |
+
They should not be assumed to stay constant across Tomli versions.
|
| 126 |
+
|
| 127 |
+
### Construct `decimal.Decimal`s from TOML floats<a name="construct-decimaldecimals-from-toml-floats"></a>
|
| 128 |
+
|
| 129 |
+
```python
|
| 130 |
+
from decimal import Decimal
|
| 131 |
+
import tomli
|
| 132 |
+
|
| 133 |
+
toml_dict = tomli.loads("precision-matters = 0.982492", parse_float=Decimal)
|
| 134 |
+
assert isinstance(toml_dict["precision-matters"], Decimal)
|
| 135 |
+
assert toml_dict["precision-matters"] == Decimal("0.982492")
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Note that `decimal.Decimal` can be replaced with another callable that converts a TOML float from string to a Python type.
|
| 139 |
+
The `decimal.Decimal` is, however, a practical choice for use cases where float inaccuracies can not be tolerated.
|
| 140 |
+
|
| 141 |
+
Illegal types are `dict` and `list`, and their subtypes.
|
| 142 |
+
A `ValueError` will be raised if `parse_float` produces illegal types.
|
| 143 |
+
|
| 144 |
+
### Building a `tomli`/`tomllib` compatibility layer<a name="building-a-tomlitomllib-compatibility-layer"></a>
|
| 145 |
+
|
| 146 |
+
Python versions 3.11+ ship with a version of Tomli:
|
| 147 |
+
the `tomllib` standard library module.
|
| 148 |
+
To build code that uses the standard library if available,
|
| 149 |
+
but still works seamlessly with Python 3.6+,
|
| 150 |
+
do the following.
|
| 151 |
+
|
| 152 |
+
Instead of a hard Tomli dependency, use the following
|
| 153 |
+
[dependency specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers/)
|
| 154 |
+
to only require Tomli when the standard library module is not available:
|
| 155 |
+
|
| 156 |
+
```
|
| 157 |
+
tomli >= 1.1.0 ; python_version < "3.11"
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
Then, in your code, import a TOML parser using the following fallback mechanism:
|
| 161 |
+
|
| 162 |
+
```python
|
| 163 |
+
import sys
|
| 164 |
+
|
| 165 |
+
if sys.version_info >= (3, 11):
|
| 166 |
+
import tomllib
|
| 167 |
+
else:
|
| 168 |
+
import tomli as tomllib
|
| 169 |
+
|
| 170 |
+
tomllib.loads("['This parses fine with Python 3.6+']")
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
## FAQ<a name="faq"></a>
|
| 174 |
+
|
| 175 |
+
### Why this parser?<a name="why-this-parser"></a>
|
| 176 |
+
|
| 177 |
+
- it's lil'
|
| 178 |
+
- pure Python with zero dependencies
|
| 179 |
+
- the fastest pure Python parser [\*](#pure-python):
|
| 180 |
+
18x as fast as [tomlkit](https://pypi.org/project/tomlkit/),
|
| 181 |
+
2.1x as fast as [toml](https://pypi.org/project/toml/)
|
| 182 |
+
- outputs [basic data types](#how-do-toml-types-map-into-python-types) only
|
| 183 |
+
- 100% spec compliant: passes all tests in
|
| 184 |
+
[toml-lang/toml-test](https://github.com/toml-lang/toml-test)
|
| 185 |
+
test suite
|
| 186 |
+
- thoroughly tested: 100% branch coverage
|
| 187 |
+
|
| 188 |
+
### Is comment preserving round-trip parsing supported?<a name="is-comment-preserving-round-trip-parsing-supported"></a>
|
| 189 |
+
|
| 190 |
+
No.
|
| 191 |
+
|
| 192 |
+
The `tomli.loads` function returns a plain `dict` that is populated with builtin types and types from the standard library only.
|
| 193 |
+
Preserving comments requires a custom type to be returned so will not be supported,
|
| 194 |
+
at least not by the `tomli.loads` and `tomli.load` functions.
|
| 195 |
+
|
| 196 |
+
Look into [TOML Kit](https://github.com/sdispater/tomlkit) if preservation of style is what you need.
|
| 197 |
+
|
| 198 |
+
### Is there a `dumps`, `write` or `encode` function?<a name="is-there-a-dumps-write-or-encode-function"></a>
|
| 199 |
+
|
| 200 |
+
[Tomli-W](https://github.com/hukkin/tomli-w) is the write-only counterpart of Tomli, providing `dump` and `dumps` functions.
|
| 201 |
+
|
| 202 |
+
The core library does not include write capability, as most TOML use cases are read-only, and Tomli intends to be minimal.
|
| 203 |
+
|
| 204 |
+
### How do TOML types map into Python types?<a name="how-do-toml-types-map-into-python-types"></a>
|
| 205 |
+
|
| 206 |
+
| TOML type | Python type | Details |
|
| 207 |
+
| ---------------- | ------------------- | ------------------------------------------------------------ |
|
| 208 |
+
| Document Root | `dict` | |
|
| 209 |
+
| Key | `str` | |
|
| 210 |
+
| String | `str` | |
|
| 211 |
+
| Integer | `int` | |
|
| 212 |
+
| Float | `float` | |
|
| 213 |
+
| Boolean | `bool` | |
|
| 214 |
+
| Offset Date-Time | `datetime.datetime` | `tzinfo` attribute set to an instance of `datetime.timezone` |
|
| 215 |
+
| Local Date-Time | `datetime.datetime` | `tzinfo` attribute set to `None` |
|
| 216 |
+
| Local Date | `datetime.date` | |
|
| 217 |
+
| Local Time | `datetime.time` | |
|
| 218 |
+
| Array | `list` | |
|
| 219 |
+
| Table | `dict` | |
|
| 220 |
+
| Inline Table | `dict` | |
|
| 221 |
+
|
| 222 |
+
## Performance<a name="performance"></a>
|
| 223 |
+
|
| 224 |
+
The `benchmark/` folder in this repository contains a performance benchmark for comparing the various Python TOML parsers.
|
| 225 |
+
|
| 226 |
+
Below are the results for commit [0724e2a](https://github.com/hukkin/tomli/tree/0724e2ab1858da7f5e05a9bffdb24c33589d951c).
|
| 227 |
+
|
| 228 |
+
### Pure Python<a name="pure-python"></a>
|
| 229 |
+
|
| 230 |
+
```console
|
| 231 |
+
foo@bar:~/dev/tomli$ python --version
|
| 232 |
+
Python 3.12.7
|
| 233 |
+
foo@bar:~/dev/tomli$ pip freeze
|
| 234 |
+
attrs==21.4.0
|
| 235 |
+
click==8.1.7
|
| 236 |
+
pytomlpp==1.0.13
|
| 237 |
+
qtoml==0.3.1
|
| 238 |
+
rtoml==0.11.0
|
| 239 |
+
toml==0.10.2
|
| 240 |
+
tomli @ file:///home/foo/dev/tomli
|
| 241 |
+
tomlkit==0.13.2
|
| 242 |
+
foo@bar:~/dev/tomli$ python benchmark/run.py
|
| 243 |
+
Parsing data.toml 5000 times:
|
| 244 |
+
------------------------------------------------------
|
| 245 |
+
parser | exec time | performance (more is better)
|
| 246 |
+
-----------+------------+-----------------------------
|
| 247 |
+
rtoml | 0.647 s | baseline (100%)
|
| 248 |
+
pytomlpp | 0.891 s | 72.62%
|
| 249 |
+
tomli | 3.14 s | 20.56%
|
| 250 |
+
toml | 6.69 s | 9.67%
|
| 251 |
+
qtoml | 8.27 s | 7.82%
|
| 252 |
+
tomlkit | 56.1 s | 1.15%
|
| 253 |
+
```
|
| 254 |
+
|
| 255 |
+
### Mypyc generated wheel<a name="mypyc-generated-wheel"></a>
|
| 256 |
+
|
| 257 |
+
```console
|
| 258 |
+
foo@bar:~/dev/tomli$ python benchmark/run.py
|
| 259 |
+
Parsing data.toml 5000 times:
|
| 260 |
+
------------------------------------------------------
|
| 261 |
+
parser | exec time | performance (more is better)
|
| 262 |
+
-----------+------------+-----------------------------
|
| 263 |
+
rtoml | 0.668 s | baseline (100%)
|
| 264 |
+
pytomlpp | 0.893 s | 74.81%
|
| 265 |
+
tomli | 1.96 s | 34.18%
|
| 266 |
+
toml | 6.64 s | 10.07%
|
| 267 |
+
qtoml | 8.26 s | 8.09%
|
| 268 |
+
tomlkit | 52.9 s | 1.26%
|
| 269 |
+
```
|
| 270 |
+
|
miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tomli-2.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
tomli-2.4.0.dist-info/METADATA,sha256=9awKH4-6kItGRs1lUwnpGq2Wm2eHYWrFccpGKjgy_84,10567
|
| 3 |
+
tomli-2.4.0.dist-info/RECORD,,
|
| 4 |
+
tomli-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
tomli-2.4.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
|
| 6 |
+
tomli-2.4.0.dist-info/direct_url.json,sha256=K768WxZ4D6EgbEhHJDiokeFkkGn6hREVXhS2YGn1-74,91
|
| 7 |
+
tomli-2.4.0.dist-info/licenses/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
|
| 8 |
+
tomli/__init__.py,sha256=ahtDjGJA2M_wWVvGpzx4YJtWxrWBx6qE-GH5-UYoECA,314
|
| 9 |
+
tomli/__pycache__/__init__.cpython-313.pyc,,
|
| 10 |
+
tomli/__pycache__/_parser.cpython-313.pyc,,
|
| 11 |
+
tomli/__pycache__/_re.cpython-313.pyc,,
|
| 12 |
+
tomli/__pycache__/_types.cpython-313.pyc,,
|
| 13 |
+
tomli/_parser.py,sha256=txeATLE3zHyZ-ushXtYfrZ3LoIs7JzQF2W2KL1gwJPg,25958
|
| 14 |
+
tomli/_re.py,sha256=oSNZ_ilFI6chEuQ01YRSoUydBQr_okF_mSdHTkFmv90,3396
|
| 15 |
+
tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
|
| 16 |
+
tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
|
miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: flit 3.12.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///home/task_176829646049141/croot/tomli_1768296482268/work"}
|
miniconda3/lib/python3.13/site-packages/tomli-2.4.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2021 Taneli Hukkinen
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
miniconda3/lib/python3.13/site-packages/tomli/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: MIT
|
| 2 |
+
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
|
| 3 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 4 |
+
|
| 5 |
+
__all__ = ("loads", "load", "TOMLDecodeError")
|
| 6 |
+
__version__ = "2.4.0" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
|
| 7 |
+
|
| 8 |
+
from ._parser import TOMLDecodeError, load, loads
|
miniconda3/lib/python3.13/site-packages/tomli/_parser.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: MIT
|
| 2 |
+
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
|
| 3 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
from types import MappingProxyType
|
| 9 |
+
|
| 10 |
+
from ._re import (
|
| 11 |
+
RE_DATETIME,
|
| 12 |
+
RE_LOCALTIME,
|
| 13 |
+
RE_NUMBER,
|
| 14 |
+
match_to_datetime,
|
| 15 |
+
match_to_localtime,
|
| 16 |
+
match_to_number,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
TYPE_CHECKING = False
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from collections.abc import Iterable
|
| 22 |
+
from typing import IO, Any, Final
|
| 23 |
+
|
| 24 |
+
from ._types import Key, ParseFloat, Pos
|
| 25 |
+
|
| 26 |
+
# Inline tables/arrays are implemented using recursion. Pathologically
|
| 27 |
+
# nested documents cause pure Python to raise RecursionError (which is OK),
|
| 28 |
+
# but mypyc binary wheels will crash unrecoverably (not OK). According to
|
| 29 |
+
# mypyc docs this will be fixed in the future:
|
| 30 |
+
# https://mypyc.readthedocs.io/en/latest/differences_from_python.html#stack-overflows
|
| 31 |
+
# Before mypyc's fix is in, recursion needs to be limited by this library.
|
| 32 |
+
# Choosing `sys.getrecursionlimit()` as maximum inline table/array nesting
|
| 33 |
+
# level, as it allows more nesting than pure Python, but still seems a far
|
| 34 |
+
# lower number than where mypyc binaries crash.
|
| 35 |
+
MAX_INLINE_NESTING: Final = sys.getrecursionlimit()
|
| 36 |
+
|
| 37 |
+
ASCII_CTRL: Final = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))
|
| 38 |
+
|
| 39 |
+
# Neither of these sets include quotation mark or backslash. They are
|
| 40 |
+
# currently handled as separate cases in the parser functions.
|
| 41 |
+
ILLEGAL_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t")
|
| 42 |
+
ILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t\n")
|
| 43 |
+
|
| 44 |
+
ILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
|
| 45 |
+
ILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS
|
| 46 |
+
|
| 47 |
+
ILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
|
| 48 |
+
|
| 49 |
+
TOML_WS: Final = frozenset(" \t")
|
| 50 |
+
TOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset("\n")
|
| 51 |
+
BARE_KEY_CHARS: Final = frozenset(
|
| 52 |
+
"abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "-_"
|
| 53 |
+
)
|
| 54 |
+
KEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'")
|
| 55 |
+
HEXDIGIT_CHARS: Final = frozenset("abcdef" "ABCDEF" "0123456789")
|
| 56 |
+
|
| 57 |
+
BASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(
|
| 58 |
+
{
|
| 59 |
+
"\\b": "\u0008", # backspace
|
| 60 |
+
"\\t": "\u0009", # tab
|
| 61 |
+
"\\n": "\u000a", # linefeed
|
| 62 |
+
"\\f": "\u000c", # form feed
|
| 63 |
+
"\\r": "\u000d", # carriage return
|
| 64 |
+
"\\e": "\u001b", # escape
|
| 65 |
+
'\\"': "\u0022", # quote
|
| 66 |
+
"\\\\": "\u005c", # backslash
|
| 67 |
+
}
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class DEPRECATED_DEFAULT:
|
| 72 |
+
"""Sentinel to be used as default arg during deprecation
|
| 73 |
+
period of TOMLDecodeError's free-form arguments."""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class TOMLDecodeError(ValueError):
|
| 77 |
+
"""An error raised if a document is not valid TOML.
|
| 78 |
+
|
| 79 |
+
Adds the following attributes to ValueError:
|
| 80 |
+
msg: The unformatted error message
|
| 81 |
+
doc: The TOML document being parsed
|
| 82 |
+
pos: The index of doc where parsing failed
|
| 83 |
+
lineno: The line corresponding to pos
|
| 84 |
+
colno: The column corresponding to pos
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
msg: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
|
| 90 |
+
doc: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
|
| 91 |
+
pos: Pos | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
|
| 92 |
+
*args: Any,
|
| 93 |
+
):
|
| 94 |
+
if (
|
| 95 |
+
args
|
| 96 |
+
or not isinstance(msg, str)
|
| 97 |
+
or not isinstance(doc, str)
|
| 98 |
+
or not isinstance(pos, int)
|
| 99 |
+
):
|
| 100 |
+
import warnings
|
| 101 |
+
|
| 102 |
+
warnings.warn(
|
| 103 |
+
"Free-form arguments for TOMLDecodeError are deprecated. "
|
| 104 |
+
"Please set 'msg' (str), 'doc' (str) and 'pos' (int) arguments only.",
|
| 105 |
+
DeprecationWarning,
|
| 106 |
+
stacklevel=2,
|
| 107 |
+
)
|
| 108 |
+
if pos is not DEPRECATED_DEFAULT:
|
| 109 |
+
args = pos, *args
|
| 110 |
+
if doc is not DEPRECATED_DEFAULT:
|
| 111 |
+
args = doc, *args
|
| 112 |
+
if msg is not DEPRECATED_DEFAULT:
|
| 113 |
+
args = msg, *args
|
| 114 |
+
ValueError.__init__(self, *args)
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
lineno = doc.count("\n", 0, pos) + 1
|
| 118 |
+
if lineno == 1:
|
| 119 |
+
colno = pos + 1
|
| 120 |
+
else:
|
| 121 |
+
colno = pos - doc.rindex("\n", 0, pos)
|
| 122 |
+
|
| 123 |
+
if pos >= len(doc):
|
| 124 |
+
coord_repr = "end of document"
|
| 125 |
+
else:
|
| 126 |
+
coord_repr = f"line {lineno}, column {colno}"
|
| 127 |
+
errmsg = f"{msg} (at {coord_repr})"
|
| 128 |
+
ValueError.__init__(self, errmsg)
|
| 129 |
+
|
| 130 |
+
self.msg = msg
|
| 131 |
+
self.doc = doc
|
| 132 |
+
self.pos = pos
|
| 133 |
+
self.lineno = lineno
|
| 134 |
+
self.colno = colno
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def load(__fp: IO[bytes], *, parse_float: ParseFloat = float) -> dict[str, Any]:
|
| 138 |
+
"""Parse TOML from a binary file object."""
|
| 139 |
+
b = __fp.read()
|
| 140 |
+
try:
|
| 141 |
+
s = b.decode()
|
| 142 |
+
except AttributeError:
|
| 143 |
+
raise TypeError(
|
| 144 |
+
"File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`"
|
| 145 |
+
) from None
|
| 146 |
+
return loads(s, parse_float=parse_float)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:
|
| 150 |
+
"""Parse TOML from a string."""
|
| 151 |
+
|
| 152 |
+
# The spec allows converting "\r\n" to "\n", even in string
|
| 153 |
+
# literals. Let's do so to simplify parsing.
|
| 154 |
+
try:
|
| 155 |
+
src = __s.replace("\r\n", "\n")
|
| 156 |
+
except (AttributeError, TypeError):
|
| 157 |
+
raise TypeError(
|
| 158 |
+
f"Expected str object, not '{type(__s).__qualname__}'"
|
| 159 |
+
) from None
|
| 160 |
+
pos = 0
|
| 161 |
+
out = Output()
|
| 162 |
+
header: Key = ()
|
| 163 |
+
parse_float = make_safe_parse_float(parse_float)
|
| 164 |
+
|
| 165 |
+
# Parse one statement at a time
|
| 166 |
+
# (typically means one line in TOML source)
|
| 167 |
+
while True:
|
| 168 |
+
# 1. Skip line leading whitespace
|
| 169 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 170 |
+
|
| 171 |
+
# 2. Parse rules. Expect one of the following:
|
| 172 |
+
# - end of file
|
| 173 |
+
# - end of line
|
| 174 |
+
# - comment
|
| 175 |
+
# - key/value pair
|
| 176 |
+
# - append dict to list (and move to its namespace)
|
| 177 |
+
# - create dict (and move to its namespace)
|
| 178 |
+
# Skip trailing whitespace when applicable.
|
| 179 |
+
try:
|
| 180 |
+
char = src[pos]
|
| 181 |
+
except IndexError:
|
| 182 |
+
break
|
| 183 |
+
if char == "\n":
|
| 184 |
+
pos += 1
|
| 185 |
+
continue
|
| 186 |
+
if char in KEY_INITIAL_CHARS:
|
| 187 |
+
pos = key_value_rule(src, pos, out, header, parse_float)
|
| 188 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 189 |
+
elif char == "[":
|
| 190 |
+
try:
|
| 191 |
+
second_char: str | None = src[pos + 1]
|
| 192 |
+
except IndexError:
|
| 193 |
+
second_char = None
|
| 194 |
+
out.flags.finalize_pending()
|
| 195 |
+
if second_char == "[":
|
| 196 |
+
pos, header = create_list_rule(src, pos, out)
|
| 197 |
+
else:
|
| 198 |
+
pos, header = create_dict_rule(src, pos, out)
|
| 199 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 200 |
+
elif char != "#":
|
| 201 |
+
raise TOMLDecodeError("Invalid statement", src, pos)
|
| 202 |
+
|
| 203 |
+
# 3. Skip comment
|
| 204 |
+
pos = skip_comment(src, pos)
|
| 205 |
+
|
| 206 |
+
# 4. Expect end of line or end of file
|
| 207 |
+
try:
|
| 208 |
+
char = src[pos]
|
| 209 |
+
except IndexError:
|
| 210 |
+
break
|
| 211 |
+
if char != "\n":
|
| 212 |
+
raise TOMLDecodeError(
|
| 213 |
+
"Expected newline or end of document after a statement", src, pos
|
| 214 |
+
)
|
| 215 |
+
pos += 1
|
| 216 |
+
|
| 217 |
+
return out.data.dict
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class Flags:
|
| 221 |
+
"""Flags that map to parsed keys/namespaces."""
|
| 222 |
+
|
| 223 |
+
# Marks an immutable namespace (inline array or inline table).
|
| 224 |
+
FROZEN: Final = 0
|
| 225 |
+
# Marks a nest that has been explicitly created and can no longer
|
| 226 |
+
# be opened using the "[table]" syntax.
|
| 227 |
+
EXPLICIT_NEST: Final = 1
|
| 228 |
+
|
| 229 |
+
def __init__(self) -> None:
|
| 230 |
+
self._flags: dict[str, dict[Any, Any]] = {}
|
| 231 |
+
self._pending_flags: set[tuple[Key, int]] = set()
|
| 232 |
+
|
| 233 |
+
def add_pending(self, key: Key, flag: int) -> None:
|
| 234 |
+
self._pending_flags.add((key, flag))
|
| 235 |
+
|
| 236 |
+
def finalize_pending(self) -> None:
|
| 237 |
+
for key, flag in self._pending_flags:
|
| 238 |
+
self.set(key, flag, recursive=False)
|
| 239 |
+
self._pending_flags.clear()
|
| 240 |
+
|
| 241 |
+
def unset_all(self, key: Key) -> None:
|
| 242 |
+
cont = self._flags
|
| 243 |
+
for k in key[:-1]:
|
| 244 |
+
if k not in cont:
|
| 245 |
+
return
|
| 246 |
+
cont = cont[k]["nested"]
|
| 247 |
+
cont.pop(key[-1], None)
|
| 248 |
+
|
| 249 |
+
def set(self, key: Key, flag: int, *, recursive: bool) -> None: # noqa: A003
|
| 250 |
+
cont = self._flags
|
| 251 |
+
key_parent, key_stem = key[:-1], key[-1]
|
| 252 |
+
for k in key_parent:
|
| 253 |
+
if k not in cont:
|
| 254 |
+
cont[k] = {"flags": set(), "recursive_flags": set(), "nested": {}}
|
| 255 |
+
cont = cont[k]["nested"]
|
| 256 |
+
if key_stem not in cont:
|
| 257 |
+
cont[key_stem] = {"flags": set(), "recursive_flags": set(), "nested": {}}
|
| 258 |
+
cont[key_stem]["recursive_flags" if recursive else "flags"].add(flag)
|
| 259 |
+
|
| 260 |
+
def is_(self, key: Key, flag: int) -> bool:
|
| 261 |
+
if not key:
|
| 262 |
+
return False # document root has no flags
|
| 263 |
+
cont = self._flags
|
| 264 |
+
for k in key[:-1]:
|
| 265 |
+
if k not in cont:
|
| 266 |
+
return False
|
| 267 |
+
inner_cont = cont[k]
|
| 268 |
+
if flag in inner_cont["recursive_flags"]:
|
| 269 |
+
return True
|
| 270 |
+
cont = inner_cont["nested"]
|
| 271 |
+
key_stem = key[-1]
|
| 272 |
+
if key_stem in cont:
|
| 273 |
+
inner_cont = cont[key_stem]
|
| 274 |
+
return flag in inner_cont["flags"] or flag in inner_cont["recursive_flags"]
|
| 275 |
+
return False
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class NestedDict:
|
| 279 |
+
def __init__(self) -> None:
|
| 280 |
+
# The parsed content of the TOML document
|
| 281 |
+
self.dict: dict[str, Any] = {}
|
| 282 |
+
|
| 283 |
+
def get_or_create_nest(
|
| 284 |
+
self,
|
| 285 |
+
key: Key,
|
| 286 |
+
*,
|
| 287 |
+
access_lists: bool = True,
|
| 288 |
+
) -> dict[str, Any]:
|
| 289 |
+
cont: Any = self.dict
|
| 290 |
+
for k in key:
|
| 291 |
+
if k not in cont:
|
| 292 |
+
cont[k] = {}
|
| 293 |
+
cont = cont[k]
|
| 294 |
+
if access_lists and isinstance(cont, list):
|
| 295 |
+
cont = cont[-1]
|
| 296 |
+
if not isinstance(cont, dict):
|
| 297 |
+
raise KeyError("There is no nest behind this key")
|
| 298 |
+
return cont # type: ignore[no-any-return]
|
| 299 |
+
|
| 300 |
+
def append_nest_to_list(self, key: Key) -> None:
|
| 301 |
+
cont = self.get_or_create_nest(key[:-1])
|
| 302 |
+
last_key = key[-1]
|
| 303 |
+
if last_key in cont:
|
| 304 |
+
list_ = cont[last_key]
|
| 305 |
+
if not isinstance(list_, list):
|
| 306 |
+
raise KeyError("An object other than list found behind this key")
|
| 307 |
+
list_.append({})
|
| 308 |
+
else:
|
| 309 |
+
cont[last_key] = [{}]
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class Output:
|
| 313 |
+
def __init__(self) -> None:
|
| 314 |
+
self.data = NestedDict()
|
| 315 |
+
self.flags = Flags()
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:
|
| 319 |
+
try:
|
| 320 |
+
while src[pos] in chars:
|
| 321 |
+
pos += 1
|
| 322 |
+
except IndexError:
|
| 323 |
+
pass
|
| 324 |
+
return pos
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def skip_until(
|
| 328 |
+
src: str,
|
| 329 |
+
pos: Pos,
|
| 330 |
+
expect: str,
|
| 331 |
+
*,
|
| 332 |
+
error_on: frozenset[str],
|
| 333 |
+
error_on_eof: bool,
|
| 334 |
+
) -> Pos:
|
| 335 |
+
try:
|
| 336 |
+
new_pos = src.index(expect, pos)
|
| 337 |
+
except ValueError:
|
| 338 |
+
new_pos = len(src)
|
| 339 |
+
if error_on_eof:
|
| 340 |
+
raise TOMLDecodeError(f"Expected {expect!r}", src, new_pos) from None
|
| 341 |
+
|
| 342 |
+
if not error_on.isdisjoint(src[pos:new_pos]):
|
| 343 |
+
while src[pos] not in error_on:
|
| 344 |
+
pos += 1
|
| 345 |
+
raise TOMLDecodeError(f"Found invalid character {src[pos]!r}", src, pos)
|
| 346 |
+
return new_pos
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def skip_comment(src: str, pos: Pos) -> Pos:
|
| 350 |
+
try:
|
| 351 |
+
char: str | None = src[pos]
|
| 352 |
+
except IndexError:
|
| 353 |
+
char = None
|
| 354 |
+
if char == "#":
|
| 355 |
+
return skip_until(
|
| 356 |
+
src, pos + 1, "\n", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False
|
| 357 |
+
)
|
| 358 |
+
return pos
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:
|
| 362 |
+
while True:
|
| 363 |
+
pos_before_skip = pos
|
| 364 |
+
pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
|
| 365 |
+
pos = skip_comment(src, pos)
|
| 366 |
+
if pos == pos_before_skip:
|
| 367 |
+
return pos
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
|
| 371 |
+
pos += 1 # Skip "["
|
| 372 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 373 |
+
pos, key = parse_key(src, pos)
|
| 374 |
+
|
| 375 |
+
if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):
|
| 376 |
+
raise TOMLDecodeError(f"Cannot declare {key} twice", src, pos)
|
| 377 |
+
out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
|
| 378 |
+
try:
|
| 379 |
+
out.data.get_or_create_nest(key)
|
| 380 |
+
except KeyError:
|
| 381 |
+
raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
|
| 382 |
+
|
| 383 |
+
if not src.startswith("]", pos):
|
| 384 |
+
raise TOMLDecodeError(
|
| 385 |
+
"Expected ']' at the end of a table declaration", src, pos
|
| 386 |
+
)
|
| 387 |
+
return pos + 1, key
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:
|
| 391 |
+
pos += 2 # Skip "[["
|
| 392 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 393 |
+
pos, key = parse_key(src, pos)
|
| 394 |
+
|
| 395 |
+
if out.flags.is_(key, Flags.FROZEN):
|
| 396 |
+
raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
|
| 397 |
+
# Free the namespace now that it points to another empty list item...
|
| 398 |
+
out.flags.unset_all(key)
|
| 399 |
+
# ...but this key precisely is still prohibited from table declaration
|
| 400 |
+
out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
|
| 401 |
+
try:
|
| 402 |
+
out.data.append_nest_to_list(key)
|
| 403 |
+
except KeyError:
|
| 404 |
+
raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
|
| 405 |
+
|
| 406 |
+
if not src.startswith("]]", pos):
|
| 407 |
+
raise TOMLDecodeError(
|
| 408 |
+
"Expected ']]' at the end of an array declaration", src, pos
|
| 409 |
+
)
|
| 410 |
+
return pos + 2, key
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def key_value_rule(
|
| 414 |
+
src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat
|
| 415 |
+
) -> Pos:
|
| 416 |
+
pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl=0)
|
| 417 |
+
key_parent, key_stem = key[:-1], key[-1]
|
| 418 |
+
abs_key_parent = header + key_parent
|
| 419 |
+
|
| 420 |
+
relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))
|
| 421 |
+
for cont_key in relative_path_cont_keys:
|
| 422 |
+
# Check that dotted key syntax does not redefine an existing table
|
| 423 |
+
if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):
|
| 424 |
+
raise TOMLDecodeError(f"Cannot redefine namespace {cont_key}", src, pos)
|
| 425 |
+
# Containers in the relative path can't be opened with the table syntax or
|
| 426 |
+
# dotted key/value syntax in following table sections.
|
| 427 |
+
out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)
|
| 428 |
+
|
| 429 |
+
if out.flags.is_(abs_key_parent, Flags.FROZEN):
|
| 430 |
+
raise TOMLDecodeError(
|
| 431 |
+
f"Cannot mutate immutable namespace {abs_key_parent}", src, pos
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
try:
|
| 435 |
+
nest = out.data.get_or_create_nest(abs_key_parent)
|
| 436 |
+
except KeyError:
|
| 437 |
+
raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
|
| 438 |
+
if key_stem in nest:
|
| 439 |
+
raise TOMLDecodeError("Cannot overwrite a value", src, pos)
|
| 440 |
+
# Mark inline table and array namespaces recursively immutable
|
| 441 |
+
if isinstance(value, (dict, list)):
|
| 442 |
+
out.flags.set(header + key, Flags.FROZEN, recursive=True)
|
| 443 |
+
nest[key_stem] = value
|
| 444 |
+
return pos
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def parse_key_value_pair(
|
| 448 |
+
src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
|
| 449 |
+
) -> tuple[Pos, Key, Any]:
|
| 450 |
+
pos, key = parse_key(src, pos)
|
| 451 |
+
try:
|
| 452 |
+
char: str | None = src[pos]
|
| 453 |
+
except IndexError:
|
| 454 |
+
char = None
|
| 455 |
+
if char != "=":
|
| 456 |
+
raise TOMLDecodeError("Expected '=' after a key in a key/value pair", src, pos)
|
| 457 |
+
pos += 1
|
| 458 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 459 |
+
pos, value = parse_value(src, pos, parse_float, nest_lvl)
|
| 460 |
+
return pos, key, value
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:
|
| 464 |
+
pos, key_part = parse_key_part(src, pos)
|
| 465 |
+
key: Key = (key_part,)
|
| 466 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 467 |
+
while True:
|
| 468 |
+
try:
|
| 469 |
+
char: str | None = src[pos]
|
| 470 |
+
except IndexError:
|
| 471 |
+
char = None
|
| 472 |
+
if char != ".":
|
| 473 |
+
return pos, key
|
| 474 |
+
pos += 1
|
| 475 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 476 |
+
pos, key_part = parse_key_part(src, pos)
|
| 477 |
+
key += (key_part,)
|
| 478 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:
|
| 482 |
+
try:
|
| 483 |
+
char: str | None = src[pos]
|
| 484 |
+
except IndexError:
|
| 485 |
+
char = None
|
| 486 |
+
if char in BARE_KEY_CHARS:
|
| 487 |
+
start_pos = pos
|
| 488 |
+
pos = skip_chars(src, pos, BARE_KEY_CHARS)
|
| 489 |
+
return pos, src[start_pos:pos]
|
| 490 |
+
if char == "'":
|
| 491 |
+
return parse_literal_str(src, pos)
|
| 492 |
+
if char == '"':
|
| 493 |
+
return parse_one_line_basic_str(src, pos)
|
| 494 |
+
raise TOMLDecodeError("Invalid initial character for a key part", src, pos)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:
|
| 498 |
+
pos += 1
|
| 499 |
+
return parse_basic_str(src, pos, multiline=False)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def parse_array(
|
| 503 |
+
src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
|
| 504 |
+
) -> tuple[Pos, list[Any]]:
|
| 505 |
+
pos += 1
|
| 506 |
+
array: list[Any] = []
|
| 507 |
+
|
| 508 |
+
pos = skip_comments_and_array_ws(src, pos)
|
| 509 |
+
if src.startswith("]", pos):
|
| 510 |
+
return pos + 1, array
|
| 511 |
+
while True:
|
| 512 |
+
pos, val = parse_value(src, pos, parse_float, nest_lvl)
|
| 513 |
+
array.append(val)
|
| 514 |
+
pos = skip_comments_and_array_ws(src, pos)
|
| 515 |
+
|
| 516 |
+
c = src[pos : pos + 1]
|
| 517 |
+
if c == "]":
|
| 518 |
+
return pos + 1, array
|
| 519 |
+
if c != ",":
|
| 520 |
+
raise TOMLDecodeError("Unclosed array", src, pos)
|
| 521 |
+
pos += 1
|
| 522 |
+
|
| 523 |
+
pos = skip_comments_and_array_ws(src, pos)
|
| 524 |
+
if src.startswith("]", pos):
|
| 525 |
+
return pos + 1, array
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def parse_inline_table(
|
| 529 |
+
src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
|
| 530 |
+
) -> tuple[Pos, dict[str, Any]]:
|
| 531 |
+
pos += 1
|
| 532 |
+
nested_dict = NestedDict()
|
| 533 |
+
flags = Flags()
|
| 534 |
+
|
| 535 |
+
pos = skip_comments_and_array_ws(src, pos)
|
| 536 |
+
if src.startswith("}", pos):
|
| 537 |
+
return pos + 1, nested_dict.dict
|
| 538 |
+
while True:
|
| 539 |
+
pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl)
|
| 540 |
+
key_parent, key_stem = key[:-1], key[-1]
|
| 541 |
+
if flags.is_(key, Flags.FROZEN):
|
| 542 |
+
raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
|
| 543 |
+
try:
|
| 544 |
+
nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)
|
| 545 |
+
except KeyError:
|
| 546 |
+
raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
|
| 547 |
+
if key_stem in nest:
|
| 548 |
+
raise TOMLDecodeError(f"Duplicate inline table key {key_stem!r}", src, pos)
|
| 549 |
+
nest[key_stem] = value
|
| 550 |
+
pos = skip_comments_and_array_ws(src, pos)
|
| 551 |
+
c = src[pos : pos + 1]
|
| 552 |
+
if c == "}":
|
| 553 |
+
return pos + 1, nested_dict.dict
|
| 554 |
+
if c != ",":
|
| 555 |
+
raise TOMLDecodeError("Unclosed inline table", src, pos)
|
| 556 |
+
pos += 1
|
| 557 |
+
pos = skip_comments_and_array_ws(src, pos)
|
| 558 |
+
if src.startswith("}", pos):
|
| 559 |
+
return pos + 1, nested_dict.dict
|
| 560 |
+
if isinstance(value, (dict, list)):
|
| 561 |
+
flags.set(key, Flags.FROZEN, recursive=True)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def parse_basic_str_escape(
|
| 565 |
+
src: str, pos: Pos, *, multiline: bool = False
|
| 566 |
+
) -> tuple[Pos, str]:
|
| 567 |
+
escape_id = src[pos : pos + 2]
|
| 568 |
+
pos += 2
|
| 569 |
+
if multiline and escape_id in {"\\ ", "\\\t", "\\\n"}:
|
| 570 |
+
# Skip whitespace until next non-whitespace character or end of
|
| 571 |
+
# the doc. Error if non-whitespace is found before newline.
|
| 572 |
+
if escape_id != "\\\n":
|
| 573 |
+
pos = skip_chars(src, pos, TOML_WS)
|
| 574 |
+
try:
|
| 575 |
+
char = src[pos]
|
| 576 |
+
except IndexError:
|
| 577 |
+
return pos, ""
|
| 578 |
+
if char != "\n":
|
| 579 |
+
raise TOMLDecodeError("Unescaped '\\' in a string", src, pos)
|
| 580 |
+
pos += 1
|
| 581 |
+
pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
|
| 582 |
+
return pos, ""
|
| 583 |
+
if escape_id == "\\x":
|
| 584 |
+
return parse_hex_char(src, pos, 2)
|
| 585 |
+
if escape_id == "\\u":
|
| 586 |
+
return parse_hex_char(src, pos, 4)
|
| 587 |
+
if escape_id == "\\U":
|
| 588 |
+
return parse_hex_char(src, pos, 8)
|
| 589 |
+
try:
|
| 590 |
+
return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]
|
| 591 |
+
except KeyError:
|
| 592 |
+
raise TOMLDecodeError("Unescaped '\\' in a string", src, pos) from None
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:
|
| 596 |
+
return parse_basic_str_escape(src, pos, multiline=True)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:
|
| 600 |
+
hex_str = src[pos : pos + hex_len]
|
| 601 |
+
if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):
|
| 602 |
+
raise TOMLDecodeError("Invalid hex value", src, pos)
|
| 603 |
+
pos += hex_len
|
| 604 |
+
hex_int = int(hex_str, 16)
|
| 605 |
+
if not is_unicode_scalar_value(hex_int):
|
| 606 |
+
raise TOMLDecodeError(
|
| 607 |
+
"Escaped character is not a Unicode scalar value", src, pos
|
| 608 |
+
)
|
| 609 |
+
return pos, chr(hex_int)
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:
|
| 613 |
+
pos += 1 # Skip starting apostrophe
|
| 614 |
+
start_pos = pos
|
| 615 |
+
pos = skip_until(
|
| 616 |
+
src, pos, "'", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True
|
| 617 |
+
)
|
| 618 |
+
return pos + 1, src[start_pos:pos] # Skip ending apostrophe
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:
|
| 622 |
+
pos += 3
|
| 623 |
+
if src.startswith("\n", pos):
|
| 624 |
+
pos += 1
|
| 625 |
+
|
| 626 |
+
if literal:
|
| 627 |
+
delim = "'"
|
| 628 |
+
end_pos = skip_until(
|
| 629 |
+
src,
|
| 630 |
+
pos,
|
| 631 |
+
"'''",
|
| 632 |
+
error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,
|
| 633 |
+
error_on_eof=True,
|
| 634 |
+
)
|
| 635 |
+
result = src[pos:end_pos]
|
| 636 |
+
pos = end_pos + 3
|
| 637 |
+
else:
|
| 638 |
+
delim = '"'
|
| 639 |
+
pos, result = parse_basic_str(src, pos, multiline=True)
|
| 640 |
+
|
| 641 |
+
# Add at maximum two extra apostrophes/quotes if the end sequence
|
| 642 |
+
# is 4 or 5 chars long instead of just 3.
|
| 643 |
+
if not src.startswith(delim, pos):
|
| 644 |
+
return pos, result
|
| 645 |
+
pos += 1
|
| 646 |
+
if not src.startswith(delim, pos):
|
| 647 |
+
return pos, result + delim
|
| 648 |
+
pos += 1
|
| 649 |
+
return pos, result + (delim * 2)
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:
|
| 653 |
+
if multiline:
|
| 654 |
+
error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS
|
| 655 |
+
parse_escapes = parse_basic_str_escape_multiline
|
| 656 |
+
else:
|
| 657 |
+
error_on = ILLEGAL_BASIC_STR_CHARS
|
| 658 |
+
parse_escapes = parse_basic_str_escape
|
| 659 |
+
result = ""
|
| 660 |
+
start_pos = pos
|
| 661 |
+
while True:
|
| 662 |
+
try:
|
| 663 |
+
char = src[pos]
|
| 664 |
+
except IndexError:
|
| 665 |
+
raise TOMLDecodeError("Unterminated string", src, pos) from None
|
| 666 |
+
if char == '"':
|
| 667 |
+
if not multiline:
|
| 668 |
+
return pos + 1, result + src[start_pos:pos]
|
| 669 |
+
if src.startswith('"""', pos):
|
| 670 |
+
return pos + 3, result + src[start_pos:pos]
|
| 671 |
+
pos += 1
|
| 672 |
+
continue
|
| 673 |
+
if char == "\\":
|
| 674 |
+
result += src[start_pos:pos]
|
| 675 |
+
pos, parsed_escape = parse_escapes(src, pos)
|
| 676 |
+
result += parsed_escape
|
| 677 |
+
start_pos = pos
|
| 678 |
+
continue
|
| 679 |
+
if char in error_on:
|
| 680 |
+
raise TOMLDecodeError(f"Illegal character {char!r}", src, pos)
|
| 681 |
+
pos += 1
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def parse_value(
|
| 685 |
+
src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
|
| 686 |
+
) -> tuple[Pos, Any]:
|
| 687 |
+
if nest_lvl > MAX_INLINE_NESTING:
|
| 688 |
+
# Pure Python should have raised RecursionError already.
|
| 689 |
+
# This ensures mypyc binaries eventually do the same.
|
| 690 |
+
raise RecursionError( # pragma: no cover
|
| 691 |
+
"TOML inline arrays/tables are nested more than the allowed"
|
| 692 |
+
f" {MAX_INLINE_NESTING} levels"
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
try:
|
| 696 |
+
char: str | None = src[pos]
|
| 697 |
+
except IndexError:
|
| 698 |
+
char = None
|
| 699 |
+
|
| 700 |
+
# IMPORTANT: order conditions based on speed of checking and likelihood
|
| 701 |
+
|
| 702 |
+
# Basic strings
|
| 703 |
+
if char == '"':
|
| 704 |
+
if src.startswith('"""', pos):
|
| 705 |
+
return parse_multiline_str(src, pos, literal=False)
|
| 706 |
+
return parse_one_line_basic_str(src, pos)
|
| 707 |
+
|
| 708 |
+
# Literal strings
|
| 709 |
+
if char == "'":
|
| 710 |
+
if src.startswith("'''", pos):
|
| 711 |
+
return parse_multiline_str(src, pos, literal=True)
|
| 712 |
+
return parse_literal_str(src, pos)
|
| 713 |
+
|
| 714 |
+
# Booleans
|
| 715 |
+
if char == "t":
|
| 716 |
+
if src.startswith("true", pos):
|
| 717 |
+
return pos + 4, True
|
| 718 |
+
if char == "f":
|
| 719 |
+
if src.startswith("false", pos):
|
| 720 |
+
return pos + 5, False
|
| 721 |
+
|
| 722 |
+
# Arrays
|
| 723 |
+
if char == "[":
|
| 724 |
+
return parse_array(src, pos, parse_float, nest_lvl + 1)
|
| 725 |
+
|
| 726 |
+
# Inline tables
|
| 727 |
+
if char == "{":
|
| 728 |
+
return parse_inline_table(src, pos, parse_float, nest_lvl + 1)
|
| 729 |
+
|
| 730 |
+
# Dates and times
|
| 731 |
+
datetime_match = RE_DATETIME.match(src, pos)
|
| 732 |
+
if datetime_match:
|
| 733 |
+
try:
|
| 734 |
+
datetime_obj = match_to_datetime(datetime_match)
|
| 735 |
+
except ValueError as e:
|
| 736 |
+
raise TOMLDecodeError("Invalid date or datetime", src, pos) from e
|
| 737 |
+
return datetime_match.end(), datetime_obj
|
| 738 |
+
localtime_match = RE_LOCALTIME.match(src, pos)
|
| 739 |
+
if localtime_match:
|
| 740 |
+
return localtime_match.end(), match_to_localtime(localtime_match)
|
| 741 |
+
|
| 742 |
+
# Integers and "normal" floats.
|
| 743 |
+
# The regex will greedily match any type starting with a decimal
|
| 744 |
+
# char, so needs to be located after handling of dates and times.
|
| 745 |
+
number_match = RE_NUMBER.match(src, pos)
|
| 746 |
+
if number_match:
|
| 747 |
+
return number_match.end(), match_to_number(number_match, parse_float)
|
| 748 |
+
|
| 749 |
+
# Special floats
|
| 750 |
+
first_three = src[pos : pos + 3]
|
| 751 |
+
if first_three in {"inf", "nan"}:
|
| 752 |
+
return pos + 3, parse_float(first_three)
|
| 753 |
+
first_four = src[pos : pos + 4]
|
| 754 |
+
if first_four in {"-inf", "+inf", "-nan", "+nan"}:
|
| 755 |
+
return pos + 4, parse_float(first_four)
|
| 756 |
+
|
| 757 |
+
raise TOMLDecodeError("Invalid value", src, pos)
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def is_unicode_scalar_value(codepoint: int) -> bool:
|
| 761 |
+
return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:
|
| 765 |
+
"""A decorator to make `parse_float` safe.
|
| 766 |
+
|
| 767 |
+
`parse_float` must not return dicts or lists, because these types
|
| 768 |
+
would be mixed with parsed TOML tables and arrays, thus confusing
|
| 769 |
+
the parser. The returned decorated callable raises `ValueError`
|
| 770 |
+
instead of returning illegal types.
|
| 771 |
+
"""
|
| 772 |
+
# The default `float` callable never returns illegal types. Optimize it.
|
| 773 |
+
if parse_float is float:
|
| 774 |
+
return float
|
| 775 |
+
|
| 776 |
+
def safe_parse_float(float_str: str) -> Any:
|
| 777 |
+
float_value = parse_float(float_str)
|
| 778 |
+
if isinstance(float_value, (dict, list)):
|
| 779 |
+
raise ValueError("parse_float must not return dicts or lists")
|
| 780 |
+
return float_value
|
| 781 |
+
|
| 782 |
+
return safe_parse_float
|
miniconda3/lib/python3.13/site-packages/tomli/_re.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: MIT
|
| 2 |
+
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
|
| 3 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from datetime import date, datetime, time, timedelta, timezone, tzinfo
|
| 8 |
+
from functools import lru_cache
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
TYPE_CHECKING = False
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from typing import Any, Final
|
| 14 |
+
|
| 15 |
+
from ._types import ParseFloat
|
| 16 |
+
|
| 17 |
+
_TIME_RE_STR: Final = r"""
|
| 18 |
+
([01][0-9]|2[0-3]) # hours
|
| 19 |
+
:([0-5][0-9]) # minutes
|
| 20 |
+
(?:
|
| 21 |
+
:([0-5][0-9]) # optional seconds
|
| 22 |
+
(?:\.([0-9]{1,6})[0-9]*)? # optional fractions of a second
|
| 23 |
+
)?
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
RE_NUMBER: Final = re.compile(
|
| 27 |
+
r"""
|
| 28 |
+
0
|
| 29 |
+
(?:
|
| 30 |
+
x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex
|
| 31 |
+
|
|
| 32 |
+
b[01](?:_?[01])* # bin
|
| 33 |
+
|
|
| 34 |
+
o[0-7](?:_?[0-7])* # oct
|
| 35 |
+
)
|
| 36 |
+
|
|
| 37 |
+
[+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part
|
| 38 |
+
(?P<floatpart>
|
| 39 |
+
(?:\.[0-9](?:_?[0-9])*)? # optional fractional part
|
| 40 |
+
(?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part
|
| 41 |
+
)
|
| 42 |
+
""",
|
| 43 |
+
flags=re.VERBOSE,
|
| 44 |
+
)
|
| 45 |
+
RE_LOCALTIME: Final = re.compile(_TIME_RE_STR, flags=re.VERBOSE)
|
| 46 |
+
RE_DATETIME: Final = re.compile(
|
| 47 |
+
rf"""
|
| 48 |
+
([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27
|
| 49 |
+
(?:
|
| 50 |
+
[Tt ]
|
| 51 |
+
{_TIME_RE_STR}
|
| 52 |
+
(?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset
|
| 53 |
+
)?
|
| 54 |
+
""",
|
| 55 |
+
flags=re.VERBOSE,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def match_to_datetime(match: re.Match[str]) -> datetime | date:
|
| 60 |
+
"""Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
|
| 61 |
+
|
| 62 |
+
Raises ValueError if the match does not correspond to a valid date
|
| 63 |
+
or datetime.
|
| 64 |
+
"""
|
| 65 |
+
(
|
| 66 |
+
year_str,
|
| 67 |
+
month_str,
|
| 68 |
+
day_str,
|
| 69 |
+
hour_str,
|
| 70 |
+
minute_str,
|
| 71 |
+
sec_str,
|
| 72 |
+
micros_str,
|
| 73 |
+
zulu_time,
|
| 74 |
+
offset_sign_str,
|
| 75 |
+
offset_hour_str,
|
| 76 |
+
offset_minute_str,
|
| 77 |
+
) = match.groups()
|
| 78 |
+
year, month, day = int(year_str), int(month_str), int(day_str)
|
| 79 |
+
if hour_str is None:
|
| 80 |
+
return date(year, month, day)
|
| 81 |
+
hour, minute = int(hour_str), int(minute_str)
|
| 82 |
+
sec = int(sec_str) if sec_str else 0
|
| 83 |
+
micros = int(micros_str.ljust(6, "0")) if micros_str else 0
|
| 84 |
+
if offset_sign_str:
|
| 85 |
+
tz: tzinfo | None = cached_tz(
|
| 86 |
+
offset_hour_str, offset_minute_str, offset_sign_str
|
| 87 |
+
)
|
| 88 |
+
elif zulu_time:
|
| 89 |
+
tz = timezone.utc
|
| 90 |
+
else: # local date-time
|
| 91 |
+
tz = None
|
| 92 |
+
return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# No need to limit cache size. This is only ever called on input
|
| 96 |
+
# that matched RE_DATETIME, so there is an implicit bound of
|
| 97 |
+
# 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.
|
| 98 |
+
@lru_cache(maxsize=None)
|
| 99 |
+
def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
|
| 100 |
+
sign = 1 if sign_str == "+" else -1
|
| 101 |
+
return timezone(
|
| 102 |
+
timedelta(
|
| 103 |
+
hours=sign * int(hour_str),
|
| 104 |
+
minutes=sign * int(minute_str),
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def match_to_localtime(match: re.Match[str]) -> time:
|
| 110 |
+
hour_str, minute_str, sec_str, micros_str = match.groups()
|
| 111 |
+
sec = int(sec_str) if sec_str else 0
|
| 112 |
+
micros = int(micros_str.ljust(6, "0")) if micros_str else 0
|
| 113 |
+
return time(int(hour_str), int(minute_str), sec, micros)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def match_to_number(match: re.Match[str], parse_float: ParseFloat) -> Any:
|
| 117 |
+
if match.group("floatpart"):
|
| 118 |
+
return parse_float(match.group())
|
| 119 |
+
return int(match.group(), 0)
|
miniconda3/lib/python3.13/site-packages/tomli/_types.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: MIT
|
| 2 |
+
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
|
| 3 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 4 |
+
|
| 5 |
+
from typing import Any, Callable, Tuple
|
| 6 |
+
|
| 7 |
+
# Type annotations
|
| 8 |
+
ParseFloat = Callable[[str], Any]
|
| 9 |
+
Key = Tuple[str, ...]
|
| 10 |
+
Pos = int
|
miniconda3/lib/python3.13/site-packages/tomli/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Marker file for PEP 561
|
miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/METADATA
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: tomlkit
|
| 3 |
+
Version: 0.13.3
|
| 4 |
+
Summary: Style preserving TOML library
|
| 5 |
+
License: MIT
|
| 6 |
+
License-File: LICENSE
|
| 7 |
+
Author: Sébastien Eustace
|
| 8 |
+
Author-email: sebastien@eustace.io
|
| 9 |
+
Requires-Python: >=3.8
|
| 10 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 11 |
+
Classifier: Programming Language :: Python :: 3
|
| 12 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 13 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 14 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 19 |
+
Project-URL: Homepage, https://github.com/sdispater/tomlkit
|
| 20 |
+
Project-URL: Repository, https://github.com/sdispater/tomlkit
|
| 21 |
+
Description-Content-Type: text/markdown
|
| 22 |
+
|
| 23 |
+
[github_release]: https://img.shields.io/github/release/sdispater/tomlkit.svg?logo=github&logoColor=white
|
| 24 |
+
[pypi_version]: https://img.shields.io/pypi/v/tomlkit.svg?logo=python&logoColor=white
|
| 25 |
+
[python_versions]: https://img.shields.io/pypi/pyversions/tomlkit.svg?logo=python&logoColor=white
|
| 26 |
+
[github_license]: https://img.shields.io/github/license/sdispater/tomlkit.svg?logo=github&logoColor=white
|
| 27 |
+
[github_action]: https://github.com/sdispater/tomlkit/actions/workflows/tests.yml/badge.svg
|
| 28 |
+
|
| 29 |
+
[![GitHub Release][github_release]](https://github.com/sdispater/tomlkit/releases/)
|
| 30 |
+
[![PyPI Version][pypi_version]](https://pypi.org/project/tomlkit/)
|
| 31 |
+
[![Python Versions][python_versions]](https://pypi.org/project/tomlkit/)
|
| 32 |
+
[![License][github_license]](https://github.com/sdispater/tomlkit/blob/master/LICENSE)
|
| 33 |
+
<br>
|
| 34 |
+
[![Tests][github_action]](https://github.com/sdispater/tomlkit/actions/workflows/tests.yml)
|
| 35 |
+
|
| 36 |
+
# TOML Kit - Style-preserving TOML library for Python
|
| 37 |
+
|
| 38 |
+
TOML Kit is a **1.0.0-compliant** [TOML](https://toml.io/) library.
|
| 39 |
+
|
| 40 |
+
It includes a parser that preserves all comments, indentations, whitespace and internal element ordering,
|
| 41 |
+
and makes them accessible and editable via an intuitive API.
|
| 42 |
+
|
| 43 |
+
You can also create new TOML documents from scratch using the provided helpers.
|
| 44 |
+
|
| 45 |
+
Part of the implementation has been adapted, improved and fixed from [Molten](https://github.com/LeopoldArkham/Molten).
|
| 46 |
+
|
| 47 |
+
## Usage
|
| 48 |
+
|
| 49 |
+
See the [documentation](https://tomlkit.readthedocs.io/) for more information.
|
| 50 |
+
|
| 51 |
+
## Installation
|
| 52 |
+
|
| 53 |
+
If you are using [Poetry](https://poetry.eustace.io),
|
| 54 |
+
add `tomlkit` to your `pyproject.toml` file by using:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
poetry add tomlkit
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
If not, you can use `pip`:
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
pip install tomlkit
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## Running tests
|
| 67 |
+
|
| 68 |
+
Please clone the repo with submodules with the following command:
|
| 69 |
+
```bash
|
| 70 |
+
git clone --recurse-submodules https://github.com/python-poetry/tomlkit.git
|
| 71 |
+
```
|
| 72 |
+
The `toml-test` submodule is required for running the tests.
|
| 73 |
+
|
| 74 |
+
You can then run the tests with
|
| 75 |
+
```bash
|
| 76 |
+
poetry run pytest -q tests
|
| 77 |
+
```
|
| 78 |
+
|
miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/RECORD
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tomlkit-0.13.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
tomlkit-0.13.3.dist-info/METADATA,sha256=WGB4KL1e47L4PjAccq_T6GvF8BdWrJh_YCViVGNwlSU,2835
|
| 3 |
+
tomlkit-0.13.3.dist-info/RECORD,,
|
| 4 |
+
tomlkit-0.13.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
tomlkit-0.13.3.dist-info/WHEEL,sha256=M5asmiAlL6HEcOq52Yi5mmk9KmTVjY2RDPtO4p9DMrc,88
|
| 6 |
+
tomlkit-0.13.3.dist-info/direct_url.json,sha256=yGFRIc96Pte9WxFw21srKfW_sY3oclqNgO5D_tqDll8,97
|
| 7 |
+
tomlkit-0.13.3.dist-info/licenses/LICENSE,sha256=8vm0YLpxnaZiat0mTTeC8nWk_3qrZ3vtoIszCRHiOts,1062
|
| 8 |
+
tomlkit/__init__.py,sha256=FI03MlAi7dh0MxLPrTcgYJgYlt_MN9-pW1X2wpf8W68,1282
|
| 9 |
+
tomlkit/__pycache__/__init__.cpython-313.pyc,,
|
| 10 |
+
tomlkit/__pycache__/_compat.cpython-313.pyc,,
|
| 11 |
+
tomlkit/__pycache__/_types.cpython-313.pyc,,
|
| 12 |
+
tomlkit/__pycache__/_utils.cpython-313.pyc,,
|
| 13 |
+
tomlkit/__pycache__/api.cpython-313.pyc,,
|
| 14 |
+
tomlkit/__pycache__/container.cpython-313.pyc,,
|
| 15 |
+
tomlkit/__pycache__/exceptions.cpython-313.pyc,,
|
| 16 |
+
tomlkit/__pycache__/items.cpython-313.pyc,,
|
| 17 |
+
tomlkit/__pycache__/parser.cpython-313.pyc,,
|
| 18 |
+
tomlkit/__pycache__/source.cpython-313.pyc,,
|
| 19 |
+
tomlkit/__pycache__/toml_char.cpython-313.pyc,,
|
| 20 |
+
tomlkit/__pycache__/toml_document.cpython-313.pyc,,
|
| 21 |
+
tomlkit/__pycache__/toml_file.cpython-313.pyc,,
|
| 22 |
+
tomlkit/_compat.py,sha256=gp7P7qNh0yY1dg0wyjiCDbVwFTdUo7p0QwjV4T3Funs,513
|
| 23 |
+
tomlkit/_types.py,sha256=42ht2m-_pJPvQ_uMKMIJf4KL6F9N0NoDa0fymfTeIC4,2619
|
| 24 |
+
tomlkit/_utils.py,sha256=m4OyWq9nw5MGabHhQKTIu1YtUD8SVJyoTImHTN6L7Yc,4089
|
| 25 |
+
tomlkit/api.py,sha256=q3ZmRM87tKChjsnuqaj6EgHtTxSfe-fPhAb5MbIg_3U,7811
|
| 26 |
+
tomlkit/container.py,sha256=940ylh_8JfrTEZsCSY6q5PJJ8TvJvOhuVagoRB-hyog,31685
|
| 27 |
+
tomlkit/exceptions.py,sha256=e-0iKjv-u2ngE6G6XMOxaoBNnKBfPNjDLmaw4YDHpoU,5703
|
| 28 |
+
tomlkit/items.py,sha256=14Ks1XFzXsJVYaBsHaJC_Iz9EKodp0bROJzF3HXjBek,56286
|
| 29 |
+
tomlkit/parser.py,sha256=GaTS0NQlEelkd1GTlnDFT3NtQdp5fC1j10_lnK3pOdI,38080
|
| 30 |
+
tomlkit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 31 |
+
tomlkit/source.py,sha256=Nith7mmPmhTf5dMSRc41bY9cuIRR_4CoqOjC-fxzfCo,4835
|
| 32 |
+
tomlkit/toml_char.py,sha256=w3sQZ0dolZ1qjZ2Rxj_svvlpRNNGB_fjfBcYD0gFnDs,1291
|
| 33 |
+
tomlkit/toml_document.py,sha256=OCTkWXd3P58EZT4SD8_ddc1YpkMaqtlS5_stHTBmMOI,110
|
| 34 |
+
tomlkit/toml_file.py,sha256=8ZzSZv2C1R9Qce2WZ122ijnl9LUZJ_1nS1xLLQT7OX4,1659
|
miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: poetry-core 2.2.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///home/task_176289666312502/conda-bld/tomlkit_1762896676945/work"}
|
miniconda3/lib/python3.13/site-packages/tomlkit-0.13.3.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2018 Sébastien Eustace
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 4 |
+
a copy of this software and associated documentation files (the
|
| 5 |
+
"Software"), to deal in the Software without restriction, including
|
| 6 |
+
without limitation the rights to use, copy, modify, merge, publish,
|
| 7 |
+
distribute, sublicense, and/or sell copies of the Software, and to
|
| 8 |
+
permit persons to whom the Software is furnished to do so, subject to
|
| 9 |
+
the following conditions:
|
| 10 |
+
|
| 11 |
+
The above copyright notice and this permission notice shall be
|
| 12 |
+
included in all copies or substantial portions of the Software.
|
| 13 |
+
|
| 14 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 15 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 16 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 17 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
| 18 |
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
| 19 |
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
| 20 |
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
miniconda3/lib/python3.13/site-packages/tomlkit/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tomlkit.api import TOMLDocument
|
| 2 |
+
from tomlkit.api import aot
|
| 3 |
+
from tomlkit.api import array
|
| 4 |
+
from tomlkit.api import boolean
|
| 5 |
+
from tomlkit.api import comment
|
| 6 |
+
from tomlkit.api import date
|
| 7 |
+
from tomlkit.api import datetime
|
| 8 |
+
from tomlkit.api import document
|
| 9 |
+
from tomlkit.api import dump
|
| 10 |
+
from tomlkit.api import dumps
|
| 11 |
+
from tomlkit.api import float_
|
| 12 |
+
from tomlkit.api import inline_table
|
| 13 |
+
from tomlkit.api import integer
|
| 14 |
+
from tomlkit.api import item
|
| 15 |
+
from tomlkit.api import key
|
| 16 |
+
from tomlkit.api import key_value
|
| 17 |
+
from tomlkit.api import load
|
| 18 |
+
from tomlkit.api import loads
|
| 19 |
+
from tomlkit.api import nl
|
| 20 |
+
from tomlkit.api import parse
|
| 21 |
+
from tomlkit.api import register_encoder
|
| 22 |
+
from tomlkit.api import string
|
| 23 |
+
from tomlkit.api import table
|
| 24 |
+
from tomlkit.api import time
|
| 25 |
+
from tomlkit.api import unregister_encoder
|
| 26 |
+
from tomlkit.api import value
|
| 27 |
+
from tomlkit.api import ws
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
__version__ = "0.13.3"
|
| 31 |
+
__all__ = [
|
| 32 |
+
"TOMLDocument",
|
| 33 |
+
"aot",
|
| 34 |
+
"array",
|
| 35 |
+
"boolean",
|
| 36 |
+
"comment",
|
| 37 |
+
"date",
|
| 38 |
+
"datetime",
|
| 39 |
+
"document",
|
| 40 |
+
"dump",
|
| 41 |
+
"dumps",
|
| 42 |
+
"float_",
|
| 43 |
+
"inline_table",
|
| 44 |
+
"integer",
|
| 45 |
+
"item",
|
| 46 |
+
"key",
|
| 47 |
+
"key_value",
|
| 48 |
+
"load",
|
| 49 |
+
"loads",
|
| 50 |
+
"nl",
|
| 51 |
+
"parse",
|
| 52 |
+
"register_encoder",
|
| 53 |
+
"string",
|
| 54 |
+
"table",
|
| 55 |
+
"time",
|
| 56 |
+
"unregister_encoder",
|
| 57 |
+
"value",
|
| 58 |
+
"ws",
|
| 59 |
+
]
|
miniconda3/lib/python3.13/site-packages/tomlkit/_compat.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
PY38 = sys.version_info >= (3, 8)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def decode(string: Any, encodings: list[str] | None = None):
|
| 13 |
+
if not isinstance(string, bytes):
|
| 14 |
+
return string
|
| 15 |
+
|
| 16 |
+
encodings = encodings or ["utf-8", "latin1", "ascii"]
|
| 17 |
+
|
| 18 |
+
for encoding in encodings:
|
| 19 |
+
with contextlib.suppress(UnicodeEncodeError, UnicodeDecodeError):
|
| 20 |
+
return string.decode(encoding)
|
| 21 |
+
|
| 22 |
+
return string.decode(encodings[0], errors="ignore")
|
miniconda3/lib/python3.13/site-packages/tomlkit/_types.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
from typing import Any
|
| 5 |
+
from typing import TypeVar
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
WT = TypeVar("WT", bound="WrapperType")
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 11 |
+
# Define _CustomList and _CustomDict as a workaround for:
|
| 12 |
+
# https://github.com/python/mypy/issues/11427
|
| 13 |
+
#
|
| 14 |
+
# According to this issue, the typeshed contains a "lie"
|
| 15 |
+
# (it adds MutableSequence to the ancestry of list and MutableMapping to
|
| 16 |
+
# the ancestry of dict) which completely messes with the type inference for
|
| 17 |
+
# Table, InlineTable, Array and Container.
|
| 18 |
+
#
|
| 19 |
+
# Importing from builtins is preferred over simple assignment, see issues:
|
| 20 |
+
# https://github.com/python/mypy/issues/8715
|
| 21 |
+
# https://github.com/python/mypy/issues/10068
|
| 22 |
+
from builtins import dict as _CustomDict
|
| 23 |
+
from builtins import float as _CustomFloat
|
| 24 |
+
from builtins import int as _CustomInt
|
| 25 |
+
from builtins import list as _CustomList
|
| 26 |
+
from typing import Callable
|
| 27 |
+
from typing import Concatenate
|
| 28 |
+
from typing import ParamSpec
|
| 29 |
+
from typing import Protocol
|
| 30 |
+
|
| 31 |
+
P = ParamSpec("P")
|
| 32 |
+
|
| 33 |
+
class WrapperType(Protocol):
|
| 34 |
+
def _new(self: WT, value: Any) -> WT: ...
|
| 35 |
+
|
| 36 |
+
else:
|
| 37 |
+
from collections.abc import MutableMapping
|
| 38 |
+
from collections.abc import MutableSequence
|
| 39 |
+
from numbers import Integral
|
| 40 |
+
from numbers import Real
|
| 41 |
+
|
| 42 |
+
class _CustomList(MutableSequence, list):
|
| 43 |
+
"""Adds MutableSequence mixin while pretending to be a builtin list"""
|
| 44 |
+
|
| 45 |
+
def __add__(self, other):
|
| 46 |
+
new_list = self.copy()
|
| 47 |
+
new_list.extend(other)
|
| 48 |
+
return new_list
|
| 49 |
+
|
| 50 |
+
def __iadd__(self, other):
|
| 51 |
+
self.extend(other)
|
| 52 |
+
return self
|
| 53 |
+
|
| 54 |
+
class _CustomDict(MutableMapping, dict):
|
| 55 |
+
"""Adds MutableMapping mixin while pretending to be a builtin dict"""
|
| 56 |
+
|
| 57 |
+
def __or__(self, other):
|
| 58 |
+
new_dict = self.copy()
|
| 59 |
+
new_dict.update(other)
|
| 60 |
+
return new_dict
|
| 61 |
+
|
| 62 |
+
def __ior__(self, other):
|
| 63 |
+
self.update(other)
|
| 64 |
+
return self
|
| 65 |
+
|
| 66 |
+
class _CustomInt(Integral, int):
|
| 67 |
+
"""Adds Integral mixin while pretending to be a builtin int"""
|
| 68 |
+
|
| 69 |
+
class _CustomFloat(Real, float):
|
| 70 |
+
"""Adds Real mixin while pretending to be a builtin float"""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def wrap_method(
|
| 74 |
+
original_method: Callable[Concatenate[WT, P], Any],
|
| 75 |
+
) -> Callable[Concatenate[WT, P], Any]:
|
| 76 |
+
def wrapper(self: WT, *args: P.args, **kwargs: P.kwargs) -> Any:
|
| 77 |
+
result = original_method(self, *args, **kwargs)
|
| 78 |
+
if result is NotImplemented:
|
| 79 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
from collections.abc import Mapping
|
| 6 |
+
from datetime import date
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from datetime import time
|
| 9 |
+
from datetime import timedelta
|
| 10 |
+
from datetime import timezone
|
| 11 |
+
from typing import Collection
|
| 12 |
+
|
| 13 |
+
from tomlkit._compat import decode
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
RFC_3339_LOOSE = re.compile(
|
| 17 |
+
"^"
|
| 18 |
+
r"(([0-9]+)-(\d{2})-(\d{2}))?" # Date
|
| 19 |
+
"("
|
| 20 |
+
"([Tt ])?" # Separator
|
| 21 |
+
r"(\d{2}):(\d{2}):(\d{2})(\.([0-9]+))?" # Time
|
| 22 |
+
r"(([Zz])|([\+|\-]([01][0-9]|2[0-3]):([0-5][0-9])))?" # Timezone
|
| 23 |
+
")?"
|
| 24 |
+
"$"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
RFC_3339_DATETIME = re.compile(
|
| 28 |
+
"^"
|
| 29 |
+
"([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])" # Date
|
| 30 |
+
"[Tt ]" # Separator
|
| 31 |
+
r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.([0-9]+))?" # Time
|
| 32 |
+
r"(([Zz])|([\+|\-]([01][0-9]|2[0-3]):([0-5][0-9])))?" # Timezone
|
| 33 |
+
"$"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
RFC_3339_DATE = re.compile("^([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$")
|
| 37 |
+
|
| 38 |
+
RFC_3339_TIME = re.compile(
|
| 39 |
+
r"^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.([0-9]+))?$"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
_utc = timezone(timedelta(), "UTC")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def parse_rfc3339(string: str) -> datetime | date | time:
|
| 46 |
+
m = RFC_3339_DATETIME.match(string)
|
| 47 |
+
if m:
|
| 48 |
+
year = int(m.group(1))
|
| 49 |
+
month = int(m.group(2))
|
| 50 |
+
day = int(m.group(3))
|
| 51 |
+
hour = int(m.group(4))
|
| 52 |
+
minute = int(m.group(5))
|
| 53 |
+
second = int(m.group(6))
|
| 54 |
+
microsecond = 0
|
| 55 |
+
|
| 56 |
+
if m.group(7):
|
| 57 |
+
microsecond = int((f"{m.group(8):<06s}")[:6])
|
| 58 |
+
|
| 59 |
+
if m.group(9):
|
| 60 |
+
# Timezone
|
| 61 |
+
tz = m.group(9)
|
| 62 |
+
if tz.upper() == "Z":
|
| 63 |
+
tzinfo = _utc
|
| 64 |
+
else:
|
| 65 |
+
sign = m.group(11)[0]
|
| 66 |
+
hour_offset, minute_offset = int(m.group(12)), int(m.group(13))
|
| 67 |
+
offset = timedelta(seconds=hour_offset * 3600 + minute_offset * 60)
|
| 68 |
+
if sign == "-":
|
| 69 |
+
offset = -offset
|
| 70 |
+
|
| 71 |
+
tzinfo = timezone(offset, f"{sign}{m.group(12)}:{m.group(13)}")
|
| 72 |
+
|
| 73 |
+
return datetime(
|
| 74 |
+
year, month, day, hour, minute, second, microsecond, tzinfo=tzinfo
|
| 75 |
+
)
|
| 76 |
+
else:
|
| 77 |
+
return datetime(year, month, day, hour, minute, second, microsecond)
|
| 78 |
+
|
| 79 |
+
m = RFC_3339_DATE.match(string)
|
| 80 |
+
if m:
|
| 81 |
+
year = int(m.group(1))
|
| 82 |
+
month = int(m.group(2))
|
| 83 |
+
day = int(m.group(3))
|
| 84 |
+
|
| 85 |
+
return date(year, month, day)
|
| 86 |
+
|
| 87 |
+
m = RFC_3339_TIME.match(string)
|
| 88 |
+
if m:
|
| 89 |
+
hour = int(m.group(1))
|
| 90 |
+
minute = int(m.group(2))
|
| 91 |
+
second = int(m.group(3))
|
| 92 |
+
microsecond = 0
|
| 93 |
+
|
| 94 |
+
if m.group(4):
|
| 95 |
+
microsecond = int((f"{m.group(5):<06s}")[:6])
|
| 96 |
+
|
| 97 |
+
return time(hour, minute, second, microsecond)
|
| 98 |
+
|
| 99 |
+
raise ValueError("Invalid RFC 339 string")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# https://toml.io/en/v1.0.0#string
|
| 103 |
+
CONTROL_CHARS = frozenset(chr(c) for c in range(0x20)) | {chr(0x7F)}
|
| 104 |
+
_escaped = {
|
| 105 |
+
"b": "\b",
|
| 106 |
+
"t": "\t",
|
| 107 |
+
"n": "\n",
|
| 108 |
+
"f": "\f",
|
| 109 |
+
"r": "\r",
|
| 110 |
+
'"': '"',
|
| 111 |
+
"\\": "\\",
|
| 112 |
+
}
|
| 113 |
+
_compact_escapes = {
|
| 114 |
+
**{v: f"\\{k}" for k, v in _escaped.items()},
|
| 115 |
+
'"""': '""\\"',
|
| 116 |
+
}
|
| 117 |
+
_basic_escapes = CONTROL_CHARS | {'"', "\\"}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _unicode_escape(seq: str) -> str:
|
| 121 |
+
return "".join(f"\\u{ord(c):04x}" for c in seq)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def escape_string(s: str, escape_sequences: Collection[str] = _basic_escapes) -> str:
|
| 125 |
+
s = decode(s)
|
| 126 |
+
|
| 127 |
+
res = []
|
| 128 |
+
start = 0
|
| 129 |
+
|
| 130 |
+
def flush(inc=1):
|
| 131 |
+
if start != i:
|
| 132 |
+
res.append(s[start:i])
|
| 133 |
+
|
| 134 |
+
return i + inc
|
| 135 |
+
|
| 136 |
+
found_sequences = {seq for seq in escape_sequences if seq in s}
|
| 137 |
+
|
| 138 |
+
i = 0
|
| 139 |
+
while i < len(s):
|
| 140 |
+
for seq in found_sequences:
|
| 141 |
+
seq_len = len(seq)
|
| 142 |
+
if s[i:].startswith(seq):
|
| 143 |
+
start = flush(seq_len)
|
| 144 |
+
res.append(_compact_escapes.get(seq) or _unicode_escape(seq))
|
| 145 |
+
i += seq_len - 1 # fast-forward escape sequence
|
| 146 |
+
i += 1
|
| 147 |
+
|
| 148 |
+
flush()
|
| 149 |
+
|
| 150 |
+
return "".join(res)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def merge_dicts(d1: dict, d2: dict) -> dict:
|
| 154 |
+
for k, v in d2.items():
|
| 155 |
+
if k in d1 and isinstance(d1[k], dict) and isinstance(v, Mapping):
|
| 156 |
+
merge_dicts(d1[k], v)
|
| 157 |
+
else:
|
| 158 |
+
d1[k] = d2[k]
|
miniconda3/lib/python3.13/site-packages/tomlkit/api.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import datetime as _datetime
|
| 5 |
+
|
| 6 |
+
from collections.abc import Mapping
|
| 7 |
+
from typing import IO
|
| 8 |
+
from typing import Iterable
|
| 9 |
+
from typing import TypeVar
|
| 10 |
+
|
| 11 |
+
from tomlkit._utils import parse_rfc3339
|
| 12 |
+
from tomlkit.container import Container
|
| 13 |
+
from tomlkit.exceptions import UnexpectedCharError
|
| 14 |
+
from tomlkit.items import CUSTOM_ENCODERS
|
| 15 |
+
from tomlkit.items import AoT
|
| 16 |
+
from tomlkit.items import Array
|
| 17 |
+
from tomlkit.items import Bool
|
| 18 |
+
from tomlkit.items import Comment
|
| 19 |
+
from tomlkit.items import Date
|
| 20 |
+
from tomlkit.items import DateTime
|
| 21 |
+
from tomlkit.items import DottedKey
|
| 22 |
+
from tomlkit.items import Encoder
|
| 23 |
+
from tomlkit.items import Float
|
| 24 |
+
from tomlkit.items import InlineTable
|
| 25 |
+
from tomlkit.items import Integer
|
| 26 |
+
from tomlkit.items import Item as _Item
|
| 27 |
+
from tomlkit.items import Key
|
| 28 |
+
from tomlkit.items import SingleKey
|
| 29 |
+
from tomlkit.items import String
|
| 30 |
+
from tomlkit.items import StringType as _StringType
|
| 31 |
+
from tomlkit.items import Table
|
| 32 |
+
from tomlkit.items import Time
|
| 33 |
+
from tomlkit.items import Trivia
|
| 34 |
+
from tomlkit.items import Whitespace
|
| 35 |
+
from tomlkit.items import item
|
| 36 |
+
from tomlkit.parser import Parser
|
| 37 |
+
from tomlkit.toml_document import TOMLDocument
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def loads(string: str | bytes) -> TOMLDocument:
|
| 41 |
+
"""
|
| 42 |
+
Parses a string into a TOMLDocument.
|
| 43 |
+
|
| 44 |
+
Alias for parse().
|
| 45 |
+
"""
|
| 46 |
+
return parse(string)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def dumps(data: Mapping, sort_keys: bool = False) -> str:
|
| 50 |
+
"""
|
| 51 |
+
Dumps a TOMLDocument into a string.
|
| 52 |
+
"""
|
| 53 |
+
if not isinstance(data, (Table, InlineTable, Container)) and isinstance(
|
| 54 |
+
data, Mapping
|
| 55 |
+
):
|
| 56 |
+
data = item(dict(data), _sort_keys=sort_keys)
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
# data should be a `Container` (and therefore implement `as_string`)
|
| 60 |
+
# for all type safe invocations of this function
|
| 61 |
+
return data.as_string() # type: ignore[attr-defined]
|
| 62 |
+
except AttributeError as ex:
|
| 63 |
+
msg = f"Expecting Mapping or TOML Table or Container, {type(data)} given"
|
| 64 |
+
raise TypeError(msg) from ex
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def load(fp: IO[str] | IO[bytes]) -> TOMLDocument:
|
| 68 |
+
"""
|
| 69 |
+
Load toml document from a file-like object.
|
| 70 |
+
"""
|
| 71 |
+
return parse(fp.read())
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def dump(data: Mapping, fp: IO[str], *, sort_keys: bool = False) -> None:
|
| 75 |
+
"""
|
| 76 |
+
Dump a TOMLDocument into a writable file stream.
|
| 77 |
+
|
| 78 |
+
:param data: a dict-like object to dump
|
| 79 |
+
:param sort_keys: if true, sort the keys in alphabetic order
|
| 80 |
+
|
| 81 |
+
:Example:
|
| 82 |
+
|
| 83 |
+
>>> with open("output.toml", "w") as fp:
|
| 84 |
+
... tomlkit.dump(data, fp)
|
| 85 |
+
"""
|
| 86 |
+
fp.write(dumps(data, sort_keys=sort_keys))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def parse(string: str | bytes) -> TOMLDocument:
|
| 90 |
+
"""
|
| 91 |
+
Parses a string or bytes into a TOMLDocument.
|
| 92 |
+
"""
|
| 93 |
+
return Parser(string).parse()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def document() -> TOMLDocument:
|
| 97 |
+
"""
|
| 98 |
+
Returns a new TOMLDocument instance.
|
| 99 |
+
"""
|
| 100 |
+
return TOMLDocument()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# Items
|
| 104 |
+
def integer(raw: str | int) -> Integer:
|
| 105 |
+
"""Create an integer item from a number or string."""
|
| 106 |
+
return item(int(raw))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def float_(raw: str | float) -> Float:
|
| 110 |
+
"""Create an float item from a number or string."""
|
| 111 |
+
return item(float(raw))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def boolean(raw: str) -> Bool:
|
| 115 |
+
"""Turn `true` or `false` into a boolean item."""
|
| 116 |
+
return item(raw == "true")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def string(
|
| 120 |
+
raw: str,
|
| 121 |
+
*,
|
| 122 |
+
literal: bool = False,
|
| 123 |
+
multiline: bool = False,
|
| 124 |
+
escape: bool = True,
|
| 125 |
+
) -> String:
|
| 126 |
+
"""Create a string item.
|
| 127 |
+
|
| 128 |
+
By default, this function will create *single line basic* strings, but
|
| 129 |
+
boolean flags (e.g. ``literal=True`` and/or ``multiline=True``)
|
| 130 |
+
can be used for personalization.
|
| 131 |
+
|
| 132 |
+
For more information, please check the spec: `<https://toml.io/en/v1.0.0#string>`__.
|
| 133 |
+
|
| 134 |
+
Common escaping rules will be applied for basic strings.
|
| 135 |
+
This can be controlled by explicitly setting ``escape=False``.
|
| 136 |
+
Please note that, if you disable escaping, you will have to make sure that
|
| 137 |
+
the given strings don't contain any forbidden character or sequence.
|
| 138 |
+
"""
|
| 139 |
+
type_ = _StringType.select(literal, multiline)
|
| 140 |
+
return String.from_raw(raw, type_, escape)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def date(raw: str) -> Date:
|
| 144 |
+
"""Create a TOML date."""
|
| 145 |
+
value = parse_rfc3339(raw)
|
| 146 |
+
if not isinstance(value, _datetime.date):
|
| 147 |
+
raise ValueError("date() only accepts date strings.")
|
| 148 |
+
|
| 149 |
+
return item(value)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def time(raw: str) -> Time:
|
| 153 |
+
"""Create a TOML time."""
|
| 154 |
+
value = parse_rfc3339(raw)
|
| 155 |
+
if not isinstance(value, _datetime.time):
|
| 156 |
+
raise ValueError("time() only accepts time strings.")
|
| 157 |
+
|
| 158 |
+
return item(value)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def datetime(raw: str) -> DateTime:
|
| 162 |
+
"""Create a TOML datetime."""
|
| 163 |
+
value = parse_rfc3339(raw)
|
| 164 |
+
if not isinstance(value, _datetime.datetime):
|
| 165 |
+
raise ValueError("datetime() only accepts datetime strings.")
|
| 166 |
+
|
| 167 |
+
return item(value)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def array(raw: str = "[]") -> Array:
|
| 171 |
+
"""Create an array item for its string representation.
|
| 172 |
+
|
| 173 |
+
:Example:
|
| 174 |
+
|
| 175 |
+
>>> array("[1, 2, 3]") # Create from a string
|
| 176 |
+
[1, 2, 3]
|
| 177 |
+
>>> a = array()
|
| 178 |
+
>>> a.extend([1, 2, 3]) # Create from a list
|
| 179 |
+
>>> a
|
| 180 |
+
[1, 2, 3]
|
| 181 |
+
"""
|
| 182 |
+
return value(raw)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def table(is_super_table: bool | None = None) -> Table:
|
| 186 |
+
"""Create an empty table.
|
| 187 |
+
|
| 188 |
+
:param is_super_table: if true, the table is a super table
|
| 189 |
+
|
| 190 |
+
:Example:
|
| 191 |
+
|
| 192 |
+
>>> doc = document()
|
| 193 |
+
>>> foo = table(True)
|
| 194 |
+
>>> bar = table()
|
| 195 |
+
>>> bar.update({'x': 1})
|
| 196 |
+
>>> foo.append('bar', bar)
|
| 197 |
+
>>> doc.append('foo', foo)
|
| 198 |
+
>>> print(doc.as_string())
|
| 199 |
+
[foo.bar]
|
| 200 |
+
x = 1
|
| 201 |
+
"""
|
| 202 |
+
return Table(Container(), Trivia(), False, is_super_table)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def inline_table() -> InlineTable:
|
| 206 |
+
"""Create an inline table.
|
| 207 |
+
|
| 208 |
+
:Example:
|
| 209 |
+
|
| 210 |
+
>>> table = inline_table()
|
| 211 |
+
>>> table.update({'x': 1, 'y': 2})
|
| 212 |
+
>>> print(table.as_string())
|
| 213 |
+
{x = 1, y = 2}
|
| 214 |
+
"""
|
| 215 |
+
return InlineTable(Container(), Trivia(), new=True)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def aot() -> AoT:
|
| 219 |
+
"""Create an array of table.
|
| 220 |
+
|
| 221 |
+
:Example:
|
| 222 |
+
|
| 223 |
+
>>> doc = document()
|
| 224 |
+
>>> aot = aot()
|
| 225 |
+
>>> aot.append(item({'x': 1}))
|
| 226 |
+
>>> doc.append('foo', aot)
|
| 227 |
+
>>> print(doc.as_string())
|
| 228 |
+
[[foo]]
|
| 229 |
+
x = 1
|
| 230 |
+
"""
|
| 231 |
+
return AoT([])
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def key(k: str | Iterable[str]) -> Key:
|
| 235 |
+
"""Create a key from a string. When a list of string is given,
|
| 236 |
+
it will create a dotted key.
|
| 237 |
+
|
| 238 |
+
:Example:
|
| 239 |
+
|
| 240 |
+
>>> doc = document()
|
| 241 |
+
>>> doc.append(key('foo'), 1)
|
| 242 |
+
>>> doc.append(key(['bar', 'baz']), 2)
|
| 243 |
+
>>> print(doc.as_string())
|
| 244 |
+
foo = 1
|
| 245 |
+
bar.baz = 2
|
| 246 |
+
"""
|
| 247 |
+
if isinstance(k, str):
|
| 248 |
+
return SingleKey(k)
|
| 249 |
+
return DottedKey([key(_k) for _k in k])
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def value(raw: str) -> _Item:
|
| 253 |
+
"""Parse a simple value from a string.
|
| 254 |
+
|
| 255 |
+
:Example:
|
| 256 |
+
|
| 257 |
+
>>> value("1")
|
| 258 |
+
1
|
| 259 |
+
>>> value("true")
|
| 260 |
+
True
|
| 261 |
+
>>> value("[1, 2, 3]")
|
| 262 |
+
[1, 2, 3]
|
| 263 |
+
"""
|
| 264 |
+
parser = Parser(raw)
|
| 265 |
+
v = parser._parse_value()
|
| 266 |
+
if not parser.end():
|
| 267 |
+
raise parser.parse_error(UnexpectedCharError, char=parser._current)
|
| 268 |
+
return v
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def key_value(src: str) -> tuple[Key, _Item]:
|
| 272 |
+
"""Parse a key-value pair from a string.
|
| 273 |
+
|
| 274 |
+
:Example:
|
| 275 |
+
|
| 276 |
+
>>> key_value("foo = 1")
|
| 277 |
+
(Key('foo'), 1)
|
| 278 |
+
"""
|
| 279 |
+
return Parser(src)._parse_key_value()
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def ws(src: str) -> Whitespace:
|
| 283 |
+
"""Create a whitespace from a string."""
|
| 284 |
+
return Whitespace(src, fixed=True)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def nl() -> Whitespace:
|
| 288 |
+
"""Create a newline item."""
|
| 289 |
+
return ws("\n")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def comment(string: str) -> Comment:
|
| 293 |
+
"""Create a comment item."""
|
| 294 |
+
return Comment(Trivia(comment_ws=" ", comment="# " + string))
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
E = TypeVar("E", bound=Encoder)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def register_encoder(encoder: E) -> E:
|
| 301 |
+
"""Add a custom encoder, which should be a function that will be called
|
| 302 |
+
if the value can't otherwise be converted. It should takes a single value
|
| 303 |
+
and return a TOMLKit item or raise a ``ConvertError``.
|
| 304 |
+
"""
|
| 305 |
+
CUSTOM_ENCODERS.append(encoder)
|
| 306 |
+
return encoder
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def unregister_encoder(encoder: Encoder) -> None:
|
| 310 |
+
"""Unregister a custom encoder."""
|
| 311 |
+
with contextlib.suppress(ValueError):
|
| 312 |
+
CUSTOM_ENCODERS.remove(encoder)
|
miniconda3/lib/python3.13/site-packages/tomlkit/container.py
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
from typing import Iterator
|
| 7 |
+
|
| 8 |
+
from tomlkit._compat import decode
|
| 9 |
+
from tomlkit._types import _CustomDict
|
| 10 |
+
from tomlkit._utils import merge_dicts
|
| 11 |
+
from tomlkit.exceptions import KeyAlreadyPresent
|
| 12 |
+
from tomlkit.exceptions import NonExistentKey
|
| 13 |
+
from tomlkit.exceptions import TOMLKitError
|
| 14 |
+
from tomlkit.items import AoT
|
| 15 |
+
from tomlkit.items import Comment
|
| 16 |
+
from tomlkit.items import Item
|
| 17 |
+
from tomlkit.items import Key
|
| 18 |
+
from tomlkit.items import Null
|
| 19 |
+
from tomlkit.items import SingleKey
|
| 20 |
+
from tomlkit.items import Table
|
| 21 |
+
from tomlkit.items import Trivia
|
| 22 |
+
from tomlkit.items import Whitespace
|
| 23 |
+
from tomlkit.items import item as _item
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_NOT_SET = object()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Container(_CustomDict):
|
| 30 |
+
"""
|
| 31 |
+
A container for items within a TOMLDocument.
|
| 32 |
+
|
| 33 |
+
This class implements the `dict` interface with copy/deepcopy protocol.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, parsed: bool = False) -> None:
|
| 37 |
+
self._map: dict[SingleKey, int | tuple[int, ...]] = {}
|
| 38 |
+
self._body: list[tuple[Key | None, Item]] = []
|
| 39 |
+
self._parsed = parsed
|
| 40 |
+
self._table_keys = []
|
| 41 |
+
|
| 42 |
+
@property
|
| 43 |
+
def body(self) -> list[tuple[Key | None, Item]]:
|
| 44 |
+
return self._body
|
| 45 |
+
|
| 46 |
+
def unwrap(self) -> dict[str, Any]:
|
| 47 |
+
"""Returns as pure python object (ppo)"""
|
| 48 |
+
unwrapped = {}
|
| 49 |
+
for k, v in self.items():
|
| 50 |
+
if k is None:
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
if isinstance(k, Key):
|
| 54 |
+
k = k.key
|
| 55 |
+
|
| 56 |
+
if hasattr(v, "unwrap"):
|
| 57 |
+
v = v.unwrap()
|
| 58 |
+
|
| 59 |
+
if k in unwrapped:
|
| 60 |
+
merge_dicts(unwrapped[k], v)
|
| 61 |
+
else:
|
| 62 |
+
unwrapped[k] = v
|
| 63 |
+
|
| 64 |
+
return unwrapped
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def value(self) -> dict[str, Any]:
|
| 68 |
+
"""The wrapped dict value"""
|
| 69 |
+
d = {}
|
| 70 |
+
for k, v in self._body:
|
| 71 |
+
if k is None:
|
| 72 |
+
continue
|
| 73 |
+
|
| 74 |
+
k = k.key
|
| 75 |
+
v = v.value
|
| 76 |
+
|
| 77 |
+
if isinstance(v, Container):
|
| 78 |
+
v = v.value
|
| 79 |
+
|
| 80 |
+
if k in d:
|
| 81 |
+
merge_dicts(d[k], v)
|
| 82 |
+
else:
|
| 83 |
+
d[k] = v
|
| 84 |
+
|
| 85 |
+
return d
|
| 86 |
+
|
| 87 |
+
def parsing(self, parsing: bool) -> None:
|
| 88 |
+
self._parsed = parsing
|
| 89 |
+
|
| 90 |
+
for _, v in self._body:
|
| 91 |
+
if isinstance(v, Table):
|
| 92 |
+
v.value.parsing(parsing)
|
| 93 |
+
elif isinstance(v, AoT):
|
| 94 |
+
for t in v.body:
|
| 95 |
+
t.value.parsing(parsing)
|
| 96 |
+
|
| 97 |
+
def add(self, key: Key | Item | str, item: Item | None = None) -> Container:
|
| 98 |
+
"""
|
| 99 |
+
Adds an item to the current Container.
|
| 100 |
+
|
| 101 |
+
:Example:
|
| 102 |
+
|
| 103 |
+
>>> # add a key-value pair
|
| 104 |
+
>>> doc.add('key', 'value')
|
| 105 |
+
>>> # add a comment or whitespace or newline
|
| 106 |
+
>>> doc.add(comment('# comment'))
|
| 107 |
+
"""
|
| 108 |
+
if item is None:
|
| 109 |
+
if not isinstance(key, (Comment, Whitespace)):
|
| 110 |
+
raise ValueError(
|
| 111 |
+
"Non comment/whitespace items must have an associated key"
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
key, item = None, key
|
| 115 |
+
|
| 116 |
+
return self.append(key, item)
|
| 117 |
+
|
| 118 |
+
def _handle_dotted_key(self, key: Key, value: Item) -> None:
|
| 119 |
+
if isinstance(value, (Table, AoT)):
|
| 120 |
+
raise TOMLKitError("Can't add a table to a dotted key")
|
| 121 |
+
name, *mid, last = key
|
| 122 |
+
name._dotted = True
|
| 123 |
+
table = current = Table(Container(True), Trivia(), False, is_super_table=True)
|
| 124 |
+
for _name in mid:
|
| 125 |
+
_name._dotted = True
|
| 126 |
+
new_table = Table(Container(True), Trivia(), False, is_super_table=True)
|
| 127 |
+
current.append(_name, new_table)
|
| 128 |
+
current = new_table
|
| 129 |
+
|
| 130 |
+
last.sep = key.sep
|
| 131 |
+
current.append(last, value)
|
| 132 |
+
|
| 133 |
+
self.append(name, table)
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
def _get_last_index_before_table(self) -> int:
|
| 137 |
+
last_index = -1
|
| 138 |
+
for i, (k, v) in enumerate(self._body):
|
| 139 |
+
if isinstance(v, Null):
|
| 140 |
+
continue # Null elements are inserted after deletion
|
| 141 |
+
|
| 142 |
+
if isinstance(v, Whitespace) and not v.is_fixed():
|
| 143 |
+
continue
|
| 144 |
+
|
| 145 |
+
if isinstance(v, (Table, AoT)) and not k.is_dotted():
|
| 146 |
+
break
|
| 147 |
+
last_index = i
|
| 148 |
+
return last_index + 1
|
| 149 |
+
|
| 150 |
+
def _validate_out_of_order_table(self, key: SingleKey | None = None) -> None:
|
| 151 |
+
if key is None:
|
| 152 |
+
for k in self._map:
|
| 153 |
+
assert k is not None
|
| 154 |
+
self._validate_out_of_order_table(k)
|
| 155 |
+
return
|
| 156 |
+
if key not in self._map or not isinstance(self._map[key], tuple):
|
| 157 |
+
return
|
| 158 |
+
OutOfOrderTableProxy.validate(self, self._map[key])
|
| 159 |
+
|
| 160 |
+
def append(
|
| 161 |
+
self, key: Key | str | None, item: Item, validate: bool = True
|
| 162 |
+
) -> Container:
|
| 163 |
+
"""Similar to :meth:`add` but both key and value must be given."""
|
| 164 |
+
if not isinstance(key, Key) and key is not None:
|
| 165 |
+
key = SingleKey(key)
|
| 166 |
+
|
| 167 |
+
if not isinstance(item, Item):
|
| 168 |
+
item = _item(item)
|
| 169 |
+
|
| 170 |
+
if key is not None and key.is_multi():
|
| 171 |
+
self._handle_dotted_key(key, item)
|
| 172 |
+
return self
|
| 173 |
+
|
| 174 |
+
if isinstance(item, (AoT, Table)) and item.name is None:
|
| 175 |
+
item.name = key.key
|
| 176 |
+
|
| 177 |
+
prev = self._previous_item()
|
| 178 |
+
prev_ws = isinstance(prev, Whitespace) or ends_with_whitespace(prev)
|
| 179 |
+
if isinstance(item, Table):
|
| 180 |
+
if not self._parsed:
|
| 181 |
+
item.invalidate_display_name()
|
| 182 |
+
if (
|
| 183 |
+
self._body
|
| 184 |
+
and not (self._parsed or item.trivia.indent or prev_ws)
|
| 185 |
+
and not key.is_dotted()
|
| 186 |
+
):
|
| 187 |
+
item.trivia.indent = "\n"
|
| 188 |
+
|
| 189 |
+
if isinstance(item, AoT) and self._body and not self._parsed:
|
| 190 |
+
item.invalidate_display_name()
|
| 191 |
+
if item and not ("\n" in item[0].trivia.indent or prev_ws):
|
| 192 |
+
item[0].trivia.indent = "\n" + item[0].trivia.indent
|
| 193 |
+
|
| 194 |
+
if key is not None and key in self:
|
| 195 |
+
current_idx = self._map[key]
|
| 196 |
+
if isinstance(current_idx, tuple):
|
| 197 |
+
current_body_element = self._body[current_idx[-1]]
|
| 198 |
+
else:
|
| 199 |
+
current_body_element = self._body[current_idx]
|
| 200 |
+
|
| 201 |
+
current = current_body_element[1]
|
| 202 |
+
|
| 203 |
+
if isinstance(item, Table):
|
| 204 |
+
if not isinstance(current, (Table, AoT)):
|
| 205 |
+
raise KeyAlreadyPresent(key)
|
| 206 |
+
|
| 207 |
+
if item.is_aot_element():
|
| 208 |
+
# New AoT element found later on
|
| 209 |
+
# Adding it to the current AoT
|
| 210 |
+
if not isinstance(current, AoT):
|
| 211 |
+
current = AoT([current, item], parsed=self._parsed)
|
| 212 |
+
|
| 213 |
+
self._replace(key, key, current)
|
| 214 |
+
else:
|
| 215 |
+
current.append(item)
|
| 216 |
+
|
| 217 |
+
return self
|
| 218 |
+
elif current.is_aot():
|
| 219 |
+
if not item.is_aot_element():
|
| 220 |
+
# Tried to define a table after an AoT with the same name.
|
| 221 |
+
raise KeyAlreadyPresent(key)
|
| 222 |
+
|
| 223 |
+
current.append(item)
|
| 224 |
+
|
| 225 |
+
return self
|
| 226 |
+
elif current.is_super_table():
|
| 227 |
+
if item.is_super_table():
|
| 228 |
+
# We need to merge both super tables
|
| 229 |
+
if (
|
| 230 |
+
key.is_dotted()
|
| 231 |
+
or current_body_element[0].is_dotted()
|
| 232 |
+
or self._table_keys[-1] != current_body_element[0]
|
| 233 |
+
):
|
| 234 |
+
if key.is_dotted() and not self._parsed:
|
| 235 |
+
idx = self._get_last_index_before_table()
|
| 236 |
+
else:
|
| 237 |
+
idx = len(self._body)
|
| 238 |
+
|
| 239 |
+
if idx < len(self._body):
|
| 240 |
+
self._insert_at(idx, key, item)
|
| 241 |
+
else:
|
| 242 |
+
self._raw_append(key, item)
|
| 243 |
+
|
| 244 |
+
if validate:
|
| 245 |
+
self._validate_out_of_order_table(key)
|
| 246 |
+
|
| 247 |
+
return self
|
| 248 |
+
|
| 249 |
+
# Create a new element to replace the old one
|
| 250 |
+
current = copy.deepcopy(current)
|
| 251 |
+
for k, v in item.value.body:
|
| 252 |
+
current.append(k, v)
|
| 253 |
+
self._body[
|
| 254 |
+
(
|
| 255 |
+
current_idx[-1]
|
| 256 |
+
if isinstance(current_idx, tuple)
|
| 257 |
+
else current_idx
|
| 258 |
+
)
|
| 259 |
+
] = (current_body_element[0], current)
|
| 260 |
+
|
| 261 |
+
return self
|
| 262 |
+
elif current_body_element[0].is_dotted():
|
| 263 |
+
raise TOMLKitError("Redefinition of an existing table")
|
| 264 |
+
elif not item.is_super_table():
|
| 265 |
+
raise KeyAlreadyPresent(key)
|
| 266 |
+
elif isinstance(item, AoT):
|
| 267 |
+
if not isinstance(current, AoT):
|
| 268 |
+
# Tried to define an AoT after a table with the same name.
|
| 269 |
+
raise KeyAlreadyPresent(key)
|
| 270 |
+
|
| 271 |
+
for table in item.body:
|
| 272 |
+
current.append(table)
|
| 273 |
+
|
| 274 |
+
return self
|
| 275 |
+
else:
|
| 276 |
+
raise KeyAlreadyPresent(key)
|
| 277 |
+
|
| 278 |
+
is_table = isinstance(item, (Table, AoT))
|
| 279 |
+
if (
|
| 280 |
+
key is not None
|
| 281 |
+
and self._body
|
| 282 |
+
and not self._parsed
|
| 283 |
+
and (not is_table or key.is_dotted())
|
| 284 |
+
):
|
| 285 |
+
# If there is already at least one table in the current container
|
| 286 |
+
# and the given item is not a table, we need to find the last
|
| 287 |
+
# item that is not a table and insert after it
|
| 288 |
+
# If no such item exists, insert at the top of the table
|
| 289 |
+
last_index = self._get_last_index_before_table()
|
| 290 |
+
|
| 291 |
+
if last_index < len(self._body):
|
| 292 |
+
after_item = self._body[last_index][1]
|
| 293 |
+
if not (
|
| 294 |
+
isinstance(after_item, Whitespace)
|
| 295 |
+
or "\n" in after_item.trivia.indent
|
| 296 |
+
):
|
| 297 |
+
after_item.trivia.indent = "\n" + after_item.trivia.indent
|
| 298 |
+
return self._insert_at(last_index, key, item)
|
| 299 |
+
else:
|
| 300 |
+
previous_item = self._body[-1][1]
|
| 301 |
+
if not (
|
| 302 |
+
isinstance(previous_item, Whitespace)
|
| 303 |
+
or ends_with_whitespace(previous_item)
|
| 304 |
+
or "\n" in previous_item.trivia.trail
|
| 305 |
+
):
|
| 306 |
+
previous_item.trivia.trail += "\n"
|
| 307 |
+
|
| 308 |
+
self._raw_append(key, item)
|
| 309 |
+
return self
|
| 310 |
+
|
| 311 |
+
def _raw_append(self, key: Key | None, item: Item) -> None:
|
| 312 |
+
if key in self._map:
|
| 313 |
+
current_idx = self._map[key]
|
| 314 |
+
if not isinstance(current_idx, tuple):
|
| 315 |
+
current_idx = (current_idx,)
|
| 316 |
+
|
| 317 |
+
current = self._body[current_idx[-1]][1]
|
| 318 |
+
if key is not None and not isinstance(current, Table):
|
| 319 |
+
raise KeyAlreadyPresent(key)
|
| 320 |
+
|
| 321 |
+
self._map[key] = (*current_idx, len(self._body))
|
| 322 |
+
elif key is not None:
|
| 323 |
+
self._map[key] = len(self._body)
|
| 324 |
+
|
| 325 |
+
self._body.append((key, item))
|
| 326 |
+
if item.is_table():
|
| 327 |
+
self._table_keys.append(key)
|
| 328 |
+
|
| 329 |
+
if key is not None:
|
| 330 |
+
dict.__setitem__(self, key.key, item.value)
|
| 331 |
+
|
| 332 |
+
def _remove_at(self, idx: int) -> None:
|
| 333 |
+
key = self._body[idx][0]
|
| 334 |
+
index = self._map.get(key)
|
| 335 |
+
if index is None:
|
| 336 |
+
raise NonExistentKey(key)
|
| 337 |
+
self._body[idx] = (None, Null())
|
| 338 |
+
|
| 339 |
+
if isinstance(index, tuple):
|
| 340 |
+
index = list(index)
|
| 341 |
+
index.remove(idx)
|
| 342 |
+
if len(index) == 1:
|
| 343 |
+
index = index.pop()
|
| 344 |
+
else:
|
| 345 |
+
index = tuple(index)
|
| 346 |
+
self._map[key] = index
|
| 347 |
+
else:
|
| 348 |
+
dict.__delitem__(self, key.key)
|
| 349 |
+
self._map.pop(key)
|
| 350 |
+
|
| 351 |
+
def remove(self, key: Key | str) -> Container:
|
| 352 |
+
"""Remove a key from the container."""
|
| 353 |
+
if not isinstance(key, Key):
|
| 354 |
+
key = SingleKey(key)
|
| 355 |
+
|
| 356 |
+
idx = self._map.pop(key, None)
|
| 357 |
+
if idx is None:
|
| 358 |
+
raise NonExistentKey(key)
|
| 359 |
+
|
| 360 |
+
if isinstance(idx, tuple):
|
| 361 |
+
for i in idx:
|
| 362 |
+
self._body[i] = (None, Null())
|
| 363 |
+
else:
|
| 364 |
+
self._body[idx] = (None, Null())
|
| 365 |
+
|
| 366 |
+
dict.__delitem__(self, key.key)
|
| 367 |
+
|
| 368 |
+
return self
|
| 369 |
+
|
| 370 |
+
def _insert_after(
|
| 371 |
+
self, key: Key | str, other_key: Key | str, item: Any
|
| 372 |
+
) -> Container:
|
| 373 |
+
if key is None:
|
| 374 |
+
raise ValueError("Key cannot be null in insert_after()")
|
| 375 |
+
|
| 376 |
+
if key not in self:
|
| 377 |
+
raise NonExistentKey(key)
|
| 378 |
+
|
| 379 |
+
if not isinstance(key, Key):
|
| 380 |
+
key = SingleKey(key)
|
| 381 |
+
|
| 382 |
+
if not isinstance(other_key, Key):
|
| 383 |
+
other_key = SingleKey(other_key)
|
| 384 |
+
|
| 385 |
+
item = _item(item)
|
| 386 |
+
|
| 387 |
+
idx = self._map[key]
|
| 388 |
+
# Insert after the max index if there are many.
|
| 389 |
+
if isinstance(idx, tuple):
|
| 390 |
+
idx = max(idx)
|
| 391 |
+
current_item = self._body[idx][1]
|
| 392 |
+
if "\n" not in current_item.trivia.trail:
|
| 393 |
+
current_item.trivia.trail += "\n"
|
| 394 |
+
|
| 395 |
+
# Increment indices after the current index
|
| 396 |
+
for k, v in self._map.items():
|
| 397 |
+
if isinstance(v, tuple):
|
| 398 |
+
new_indices = []
|
| 399 |
+
for v_ in v:
|
| 400 |
+
if v_ > idx:
|
| 401 |
+
v_ = v_ + 1
|
| 402 |
+
|
| 403 |
+
new_indices.append(v_)
|
| 404 |
+
|
| 405 |
+
self._map[k] = tuple(new_indices)
|
| 406 |
+
elif v > idx:
|
| 407 |
+
self._map[k] = v + 1
|
| 408 |
+
|
| 409 |
+
self._map[other_key] = idx + 1
|
| 410 |
+
self._body.insert(idx + 1, (other_key, item))
|
| 411 |
+
|
| 412 |
+
if key is not None:
|
| 413 |
+
dict.__setitem__(self, other_key.key, item.value)
|
| 414 |
+
|
| 415 |
+
return self
|
| 416 |
+
|
| 417 |
+
def _insert_at(self, idx: int, key: Key | str, item: Any) -> Container:
|
| 418 |
+
if idx > len(self._body) - 1:
|
| 419 |
+
raise ValueError(f"Unable to insert at position {idx}")
|
| 420 |
+
|
| 421 |
+
if not isinstance(key, Key):
|
| 422 |
+
key = SingleKey(key)
|
| 423 |
+
|
| 424 |
+
item = _item(item)
|
| 425 |
+
|
| 426 |
+
if idx > 0:
|
| 427 |
+
previous_item = self._body[idx - 1][1]
|
| 428 |
+
if not (
|
| 429 |
+
isinstance(previous_item, Whitespace)
|
| 430 |
+
or ends_with_whitespace(previous_item)
|
| 431 |
+
or isinstance(item, (AoT, Table))
|
| 432 |
+
or "\n" in previous_item.trivia.trail
|
| 433 |
+
):
|
| 434 |
+
previous_item.trivia.trail += "\n"
|
| 435 |
+
|
| 436 |
+
# Increment indices after the current index
|
| 437 |
+
for k, v in self._map.items():
|
| 438 |
+
if isinstance(v, tuple):
|
| 439 |
+
new_indices = []
|
| 440 |
+
for v_ in v:
|
| 441 |
+
if v_ >= idx:
|
| 442 |
+
v_ = v_ + 1
|
| 443 |
+
|
| 444 |
+
new_indices.append(v_)
|
| 445 |
+
|
| 446 |
+
self._map[k] = tuple(new_indices)
|
| 447 |
+
elif v >= idx:
|
| 448 |
+
self._map[k] = v + 1
|
| 449 |
+
|
| 450 |
+
if key in self._map:
|
| 451 |
+
current_idx = self._map[key]
|
| 452 |
+
if not isinstance(current_idx, tuple):
|
| 453 |
+
current_idx = (current_idx,)
|
| 454 |
+
self._map[key] = (*current_idx, idx)
|
| 455 |
+
else:
|
| 456 |
+
self._map[key] = idx
|
| 457 |
+
self._body.insert(idx, (key, item))
|
| 458 |
+
|
| 459 |
+
dict.__setitem__(self, key.key, item.value)
|
| 460 |
+
|
| 461 |
+
return self
|
| 462 |
+
|
| 463 |
+
def item(self, key: Key | str) -> Item:
|
| 464 |
+
"""Get an item for the given key."""
|
| 465 |
+
if not isinstance(key, Key):
|
| 466 |
+
key = SingleKey(key)
|
| 467 |
+
|
| 468 |
+
idx = self._map.get(key)
|
| 469 |
+
if idx is None:
|
| 470 |
+
raise NonExistentKey(key)
|
| 471 |
+
|
| 472 |
+
if isinstance(idx, tuple):
|
| 473 |
+
# The item we are getting is an out of order table
|
| 474 |
+
# so we need a proxy to retrieve the proper objects
|
| 475 |
+
# from the parent container
|
| 476 |
+
return OutOfOrderTableProxy(self, idx)
|
| 477 |
+
|
| 478 |
+
return self._body[idx][1]
|
| 479 |
+
|
| 480 |
+
def last_item(self) -> Item | None:
|
| 481 |
+
"""Get the last item."""
|
| 482 |
+
if self._body:
|
| 483 |
+
return self._body[-1][1]
|
| 484 |
+
|
| 485 |
+
def as_string(self) -> str:
|
| 486 |
+
"""Render as TOML string."""
|
| 487 |
+
s = ""
|
| 488 |
+
for k, v in self._body:
|
| 489 |
+
if k is not None:
|
| 490 |
+
if isinstance(v, Table):
|
| 491 |
+
if (
|
| 492 |
+
s.strip(" ")
|
| 493 |
+
and not s.strip(" ").endswith("\n")
|
| 494 |
+
and "\n" not in v.trivia.indent
|
| 495 |
+
):
|
| 496 |
+
s += "\n"
|
| 497 |
+
s += self._render_table(k, v)
|
| 498 |
+
elif isinstance(v, AoT):
|
| 499 |
+
if (
|
| 500 |
+
s.strip(" ")
|
| 501 |
+
and not s.strip(" ").endswith("\n")
|
| 502 |
+
and "\n" not in v.trivia.indent
|
| 503 |
+
):
|
| 504 |
+
s += "\n"
|
| 505 |
+
s += self._render_aot(k, v)
|
| 506 |
+
else:
|
| 507 |
+
s += self._render_simple_item(k, v)
|
| 508 |
+
else:
|
| 509 |
+
s += self._render_simple_item(k, v)
|
| 510 |
+
|
| 511 |
+
return s
|
| 512 |
+
|
| 513 |
+
def _render_table(self, key: Key, table: Table, prefix: str | None = None) -> str:
|
| 514 |
+
cur = ""
|
| 515 |
+
|
| 516 |
+
if table.display_name is not None:
|
| 517 |
+
_key = table.display_name
|
| 518 |
+
else:
|
| 519 |
+
_key = key.as_string()
|
| 520 |
+
|
| 521 |
+
if prefix is not None:
|
| 522 |
+
_key = prefix + "." + _key
|
| 523 |
+
|
| 524 |
+
if not table.is_super_table() or (
|
| 525 |
+
any(
|
| 526 |
+
not isinstance(v, (Table, AoT, Whitespace, Null))
|
| 527 |
+
for _, v in table.value.body
|
| 528 |
+
)
|
| 529 |
+
and not key.is_dotted()
|
| 530 |
+
):
|
| 531 |
+
open_, close = "[", "]"
|
| 532 |
+
if table.is_aot_element():
|
| 533 |
+
open_, close = "[[", "]]"
|
| 534 |
+
|
| 535 |
+
newline_in_table_trivia = (
|
| 536 |
+
"\n" if "\n" not in table.trivia.trail and len(table.value) > 0 else ""
|
| 537 |
+
)
|
| 538 |
+
cur += (
|
| 539 |
+
f"{table.trivia.indent}"
|
| 540 |
+
f"{open_}"
|
| 541 |
+
f"{decode(_key)}"
|
| 542 |
+
f"{close}"
|
| 543 |
+
f"{table.trivia.comment_ws}"
|
| 544 |
+
f"{decode(table.trivia.comment)}"
|
| 545 |
+
f"{table.trivia.trail}"
|
| 546 |
+
f"{newline_in_table_trivia}"
|
| 547 |
+
)
|
| 548 |
+
elif table.trivia.indent == "\n":
|
| 549 |
+
cur += table.trivia.indent
|
| 550 |
+
|
| 551 |
+
for k, v in table.value.body:
|
| 552 |
+
if isinstance(v, Table):
|
| 553 |
+
if (
|
| 554 |
+
cur.strip(" ")
|
| 555 |
+
and not cur.strip(" ").endswith("\n")
|
| 556 |
+
and "\n" not in v.trivia.indent
|
| 557 |
+
):
|
| 558 |
+
cur += "\n"
|
| 559 |
+
if v.is_super_table():
|
| 560 |
+
if k.is_dotted() and not key.is_dotted():
|
| 561 |
+
# Dotted key inside table
|
| 562 |
+
cur += self._render_table(k, v)
|
| 563 |
+
else:
|
| 564 |
+
cur += self._render_table(k, v, prefix=_key)
|
| 565 |
+
else:
|
| 566 |
+
cur += self._render_table(k, v, prefix=_key)
|
| 567 |
+
elif isinstance(v, AoT):
|
| 568 |
+
if (
|
| 569 |
+
cur.strip(" ")
|
| 570 |
+
and not cur.strip(" ").endswith("\n")
|
| 571 |
+
and "\n" not in v.trivia.indent
|
| 572 |
+
):
|
| 573 |
+
cur += "\n"
|
| 574 |
+
cur += self._render_aot(k, v, prefix=_key)
|
| 575 |
+
else:
|
| 576 |
+
cur += self._render_simple_item(
|
| 577 |
+
k, v, prefix=_key if key.is_dotted() else None
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
return cur
|
| 581 |
+
|
| 582 |
+
def _render_aot(self, key, aot, prefix=None):
|
| 583 |
+
_key = key.as_string()
|
| 584 |
+
if prefix is not None:
|
| 585 |
+
_key = prefix + "." + _key
|
| 586 |
+
|
| 587 |
+
cur = ""
|
| 588 |
+
_key = decode(_key)
|
| 589 |
+
for table in aot.body:
|
| 590 |
+
cur += self._render_aot_table(table, prefix=_key)
|
| 591 |
+
|
| 592 |
+
return cur
|
| 593 |
+
|
| 594 |
+
def _render_aot_table(self, table: Table, prefix: str | None = None) -> str:
|
| 595 |
+
cur = ""
|
| 596 |
+
_key = prefix or ""
|
| 597 |
+
open_, close = "[[", "]]"
|
| 598 |
+
|
| 599 |
+
cur += (
|
| 600 |
+
f"{table.trivia.indent}"
|
| 601 |
+
f"{open_}"
|
| 602 |
+
f"{decode(_key)}"
|
| 603 |
+
f"{close}"
|
| 604 |
+
f"{table.trivia.comment_ws}"
|
| 605 |
+
f"{decode(table.trivia.comment)}"
|
| 606 |
+
f"{table.trivia.trail}"
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
for k, v in table.value.body:
|
| 610 |
+
if isinstance(v, Table):
|
| 611 |
+
if v.is_super_table():
|
| 612 |
+
if k.is_dotted():
|
| 613 |
+
# Dotted key inside table
|
| 614 |
+
cur += self._render_table(k, v)
|
| 615 |
+
else:
|
| 616 |
+
cur += self._render_table(k, v, prefix=_key)
|
| 617 |
+
else:
|
| 618 |
+
cur += self._render_table(k, v, prefix=_key)
|
| 619 |
+
elif isinstance(v, AoT):
|
| 620 |
+
cur += self._render_aot(k, v, prefix=_key)
|
| 621 |
+
else:
|
| 622 |
+
cur += self._render_simple_item(k, v)
|
| 623 |
+
|
| 624 |
+
return cur
|
| 625 |
+
|
| 626 |
+
def _render_simple_item(self, key, item, prefix=None):
|
| 627 |
+
if key is None:
|
| 628 |
+
return item.as_string()
|
| 629 |
+
|
| 630 |
+
_key = key.as_string()
|
| 631 |
+
if prefix is not None:
|
| 632 |
+
_key = prefix + "." + _key
|
| 633 |
+
|
| 634 |
+
return (
|
| 635 |
+
f"{item.trivia.indent}"
|
| 636 |
+
f"{decode(_key)}"
|
| 637 |
+
f"{key.sep}"
|
| 638 |
+
f"{decode(item.as_string())}"
|
| 639 |
+
f"{item.trivia.comment_ws}"
|
| 640 |
+
f"{decode(item.trivia.comment)}"
|
| 641 |
+
f"{item.trivia.trail}"
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
def __len__(self) -> int:
|
| 645 |
+
return dict.__len__(self)
|
| 646 |
+
|
| 647 |
+
def __iter__(self) -> Iterator[str]:
|
| 648 |
+
return iter(dict.keys(self))
|
| 649 |
+
|
| 650 |
+
# Dictionary methods
|
| 651 |
+
def __getitem__(self, key: Key | str) -> Item | Container:
|
| 652 |
+
item = self.item(key)
|
| 653 |
+
if isinstance(item, Item) and item.is_boolean():
|
| 654 |
+
return item.value
|
| 655 |
+
|
| 656 |
+
return item
|
| 657 |
+
|
| 658 |
+
def __setitem__(self, key: Key | str, value: Any) -> None:
|
| 659 |
+
if key is not None and key in self:
|
| 660 |
+
old_key = next(filter(lambda k: k == key, self._map))
|
| 661 |
+
self._replace(old_key, key, value)
|
| 662 |
+
else:
|
| 663 |
+
self.append(key, value)
|
| 664 |
+
|
| 665 |
+
def __delitem__(self, key: Key | str) -> None:
|
| 666 |
+
self.remove(key)
|
| 667 |
+
|
| 668 |
+
def setdefault(self, key: Key | str, default: Any) -> Any:
|
| 669 |
+
super().setdefault(key, default=default)
|
| 670 |
+
return self[key]
|
| 671 |
+
|
| 672 |
+
def _replace(self, key: Key | str, new_key: Key | str, value: Item) -> None:
|
| 673 |
+
if not isinstance(key, Key):
|
| 674 |
+
key = SingleKey(key)
|
| 675 |
+
|
| 676 |
+
idx = self._map.get(key)
|
| 677 |
+
if idx is None:
|
| 678 |
+
raise NonExistentKey(key)
|
| 679 |
+
|
| 680 |
+
self._replace_at(idx, new_key, value)
|
| 681 |
+
|
| 682 |
+
def _replace_at(
|
| 683 |
+
self, idx: int | tuple[int], new_key: Key | str, value: Item
|
| 684 |
+
) -> None:
|
| 685 |
+
value = _item(value)
|
| 686 |
+
|
| 687 |
+
if isinstance(idx, tuple):
|
| 688 |
+
for i in idx[1:]:
|
| 689 |
+
self._body[i] = (None, Null())
|
| 690 |
+
|
| 691 |
+
idx = idx[0]
|
| 692 |
+
|
| 693 |
+
k, v = self._body[idx]
|
| 694 |
+
if not isinstance(new_key, Key):
|
| 695 |
+
if (
|
| 696 |
+
isinstance(value, (AoT, Table)) != isinstance(v, (AoT, Table))
|
| 697 |
+
or new_key != k.key
|
| 698 |
+
):
|
| 699 |
+
new_key = SingleKey(new_key)
|
| 700 |
+
else: # Inherit the sep of the old key
|
| 701 |
+
new_key = k
|
| 702 |
+
|
| 703 |
+
del self._map[k]
|
| 704 |
+
self._map[new_key] = idx
|
| 705 |
+
if new_key != k:
|
| 706 |
+
dict.__delitem__(self, k)
|
| 707 |
+
|
| 708 |
+
if isinstance(value, (AoT, Table)) != isinstance(v, (AoT, Table)):
|
| 709 |
+
# new tables should appear after all non-table values
|
| 710 |
+
self.remove(k)
|
| 711 |
+
for i in range(idx, len(self._body)):
|
| 712 |
+
if isinstance(self._body[i][1], (AoT, Table)):
|
| 713 |
+
self._insert_at(i, new_key, value)
|
| 714 |
+
idx = i
|
| 715 |
+
break
|
| 716 |
+
else:
|
| 717 |
+
idx = -1
|
| 718 |
+
self.append(new_key, value)
|
| 719 |
+
else:
|
| 720 |
+
# Copying trivia
|
| 721 |
+
if not isinstance(value, (Whitespace, AoT)):
|
| 722 |
+
value.trivia.indent = v.trivia.indent
|
| 723 |
+
value.trivia.comment_ws = value.trivia.comment_ws or v.trivia.comment_ws
|
| 724 |
+
value.trivia.comment = value.trivia.comment or v.trivia.comment
|
| 725 |
+
value.trivia.trail = v.trivia.trail
|
| 726 |
+
self._body[idx] = (new_key, value)
|
| 727 |
+
|
| 728 |
+
if hasattr(value, "invalidate_display_name"):
|
| 729 |
+
value.invalidate_display_name() # type: ignore[attr-defined]
|
| 730 |
+
|
| 731 |
+
if isinstance(value, Table):
|
| 732 |
+
# Insert a cosmetic new line for tables if:
|
| 733 |
+
# - it does not have it yet OR is not followed by one
|
| 734 |
+
# - it is not the last item, or
|
| 735 |
+
# - The table being replaced has a newline
|
| 736 |
+
last, _ = self._previous_item_with_index()
|
| 737 |
+
idx = last if idx < 0 else idx
|
| 738 |
+
has_ws = ends_with_whitespace(value)
|
| 739 |
+
replace_has_ws = (
|
| 740 |
+
isinstance(v, Table)
|
| 741 |
+
and v.value.body
|
| 742 |
+
and isinstance(v.value.body[-1][1], Whitespace)
|
| 743 |
+
)
|
| 744 |
+
next_ws = idx < last and isinstance(self._body[idx + 1][1], Whitespace)
|
| 745 |
+
if (idx < last or replace_has_ws) and not (next_ws or has_ws):
|
| 746 |
+
value.append(None, Whitespace("\n"))
|
| 747 |
+
|
| 748 |
+
dict.__setitem__(self, new_key.key, value.value)
|
| 749 |
+
|
| 750 |
+
def __str__(self) -> str:
|
| 751 |
+
return str(self.value)
|
| 752 |
+
|
| 753 |
+
def __repr__(self) -> str:
|
| 754 |
+
return repr(self.value)
|
| 755 |
+
|
| 756 |
+
def __eq__(self, other: dict) -> bool:
|
| 757 |
+
if not isinstance(other, dict):
|
| 758 |
+
return NotImplemented
|
| 759 |
+
|
| 760 |
+
return self.value == other
|
| 761 |
+
|
| 762 |
+
def _getstate(self, protocol):
|
| 763 |
+
return (self._parsed,)
|
| 764 |
+
|
| 765 |
+
def __reduce__(self):
|
| 766 |
+
return self.__reduce_ex__(2)
|
| 767 |
+
|
| 768 |
+
def __reduce_ex__(self, protocol):
|
| 769 |
+
return (
|
| 770 |
+
self.__class__,
|
| 771 |
+
self._getstate(protocol),
|
| 772 |
+
(self._map, self._body, self._parsed, self._table_keys),
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
def __setstate__(self, state):
|
| 776 |
+
self._map = state[0]
|
| 777 |
+
self._body = state[1]
|
| 778 |
+
self._parsed = state[2]
|
| 779 |
+
self._table_keys = state[3]
|
| 780 |
+
|
| 781 |
+
for key, item in self._body:
|
| 782 |
+
if key is not None:
|
| 783 |
+
dict.__setitem__(self, key.key, item.value)
|
| 784 |
+
|
| 785 |
+
def copy(self) -> Container:
|
| 786 |
+
return copy.copy(self)
|
| 787 |
+
|
| 788 |
+
def __copy__(self) -> Container:
|
| 789 |
+
c = self.__class__(self._parsed)
|
| 790 |
+
for k, v in dict.items(self):
|
| 791 |
+
dict.__setitem__(c, k, v)
|
| 792 |
+
|
| 793 |
+
c._body += self.body
|
| 794 |
+
c._map.update(self._map)
|
| 795 |
+
|
| 796 |
+
return c
|
| 797 |
+
|
| 798 |
+
def _previous_item_with_index(
|
| 799 |
+
self, idx: int | None = None, ignore=(Null,)
|
| 800 |
+
) -> tuple[int, Item] | None:
|
| 801 |
+
"""Find the immediate previous item before index ``idx``"""
|
| 802 |
+
if idx is None or idx > len(self._body):
|
| 803 |
+
idx = len(self._body)
|
| 804 |
+
for i in range(idx - 1, -1, -1):
|
| 805 |
+
v = self._body[i][-1]
|
| 806 |
+
if not isinstance(v, ignore):
|
| 807 |
+
return i, v
|
| 808 |
+
return None
|
| 809 |
+
|
| 810 |
+
def _previous_item(self, idx: int | None = None, ignore=(Null,)) -> Item | None:
|
| 811 |
+
"""Find the immediate previous item before index ``idx``.
|
| 812 |
+
If ``idx`` is not given, the last item is returned.
|
| 813 |
+
"""
|
| 814 |
+
prev = self._previous_item_with_index(idx, ignore)
|
| 815 |
+
return prev[-1] if prev else None
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
class OutOfOrderTableProxy(_CustomDict):
|
| 819 |
+
@staticmethod
|
| 820 |
+
def validate(container: Container, indices: tuple[int, ...]) -> None:
|
| 821 |
+
"""Validate out of order tables in the given container"""
|
| 822 |
+
# Append all items to a temp container to see if there is any error
|
| 823 |
+
temp_container = Container(True)
|
| 824 |
+
for i in indices:
|
| 825 |
+
_, item = container._body[i]
|
| 826 |
+
|
| 827 |
+
if isinstance(item, Table):
|
| 828 |
+
for k, v in item.value.body:
|
| 829 |
+
temp_container.append(k, v, validate=False)
|
| 830 |
+
|
| 831 |
+
temp_container._validate_out_of_order_table()
|
| 832 |
+
|
| 833 |
+
def __init__(self, container: Container, indices: tuple[int, ...]) -> None:
|
| 834 |
+
self._container = container
|
| 835 |
+
self._internal_container = Container(True)
|
| 836 |
+
self._tables: list[Table] = []
|
| 837 |
+
self._tables_map: dict[Key, list[int]] = {}
|
| 838 |
+
|
| 839 |
+
for i in indices:
|
| 840 |
+
_, item = self._container._body[i]
|
| 841 |
+
|
| 842 |
+
if isinstance(item, Table):
|
| 843 |
+
self._tables.append(item)
|
| 844 |
+
table_idx = len(self._tables) - 1
|
| 845 |
+
for k, v in item.value.body:
|
| 846 |
+
self._internal_container._raw_append(k, v)
|
| 847 |
+
indices = self._tables_map.setdefault(k, [])
|
| 848 |
+
if table_idx not in indices:
|
| 849 |
+
indices.append(table_idx)
|
| 850 |
+
if k is not None:
|
| 851 |
+
dict.__setitem__(self, k.key, v)
|
| 852 |
+
|
| 853 |
+
self._internal_container._validate_out_of_order_table()
|
| 854 |
+
|
| 855 |
+
def unwrap(self) -> str:
|
| 856 |
+
return self._internal_container.unwrap()
|
| 857 |
+
|
| 858 |
+
@property
|
| 859 |
+
def value(self):
|
| 860 |
+
return self._internal_container.value
|
| 861 |
+
|
| 862 |
+
def __getitem__(self, key: Key | str) -> Any:
|
| 863 |
+
if key not in self._internal_container:
|
| 864 |
+
raise NonExistentKey(key)
|
| 865 |
+
|
| 866 |
+
return self._internal_container[key]
|
| 867 |
+
|
| 868 |
+
def __setitem__(self, key: Key | str, value: Any) -> None:
|
| 869 |
+
from .items import item
|
| 870 |
+
|
| 871 |
+
def _is_table_or_aot(it: Any) -> bool:
|
| 872 |
+
return isinstance(item(it), (Table, AoT))
|
| 873 |
+
|
| 874 |
+
if key in self._tables_map:
|
| 875 |
+
# Overwrite the first table and remove others
|
| 876 |
+
indices = self._tables_map[key]
|
| 877 |
+
while len(indices) > 1:
|
| 878 |
+
table = self._tables[indices.pop()]
|
| 879 |
+
self._remove_table(table)
|
| 880 |
+
old_value = self._tables[indices[0]][key]
|
| 881 |
+
if _is_table_or_aot(old_value) and not _is_table_or_aot(value):
|
| 882 |
+
# Remove the entry from the map and set value again.
|
| 883 |
+
del self._tables[indices[0]][key]
|
| 884 |
+
del self._tables_map[key]
|
| 885 |
+
self[key] = value
|
| 886 |
+
return
|
| 887 |
+
self._tables[indices[0]][key] = value
|
| 888 |
+
elif self._tables:
|
| 889 |
+
if not _is_table_or_aot(value): # if the value is a plain value
|
| 890 |
+
for table in self._tables:
|
| 891 |
+
# find the first table that allows plain values
|
| 892 |
+
if any(not _is_table_or_aot(v) for _, v in table.items()):
|
| 893 |
+
table[key] = value
|
| 894 |
+
break
|
| 895 |
+
else:
|
| 896 |
+
self._tables[0][key] = value
|
| 897 |
+
else:
|
| 898 |
+
self._tables[0][key] = value
|
| 899 |
+
else:
|
| 900 |
+
self._container[key] = value
|
| 901 |
+
|
| 902 |
+
self._internal_container[key] = value
|
| 903 |
+
if key is not None:
|
| 904 |
+
dict.__setitem__(self, key, value)
|
| 905 |
+
|
| 906 |
+
def _remove_table(self, table: Table) -> None:
|
| 907 |
+
"""Remove table from the parent container"""
|
| 908 |
+
self._tables.remove(table)
|
| 909 |
+
for idx, item in enumerate(self._container._body):
|
| 910 |
+
if item[1] is table:
|
| 911 |
+
self._container._remove_at(idx)
|
| 912 |
+
break
|
| 913 |
+
|
| 914 |
+
def __delitem__(self, key: Key | str) -> None:
|
| 915 |
+
if key not in self._tables_map:
|
| 916 |
+
raise NonExistentKey(key)
|
| 917 |
+
|
| 918 |
+
for i in reversed(self._tables_map[key]):
|
| 919 |
+
table = self._tables[i]
|
| 920 |
+
del table[key]
|
| 921 |
+
if not table and len(self._tables) > 1:
|
| 922 |
+
self._remove_table(table)
|
| 923 |
+
|
| 924 |
+
del self._tables_map[key]
|
| 925 |
+
del self._internal_container[key]
|
| 926 |
+
if key is not None:
|
| 927 |
+
dict.__delitem__(self, key)
|
| 928 |
+
|
| 929 |
+
def __iter__(self) -> Iterator[str]:
|
| 930 |
+
return iter(dict.keys(self))
|
| 931 |
+
|
| 932 |
+
def __len__(self) -> int:
|
| 933 |
+
return dict.__len__(self)
|
| 934 |
+
|
| 935 |
+
def setdefault(self, key: Key | str, default: Any) -> Any:
|
| 936 |
+
super().setdefault(key, default=default)
|
| 937 |
+
return self[key]
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
def ends_with_whitespace(it: Any) -> bool:
|
| 941 |
+
"""Returns ``True`` if the given item ``it`` is a ``Table`` or ``AoT`` object
|
| 942 |
+
ending with a ``Whitespace``.
|
| 943 |
+
"""
|
| 944 |
+
return (
|
| 945 |
+
isinstance(it, Table) and isinstance(it.value._previous_item(), Whitespace)
|
| 946 |
+
) or (isinstance(it, AoT) and len(it) > 0 and isinstance(it[-1], Whitespace))
|
miniconda3/lib/python3.13/site-packages/tomlkit/exceptions.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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TOMLKitError(Exception):
|
| 7 |
+
pass
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ParseError(ValueError, TOMLKitError):
|
| 11 |
+
"""
|
| 12 |
+
This error occurs when the parser encounters a syntax error
|
| 13 |
+
in the TOML being parsed. The error references the line and
|
| 14 |
+
location within the line where the error was encountered.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, line: int, col: int, message: str | None = None) -> None:
|
| 18 |
+
self._line = line
|
| 19 |
+
self._col = col
|
| 20 |
+
|
| 21 |
+
if message is None:
|
| 22 |
+
message = "TOML parse error"
|
| 23 |
+
|
| 24 |
+
super().__init__(f"{message} at line {self._line} col {self._col}")
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def line(self):
|
| 28 |
+
return self._line
|
| 29 |
+
|
| 30 |
+
@property
|
| 31 |
+
def col(self):
|
| 32 |
+
return self._col
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class MixedArrayTypesError(ParseError):
|
| 36 |
+
"""
|
| 37 |
+
An array was found that had two or more element types.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, line: int, col: int) -> None:
|
| 41 |
+
message = "Mixed types found in array"
|
| 42 |
+
|
| 43 |
+
super().__init__(line, col, message=message)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class InvalidNumberError(ParseError):
|
| 47 |
+
"""
|
| 48 |
+
A numeric field was improperly specified.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(self, line: int, col: int) -> None:
|
| 52 |
+
message = "Invalid number"
|
| 53 |
+
|
| 54 |
+
super().__init__(line, col, message=message)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class InvalidDateTimeError(ParseError):
|
| 58 |
+
"""
|
| 59 |
+
A datetime field was improperly specified.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(self, line: int, col: int) -> None:
|
| 63 |
+
message = "Invalid datetime"
|
| 64 |
+
|
| 65 |
+
super().__init__(line, col, message=message)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class InvalidDateError(ParseError):
|
| 69 |
+
"""
|
| 70 |
+
A date field was improperly specified.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(self, line: int, col: int) -> None:
|
| 74 |
+
message = "Invalid date"
|
| 75 |
+
|
| 76 |
+
super().__init__(line, col, message=message)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class InvalidTimeError(ParseError):
|
| 80 |
+
"""
|
| 81 |
+
A date field was improperly specified.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(self, line: int, col: int) -> None:
|
| 85 |
+
message = "Invalid time"
|
| 86 |
+
|
| 87 |
+
super().__init__(line, col, message=message)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class InvalidNumberOrDateError(ParseError):
|
| 91 |
+
"""
|
| 92 |
+
A numeric or date field was improperly specified.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(self, line: int, col: int) -> None:
|
| 96 |
+
message = "Invalid number or date format"
|
| 97 |
+
|
| 98 |
+
super().__init__(line, col, message=message)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class InvalidUnicodeValueError(ParseError):
|
| 102 |
+
"""
|
| 103 |
+
A unicode code was improperly specified.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(self, line: int, col: int) -> None:
|
| 107 |
+
message = "Invalid unicode value"
|
| 108 |
+
|
| 109 |
+
super().__init__(line, col, message=message)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class UnexpectedCharError(ParseError):
|
| 113 |
+
"""
|
| 114 |
+
An unexpected character was found during parsing.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
def __init__(self, line: int, col: int, char: str) -> None:
|
| 118 |
+
message = f"Unexpected character: {char!r}"
|
| 119 |
+
|
| 120 |
+
super().__init__(line, col, message=message)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class EmptyKeyError(ParseError):
|
| 124 |
+
"""
|
| 125 |
+
An empty key was found during parsing.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(self, line: int, col: int) -> None:
|
| 129 |
+
message = "Empty key"
|
| 130 |
+
|
| 131 |
+
super().__init__(line, col, message=message)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class EmptyTableNameError(ParseError):
|
| 135 |
+
"""
|
| 136 |
+
An empty table name was found during parsing.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def __init__(self, line: int, col: int) -> None:
|
| 140 |
+
message = "Empty table name"
|
| 141 |
+
|
| 142 |
+
super().__init__(line, col, message=message)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class InvalidCharInStringError(ParseError):
|
| 146 |
+
"""
|
| 147 |
+
The string being parsed contains an invalid character.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
def __init__(self, line: int, col: int, char: str) -> None:
|
| 151 |
+
message = f"Invalid character {char!r} in string"
|
| 152 |
+
|
| 153 |
+
super().__init__(line, col, message=message)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class UnexpectedEofError(ParseError):
|
| 157 |
+
"""
|
| 158 |
+
The TOML being parsed ended before the end of a statement.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
def __init__(self, line: int, col: int) -> None:
|
| 162 |
+
message = "Unexpected end of file"
|
| 163 |
+
|
| 164 |
+
super().__init__(line, col, message=message)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class InternalParserError(ParseError):
|
| 168 |
+
"""
|
| 169 |
+
An error that indicates a bug in the parser.
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
def __init__(self, line: int, col: int, message: str | None = None) -> None:
|
| 173 |
+
msg = "Internal parser error"
|
| 174 |
+
if message:
|
| 175 |
+
msg += f" ({message})"
|
| 176 |
+
|
| 177 |
+
super().__init__(line, col, message=msg)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class NonExistentKey(KeyError, TOMLKitError):
|
| 181 |
+
"""
|
| 182 |
+
A non-existent key was used.
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
def __init__(self, key):
|
| 186 |
+
message = f'Key "{key}" does not exist.'
|
| 187 |
+
|
| 188 |
+
super().__init__(message)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class KeyAlreadyPresent(TOMLKitError):
|
| 192 |
+
"""
|
| 193 |
+
An already present key was used.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
def __init__(self, key):
|
| 197 |
+
key = getattr(key, "key", key)
|
| 198 |
+
message = f'Key "{key}" already exists.'
|
| 199 |
+
|
| 200 |
+
super().__init__(message)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class InvalidControlChar(ParseError):
|
| 204 |
+
def __init__(self, line: int, col: int, char: int, type: str) -> None:
|
| 205 |
+
display_code = "\\u00"
|
| 206 |
+
|
| 207 |
+
if char < 16:
|
| 208 |
+
display_code += "0"
|
| 209 |
+
|
| 210 |
+
display_code += hex(char)[2:]
|
| 211 |
+
|
| 212 |
+
message = (
|
| 213 |
+
"Control characters (codes less than 0x1f and 0x7f)"
|
| 214 |
+
f" are not allowed in {type}, "
|
| 215 |
+
f"use {display_code} instead"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
super().__init__(line, col, message=message)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class InvalidStringError(ValueError, TOMLKitError):
|
| 222 |
+
def __init__(self, value: str, invalid_sequences: Collection[str], delimiter: str):
|
| 223 |
+
repr_ = repr(value)[1:-1]
|
| 224 |
+
super().__init__(
|
| 225 |
+
f"Invalid string: {delimiter}{repr_}{delimiter}. "
|
| 226 |
+
f"The character sequences {invalid_sequences} are invalid."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class ConvertError(TypeError, ValueError, TOMLKitError):
|
| 231 |
+
"""Raised when item() fails to convert a value.
|
| 232 |
+
It should be a TypeError, but due to historical reasons
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import string
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
from datetime import date
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from datetime import time
|
| 14 |
+
from datetime import tzinfo
|
| 15 |
+
from enum import Enum
|
| 16 |
+
from typing import TYPE_CHECKING
|
| 17 |
+
from typing import Any
|
| 18 |
+
from typing import Callable
|
| 19 |
+
from typing import Collection
|
| 20 |
+
from typing import Iterable
|
| 21 |
+
from typing import Iterator
|
| 22 |
+
from typing import Sequence
|
| 23 |
+
from typing import TypeVar
|
| 24 |
+
from typing import cast
|
| 25 |
+
from typing import overload
|
| 26 |
+
|
| 27 |
+
from tomlkit._compat import PY38
|
| 28 |
+
from tomlkit._compat import decode
|
| 29 |
+
from tomlkit._types import _CustomDict
|
| 30 |
+
from tomlkit._types import _CustomFloat
|
| 31 |
+
from tomlkit._types import _CustomInt
|
| 32 |
+
from tomlkit._types import _CustomList
|
| 33 |
+
from tomlkit._types import wrap_method
|
| 34 |
+
from tomlkit._utils import CONTROL_CHARS
|
| 35 |
+
from tomlkit._utils import escape_string
|
| 36 |
+
from tomlkit.exceptions import ConvertError
|
| 37 |
+
from tomlkit.exceptions import InvalidStringError
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from tomlkit import container
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
ItemT = TypeVar("ItemT", bound="Item")
|
| 45 |
+
Encoder = Callable[[Any], "Item"]
|
| 46 |
+
CUSTOM_ENCODERS: list[Encoder] = []
|
| 47 |
+
AT = TypeVar("AT", bound="AbstractTable")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@overload
|
| 51 |
+
def item(value: bool, _parent: Item | None = ..., _sort_keys: bool = ...) -> Bool: ...
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@overload
|
| 55 |
+
def item(value: int, _parent: Item | None = ..., _sort_keys: bool = ...) -> Integer: ...
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@overload
|
| 59 |
+
def item(value: float, _parent: Item | None = ..., _sort_keys: bool = ...) -> Float: ...
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@overload
|
| 63 |
+
def item(value: str, _parent: Item | None = ..., _sort_keys: bool = ...) -> String: ...
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@overload
|
| 67 |
+
def item(
|
| 68 |
+
value: datetime, _parent: Item | None = ..., _sort_keys: bool = ...
|
| 69 |
+
) -> DateTime: ...
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@overload
|
| 73 |
+
def item(value: date, _parent: Item | None = ..., _sort_keys: bool = ...) -> Date: ...
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@overload
|
| 77 |
+
def item(value: time, _parent: Item | None = ..., _sort_keys: bool = ...) -> Time: ...
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@overload
|
| 81 |
+
def item(
|
| 82 |
+
value: Sequence[dict], _parent: Item | None = ..., _sort_keys: bool = ...
|
| 83 |
+
) -> AoT: ...
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@overload
|
| 87 |
+
def item(
|
| 88 |
+
value: Sequence, _parent: Item | None = ..., _sort_keys: bool = ...
|
| 89 |
+
) -> Array: ...
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@overload
|
| 93 |
+
def item(value: dict, _parent: Array = ..., _sort_keys: bool = ...) -> InlineTable: ...
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@overload
|
| 97 |
+
def item(value: dict, _parent: Item | None = ..., _sort_keys: bool = ...) -> Table: ...
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@overload
|
| 101 |
+
def item(value: ItemT, _parent: Item | None = ..., _sort_keys: bool = ...) -> ItemT: ...
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def item(value: Any, _parent: Item | None = None, _sort_keys: bool = False) -> Item:
|
| 105 |
+
"""Create a TOML item from a Python object.
|
| 106 |
+
|
| 107 |
+
:Example:
|
| 108 |
+
|
| 109 |
+
>>> item(42)
|
| 110 |
+
42
|
| 111 |
+
>>> item([1, 2, 3])
|
| 112 |
+
[1, 2, 3]
|
| 113 |
+
>>> item({'a': 1, 'b': 2})
|
| 114 |
+
a = 1
|
| 115 |
+
b = 2
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
from tomlkit.container import Container
|
| 119 |
+
|
| 120 |
+
if isinstance(value, Item):
|
| 121 |
+
return value
|
| 122 |
+
|
| 123 |
+
if isinstance(value, bool):
|
| 124 |
+
return Bool(value, Trivia())
|
| 125 |
+
elif isinstance(value, int):
|
| 126 |
+
return Integer(value, Trivia(), str(value))
|
| 127 |
+
elif isinstance(value, float):
|
| 128 |
+
return Float(value, Trivia(), str(value))
|
| 129 |
+
elif isinstance(value, dict):
|
| 130 |
+
table_constructor = (
|
| 131 |
+
InlineTable if isinstance(_parent, (Array, InlineTable)) else Table
|
| 132 |
+
)
|
| 133 |
+
val = table_constructor(Container(), Trivia(), False)
|
| 134 |
+
for k, v in sorted(
|
| 135 |
+
value.items(),
|
| 136 |
+
key=lambda i: (isinstance(i[1], dict), i[0]) if _sort_keys else 1,
|
| 137 |
+
):
|
| 138 |
+
val[k] = item(v, _parent=val, _sort_keys=_sort_keys)
|
| 139 |
+
|
| 140 |
+
return val
|
| 141 |
+
elif isinstance(value, (list, tuple)):
|
| 142 |
+
if (
|
| 143 |
+
value
|
| 144 |
+
and all(isinstance(v, dict) for v in value)
|
| 145 |
+
and (_parent is None or isinstance(_parent, Table))
|
| 146 |
+
):
|
| 147 |
+
a = AoT([])
|
| 148 |
+
table_constructor = Table
|
| 149 |
+
else:
|
| 150 |
+
a = Array([], Trivia())
|
| 151 |
+
table_constructor = InlineTable
|
| 152 |
+
|
| 153 |
+
for v in value:
|
| 154 |
+
if isinstance(v, dict):
|
| 155 |
+
table = table_constructor(Container(), Trivia(), True)
|
| 156 |
+
|
| 157 |
+
for k, _v in sorted(
|
| 158 |
+
v.items(),
|
| 159 |
+
key=lambda i: (isinstance(i[1], dict), i[0] if _sort_keys else 1),
|
| 160 |
+
):
|
| 161 |
+
i = item(_v, _parent=table, _sort_keys=_sort_keys)
|
| 162 |
+
if isinstance(table, InlineTable):
|
| 163 |
+
i.trivia.trail = ""
|
| 164 |
+
|
| 165 |
+
table[k] = i
|
| 166 |
+
|
| 167 |
+
v = table
|
| 168 |
+
|
| 169 |
+
a.append(v)
|
| 170 |
+
|
| 171 |
+
return a
|
| 172 |
+
elif isinstance(value, str):
|
| 173 |
+
return String.from_raw(value)
|
| 174 |
+
elif isinstance(value, datetime):
|
| 175 |
+
return DateTime(
|
| 176 |
+
value.year,
|
| 177 |
+
value.month,
|
| 178 |
+
value.day,
|
| 179 |
+
value.hour,
|
| 180 |
+
value.minute,
|
| 181 |
+
value.second,
|
| 182 |
+
value.microsecond,
|
| 183 |
+
value.tzinfo,
|
| 184 |
+
Trivia(),
|
| 185 |
+
value.isoformat().replace("+00:00", "Z"),
|
| 186 |
+
)
|
| 187 |
+
elif isinstance(value, date):
|
| 188 |
+
return Date(value.year, value.month, value.day, Trivia(), value.isoformat())
|
| 189 |
+
elif isinstance(value, time):
|
| 190 |
+
return Time(
|
| 191 |
+
value.hour,
|
| 192 |
+
value.minute,
|
| 193 |
+
value.second,
|
| 194 |
+
value.microsecond,
|
| 195 |
+
value.tzinfo,
|
| 196 |
+
Trivia(),
|
| 197 |
+
value.isoformat(),
|
| 198 |
+
)
|
| 199 |
+
else:
|
| 200 |
+
for encoder in CUSTOM_ENCODERS:
|
| 201 |
+
try:
|
| 202 |
+
rv = encoder(value)
|
| 203 |
+
except ConvertError:
|
| 204 |
+
pass
|
| 205 |
+
else:
|
| 206 |
+
if not isinstance(rv, Item):
|
| 207 |
+
raise ConvertError(
|
| 208 |
+
f"Custom encoder is expected to return an instance of Item, got {type(rv)}"
|
| 209 |
+
)
|
| 210 |
+
return rv
|
| 211 |
+
|
| 212 |
+
raise ConvertError(f"Unable to convert an object of {type(value)} to a TOML item")
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class StringType(Enum):
|
| 216 |
+
# Single Line Basic
|
| 217 |
+
SLB = '"'
|
| 218 |
+
# Multi Line Basic
|
| 219 |
+
MLB = '"""'
|
| 220 |
+
# Single Line Literal
|
| 221 |
+
SLL = "'"
|
| 222 |
+
# Multi Line Literal
|
| 223 |
+
MLL = "'''"
|
| 224 |
+
|
| 225 |
+
@classmethod
|
| 226 |
+
def select(cls, literal=False, multiline=False) -> StringType:
|
| 227 |
+
return {
|
| 228 |
+
(False, False): cls.SLB,
|
| 229 |
+
(False, True): cls.MLB,
|
| 230 |
+
(True, False): cls.SLL,
|
| 231 |
+
(True, True): cls.MLL,
|
| 232 |
+
}[(literal, multiline)]
|
| 233 |
+
|
| 234 |
+
@property
|
| 235 |
+
def escaped_sequences(self) -> Collection[str]:
|
| 236 |
+
# https://toml.io/en/v1.0.0#string
|
| 237 |
+
escaped_in_basic = CONTROL_CHARS | {"\\"}
|
| 238 |
+
allowed_in_multiline = {"\n", "\r"}
|
| 239 |
+
return {
|
| 240 |
+
StringType.SLB: escaped_in_basic | {'"'},
|
| 241 |
+
StringType.MLB: (escaped_in_basic | {'"""'}) - allowed_in_multiline,
|
| 242 |
+
StringType.SLL: (),
|
| 243 |
+
StringType.MLL: (),
|
| 244 |
+
}[self]
|
| 245 |
+
|
| 246 |
+
@property
|
| 247 |
+
def invalid_sequences(self) -> Collection[str]:
|
| 248 |
+
# https://toml.io/en/v1.0.0#string
|
| 249 |
+
forbidden_in_literal = CONTROL_CHARS - {"\t"}
|
| 250 |
+
allowed_in_multiline = {"\n", "\r"}
|
| 251 |
+
return {
|
| 252 |
+
StringType.SLB: (),
|
| 253 |
+
StringType.MLB: (),
|
| 254 |
+
StringType.SLL: forbidden_in_literal | {"'"},
|
| 255 |
+
StringType.MLL: (forbidden_in_literal | {"'''"}) - allowed_in_multiline,
|
| 256 |
+
}[self]
|
| 257 |
+
|
| 258 |
+
@property
|
| 259 |
+
def unit(self) -> str:
|
| 260 |
+
return self.value[0]
|
| 261 |
+
|
| 262 |
+
def is_basic(self) -> bool:
|
| 263 |
+
return self in {StringType.SLB, StringType.MLB}
|
| 264 |
+
|
| 265 |
+
def is_literal(self) -> bool:
|
| 266 |
+
return self in {StringType.SLL, StringType.MLL}
|
| 267 |
+
|
| 268 |
+
def is_singleline(self) -> bool:
|
| 269 |
+
return self in {StringType.SLB, StringType.SLL}
|
| 270 |
+
|
| 271 |
+
def is_multiline(self) -> bool:
|
| 272 |
+
return self in {StringType.MLB, StringType.MLL}
|
| 273 |
+
|
| 274 |
+
def toggle(self) -> StringType:
|
| 275 |
+
return {
|
| 276 |
+
StringType.SLB: StringType.MLB,
|
| 277 |
+
StringType.MLB: StringType.SLB,
|
| 278 |
+
StringType.SLL: StringType.MLL,
|
| 279 |
+
StringType.MLL: StringType.SLL,
|
| 280 |
+
}[self]
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class BoolType(Enum):
|
| 284 |
+
TRUE = "true"
|
| 285 |
+
FALSE = "false"
|
| 286 |
+
|
| 287 |
+
def __bool__(self):
|
| 288 |
+
return {BoolType.TRUE: True, BoolType.FALSE: False}[self]
|
| 289 |
+
|
| 290 |
+
def __iter__(self):
|
| 291 |
+
return iter(self.value)
|
| 292 |
+
|
| 293 |
+
def __len__(self):
|
| 294 |
+
return len(self.value)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@dataclasses.dataclass
|
| 298 |
+
class Trivia:
|
| 299 |
+
"""
|
| 300 |
+
Trivia information (aka metadata).
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
# Whitespace before a value.
|
| 304 |
+
indent: str = ""
|
| 305 |
+
# Whitespace after a value, but before a comment.
|
| 306 |
+
comment_ws: str = ""
|
| 307 |
+
# Comment, starting with # character, or empty string if no comment.
|
| 308 |
+
comment: str = ""
|
| 309 |
+
# Trailing newline.
|
| 310 |
+
trail: str = "\n"
|
| 311 |
+
|
| 312 |
+
def copy(self) -> Trivia:
|
| 313 |
+
return dataclasses.replace(self)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class KeyType(Enum):
|
| 317 |
+
"""
|
| 318 |
+
The type of a Key.
|
| 319 |
+
|
| 320 |
+
Keys can be bare (unquoted), or quoted using basic ("), or literal (')
|
| 321 |
+
quotes following the same escaping rules as single-line StringType.
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
Bare = ""
|
| 325 |
+
Basic = '"'
|
| 326 |
+
Literal = "'"
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class Key(abc.ABC):
|
| 330 |
+
"""Base class for a key"""
|
| 331 |
+
|
| 332 |
+
sep: str
|
| 333 |
+
_original: str
|
| 334 |
+
_keys: list[SingleKey]
|
| 335 |
+
_dotted: bool
|
| 336 |
+
key: str
|
| 337 |
+
|
| 338 |
+
@abc.abstractmethod
|
| 339 |
+
def __hash__(self) -> int:
|
| 340 |
+
pass
|
| 341 |
+
|
| 342 |
+
@abc.abstractmethod
|
| 343 |
+
def __eq__(self, __o: object) -> bool:
|
| 344 |
+
pass
|
| 345 |
+
|
| 346 |
+
def is_dotted(self) -> bool:
|
| 347 |
+
"""If the key is followed by other keys"""
|
| 348 |
+
return self._dotted
|
| 349 |
+
|
| 350 |
+
def __iter__(self) -> Iterator[SingleKey]:
|
| 351 |
+
return iter(self._keys)
|
| 352 |
+
|
| 353 |
+
def concat(self, other: Key) -> DottedKey:
|
| 354 |
+
"""Concatenate keys into a dotted key"""
|
| 355 |
+
keys = self._keys + other._keys
|
| 356 |
+
return DottedKey(keys, sep=self.sep)
|
| 357 |
+
|
| 358 |
+
def is_multi(self) -> bool:
|
| 359 |
+
"""Check if the key contains multiple keys"""
|
| 360 |
+
return len(self._keys) > 1
|
| 361 |
+
|
| 362 |
+
def as_string(self) -> str:
|
| 363 |
+
"""The TOML representation"""
|
| 364 |
+
return self._original
|
| 365 |
+
|
| 366 |
+
def __str__(self) -> str:
|
| 367 |
+
return self.as_string()
|
| 368 |
+
|
| 369 |
+
def __repr__(self) -> str:
|
| 370 |
+
return f"<Key {self.as_string()}>"
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class SingleKey(Key):
|
| 374 |
+
"""A single key"""
|
| 375 |
+
|
| 376 |
+
def __init__(
|
| 377 |
+
self,
|
| 378 |
+
k: str,
|
| 379 |
+
t: KeyType | None = None,
|
| 380 |
+
sep: str | None = None,
|
| 381 |
+
original: str | None = None,
|
| 382 |
+
) -> None:
|
| 383 |
+
if not isinstance(k, str):
|
| 384 |
+
raise TypeError("Keys must be strings")
|
| 385 |
+
|
| 386 |
+
if t is None:
|
| 387 |
+
if not k or any(
|
| 388 |
+
c not in string.ascii_letters + string.digits + "-" + "_" for c in k
|
| 389 |
+
):
|
| 390 |
+
t = KeyType.Basic
|
| 391 |
+
else:
|
| 392 |
+
t = KeyType.Bare
|
| 393 |
+
|
| 394 |
+
self.t = t
|
| 395 |
+
if sep is None:
|
| 396 |
+
sep = " = "
|
| 397 |
+
|
| 398 |
+
self.sep = sep
|
| 399 |
+
self.key = k
|
| 400 |
+
if original is None:
|
| 401 |
+
key_str = escape_string(k) if t == KeyType.Basic else k
|
| 402 |
+
original = f"{t.value}{key_str}{t.value}"
|
| 403 |
+
|
| 404 |
+
self._original = original
|
| 405 |
+
self._keys = [self]
|
| 406 |
+
self._dotted = False
|
| 407 |
+
|
| 408 |
+
@property
|
| 409 |
+
def delimiter(self) -> str:
|
| 410 |
+
"""The delimiter: double quote/single quote/none"""
|
| 411 |
+
return self.t.value
|
| 412 |
+
|
| 413 |
+
def is_bare(self) -> bool:
|
| 414 |
+
"""Check if the key is bare"""
|
| 415 |
+
return self.t == KeyType.Bare
|
| 416 |
+
|
| 417 |
+
def __hash__(self) -> int:
|
| 418 |
+
return hash(self.key)
|
| 419 |
+
|
| 420 |
+
def __eq__(self, other: Any) -> bool:
|
| 421 |
+
if isinstance(other, Key):
|
| 422 |
+
return isinstance(other, SingleKey) and self.key == other.key
|
| 423 |
+
|
| 424 |
+
return self.key == other
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class DottedKey(Key):
|
| 428 |
+
def __init__(
|
| 429 |
+
self,
|
| 430 |
+
keys: Iterable[SingleKey],
|
| 431 |
+
sep: str | None = None,
|
| 432 |
+
original: str | None = None,
|
| 433 |
+
) -> None:
|
| 434 |
+
self._keys = list(keys)
|
| 435 |
+
if original is None:
|
| 436 |
+
original = ".".join(k.as_string() for k in self._keys)
|
| 437 |
+
|
| 438 |
+
self.sep = " = " if sep is None else sep
|
| 439 |
+
self._original = original
|
| 440 |
+
self._dotted = False
|
| 441 |
+
self.key = ".".join(k.key for k in self._keys)
|
| 442 |
+
|
| 443 |
+
def __hash__(self) -> int:
|
| 444 |
+
return hash(tuple(self._keys))
|
| 445 |
+
|
| 446 |
+
def __eq__(self, __o: object) -> bool:
|
| 447 |
+
return isinstance(__o, DottedKey) and self._keys == __o._keys
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class Item:
|
| 451 |
+
"""
|
| 452 |
+
An item within a TOML document.
|
| 453 |
+
"""
|
| 454 |
+
|
| 455 |
+
def __init__(self, trivia: Trivia) -> None:
|
| 456 |
+
self._trivia = trivia
|
| 457 |
+
|
| 458 |
+
@property
|
| 459 |
+
def trivia(self) -> Trivia:
|
| 460 |
+
"""The trivia element associated with this item"""
|
| 461 |
+
return self._trivia
|
| 462 |
+
|
| 463 |
+
@property
|
| 464 |
+
def discriminant(self) -> int:
|
| 465 |
+
raise NotImplementedError()
|
| 466 |
+
|
| 467 |
+
def as_string(self) -> str:
|
| 468 |
+
"""The TOML representation"""
|
| 469 |
+
raise NotImplementedError()
|
| 470 |
+
|
| 471 |
+
@property
|
| 472 |
+
def value(self) -> Any:
|
| 473 |
+
return self
|
| 474 |
+
|
| 475 |
+
def unwrap(self) -> Any:
|
| 476 |
+
"""Returns as pure python object (ppo)"""
|
| 477 |
+
raise NotImplementedError()
|
| 478 |
+
|
| 479 |
+
# Helpers
|
| 480 |
+
|
| 481 |
+
def comment(self, comment: str) -> Item:
|
| 482 |
+
"""Attach a comment to this item"""
|
| 483 |
+
if not comment.strip().startswith("#"):
|
| 484 |
+
comment = "# " + comment
|
| 485 |
+
|
| 486 |
+
self._trivia.comment_ws = " "
|
| 487 |
+
self._trivia.comment = comment
|
| 488 |
+
|
| 489 |
+
return self
|
| 490 |
+
|
| 491 |
+
def indent(self, indent: int) -> Item:
|
| 492 |
+
"""Indent this item with given number of spaces"""
|
| 493 |
+
if self._trivia.indent.startswith("\n"):
|
| 494 |
+
self._trivia.indent = "\n" + " " * indent
|
| 495 |
+
else:
|
| 496 |
+
self._trivia.indent = " " * indent
|
| 497 |
+
|
| 498 |
+
return self
|
| 499 |
+
|
| 500 |
+
def is_boolean(self) -> bool:
|
| 501 |
+
return isinstance(self, Bool)
|
| 502 |
+
|
| 503 |
+
def is_table(self) -> bool:
|
| 504 |
+
return isinstance(self, Table)
|
| 505 |
+
|
| 506 |
+
def is_inline_table(self) -> bool:
|
| 507 |
+
return isinstance(self, InlineTable)
|
| 508 |
+
|
| 509 |
+
def is_aot(self) -> bool:
|
| 510 |
+
return isinstance(self, AoT)
|
| 511 |
+
|
| 512 |
+
def _getstate(self, protocol=3):
|
| 513 |
+
return (self._trivia,)
|
| 514 |
+
|
| 515 |
+
def __reduce__(self):
|
| 516 |
+
return self.__reduce_ex__(2)
|
| 517 |
+
|
| 518 |
+
def __reduce_ex__(self, protocol):
|
| 519 |
+
return self.__class__, self._getstate(protocol)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
class Whitespace(Item):
|
| 523 |
+
"""
|
| 524 |
+
A whitespace literal.
|
| 525 |
+
"""
|
| 526 |
+
|
| 527 |
+
def __init__(self, s: str, fixed: bool = False) -> None:
|
| 528 |
+
self._s = s
|
| 529 |
+
self._fixed = fixed
|
| 530 |
+
|
| 531 |
+
@property
|
| 532 |
+
def s(self) -> str:
|
| 533 |
+
return self._s
|
| 534 |
+
|
| 535 |
+
@property
|
| 536 |
+
def value(self) -> str:
|
| 537 |
+
"""The wrapped string of the whitespace"""
|
| 538 |
+
return self._s
|
| 539 |
+
|
| 540 |
+
@property
|
| 541 |
+
def trivia(self) -> Trivia:
|
| 542 |
+
raise RuntimeError("Called trivia on a Whitespace variant.")
|
| 543 |
+
|
| 544 |
+
@property
|
| 545 |
+
def discriminant(self) -> int:
|
| 546 |
+
return 0
|
| 547 |
+
|
| 548 |
+
def is_fixed(self) -> bool:
|
| 549 |
+
"""If the whitespace is fixed, it can't be merged or discarded from the output."""
|
| 550 |
+
return self._fixed
|
| 551 |
+
|
| 552 |
+
def as_string(self) -> str:
|
| 553 |
+
return self._s
|
| 554 |
+
|
| 555 |
+
def __repr__(self) -> str:
|
| 556 |
+
return f"<{self.__class__.__name__} {self._s!r}>"
|
| 557 |
+
|
| 558 |
+
def _getstate(self, protocol=3):
|
| 559 |
+
return self._s, self._fixed
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class Comment(Item):
|
| 563 |
+
"""
|
| 564 |
+
A comment literal.
|
| 565 |
+
"""
|
| 566 |
+
|
| 567 |
+
@property
|
| 568 |
+
def discriminant(self) -> int:
|
| 569 |
+
return 1
|
| 570 |
+
|
| 571 |
+
def as_string(self) -> str:
|
| 572 |
+
return (
|
| 573 |
+
f"{self._trivia.indent}{decode(self._trivia.comment)}{self._trivia.trail}"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
def __str__(self) -> str:
|
| 577 |
+
return f"{self._trivia.indent}{decode(self._trivia.comment)}"
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
class Integer(Item, _CustomInt):
|
| 581 |
+
"""
|
| 582 |
+
An integer literal.
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
def __new__(cls, value: int, trivia: Trivia, raw: str) -> Integer:
|
| 586 |
+
return int.__new__(cls, value)
|
| 587 |
+
|
| 588 |
+
def __init__(self, value: int, trivia: Trivia, raw: str) -> None:
|
| 589 |
+
super().__init__(trivia)
|
| 590 |
+
self._original = value
|
| 591 |
+
self._raw = raw
|
| 592 |
+
self._sign = False
|
| 593 |
+
|
| 594 |
+
if re.match(r"^[+\-]\d+$", raw):
|
| 595 |
+
self._sign = True
|
| 596 |
+
|
| 597 |
+
def unwrap(self) -> int:
|
| 598 |
+
return self._original
|
| 599 |
+
|
| 600 |
+
__int__ = unwrap
|
| 601 |
+
|
| 602 |
+
def __hash__(self) -> int:
|
| 603 |
+
return hash(self.unwrap())
|
| 604 |
+
|
| 605 |
+
@property
|
| 606 |
+
def discriminant(self) -> int:
|
| 607 |
+
return 2
|
| 608 |
+
|
| 609 |
+
@property
|
| 610 |
+
def value(self) -> int:
|
| 611 |
+
"""The wrapped integer value"""
|
| 612 |
+
return self
|
| 613 |
+
|
| 614 |
+
def as_string(self) -> str:
|
| 615 |
+
return self._raw
|
| 616 |
+
|
| 617 |
+
def _new(self, result):
|
| 618 |
+
raw = str(result)
|
| 619 |
+
if self._sign and result >= 0:
|
| 620 |
+
raw = f"+{raw}"
|
| 621 |
+
|
| 622 |
+
return Integer(result, self._trivia, raw)
|
| 623 |
+
|
| 624 |
+
def _getstate(self, protocol=3):
|
| 625 |
+
return int(self), self._trivia, self._raw
|
| 626 |
+
|
| 627 |
+
# int methods
|
| 628 |
+
__abs__ = wrap_method(int.__abs__)
|
| 629 |
+
__add__ = wrap_method(int.__add__)
|
| 630 |
+
__and__ = wrap_method(int.__and__)
|
| 631 |
+
__ceil__ = wrap_method(int.__ceil__)
|
| 632 |
+
__eq__ = int.__eq__
|
| 633 |
+
__floor__ = wrap_method(int.__floor__)
|
| 634 |
+
__floordiv__ = wrap_method(int.__floordiv__)
|
| 635 |
+
__invert__ = wrap_method(int.__invert__)
|
| 636 |
+
__le__ = int.__le__
|
| 637 |
+
__lshift__ = wrap_method(int.__lshift__)
|
| 638 |
+
__lt__ = int.__lt__
|
| 639 |
+
__mod__ = wrap_method(int.__mod__)
|
| 640 |
+
__mul__ = wrap_method(int.__mul__)
|
| 641 |
+
__neg__ = wrap_method(int.__neg__)
|
| 642 |
+
__or__ = wrap_method(int.__or__)
|
| 643 |
+
__pos__ = wrap_method(int.__pos__)
|
| 644 |
+
__pow__ = wrap_method(int.__pow__)
|
| 645 |
+
__radd__ = wrap_method(int.__radd__)
|
| 646 |
+
__rand__ = wrap_method(int.__rand__)
|
| 647 |
+
__rfloordiv__ = wrap_method(int.__rfloordiv__)
|
| 648 |
+
__rlshift__ = wrap_method(int.__rlshift__)
|
| 649 |
+
__rmod__ = wrap_method(int.__rmod__)
|
| 650 |
+
__rmul__ = wrap_method(int.__rmul__)
|
| 651 |
+
__ror__ = wrap_method(int.__ror__)
|
| 652 |
+
__round__ = wrap_method(int.__round__)
|
| 653 |
+
__rpow__ = wrap_method(int.__rpow__)
|
| 654 |
+
__rrshift__ = wrap_method(int.__rrshift__)
|
| 655 |
+
__rshift__ = wrap_method(int.__rshift__)
|
| 656 |
+
__rxor__ = wrap_method(int.__rxor__)
|
| 657 |
+
__trunc__ = wrap_method(int.__trunc__)
|
| 658 |
+
__xor__ = wrap_method(int.__xor__)
|
| 659 |
+
|
| 660 |
+
def __rtruediv__(self, other):
|
| 661 |
+
result = int.__rtruediv__(self, other)
|
| 662 |
+
if result is NotImplemented:
|
| 663 |
+
return result
|
| 664 |
+
return Float._new(self, result)
|
| 665 |
+
|
| 666 |
+
def __truediv__(self, other):
|
| 667 |
+
result = int.__truediv__(self, other)
|
| 668 |
+
if result is NotImplemented:
|
| 669 |
+
return result
|
| 670 |
+
return Float._new(self, result)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
class Float(Item, _CustomFloat):
|
| 674 |
+
"""
|
| 675 |
+
A float literal.
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
def __new__(cls, value: float, trivia: Trivia, raw: str) -> Float:
|
| 679 |
+
return float.__new__(cls, value)
|
| 680 |
+
|
| 681 |
+
def __init__(self, value: float, trivia: Trivia, raw: str) -> None:
|
| 682 |
+
super().__init__(trivia)
|
| 683 |
+
self._original = value
|
| 684 |
+
self._raw = raw
|
| 685 |
+
self._sign = False
|
| 686 |
+
|
| 687 |
+
if re.match(r"^[+\-].+$", raw):
|
| 688 |
+
self._sign = True
|
| 689 |
+
|
| 690 |
+
def unwrap(self) -> float:
|
| 691 |
+
return self._original
|
| 692 |
+
|
| 693 |
+
__float__ = unwrap
|
| 694 |
+
|
| 695 |
+
def __hash__(self) -> int:
|
| 696 |
+
return hash(self.unwrap())
|
| 697 |
+
|
| 698 |
+
@property
|
| 699 |
+
def discriminant(self) -> int:
|
| 700 |
+
return 3
|
| 701 |
+
|
| 702 |
+
@property
|
| 703 |
+
def value(self) -> float:
|
| 704 |
+
"""The wrapped float value"""
|
| 705 |
+
return self
|
| 706 |
+
|
| 707 |
+
def as_string(self) -> str:
|
| 708 |
+
return self._raw
|
| 709 |
+
|
| 710 |
+
def _new(self, result):
|
| 711 |
+
raw = str(result)
|
| 712 |
+
|
| 713 |
+
if self._sign and result >= 0:
|
| 714 |
+
raw = f"+{raw}"
|
| 715 |
+
|
| 716 |
+
return Float(result, self._trivia, raw)
|
| 717 |
+
|
| 718 |
+
def _getstate(self, protocol=3):
|
| 719 |
+
return float(self), self._trivia, self._raw
|
| 720 |
+
|
| 721 |
+
# float methods
|
| 722 |
+
__abs__ = wrap_method(float.__abs__)
|
| 723 |
+
__add__ = wrap_method(float.__add__)
|
| 724 |
+
__eq__ = float.__eq__
|
| 725 |
+
__floordiv__ = wrap_method(float.__floordiv__)
|
| 726 |
+
__le__ = float.__le__
|
| 727 |
+
__lt__ = float.__lt__
|
| 728 |
+
__mod__ = wrap_method(float.__mod__)
|
| 729 |
+
__mul__ = wrap_method(float.__mul__)
|
| 730 |
+
__neg__ = wrap_method(float.__neg__)
|
| 731 |
+
__pos__ = wrap_method(float.__pos__)
|
| 732 |
+
__pow__ = wrap_method(float.__pow__)
|
| 733 |
+
__radd__ = wrap_method(float.__radd__)
|
| 734 |
+
__rfloordiv__ = wrap_method(float.__rfloordiv__)
|
| 735 |
+
__rmod__ = wrap_method(float.__rmod__)
|
| 736 |
+
__rmul__ = wrap_method(float.__rmul__)
|
| 737 |
+
__round__ = wrap_method(float.__round__)
|
| 738 |
+
__rpow__ = wrap_method(float.__rpow__)
|
| 739 |
+
__rtruediv__ = wrap_method(float.__rtruediv__)
|
| 740 |
+
__truediv__ = wrap_method(float.__truediv__)
|
| 741 |
+
__trunc__ = float.__trunc__
|
| 742 |
+
|
| 743 |
+
if sys.version_info >= (3, 9):
|
| 744 |
+
__ceil__ = float.__ceil__
|
| 745 |
+
__floor__ = float.__floor__
|
| 746 |
+
else:
|
| 747 |
+
__ceil__ = math.ceil
|
| 748 |
+
__floor__ = math.floor
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
class Bool(Item):
|
| 752 |
+
"""
|
| 753 |
+
A boolean literal.
|
| 754 |
+
"""
|
| 755 |
+
|
| 756 |
+
def __init__(self, t: int, trivia: Trivia) -> None:
|
| 757 |
+
super().__init__(trivia)
|
| 758 |
+
|
| 759 |
+
self._value = bool(t)
|
| 760 |
+
|
| 761 |
+
def unwrap(self) -> bool:
|
| 762 |
+
return bool(self)
|
| 763 |
+
|
| 764 |
+
@property
|
| 765 |
+
def discriminant(self) -> int:
|
| 766 |
+
return 4
|
| 767 |
+
|
| 768 |
+
@property
|
| 769 |
+
def value(self) -> bool:
|
| 770 |
+
"""The wrapped boolean value"""
|
| 771 |
+
return self._value
|
| 772 |
+
|
| 773 |
+
def as_string(self) -> str:
|
| 774 |
+
return str(self._value).lower()
|
| 775 |
+
|
| 776 |
+
def _getstate(self, protocol=3):
|
| 777 |
+
return self._value, self._trivia
|
| 778 |
+
|
| 779 |
+
def __bool__(self):
|
| 780 |
+
return self._value
|
| 781 |
+
|
| 782 |
+
__nonzero__ = __bool__
|
| 783 |
+
|
| 784 |
+
def __eq__(self, other):
|
| 785 |
+
if not isinstance(other, bool):
|
| 786 |
+
return NotImplemented
|
| 787 |
+
|
| 788 |
+
return other == self._value
|
| 789 |
+
|
| 790 |
+
def __hash__(self):
|
| 791 |
+
return hash(self._value)
|
| 792 |
+
|
| 793 |
+
def __repr__(self):
|
| 794 |
+
return repr(self._value)
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
class DateTime(Item, datetime):
|
| 798 |
+
"""
|
| 799 |
+
A datetime literal.
|
| 800 |
+
"""
|
| 801 |
+
|
| 802 |
+
def __new__(
|
| 803 |
+
cls,
|
| 804 |
+
year: int,
|
| 805 |
+
month: int,
|
| 806 |
+
day: int,
|
| 807 |
+
hour: int,
|
| 808 |
+
minute: int,
|
| 809 |
+
second: int,
|
| 810 |
+
microsecond: int,
|
| 811 |
+
tzinfo: tzinfo | None,
|
| 812 |
+
*_: Any,
|
| 813 |
+
**kwargs: Any,
|
| 814 |
+
) -> datetime:
|
| 815 |
+
return datetime.__new__(
|
| 816 |
+
cls,
|
| 817 |
+
year,
|
| 818 |
+
month,
|
| 819 |
+
day,
|
| 820 |
+
hour,
|
| 821 |
+
minute,
|
| 822 |
+
second,
|
| 823 |
+
microsecond,
|
| 824 |
+
tzinfo=tzinfo,
|
| 825 |
+
**kwargs,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
def __init__(
|
| 829 |
+
self,
|
| 830 |
+
year: int,
|
| 831 |
+
month: int,
|
| 832 |
+
day: int,
|
| 833 |
+
hour: int,
|
| 834 |
+
minute: int,
|
| 835 |
+
second: int,
|
| 836 |
+
microsecond: int,
|
| 837 |
+
tzinfo: tzinfo | None,
|
| 838 |
+
trivia: Trivia | None = None,
|
| 839 |
+
raw: str | None = None,
|
| 840 |
+
**kwargs: Any,
|
| 841 |
+
) -> None:
|
| 842 |
+
super().__init__(trivia or Trivia())
|
| 843 |
+
|
| 844 |
+
self._raw = raw or self.isoformat()
|
| 845 |
+
|
| 846 |
+
def unwrap(self) -> datetime:
|
| 847 |
+
(
|
| 848 |
+
year,
|
| 849 |
+
month,
|
| 850 |
+
day,
|
| 851 |
+
hour,
|
| 852 |
+
minute,
|
| 853 |
+
second,
|
| 854 |
+
microsecond,
|
| 855 |
+
tzinfo,
|
| 856 |
+
_,
|
| 857 |
+
_,
|
| 858 |
+
) = self._getstate()
|
| 859 |
+
return datetime(year, month, day, hour, minute, second, microsecond, tzinfo)
|
| 860 |
+
|
| 861 |
+
@property
|
| 862 |
+
def discriminant(self) -> int:
|
| 863 |
+
return 5
|
| 864 |
+
|
| 865 |
+
@property
|
| 866 |
+
def value(self) -> datetime:
|
| 867 |
+
return self
|
| 868 |
+
|
| 869 |
+
def as_string(self) -> str:
|
| 870 |
+
return self._raw
|
| 871 |
+
|
| 872 |
+
def __add__(self, other):
|
| 873 |
+
if PY38:
|
| 874 |
+
result = datetime(
|
| 875 |
+
self.year,
|
| 876 |
+
self.month,
|
| 877 |
+
self.day,
|
| 878 |
+
self.hour,
|
| 879 |
+
self.minute,
|
| 880 |
+
self.second,
|
| 881 |
+
self.microsecond,
|
| 882 |
+
self.tzinfo,
|
| 883 |
+
).__add__(other)
|
| 884 |
+
else:
|
| 885 |
+
result = super().__add__(other)
|
| 886 |
+
|
| 887 |
+
return self._new(result)
|
| 888 |
+
|
| 889 |
+
def __sub__(self, other):
|
| 890 |
+
if PY38:
|
| 891 |
+
result = datetime(
|
| 892 |
+
self.year,
|
| 893 |
+
self.month,
|
| 894 |
+
self.day,
|
| 895 |
+
self.hour,
|
| 896 |
+
self.minute,
|
| 897 |
+
self.second,
|
| 898 |
+
self.microsecond,
|
| 899 |
+
self.tzinfo,
|
| 900 |
+
).__sub__(other)
|
| 901 |
+
else:
|
| 902 |
+
result = super().__sub__(other)
|
| 903 |
+
|
| 904 |
+
if isinstance(result, datetime):
|
| 905 |
+
result = self._new(result)
|
| 906 |
+
|
| 907 |
+
return result
|
| 908 |
+
|
| 909 |
+
def replace(self, *args: Any, **kwargs: Any) -> datetime:
|
| 910 |
+
return self._new(super().replace(*args, **kwargs))
|
| 911 |
+
|
| 912 |
+
def astimezone(self, tz: tzinfo) -> datetime:
|
| 913 |
+
result = super().astimezone(tz)
|
| 914 |
+
if PY38:
|
| 915 |
+
return result
|
| 916 |
+
return self._new(result)
|
| 917 |
+
|
| 918 |
+
def _new(self, result) -> DateTime:
|
| 919 |
+
raw = result.isoformat()
|
| 920 |
+
|
| 921 |
+
return DateTime(
|
| 922 |
+
result.year,
|
| 923 |
+
result.month,
|
| 924 |
+
result.day,
|
| 925 |
+
result.hour,
|
| 926 |
+
result.minute,
|
| 927 |
+
result.second,
|
| 928 |
+
result.microsecond,
|
| 929 |
+
result.tzinfo,
|
| 930 |
+
self._trivia,
|
| 931 |
+
raw,
|
| 932 |
+
)
|
| 933 |
+
|
| 934 |
+
def _getstate(self, protocol=3):
|
| 935 |
+
return (
|
| 936 |
+
self.year,
|
| 937 |
+
self.month,
|
| 938 |
+
self.day,
|
| 939 |
+
self.hour,
|
| 940 |
+
self.minute,
|
| 941 |
+
self.second,
|
| 942 |
+
self.microsecond,
|
| 943 |
+
self.tzinfo,
|
| 944 |
+
self._trivia,
|
| 945 |
+
self._raw,
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
class Date(Item, date):
|
| 950 |
+
"""
|
| 951 |
+
A date literal.
|
| 952 |
+
"""
|
| 953 |
+
|
| 954 |
+
def __new__(cls, year: int, month: int, day: int, *_: Any) -> date:
|
| 955 |
+
return date.__new__(cls, year, month, day)
|
| 956 |
+
|
| 957 |
+
def __init__(
|
| 958 |
+
self,
|
| 959 |
+
year: int,
|
| 960 |
+
month: int,
|
| 961 |
+
day: int,
|
| 962 |
+
trivia: Trivia | None = None,
|
| 963 |
+
raw: str = "",
|
| 964 |
+
) -> None:
|
| 965 |
+
super().__init__(trivia or Trivia())
|
| 966 |
+
|
| 967 |
+
self._raw = raw
|
| 968 |
+
|
| 969 |
+
def unwrap(self) -> date:
|
| 970 |
+
(year, month, day, _, _) = self._getstate()
|
| 971 |
+
return date(year, month, day)
|
| 972 |
+
|
| 973 |
+
@property
|
| 974 |
+
def discriminant(self) -> int:
|
| 975 |
+
return 6
|
| 976 |
+
|
| 977 |
+
@property
|
| 978 |
+
def value(self) -> date:
|
| 979 |
+
return self
|
| 980 |
+
|
| 981 |
+
def as_string(self) -> str:
|
| 982 |
+
return self._raw
|
| 983 |
+
|
| 984 |
+
def __add__(self, other):
|
| 985 |
+
if PY38:
|
| 986 |
+
result = date(self.year, self.month, self.day).__add__(other)
|
| 987 |
+
else:
|
| 988 |
+
result = super().__add__(other)
|
| 989 |
+
|
| 990 |
+
return self._new(result)
|
| 991 |
+
|
| 992 |
+
def __sub__(self, other):
|
| 993 |
+
if PY38:
|
| 994 |
+
result = date(self.year, self.month, self.day).__sub__(other)
|
| 995 |
+
else:
|
| 996 |
+
result = super().__sub__(other)
|
| 997 |
+
|
| 998 |
+
if isinstance(result, date):
|
| 999 |
+
result = self._new(result)
|
| 1000 |
+
|
| 1001 |
+
return result
|
| 1002 |
+
|
| 1003 |
+
def replace(self, *args: Any, **kwargs: Any) -> date:
|
| 1004 |
+
return self._new(super().replace(*args, **kwargs))
|
| 1005 |
+
|
| 1006 |
+
def _new(self, result):
|
| 1007 |
+
raw = result.isoformat()
|
| 1008 |
+
|
| 1009 |
+
return Date(result.year, result.month, result.day, self._trivia, raw)
|
| 1010 |
+
|
| 1011 |
+
def _getstate(self, protocol=3):
|
| 1012 |
+
return (self.year, self.month, self.day, self._trivia, self._raw)
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
class Time(Item, time):
|
| 1016 |
+
"""
|
| 1017 |
+
A time literal.
|
| 1018 |
+
"""
|
| 1019 |
+
|
| 1020 |
+
def __new__(
|
| 1021 |
+
cls,
|
| 1022 |
+
hour: int,
|
| 1023 |
+
minute: int,
|
| 1024 |
+
second: int,
|
| 1025 |
+
microsecond: int,
|
| 1026 |
+
tzinfo: tzinfo | None,
|
| 1027 |
+
*_: Any,
|
| 1028 |
+
) -> time:
|
| 1029 |
+
return time.__new__(cls, hour, minute, second, microsecond, tzinfo)
|
| 1030 |
+
|
| 1031 |
+
def __init__(
|
| 1032 |
+
self,
|
| 1033 |
+
hour: int,
|
| 1034 |
+
minute: int,
|
| 1035 |
+
second: int,
|
| 1036 |
+
microsecond: int,
|
| 1037 |
+
tzinfo: tzinfo | None,
|
| 1038 |
+
trivia: Trivia | None = None,
|
| 1039 |
+
raw: str = "",
|
| 1040 |
+
) -> None:
|
| 1041 |
+
super().__init__(trivia or Trivia())
|
| 1042 |
+
|
| 1043 |
+
self._raw = raw
|
| 1044 |
+
|
| 1045 |
+
def unwrap(self) -> time:
|
| 1046 |
+
(hour, minute, second, microsecond, tzinfo, _, _) = self._getstate()
|
| 1047 |
+
return time(hour, minute, second, microsecond, tzinfo)
|
| 1048 |
+
|
| 1049 |
+
@property
|
| 1050 |
+
def discriminant(self) -> int:
|
| 1051 |
+
return 7
|
| 1052 |
+
|
| 1053 |
+
@property
|
| 1054 |
+
def value(self) -> time:
|
| 1055 |
+
return self
|
| 1056 |
+
|
| 1057 |
+
def as_string(self) -> str:
|
| 1058 |
+
return self._raw
|
| 1059 |
+
|
| 1060 |
+
def replace(self, *args: Any, **kwargs: Any) -> time:
|
| 1061 |
+
return self._new(super().replace(*args, **kwargs))
|
| 1062 |
+
|
| 1063 |
+
def _new(self, result):
|
| 1064 |
+
raw = result.isoformat()
|
| 1065 |
+
|
| 1066 |
+
return Time(
|
| 1067 |
+
result.hour,
|
| 1068 |
+
result.minute,
|
| 1069 |
+
result.second,
|
| 1070 |
+
result.microsecond,
|
| 1071 |
+
result.tzinfo,
|
| 1072 |
+
self._trivia,
|
| 1073 |
+
raw,
|
| 1074 |
+
)
|
| 1075 |
+
|
| 1076 |
+
def _getstate(self, protocol: int = 3) -> tuple:
|
| 1077 |
+
return (
|
| 1078 |
+
self.hour,
|
| 1079 |
+
self.minute,
|
| 1080 |
+
self.second,
|
| 1081 |
+
self.microsecond,
|
| 1082 |
+
self.tzinfo,
|
| 1083 |
+
self._trivia,
|
| 1084 |
+
self._raw,
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
class _ArrayItemGroup:
|
| 1089 |
+
__slots__ = ("comma", "comment", "indent", "value")
|
| 1090 |
+
|
| 1091 |
+
def __init__(
|
| 1092 |
+
self,
|
| 1093 |
+
value: Item | None = None,
|
| 1094 |
+
indent: Whitespace | None = None,
|
| 1095 |
+
comma: Whitespace | None = None,
|
| 1096 |
+
comment: Comment | None = None,
|
| 1097 |
+
) -> None:
|
| 1098 |
+
self.value = value
|
| 1099 |
+
self.indent = indent
|
| 1100 |
+
self.comma = comma
|
| 1101 |
+
self.comment = comment
|
| 1102 |
+
|
| 1103 |
+
def __iter__(self) -> Iterator[Item]:
|
| 1104 |
+
return filter(
|
| 1105 |
+
lambda x: x is not None, (self.indent, self.value, self.comma, self.comment)
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
def __repr__(self) -> str:
|
| 1109 |
+
return repr(tuple(self))
|
| 1110 |
+
|
| 1111 |
+
def is_whitespace(self) -> bool:
|
| 1112 |
+
return self.value is None and self.comment is None
|
| 1113 |
+
|
| 1114 |
+
def __bool__(self) -> bool:
|
| 1115 |
+
try:
|
| 1116 |
+
next(iter(self))
|
| 1117 |
+
except StopIteration:
|
| 1118 |
+
return False
|
| 1119 |
+
return True
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
class Array(Item, _CustomList):
|
| 1123 |
+
"""
|
| 1124 |
+
An array literal
|
| 1125 |
+
"""
|
| 1126 |
+
|
| 1127 |
+
def __init__(
|
| 1128 |
+
self, value: list[Item], trivia: Trivia, multiline: bool = False
|
| 1129 |
+
) -> None:
|
| 1130 |
+
super().__init__(trivia)
|
| 1131 |
+
list.__init__(
|
| 1132 |
+
self,
|
| 1133 |
+
[v for v in value if not isinstance(v, (Whitespace, Comment, Null))],
|
| 1134 |
+
)
|
| 1135 |
+
self._index_map: dict[int, int] = {}
|
| 1136 |
+
self._value = self._group_values(value)
|
| 1137 |
+
self._multiline = multiline
|
| 1138 |
+
self._reindex()
|
| 1139 |
+
|
| 1140 |
+
def _group_values(self, value: list[Item]) -> list[_ArrayItemGroup]:
|
| 1141 |
+
"""Group the values into (indent, value, comma, comment) tuples"""
|
| 1142 |
+
groups = []
|
| 1143 |
+
this_group = _ArrayItemGroup()
|
| 1144 |
+
start_new_group = False
|
| 1145 |
+
for item in value:
|
| 1146 |
+
if isinstance(item, Whitespace):
|
| 1147 |
+
if "," not in item.s or start_new_group:
|
| 1148 |
+
groups.append(this_group)
|
| 1149 |
+
this_group = _ArrayItemGroup(indent=item)
|
| 1150 |
+
start_new_group = False
|
| 1151 |
+
else:
|
| 1152 |
+
if this_group.value is None:
|
| 1153 |
+
# when comma is met and no value is provided, add a dummy Null
|
| 1154 |
+
this_group.value = Null()
|
| 1155 |
+
this_group.comma = item
|
| 1156 |
+
elif isinstance(item, Comment):
|
| 1157 |
+
if this_group.value is None:
|
| 1158 |
+
this_group.value = Null()
|
| 1159 |
+
this_group.comment = item
|
| 1160 |
+
# Comments are the last item in a group.
|
| 1161 |
+
start_new_group = True
|
| 1162 |
+
elif this_group.value is None:
|
| 1163 |
+
this_group.value = item
|
| 1164 |
+
else:
|
| 1165 |
+
groups.append(this_group)
|
| 1166 |
+
this_group = _ArrayItemGroup(value=item)
|
| 1167 |
+
groups.append(this_group)
|
| 1168 |
+
return [group for group in groups if group]
|
| 1169 |
+
|
| 1170 |
+
def unwrap(self) -> list[Any]:
|
| 1171 |
+
unwrapped = []
|
| 1172 |
+
for v in self:
|
| 1173 |
+
if hasattr(v, "unwrap"):
|
| 1174 |
+
unwrapped.append(v.unwrap())
|
| 1175 |
+
else:
|
| 1176 |
+
unwrapped.append(v)
|
| 1177 |
+
return unwrapped
|
| 1178 |
+
|
| 1179 |
+
@property
|
| 1180 |
+
def discriminant(self) -> int:
|
| 1181 |
+
return 8
|
| 1182 |
+
|
| 1183 |
+
@property
|
| 1184 |
+
def value(self) -> list:
|
| 1185 |
+
return self
|
| 1186 |
+
|
| 1187 |
+
def _iter_items(self) -> Iterator[Item]:
|
| 1188 |
+
for v in self._value:
|
| 1189 |
+
yield from v
|
| 1190 |
+
|
| 1191 |
+
def multiline(self, multiline: bool) -> Array:
|
| 1192 |
+
"""Change the array to display in multiline or not.
|
| 1193 |
+
|
| 1194 |
+
:Example:
|
| 1195 |
+
|
| 1196 |
+
>>> a = item([1, 2, 3])
|
| 1197 |
+
>>> print(a.as_string())
|
| 1198 |
+
[1, 2, 3]
|
| 1199 |
+
>>> print(a.multiline(True).as_string())
|
| 1200 |
+
[
|
| 1201 |
+
1,
|
| 1202 |
+
2,
|
| 1203 |
+
3,
|
| 1204 |
+
]
|
| 1205 |
+
"""
|
| 1206 |
+
self._multiline = multiline
|
| 1207 |
+
|
| 1208 |
+
return self
|
| 1209 |
+
|
| 1210 |
+
def as_string(self) -> str:
|
| 1211 |
+
if not self._multiline or not self._value:
|
| 1212 |
+
return f"[{''.join(v.as_string() for v in self._iter_items())}]"
|
| 1213 |
+
|
| 1214 |
+
s = "[\n"
|
| 1215 |
+
s += "".join(
|
| 1216 |
+
self.trivia.indent
|
| 1217 |
+
+ " " * 4
|
| 1218 |
+
+ v.value.as_string()
|
| 1219 |
+
+ ("," if not isinstance(v.value, Null) else "")
|
| 1220 |
+
+ (v.comment.as_string() if v.comment is not None else "")
|
| 1221 |
+
+ "\n"
|
| 1222 |
+
for v in self._value
|
| 1223 |
+
if v.value is not None
|
| 1224 |
+
)
|
| 1225 |
+
s += self.trivia.indent + "]"
|
| 1226 |
+
|
| 1227 |
+
return s
|
| 1228 |
+
|
| 1229 |
+
def _reindex(self) -> None:
|
| 1230 |
+
self._index_map.clear()
|
| 1231 |
+
index = 0
|
| 1232 |
+
for i, v in enumerate(self._value):
|
| 1233 |
+
if v.value is None or isinstance(v.value, Null):
|
| 1234 |
+
continue
|
| 1235 |
+
self._index_map[index] = i
|
| 1236 |
+
index += 1
|
| 1237 |
+
|
| 1238 |
+
def add_line(
|
| 1239 |
+
self,
|
| 1240 |
+
*items: Any,
|
| 1241 |
+
indent: str = " ",
|
| 1242 |
+
comment: str | None = None,
|
| 1243 |
+
add_comma: bool = True,
|
| 1244 |
+
newline: bool = True,
|
| 1245 |
+
) -> None:
|
| 1246 |
+
"""Add multiple items in a line to control the format precisely.
|
| 1247 |
+
When add_comma is True, only accept actual values and
|
| 1248 |
+
", " will be added between values automatically.
|
| 1249 |
+
|
| 1250 |
+
:Example:
|
| 1251 |
+
|
| 1252 |
+
>>> a = array()
|
| 1253 |
+
>>> a.add_line(1, 2, 3)
|
| 1254 |
+
>>> a.add_line(4, 5, 6)
|
| 1255 |
+
>>> a.add_line(indent="")
|
| 1256 |
+
>>> print(a.as_string())
|
| 1257 |
+
[
|
| 1258 |
+
1, 2, 3,
|
| 1259 |
+
4, 5, 6,
|
| 1260 |
+
]
|
| 1261 |
+
"""
|
| 1262 |
+
new_values: list[Item] = []
|
| 1263 |
+
first_indent = f"\n{indent}" if newline else indent
|
| 1264 |
+
if first_indent:
|
| 1265 |
+
new_values.append(Whitespace(first_indent))
|
| 1266 |
+
whitespace = ""
|
| 1267 |
+
data_values = []
|
| 1268 |
+
for i, el in enumerate(items):
|
| 1269 |
+
it = item(el, _parent=self)
|
| 1270 |
+
if isinstance(it, Comment) or (add_comma and isinstance(el, Whitespace)):
|
| 1271 |
+
raise ValueError(f"item type {type(it)} is not allowed in add_line")
|
| 1272 |
+
if not isinstance(it, Whitespace):
|
| 1273 |
+
if whitespace:
|
| 1274 |
+
new_values.append(Whitespace(whitespace))
|
| 1275 |
+
whitespace = ""
|
| 1276 |
+
new_values.append(it)
|
| 1277 |
+
data_values.append(it.value)
|
| 1278 |
+
if add_comma:
|
| 1279 |
+
new_values.append(Whitespace(","))
|
| 1280 |
+
if i != len(items) - 1:
|
| 1281 |
+
new_values.append(Whitespace(" "))
|
| 1282 |
+
elif "," not in it.s:
|
| 1283 |
+
whitespace += it.s
|
| 1284 |
+
else:
|
| 1285 |
+
new_values.append(it)
|
| 1286 |
+
if whitespace:
|
| 1287 |
+
new_values.append(Whitespace(whitespace))
|
| 1288 |
+
if comment:
|
| 1289 |
+
indent = " " if items else ""
|
| 1290 |
+
new_values.append(
|
| 1291 |
+
Comment(Trivia(indent=indent, comment=f"# {comment}", trail=""))
|
| 1292 |
+
)
|
| 1293 |
+
list.extend(self, data_values)
|
| 1294 |
+
if len(self._value) > 0:
|
| 1295 |
+
last_item = self._value[-1]
|
| 1296 |
+
last_value_item = next(
|
| 1297 |
+
(
|
| 1298 |
+
v
|
| 1299 |
+
for v in self._value[::-1]
|
| 1300 |
+
if v.value is not None and not isinstance(v.value, Null)
|
| 1301 |
+
),
|
| 1302 |
+
None,
|
| 1303 |
+
)
|
| 1304 |
+
if last_value_item is not None:
|
| 1305 |
+
last_value_item.comma = Whitespace(",")
|
| 1306 |
+
if last_item.is_whitespace():
|
| 1307 |
+
self._value[-1:-1] = self._group_values(new_values)
|
| 1308 |
+
else:
|
| 1309 |
+
self._value.extend(self._group_values(new_values))
|
| 1310 |
+
else:
|
| 1311 |
+
self._value.extend(self._group_values(new_values))
|
| 1312 |
+
self._reindex()
|
| 1313 |
+
|
| 1314 |
+
def clear(self) -> None:
|
| 1315 |
+
"""Clear the array."""
|
| 1316 |
+
list.clear(self)
|
| 1317 |
+
self._index_map.clear()
|
| 1318 |
+
self._value.clear()
|
| 1319 |
+
|
| 1320 |
+
def __len__(self) -> int:
|
| 1321 |
+
return list.__len__(self)
|
| 1322 |
+
|
| 1323 |
+
def item(self, index: int) -> Item:
|
| 1324 |
+
rv = list.__getitem__(self, index)
|
| 1325 |
+
return cast(Item, rv)
|
| 1326 |
+
|
| 1327 |
+
def __getitem__(self, key: int | slice) -> Any:
|
| 1328 |
+
rv = list.__getitem__(self, key)
|
| 1329 |
+
if isinstance(rv, Bool):
|
| 1330 |
+
return rv.value
|
| 1331 |
+
return rv
|
| 1332 |
+
|
| 1333 |
+
def __setitem__(self, key: int | slice, value: Any) -> Any:
|
| 1334 |
+
it = item(value, _parent=self)
|
| 1335 |
+
list.__setitem__(self, key, it)
|
| 1336 |
+
if isinstance(key, slice):
|
| 1337 |
+
raise ValueError("slice assignment is not supported")
|
| 1338 |
+
if key < 0:
|
| 1339 |
+
key += len(self)
|
| 1340 |
+
self._value[self._index_map[key]].value = it
|
| 1341 |
+
|
| 1342 |
+
def insert(self, pos: int, value: Any) -> None:
|
| 1343 |
+
it = item(value, _parent=self)
|
| 1344 |
+
length = len(self)
|
| 1345 |
+
if not isinstance(it, (Comment, Whitespace)):
|
| 1346 |
+
list.insert(self, pos, it)
|
| 1347 |
+
if pos < 0:
|
| 1348 |
+
pos += length
|
| 1349 |
+
if pos < 0:
|
| 1350 |
+
pos = 0
|
| 1351 |
+
|
| 1352 |
+
idx = 0 # insert position of the self._value list
|
| 1353 |
+
default_indent = " "
|
| 1354 |
+
if pos < length:
|
| 1355 |
+
try:
|
| 1356 |
+
idx = self._index_map[pos]
|
| 1357 |
+
except KeyError as e:
|
| 1358 |
+
raise IndexError("list index out of range") from e
|
| 1359 |
+
else:
|
| 1360 |
+
idx = len(self._value)
|
| 1361 |
+
if idx >= 1 and self._value[idx - 1].is_whitespace():
|
| 1362 |
+
# The last item is a pure whitespace(\n ), insert before it
|
| 1363 |
+
idx -= 1
|
| 1364 |
+
if (
|
| 1365 |
+
self._value[idx].indent is not None
|
| 1366 |
+
and "\n" in self._value[idx].indent.s
|
| 1367 |
+
):
|
| 1368 |
+
default_indent = "\n "
|
| 1369 |
+
indent: Item | None = None
|
| 1370 |
+
comma: Item | None = Whitespace(",") if pos < length else None
|
| 1371 |
+
if idx < len(self._value) and not self._value[idx].is_whitespace():
|
| 1372 |
+
# Prefer to copy the indentation from the item after
|
| 1373 |
+
indent = self._value[idx].indent
|
| 1374 |
+
if idx > 0:
|
| 1375 |
+
last_item = self._value[idx - 1]
|
| 1376 |
+
if indent is None:
|
| 1377 |
+
indent = last_item.indent
|
| 1378 |
+
if not isinstance(last_item.value, Null) and "\n" in default_indent:
|
| 1379 |
+
# Copy the comma from the last item if 1) it contains a value and
|
| 1380 |
+
# 2) the array is multiline
|
| 1381 |
+
comma = last_item.comma
|
| 1382 |
+
if last_item.comma is None and not isinstance(last_item.value, Null):
|
| 1383 |
+
# Add comma to the last item to separate it from the following items.
|
| 1384 |
+
last_item.comma = Whitespace(",")
|
| 1385 |
+
if indent is None and (idx > 0 or "\n" in default_indent):
|
| 1386 |
+
# apply default indent if it isn't the first item or the array is multiline.
|
| 1387 |
+
indent = Whitespace(default_indent)
|
| 1388 |
+
new_item = _ArrayItemGroup(value=it, indent=indent, comma=comma)
|
| 1389 |
+
self._value.insert(idx, new_item)
|
| 1390 |
+
self._reindex()
|
| 1391 |
+
|
| 1392 |
+
def __delitem__(self, key: int | slice):
|
| 1393 |
+
length = len(self)
|
| 1394 |
+
list.__delitem__(self, key)
|
| 1395 |
+
|
| 1396 |
+
if isinstance(key, slice):
|
| 1397 |
+
indices_to_remove = list(
|
| 1398 |
+
range(key.start or 0, key.stop or length, key.step or 1)
|
| 1399 |
+
)
|
| 1400 |
+
else:
|
| 1401 |
+
indices_to_remove = [length + key if key < 0 else key]
|
| 1402 |
+
for i in sorted(indices_to_remove, reverse=True):
|
| 1403 |
+
try:
|
| 1404 |
+
idx = self._index_map[i]
|
| 1405 |
+
except KeyError as e:
|
| 1406 |
+
if not isinstance(key, slice):
|
| 1407 |
+
raise IndexError("list index out of range") from e
|
| 1408 |
+
else:
|
| 1409 |
+
group_rm = self._value[idx]
|
| 1410 |
+
del self._value[idx]
|
| 1411 |
+
if (
|
| 1412 |
+
idx == 0
|
| 1413 |
+
and len(self._value) > 0
|
| 1414 |
+
and self._value[idx].indent
|
| 1415 |
+
and "\n" not in self._value[idx].indent.s
|
| 1416 |
+
):
|
| 1417 |
+
# Remove the indentation of the first item if not newline
|
| 1418 |
+
self._value[idx].indent = None
|
| 1419 |
+
comma_in_indent = (
|
| 1420 |
+
group_rm.indent is not None and "," in group_rm.indent.s
|
| 1421 |
+
)
|
| 1422 |
+
comma_in_comma = group_rm.comma is not None and "," in group_rm.comma.s
|
| 1423 |
+
if comma_in_indent and comma_in_comma:
|
| 1424 |
+
# Removed group had both commas. Add one to the next group.
|
| 1425 |
+
group = self._value[idx] if len(self._value) > idx else None
|
| 1426 |
+
if group is not None:
|
| 1427 |
+
if group.indent is None:
|
| 1428 |
+
group.indent = Whitespace(",")
|
| 1429 |
+
elif "," not in group.indent.s:
|
| 1430 |
+
# Insert the comma after the newline
|
| 1431 |
+
try:
|
| 1432 |
+
newline_index = group.indent.s.index("\n")
|
| 1433 |
+
group.indent._s = (
|
| 1434 |
+
group.indent.s[: newline_index + 1]
|
| 1435 |
+
+ ","
|
| 1436 |
+
+ group.indent.s[newline_index + 1 :]
|
| 1437 |
+
)
|
| 1438 |
+
except ValueError:
|
| 1439 |
+
group.indent._s = "," + group.indent.s
|
| 1440 |
+
elif not comma_in_indent and not comma_in_comma:
|
| 1441 |
+
# Removed group had no commas. Remove the next comma found.
|
| 1442 |
+
for j in range(idx, len(self._value)):
|
| 1443 |
+
group = self._value[j]
|
| 1444 |
+
if group.indent is not None and "," in group.indent.s:
|
| 1445 |
+
group.indent._s = group.indent.s.replace(",", "", 1)
|
| 1446 |
+
break
|
| 1447 |
+
if group_rm.indent is not None and "\n" in group_rm.indent.s:
|
| 1448 |
+
# Restore the removed group's newline onto the next group
|
| 1449 |
+
# if the next group does not have a newline.
|
| 1450 |
+
# i.e. the two were on the same line
|
| 1451 |
+
group = self._value[idx] if len(self._value) > idx else None
|
| 1452 |
+
if group is not None and (
|
| 1453 |
+
group.indent is None or "\n" not in group.indent.s
|
| 1454 |
+
):
|
| 1455 |
+
group.indent = group_rm.indent
|
| 1456 |
+
|
| 1457 |
+
if len(self._value) > 0:
|
| 1458 |
+
v = self._value[-1]
|
| 1459 |
+
if not v.is_whitespace():
|
| 1460 |
+
# remove the comma of the last item
|
| 1461 |
+
v.comma = None
|
| 1462 |
+
|
| 1463 |
+
self._reindex()
|
| 1464 |
+
|
| 1465 |
+
def _getstate(self, protocol=3):
|
| 1466 |
+
return list(self._iter_items()), self._trivia, self._multiline
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
class AbstractTable(Item, _CustomDict):
|
| 1470 |
+
"""Common behaviour of both :class:`Table` and :class:`InlineTable`"""
|
| 1471 |
+
|
| 1472 |
+
def __init__(self, value: container.Container, trivia: Trivia):
|
| 1473 |
+
Item.__init__(self, trivia)
|
| 1474 |
+
|
| 1475 |
+
self._value = value
|
| 1476 |
+
|
| 1477 |
+
for k, v in self._value.body:
|
| 1478 |
+
if k is not None:
|
| 1479 |
+
dict.__setitem__(self, k.key, v)
|
| 1480 |
+
|
| 1481 |
+
def unwrap(self) -> dict[str, Any]:
|
| 1482 |
+
unwrapped = {}
|
| 1483 |
+
for k, v in self.items():
|
| 1484 |
+
if isinstance(k, Key):
|
| 1485 |
+
k = k.key
|
| 1486 |
+
if hasattr(v, "unwrap"):
|
| 1487 |
+
v = v.unwrap()
|
| 1488 |
+
unwrapped[k] = v
|
| 1489 |
+
|
| 1490 |
+
return unwrapped
|
| 1491 |
+
|
| 1492 |
+
@property
|
| 1493 |
+
def value(self) -> container.Container:
|
| 1494 |
+
return self._value
|
| 1495 |
+
|
| 1496 |
+
@overload
|
| 1497 |
+
def append(self: AT, key: None, value: Comment | Whitespace) -> AT: ...
|
| 1498 |
+
|
| 1499 |
+
@overload
|
| 1500 |
+
def append(self: AT, key: Key | str, value: Any) -> AT: ...
|
| 1501 |
+
|
| 1502 |
+
def append(self, key, value):
|
| 1503 |
+
raise NotImplementedError
|
| 1504 |
+
|
| 1505 |
+
@overload
|
| 1506 |
+
def add(self: AT, key: Comment | Whitespace) -> AT: ...
|
| 1507 |
+
|
| 1508 |
+
@overload
|
| 1509 |
+
def add(self: AT, key: Key | str, value: Any = ...) -> AT: ...
|
| 1510 |
+
|
| 1511 |
+
def add(self, key, value=None):
|
| 1512 |
+
if value is None:
|
| 1513 |
+
if not isinstance(key, (Comment, Whitespace)):
|
| 1514 |
+
msg = "Non comment/whitespace items must have an associated key"
|
| 1515 |
+
raise ValueError(msg)
|
| 1516 |
+
|
| 1517 |
+
key, value = None, key
|
| 1518 |
+
|
| 1519 |
+
return self.append(key, value)
|
| 1520 |
+
|
| 1521 |
+
def remove(self: AT, key: Key | str) -> AT:
|
| 1522 |
+
self._value.remove(key)
|
| 1523 |
+
|
| 1524 |
+
if isinstance(key, Key):
|
| 1525 |
+
key = key.key
|
| 1526 |
+
|
| 1527 |
+
if key is not None:
|
| 1528 |
+
dict.__delitem__(self, key)
|
| 1529 |
+
|
| 1530 |
+
return self
|
| 1531 |
+
|
| 1532 |
+
def item(self, key: Key | str) -> Item:
|
| 1533 |
+
return self._value.item(key)
|
| 1534 |
+
|
| 1535 |
+
def setdefault(self, key: Key | str, default: Any) -> Any:
|
| 1536 |
+
super().setdefault(key, default)
|
| 1537 |
+
return self[key]
|
| 1538 |
+
|
| 1539 |
+
def __str__(self):
|
| 1540 |
+
return str(self.value)
|
| 1541 |
+
|
| 1542 |
+
def copy(self: AT) -> AT:
|
| 1543 |
+
return copy.copy(self)
|
| 1544 |
+
|
| 1545 |
+
def __repr__(self) -> str:
|
| 1546 |
+
return repr(self.value)
|
| 1547 |
+
|
| 1548 |
+
def __iter__(self) -> Iterator[str]:
|
| 1549 |
+
return iter(self._value)
|
| 1550 |
+
|
| 1551 |
+
def __len__(self) -> int:
|
| 1552 |
+
return len(self._value)
|
| 1553 |
+
|
| 1554 |
+
def __delitem__(self, key: Key | str) -> None:
|
| 1555 |
+
self.remove(key)
|
| 1556 |
+
|
| 1557 |
+
def __getitem__(self, key: Key | str) -> Item:
|
| 1558 |
+
return cast(Item, self._value[key])
|
| 1559 |
+
|
| 1560 |
+
def __setitem__(self, key: Key | str, value: Any) -> None:
|
| 1561 |
+
if not isinstance(value, Item):
|
| 1562 |
+
value = item(value, _parent=self)
|
| 1563 |
+
|
| 1564 |
+
is_replace = key in self
|
| 1565 |
+
self._value[key] = value
|
| 1566 |
+
|
| 1567 |
+
if key is not None:
|
| 1568 |
+
dict.__setitem__(self, key, value)
|
| 1569 |
+
|
| 1570 |
+
if is_replace:
|
| 1571 |
+
return
|
| 1572 |
+
m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
|
| 1573 |
+
if not m:
|
| 1574 |
+
return
|
| 1575 |
+
|
| 1576 |
+
indent = m.group(1)
|
| 1577 |
+
|
| 1578 |
+
if not isinstance(value, Whitespace):
|
| 1579 |
+
m = re.match("(?s)^([^ ]*)(.*)$", value.trivia.indent)
|
| 1580 |
+
if not m:
|
| 1581 |
+
value.trivia.indent = indent
|
| 1582 |
+
else:
|
| 1583 |
+
value.trivia.indent = m.group(1) + indent + m.group(2)
|
| 1584 |
+
|
| 1585 |
+
|
| 1586 |
+
class Table(AbstractTable):
|
| 1587 |
+
"""
|
| 1588 |
+
A table literal.
|
| 1589 |
+
"""
|
| 1590 |
+
|
| 1591 |
+
def __init__(
|
| 1592 |
+
self,
|
| 1593 |
+
value: container.Container,
|
| 1594 |
+
trivia: Trivia,
|
| 1595 |
+
is_aot_element: bool,
|
| 1596 |
+
is_super_table: bool | None = None,
|
| 1597 |
+
name: str | None = None,
|
| 1598 |
+
display_name: str | None = None,
|
| 1599 |
+
) -> None:
|
| 1600 |
+
super().__init__(value, trivia)
|
| 1601 |
+
|
| 1602 |
+
self.name = name
|
| 1603 |
+
self.display_name = display_name
|
| 1604 |
+
self._is_aot_element = is_aot_element
|
| 1605 |
+
self._is_super_table = is_super_table
|
| 1606 |
+
|
| 1607 |
+
@property
|
| 1608 |
+
def discriminant(self) -> int:
|
| 1609 |
+
return 9
|
| 1610 |
+
|
| 1611 |
+
def __copy__(self) -> Table:
|
| 1612 |
+
return type(self)(
|
| 1613 |
+
self._value.copy(),
|
| 1614 |
+
self._trivia.copy(),
|
| 1615 |
+
self._is_aot_element,
|
| 1616 |
+
self._is_super_table,
|
| 1617 |
+
self.name,
|
| 1618 |
+
self.display_name,
|
| 1619 |
+
)
|
| 1620 |
+
|
| 1621 |
+
def append(self, key: Key | str | None, _item: Any) -> Table:
|
| 1622 |
+
"""
|
| 1623 |
+
Appends a (key, item) to the table.
|
| 1624 |
+
"""
|
| 1625 |
+
if not isinstance(_item, Item):
|
| 1626 |
+
_item = item(_item, _parent=self)
|
| 1627 |
+
|
| 1628 |
+
self._value.append(key, _item)
|
| 1629 |
+
|
| 1630 |
+
if isinstance(key, Key):
|
| 1631 |
+
key = next(iter(key)).key
|
| 1632 |
+
_item = self._value[key]
|
| 1633 |
+
|
| 1634 |
+
if key is not None:
|
| 1635 |
+
dict.__setitem__(self, key, _item)
|
| 1636 |
+
|
| 1637 |
+
m = re.match(r"(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
|
| 1638 |
+
if not m:
|
| 1639 |
+
return self
|
| 1640 |
+
|
| 1641 |
+
indent = m.group(1)
|
| 1642 |
+
|
| 1643 |
+
if not isinstance(_item, Whitespace):
|
| 1644 |
+
m = re.match("(?s)^([^ ]*)(.*)$", _item.trivia.indent)
|
| 1645 |
+
if not m:
|
| 1646 |
+
_item.trivia.indent = indent
|
| 1647 |
+
else:
|
| 1648 |
+
_item.trivia.indent = m.group(1) + indent + m.group(2)
|
| 1649 |
+
|
| 1650 |
+
return self
|
| 1651 |
+
|
| 1652 |
+
def raw_append(self, key: Key | str | None, _item: Any) -> Table:
|
| 1653 |
+
"""Similar to :meth:`append` but does not copy indentation."""
|
| 1654 |
+
if not isinstance(_item, Item):
|
| 1655 |
+
_item = item(_item)
|
| 1656 |
+
|
| 1657 |
+
self._value.append(key, _item, validate=False)
|
| 1658 |
+
|
| 1659 |
+
if isinstance(key, Key):
|
| 1660 |
+
key = next(iter(key)).key
|
| 1661 |
+
_item = self._value[key]
|
| 1662 |
+
|
| 1663 |
+
if key is not None:
|
| 1664 |
+
dict.__setitem__(self, key, _item)
|
| 1665 |
+
|
| 1666 |
+
return self
|
| 1667 |
+
|
| 1668 |
+
def is_aot_element(self) -> bool:
|
| 1669 |
+
"""True if the table is the direct child of an AOT element."""
|
| 1670 |
+
return self._is_aot_element
|
| 1671 |
+
|
| 1672 |
+
def is_super_table(self) -> bool:
|
| 1673 |
+
"""A super table is the intermediate parent of a nested table as in [a.b.c].
|
| 1674 |
+
If true, it won't appear in the TOML representation."""
|
| 1675 |
+
if self._is_super_table is not None:
|
| 1676 |
+
return self._is_super_table
|
| 1677 |
+
if not self:
|
| 1678 |
+
return False
|
| 1679 |
+
# If the table has children and all children are tables, then it is a super table.
|
| 1680 |
+
for k, child in self.items():
|
| 1681 |
+
if not isinstance(k, Key):
|
| 1682 |
+
k = SingleKey(k)
|
| 1683 |
+
index = self.value._map[k]
|
| 1684 |
+
if isinstance(index, tuple):
|
| 1685 |
+
return False
|
| 1686 |
+
real_key = self.value.body[index][0]
|
| 1687 |
+
if (
|
| 1688 |
+
not isinstance(child, (Table, AoT))
|
| 1689 |
+
or real_key is None
|
| 1690 |
+
or real_key.is_dotted()
|
| 1691 |
+
):
|
| 1692 |
+
return False
|
| 1693 |
+
return True
|
| 1694 |
+
|
| 1695 |
+
def as_string(self) -> str:
|
| 1696 |
+
return self._value.as_string()
|
| 1697 |
+
|
| 1698 |
+
# Helpers
|
| 1699 |
+
|
| 1700 |
+
def indent(self, indent: int) -> Table:
|
| 1701 |
+
"""Indent the table with given number of spaces."""
|
| 1702 |
+
super().indent(indent)
|
| 1703 |
+
|
| 1704 |
+
m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
|
| 1705 |
+
if not m:
|
| 1706 |
+
indent_str = ""
|
| 1707 |
+
else:
|
| 1708 |
+
indent_str = m.group(1)
|
| 1709 |
+
|
| 1710 |
+
for _, item in self._value.body:
|
| 1711 |
+
if not isinstance(item, Whitespace):
|
| 1712 |
+
item.trivia.indent = indent_str + item.trivia.indent
|
| 1713 |
+
|
| 1714 |
+
return self
|
| 1715 |
+
|
| 1716 |
+
def invalidate_display_name(self):
|
| 1717 |
+
"""Call ``invalidate_display_name`` on the contained tables"""
|
| 1718 |
+
self.display_name = None
|
| 1719 |
+
|
| 1720 |
+
for child in self.values():
|
| 1721 |
+
if hasattr(child, "invalidate_display_name"):
|
| 1722 |
+
child.invalidate_display_name()
|
| 1723 |
+
|
| 1724 |
+
def _getstate(self, protocol: int = 3) -> tuple:
|
| 1725 |
+
return (
|
| 1726 |
+
self._value,
|
| 1727 |
+
self._trivia,
|
| 1728 |
+
self._is_aot_element,
|
| 1729 |
+
self._is_super_table,
|
| 1730 |
+
self.name,
|
| 1731 |
+
self.display_name,
|
| 1732 |
+
)
|
| 1733 |
+
|
| 1734 |
+
|
| 1735 |
+
class InlineTable(AbstractTable):
|
| 1736 |
+
"""
|
| 1737 |
+
An inline table literal.
|
| 1738 |
+
"""
|
| 1739 |
+
|
| 1740 |
+
def __init__(
|
| 1741 |
+
self, value: container.Container, trivia: Trivia, new: bool = False
|
| 1742 |
+
) -> None:
|
| 1743 |
+
super().__init__(value, trivia)
|
| 1744 |
+
|
| 1745 |
+
self._new = new
|
| 1746 |
+
|
| 1747 |
+
@property
|
| 1748 |
+
def discriminant(self) -> int:
|
| 1749 |
+
return 10
|
| 1750 |
+
|
| 1751 |
+
def append(self, key: Key | str | None, _item: Any) -> InlineTable:
|
| 1752 |
+
"""
|
| 1753 |
+
Appends a (key, item) to the table.
|
| 1754 |
+
"""
|
| 1755 |
+
if not isinstance(_item, Item):
|
| 1756 |
+
_item = item(_item, _parent=self)
|
| 1757 |
+
|
| 1758 |
+
if not isinstance(_item, (Whitespace, Comment)):
|
| 1759 |
+
if not _item.trivia.indent and len(self._value) > 0 and not self._new:
|
| 1760 |
+
_item.trivia.indent = " "
|
| 1761 |
+
if _item.trivia.comment:
|
| 1762 |
+
_item.trivia.comment = ""
|
| 1763 |
+
|
| 1764 |
+
self._value.append(key, _item)
|
| 1765 |
+
|
| 1766 |
+
if isinstance(key, Key):
|
| 1767 |
+
key = key.key
|
| 1768 |
+
|
| 1769 |
+
if key is not None:
|
| 1770 |
+
dict.__setitem__(self, key, _item)
|
| 1771 |
+
|
| 1772 |
+
return self
|
| 1773 |
+
|
| 1774 |
+
def as_string(self) -> str:
|
| 1775 |
+
buf = "{"
|
| 1776 |
+
last_item_idx = next(
|
| 1777 |
+
(
|
| 1778 |
+
i
|
| 1779 |
+
for i in range(len(self._value.body) - 1, -1, -1)
|
| 1780 |
+
if self._value.body[i][0] is not None
|
| 1781 |
+
),
|
| 1782 |
+
None,
|
| 1783 |
+
)
|
| 1784 |
+
for i, (k, v) in enumerate(self._value.body):
|
| 1785 |
+
if k is None:
|
| 1786 |
+
if i == len(self._value.body) - 1:
|
| 1787 |
+
if self._new:
|
| 1788 |
+
buf = buf.rstrip(", ")
|
| 1789 |
+
else:
|
| 1790 |
+
buf = buf.rstrip(",")
|
| 1791 |
+
|
| 1792 |
+
buf += v.as_string()
|
| 1793 |
+
|
| 1794 |
+
continue
|
| 1795 |
+
|
| 1796 |
+
v_trivia_trail = v.trivia.trail.replace("\n", "")
|
| 1797 |
+
buf += (
|
| 1798 |
+
f"{v.trivia.indent}"
|
| 1799 |
+
f"{k.as_string() + ('.' if k.is_dotted() else '')}"
|
| 1800 |
+
f"{k.sep}"
|
| 1801 |
+
f"{v.as_string()}"
|
| 1802 |
+
f"{v.trivia.comment}"
|
| 1803 |
+
f"{v_trivia_trail}"
|
| 1804 |
+
)
|
| 1805 |
+
|
| 1806 |
+
if last_item_idx is not None and i < last_item_idx:
|
| 1807 |
+
buf += ","
|
| 1808 |
+
if self._new:
|
| 1809 |
+
buf += " "
|
| 1810 |
+
|
| 1811 |
+
buf += "}"
|
| 1812 |
+
|
| 1813 |
+
return buf
|
| 1814 |
+
|
| 1815 |
+
def __setitem__(self, key: Key | str, value: Any) -> None:
|
| 1816 |
+
if hasattr(value, "trivia") and value.trivia.comment:
|
| 1817 |
+
value.trivia.comment = ""
|
| 1818 |
+
super().__setitem__(key, value)
|
| 1819 |
+
|
| 1820 |
+
def __copy__(self) -> InlineTable:
|
| 1821 |
+
return type(self)(self._value.copy(), self._trivia.copy(), self._new)
|
| 1822 |
+
|
| 1823 |
+
def _getstate(self, protocol: int = 3) -> tuple:
|
| 1824 |
+
return (self._value, self._trivia)
|
| 1825 |
+
|
| 1826 |
+
|
| 1827 |
+
class String(str, Item):
|
| 1828 |
+
"""
|
| 1829 |
+
A string literal.
|
| 1830 |
+
"""
|
| 1831 |
+
|
| 1832 |
+
def __new__(cls, t, value, original, trivia):
|
| 1833 |
+
return super().__new__(cls, value)
|
| 1834 |
+
|
| 1835 |
+
def __init__(self, t: StringType, _: str, original: str, trivia: Trivia) -> None:
|
| 1836 |
+
super().__init__(trivia)
|
| 1837 |
+
|
| 1838 |
+
self._t = t
|
| 1839 |
+
self._original = original
|
| 1840 |
+
|
| 1841 |
+
def unwrap(self) -> str:
|
| 1842 |
+
return str(self)
|
| 1843 |
+
|
| 1844 |
+
@property
|
| 1845 |
+
def discriminant(self) -> int:
|
| 1846 |
+
return 11
|
| 1847 |
+
|
| 1848 |
+
@property
|
| 1849 |
+
def value(self) -> str:
|
| 1850 |
+
return self
|
| 1851 |
+
|
| 1852 |
+
def as_string(self) -> str:
|
| 1853 |
+
return f"{self._t.value}{decode(self._original)}{self._t.value}"
|
| 1854 |
+
|
| 1855 |
+
def __add__(self: ItemT, other: str) -> ItemT:
|
| 1856 |
+
if not isinstance(other, str):
|
| 1857 |
+
return NotImplemented
|
| 1858 |
+
result = super().__add__(other)
|
| 1859 |
+
original = self._original + getattr(other, "_original", other)
|
| 1860 |
+
|
| 1861 |
+
return self._new(result, original)
|
| 1862 |
+
|
| 1863 |
+
def _new(self, result: str, original: str) -> String:
|
| 1864 |
+
return String(self._t, result, original, self._trivia)
|
| 1865 |
+
|
| 1866 |
+
def _getstate(self, protocol=3):
|
| 1867 |
+
return self._t, str(self), self._original, self._trivia
|
| 1868 |
+
|
| 1869 |
+
@classmethod
|
| 1870 |
+
def from_raw(cls, value: str, type_=StringType.SLB, escape=True) -> String:
|
| 1871 |
+
value = decode(value)
|
| 1872 |
+
|
| 1873 |
+
invalid = type_.invalid_sequences
|
| 1874 |
+
if any(c in value for c in invalid):
|
| 1875 |
+
raise InvalidStringError(value, invalid, type_.value)
|
| 1876 |
+
|
| 1877 |
+
escaped = type_.escaped_sequences
|
| 1878 |
+
string_value = escape_string(value, escaped) if escape and escaped else value
|
| 1879 |
+
|
| 1880 |
+
return cls(type_, decode(value), string_value, Trivia())
|
| 1881 |
+
|
| 1882 |
+
|
| 1883 |
+
class AoT(Item, _CustomList):
|
| 1884 |
+
"""
|
| 1885 |
+
An array of table literal
|
| 1886 |
+
"""
|
| 1887 |
+
|
| 1888 |
+
def __init__(
|
| 1889 |
+
self, body: list[Table], name: str | None = None, parsed: bool = False
|
| 1890 |
+
) -> None:
|
| 1891 |
+
self.name = name
|
| 1892 |
+
self._body: list[Table] = []
|
| 1893 |
+
self._parsed = parsed
|
| 1894 |
+
|
| 1895 |
+
super().__init__(Trivia(trail=""))
|
| 1896 |
+
|
| 1897 |
+
for table in body:
|
| 1898 |
+
self.append(table)
|
| 1899 |
+
|
| 1900 |
+
def unwrap(self) -> list[dict[str, Any]]:
|
| 1901 |
+
unwrapped = []
|
| 1902 |
+
for t in self._body:
|
| 1903 |
+
if hasattr(t, "unwrap"):
|
| 1904 |
+
unwrapped.append(t.unwrap())
|
| 1905 |
+
else:
|
| 1906 |
+
unwrapped.append(t)
|
| 1907 |
+
return unwrapped
|
| 1908 |
+
|
| 1909 |
+
@property
|
| 1910 |
+
def body(self) -> list[Table]:
|
| 1911 |
+
return self._body
|
| 1912 |
+
|
| 1913 |
+
@property
|
| 1914 |
+
def discriminant(self) -> int:
|
| 1915 |
+
return 12
|
| 1916 |
+
|
| 1917 |
+
@property
|
| 1918 |
+
def value(self) -> list[dict[Any, Any]]:
|
| 1919 |
+
return [v.value for v in self._body]
|
| 1920 |
+
|
| 1921 |
+
def __len__(self) -> int:
|
| 1922 |
+
return len(self._body)
|
| 1923 |
+
|
| 1924 |
+
@overload
|
| 1925 |
+
def __getitem__(self, key: slice) -> list[Table]: ...
|
| 1926 |
+
|
| 1927 |
+
@overload
|
| 1928 |
+
def __getitem__(self, key: int) -> Table: ...
|
| 1929 |
+
|
| 1930 |
+
def __getitem__(self, key):
|
| 1931 |
+
return self._body[key]
|
| 1932 |
+
|
| 1933 |
+
def __setitem__(self, key: slice | int, value: Any) -> None:
|
| 1934 |
+
self._body[key] = item(value, _parent=self)
|
| 1935 |
+
|
| 1936 |
+
def __delitem__(self, key: slice | int) -> None:
|
| 1937 |
+
del self._body[key]
|
| 1938 |
+
list.__delitem__(self, key)
|
| 1939 |
+
|
| 1940 |
+
def insert(self, index: int, value: dict) -> None:
|
| 1941 |
+
value = item(value, _parent=self)
|
| 1942 |
+
if not isinstance(value, Table):
|
| 1943 |
+
raise ValueError(f"Unsupported insert value type: {type(value)}")
|
| 1944 |
+
length = len(self)
|
| 1945 |
+
if index < 0:
|
| 1946 |
+
index += length
|
| 1947 |
+
if index < 0:
|
| 1948 |
+
index = 0
|
| 1949 |
+
elif index >= length:
|
| 1950 |
+
index = length
|
| 1951 |
+
m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
|
| 1952 |
+
if m:
|
| 1953 |
+
indent = m.group(1)
|
| 1954 |
+
|
| 1955 |
+
m = re.match("(?s)^([^ ]*)(.*)$", value.trivia.indent)
|
| 1956 |
+
if not m:
|
| 1957 |
+
value.trivia.indent = indent
|
| 1958 |
+
else:
|
| 1959 |
+
value.trivia.indent = m.group(1) + indent + m.group(2)
|
| 1960 |
+
prev_table = self._body[index - 1] if 0 < index and length else None
|
| 1961 |
+
next_table = self._body[index + 1] if index < length - 1 else None
|
| 1962 |
+
if not self._parsed:
|
| 1963 |
+
if prev_table and "\n" not in value.trivia.indent:
|
| 1964 |
+
value.trivia.indent = "\n" + value.trivia.indent
|
| 1965 |
+
if next_table and "\n" not in next_table.trivia.indent:
|
| 1966 |
+
next_table.trivia.indent = "\n" + next_table.trivia.indent
|
| 1967 |
+
self._body.insert(index, value)
|
| 1968 |
+
list.insert(self, index, value)
|
| 1969 |
+
|
| 1970 |
+
def invalidate_display_name(self):
|
| 1971 |
+
"""Call ``invalidate_display_name`` on the contained tables"""
|
| 1972 |
+
for child in self:
|
| 1973 |
+
if hasattr(child, "invalidate_display_name"):
|
| 1974 |
+
child.invalidate_display_name()
|
| 1975 |
+
|
| 1976 |
+
def as_string(self) -> str:
|
| 1977 |
+
b = ""
|
| 1978 |
+
for table in self._body:
|
| 1979 |
+
b += table.as_string()
|
| 1980 |
+
|
| 1981 |
+
return b
|
| 1982 |
+
|
| 1983 |
+
def __repr__(self) -> str:
|
| 1984 |
+
return f"<AoT {self.value}>"
|
| 1985 |
+
|
| 1986 |
+
def _getstate(self, protocol=3):
|
| 1987 |
+
return self._body, self.name, self._parsed
|
| 1988 |
+
|
| 1989 |
+
|
| 1990 |
+
class Null(Item):
|
| 1991 |
+
"""
|
| 1992 |
+
A null item.
|
| 1993 |
+
"""
|
| 1994 |
+
|
| 1995 |
+
def __init__(self) -> None:
|
| 1996 |
+
super().__init__(Trivia(trail=""))
|
| 1997 |
+
|
| 1998 |
+
def unwrap(self) -> None:
|
| 1999 |
+
return None
|
| 2000 |
+
|
| 2001 |
+
@property
|
| 2002 |
+
def discriminant(self) -> int:
|
| 2003 |
+
return -1
|
| 2004 |
+
|
| 2005 |
+
@property
|
| 2006 |
+
def value(self) -> None:
|
| 2007 |
+
return None
|
| 2008 |
+
|
| 2009 |
+
def as_string(self) -> str:
|
| 2010 |
+
return ""
|
| 2011 |
+
|
| 2012 |
+
def _getstate(self, protocol=3) -> tuple:
|
| 2013 |
+
return ()
|
miniconda3/lib/python3.13/site-packages/tomlkit/parser.py
ADDED
|
@@ -0,0 +1,1140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import re
|
| 5 |
+
import string
|
| 6 |
+
|
| 7 |
+
from tomlkit._compat import decode
|
| 8 |
+
from tomlkit._utils import RFC_3339_LOOSE
|
| 9 |
+
from tomlkit._utils import _escaped
|
| 10 |
+
from tomlkit._utils import parse_rfc3339
|
| 11 |
+
from tomlkit.container import Container
|
| 12 |
+
from tomlkit.exceptions import EmptyKeyError
|
| 13 |
+
from tomlkit.exceptions import EmptyTableNameError
|
| 14 |
+
from tomlkit.exceptions import InternalParserError
|
| 15 |
+
from tomlkit.exceptions import InvalidCharInStringError
|
| 16 |
+
from tomlkit.exceptions import InvalidControlChar
|
| 17 |
+
from tomlkit.exceptions import InvalidDateError
|
| 18 |
+
from tomlkit.exceptions import InvalidDateTimeError
|
| 19 |
+
from tomlkit.exceptions import InvalidNumberError
|
| 20 |
+
from tomlkit.exceptions import InvalidTimeError
|
| 21 |
+
from tomlkit.exceptions import InvalidUnicodeValueError
|
| 22 |
+
from tomlkit.exceptions import ParseError
|
| 23 |
+
from tomlkit.exceptions import UnexpectedCharError
|
| 24 |
+
from tomlkit.exceptions import UnexpectedEofError
|
| 25 |
+
from tomlkit.items import AoT
|
| 26 |
+
from tomlkit.items import Array
|
| 27 |
+
from tomlkit.items import Bool
|
| 28 |
+
from tomlkit.items import BoolType
|
| 29 |
+
from tomlkit.items import Comment
|
| 30 |
+
from tomlkit.items import Date
|
| 31 |
+
from tomlkit.items import DateTime
|
| 32 |
+
from tomlkit.items import Float
|
| 33 |
+
from tomlkit.items import InlineTable
|
| 34 |
+
from tomlkit.items import Integer
|
| 35 |
+
from tomlkit.items import Item
|
| 36 |
+
from tomlkit.items import Key
|
| 37 |
+
from tomlkit.items import KeyType
|
| 38 |
+
from tomlkit.items import Null
|
| 39 |
+
from tomlkit.items import SingleKey
|
| 40 |
+
from tomlkit.items import String
|
| 41 |
+
from tomlkit.items import StringType
|
| 42 |
+
from tomlkit.items import Table
|
| 43 |
+
from tomlkit.items import Time
|
| 44 |
+
from tomlkit.items import Trivia
|
| 45 |
+
from tomlkit.items import Whitespace
|
| 46 |
+
from tomlkit.source import Source
|
| 47 |
+
from tomlkit.toml_char import TOMLChar
|
| 48 |
+
from tomlkit.toml_document import TOMLDocument
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
CTRL_I = 0x09 # Tab
|
| 52 |
+
CTRL_J = 0x0A # Line feed
|
| 53 |
+
CTRL_M = 0x0D # Carriage return
|
| 54 |
+
CTRL_CHAR_LIMIT = 0x1F
|
| 55 |
+
CHR_DEL = 0x7F
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Parser:
|
| 59 |
+
"""
|
| 60 |
+
Parser for TOML documents.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, string: str | bytes) -> None:
|
| 64 |
+
# Input to parse
|
| 65 |
+
self._src = Source(decode(string))
|
| 66 |
+
|
| 67 |
+
self._aot_stack: list[Key] = []
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def _state(self):
|
| 71 |
+
return self._src.state
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def _idx(self):
|
| 75 |
+
return self._src.idx
|
| 76 |
+
|
| 77 |
+
@property
|
| 78 |
+
def _current(self):
|
| 79 |
+
return self._src.current
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def _marker(self):
|
| 83 |
+
return self._src.marker
|
| 84 |
+
|
| 85 |
+
def extract(self) -> str:
|
| 86 |
+
"""
|
| 87 |
+
Extracts the value between marker and index
|
| 88 |
+
"""
|
| 89 |
+
return self._src.extract()
|
| 90 |
+
|
| 91 |
+
def inc(self, exception: type[ParseError] | None = None) -> bool:
|
| 92 |
+
"""
|
| 93 |
+
Increments the parser if the end of the input has not been reached.
|
| 94 |
+
Returns whether or not it was able to advance.
|
| 95 |
+
"""
|
| 96 |
+
return self._src.inc(exception=exception)
|
| 97 |
+
|
| 98 |
+
def inc_n(self, n: int, exception: type[ParseError] | None = None) -> bool:
|
| 99 |
+
"""
|
| 100 |
+
Increments the parser by n characters
|
| 101 |
+
if the end of the input has not been reached.
|
| 102 |
+
"""
|
| 103 |
+
return self._src.inc_n(n=n, exception=exception)
|
| 104 |
+
|
| 105 |
+
def consume(self, chars, min=0, max=-1):
|
| 106 |
+
"""
|
| 107 |
+
Consume chars until min/max is satisfied is valid.
|
| 108 |
+
"""
|
| 109 |
+
return self._src.consume(chars=chars, min=min, max=max)
|
| 110 |
+
|
| 111 |
+
def end(self) -> bool:
|
| 112 |
+
"""
|
| 113 |
+
Returns True if the parser has reached the end of the input.
|
| 114 |
+
"""
|
| 115 |
+
return self._src.end()
|
| 116 |
+
|
| 117 |
+
def mark(self) -> None:
|
| 118 |
+
"""
|
| 119 |
+
Sets the marker to the index's current position
|
| 120 |
+
"""
|
| 121 |
+
self._src.mark()
|
| 122 |
+
|
| 123 |
+
def parse_error(self, exception=ParseError, *args, **kwargs):
|
| 124 |
+
"""
|
| 125 |
+
Creates a generic "parse error" at the current position.
|
| 126 |
+
"""
|
| 127 |
+
return self._src.parse_error(exception, *args, **kwargs)
|
| 128 |
+
|
| 129 |
+
def parse(self) -> TOMLDocument:
|
| 130 |
+
body = TOMLDocument(True)
|
| 131 |
+
|
| 132 |
+
# Take all keyvals outside of tables/AoT's.
|
| 133 |
+
while not self.end():
|
| 134 |
+
# Break out if a table is found
|
| 135 |
+
if self._current == "[":
|
| 136 |
+
break
|
| 137 |
+
|
| 138 |
+
# Otherwise, take and append one KV
|
| 139 |
+
item = self._parse_item()
|
| 140 |
+
if not item:
|
| 141 |
+
break
|
| 142 |
+
|
| 143 |
+
key, value = item
|
| 144 |
+
if (key is not None and key.is_multi()) or not self._merge_ws(value, body):
|
| 145 |
+
# We actually have a table
|
| 146 |
+
try:
|
| 147 |
+
body.append(key, value)
|
| 148 |
+
except Exception as e:
|
| 149 |
+
raise self.parse_error(ParseError, str(e)) from e
|
| 150 |
+
|
| 151 |
+
self.mark()
|
| 152 |
+
|
| 153 |
+
while not self.end():
|
| 154 |
+
key, value = self._parse_table()
|
| 155 |
+
if isinstance(value, Table) and value.is_aot_element():
|
| 156 |
+
# This is just the first table in an AoT. Parse the rest of the array
|
| 157 |
+
# along with it.
|
| 158 |
+
value = self._parse_aot(value, key)
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
body.append(key, value)
|
| 162 |
+
except Exception as e:
|
| 163 |
+
raise self.parse_error(ParseError, str(e)) from e
|
| 164 |
+
|
| 165 |
+
body.parsing(False)
|
| 166 |
+
|
| 167 |
+
return body
|
| 168 |
+
|
| 169 |
+
def _merge_ws(self, item: Item, container: Container) -> bool:
|
| 170 |
+
"""
|
| 171 |
+
Merges the given Item with the last one currently in the given Container if
|
| 172 |
+
both are whitespace items.
|
| 173 |
+
|
| 174 |
+
Returns True if the items were merged.
|
| 175 |
+
"""
|
| 176 |
+
last = container.last_item()
|
| 177 |
+
if not last:
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
if not isinstance(item, Whitespace) or not isinstance(last, Whitespace):
|
| 181 |
+
return False
|
| 182 |
+
|
| 183 |
+
start = self._idx - (len(last.s) + len(item.s))
|
| 184 |
+
container.body[-1] = (
|
| 185 |
+
container.body[-1][0],
|
| 186 |
+
Whitespace(self._src[start : self._idx]),
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
return True
|
| 190 |
+
|
| 191 |
+
def _is_child(self, parent: Key, child: Key) -> bool:
|
| 192 |
+
"""
|
| 193 |
+
Returns whether a key is strictly a child of another key.
|
| 194 |
+
AoT siblings are not considered children of one another.
|
| 195 |
+
"""
|
| 196 |
+
parent_parts = tuple(parent)
|
| 197 |
+
child_parts = tuple(child)
|
| 198 |
+
|
| 199 |
+
if parent_parts == child_parts:
|
| 200 |
+
return False
|
| 201 |
+
|
| 202 |
+
return parent_parts == child_parts[: len(parent_parts)]
|
| 203 |
+
|
| 204 |
+
def _parse_item(self) -> tuple[Key | None, Item] | None:
|
| 205 |
+
"""
|
| 206 |
+
Attempts to parse the next item and returns it, along with its key
|
| 207 |
+
if the item is value-like.
|
| 208 |
+
"""
|
| 209 |
+
self.mark()
|
| 210 |
+
with self._state as state:
|
| 211 |
+
while True:
|
| 212 |
+
c = self._current
|
| 213 |
+
if c == "\n":
|
| 214 |
+
# Found a newline; Return all whitespace found up to this point.
|
| 215 |
+
self.inc()
|
| 216 |
+
|
| 217 |
+
return None, Whitespace(self.extract())
|
| 218 |
+
elif c in " \t\r":
|
| 219 |
+
# Skip whitespace.
|
| 220 |
+
if not self.inc():
|
| 221 |
+
return None, Whitespace(self.extract())
|
| 222 |
+
elif c == "#":
|
| 223 |
+
# Found a comment, parse it
|
| 224 |
+
indent = self.extract()
|
| 225 |
+
cws, comment, trail = self._parse_comment_trail()
|
| 226 |
+
|
| 227 |
+
return None, Comment(Trivia(indent, cws, comment, trail))
|
| 228 |
+
elif c == "[":
|
| 229 |
+
# Found a table, delegate to the calling function.
|
| 230 |
+
return
|
| 231 |
+
else:
|
| 232 |
+
# Beginning of a KV pair.
|
| 233 |
+
# Return to beginning of whitespace so it gets included
|
| 234 |
+
# as indentation for the KV about to be parsed.
|
| 235 |
+
state.restore = True
|
| 236 |
+
break
|
| 237 |
+
|
| 238 |
+
return self._parse_key_value(True)
|
| 239 |
+
|
| 240 |
+
def _parse_comment_trail(self, parse_trail: bool = True) -> tuple[str, str, str]:
|
| 241 |
+
"""
|
| 242 |
+
Returns (comment_ws, comment, trail)
|
| 243 |
+
If there is no comment, comment_ws and comment will
|
| 244 |
+
simply be empty.
|
| 245 |
+
"""
|
| 246 |
+
if self.end():
|
| 247 |
+
return "", "", ""
|
| 248 |
+
|
| 249 |
+
comment = ""
|
| 250 |
+
comment_ws = ""
|
| 251 |
+
self.mark()
|
| 252 |
+
|
| 253 |
+
while True:
|
| 254 |
+
c = self._current
|
| 255 |
+
|
| 256 |
+
if c == "\n":
|
| 257 |
+
break
|
| 258 |
+
elif c == "#":
|
| 259 |
+
comment_ws = self.extract()
|
| 260 |
+
|
| 261 |
+
self.mark()
|
| 262 |
+
self.inc() # Skip #
|
| 263 |
+
|
| 264 |
+
# The comment itself
|
| 265 |
+
while not self.end() and not self._current.is_nl():
|
| 266 |
+
code = ord(self._current)
|
| 267 |
+
if code == CHR_DEL or (code <= CTRL_CHAR_LIMIT and code != CTRL_I):
|
| 268 |
+
raise self.parse_error(InvalidControlChar, code, "comments")
|
| 269 |
+
|
| 270 |
+
if not self.inc():
|
| 271 |
+
break
|
| 272 |
+
|
| 273 |
+
comment = self.extract()
|
| 274 |
+
self.mark()
|
| 275 |
+
|
| 276 |
+
break
|
| 277 |
+
elif c in " \t\r":
|
| 278 |
+
self.inc()
|
| 279 |
+
else:
|
| 280 |
+
raise self.parse_error(UnexpectedCharError, c)
|
| 281 |
+
|
| 282 |
+
if self.end():
|
| 283 |
+
break
|
| 284 |
+
|
| 285 |
+
trail = ""
|
| 286 |
+
if parse_trail:
|
| 287 |
+
while self._current.is_spaces() and self.inc():
|
| 288 |
+
pass
|
| 289 |
+
|
| 290 |
+
if self._current == "\r":
|
| 291 |
+
self.inc()
|
| 292 |
+
|
| 293 |
+
if self._current == "\n":
|
| 294 |
+
self.inc()
|
| 295 |
+
|
| 296 |
+
if self._idx != self._marker or self._current.is_ws():
|
| 297 |
+
trail = self.extract()
|
| 298 |
+
|
| 299 |
+
return comment_ws, comment, trail
|
| 300 |
+
|
| 301 |
+
def _parse_key_value(self, parse_comment: bool = False) -> tuple[Key, Item]:
|
| 302 |
+
# Leading indent
|
| 303 |
+
self.mark()
|
| 304 |
+
|
| 305 |
+
while self._current.is_spaces() and self.inc():
|
| 306 |
+
pass
|
| 307 |
+
|
| 308 |
+
indent = self.extract()
|
| 309 |
+
|
| 310 |
+
# Key
|
| 311 |
+
key = self._parse_key()
|
| 312 |
+
|
| 313 |
+
self.mark()
|
| 314 |
+
|
| 315 |
+
found_equals = self._current == "="
|
| 316 |
+
while self._current.is_kv_sep() and self.inc():
|
| 317 |
+
if self._current == "=":
|
| 318 |
+
if found_equals:
|
| 319 |
+
raise self.parse_error(UnexpectedCharError, "=")
|
| 320 |
+
else:
|
| 321 |
+
found_equals = True
|
| 322 |
+
if not found_equals:
|
| 323 |
+
raise self.parse_error(UnexpectedCharError, self._current)
|
| 324 |
+
|
| 325 |
+
if not key.sep:
|
| 326 |
+
key.sep = self.extract()
|
| 327 |
+
else:
|
| 328 |
+
key.sep += self.extract()
|
| 329 |
+
|
| 330 |
+
# Value
|
| 331 |
+
val = self._parse_value()
|
| 332 |
+
# Comment
|
| 333 |
+
if parse_comment:
|
| 334 |
+
cws, comment, trail = self._parse_comment_trail()
|
| 335 |
+
meta = val.trivia
|
| 336 |
+
if not meta.comment_ws:
|
| 337 |
+
meta.comment_ws = cws
|
| 338 |
+
|
| 339 |
+
meta.comment = comment
|
| 340 |
+
meta.trail = trail
|
| 341 |
+
else:
|
| 342 |
+
val.trivia.trail = ""
|
| 343 |
+
|
| 344 |
+
val.trivia.indent = indent
|
| 345 |
+
|
| 346 |
+
return key, val
|
| 347 |
+
|
| 348 |
+
def _parse_key(self) -> Key:
|
| 349 |
+
"""
|
| 350 |
+
Parses a Key at the current position;
|
| 351 |
+
WS before the key must be exhausted first at the callsite.
|
| 352 |
+
"""
|
| 353 |
+
self.mark()
|
| 354 |
+
while self._current.is_spaces() and self.inc():
|
| 355 |
+
# Skip any leading whitespace
|
| 356 |
+
pass
|
| 357 |
+
if self._current in "\"'":
|
| 358 |
+
return self._parse_quoted_key()
|
| 359 |
+
else:
|
| 360 |
+
return self._parse_bare_key()
|
| 361 |
+
|
| 362 |
+
def _parse_quoted_key(self) -> Key:
|
| 363 |
+
"""
|
| 364 |
+
Parses a key enclosed in either single or double quotes.
|
| 365 |
+
"""
|
| 366 |
+
# Extract the leading whitespace
|
| 367 |
+
original = self.extract()
|
| 368 |
+
quote_style = self._current
|
| 369 |
+
key_type = next((t for t in KeyType if t.value == quote_style), None)
|
| 370 |
+
|
| 371 |
+
if key_type is None:
|
| 372 |
+
raise RuntimeError("Should not have entered _parse_quoted_key()")
|
| 373 |
+
|
| 374 |
+
key_str = self._parse_string(
|
| 375 |
+
StringType.SLB if key_type == KeyType.Basic else StringType.SLL
|
| 376 |
+
)
|
| 377 |
+
if key_str._t.is_multiline():
|
| 378 |
+
raise self.parse_error(UnexpectedCharError, key_str._t.value)
|
| 379 |
+
original += key_str.as_string()
|
| 380 |
+
self.mark()
|
| 381 |
+
while self._current.is_spaces() and self.inc():
|
| 382 |
+
pass
|
| 383 |
+
original += self.extract()
|
| 384 |
+
key = SingleKey(str(key_str), t=key_type, sep="", original=original)
|
| 385 |
+
if self._current == ".":
|
| 386 |
+
self.inc()
|
| 387 |
+
key = key.concat(self._parse_key())
|
| 388 |
+
|
| 389 |
+
return key
|
| 390 |
+
|
| 391 |
+
def _parse_bare_key(self) -> Key:
|
| 392 |
+
"""
|
| 393 |
+
Parses a bare key.
|
| 394 |
+
"""
|
| 395 |
+
while (
|
| 396 |
+
self._current.is_bare_key_char() or self._current.is_spaces()
|
| 397 |
+
) and self.inc():
|
| 398 |
+
pass
|
| 399 |
+
|
| 400 |
+
original = self.extract()
|
| 401 |
+
key = original.strip()
|
| 402 |
+
if not key:
|
| 403 |
+
# Empty key
|
| 404 |
+
raise self.parse_error(EmptyKeyError)
|
| 405 |
+
|
| 406 |
+
if " " in key:
|
| 407 |
+
# Bare key with spaces in it
|
| 408 |
+
raise self.parse_error(ParseError, f'Invalid key "{key}"')
|
| 409 |
+
|
| 410 |
+
key = SingleKey(key, KeyType.Bare, "", original)
|
| 411 |
+
|
| 412 |
+
if self._current == ".":
|
| 413 |
+
self.inc()
|
| 414 |
+
key = key.concat(self._parse_key())
|
| 415 |
+
|
| 416 |
+
return key
|
| 417 |
+
|
| 418 |
+
def _parse_value(self) -> Item:
|
| 419 |
+
"""
|
| 420 |
+
Attempts to parse a value at the current position.
|
| 421 |
+
"""
|
| 422 |
+
self.mark()
|
| 423 |
+
c = self._current
|
| 424 |
+
trivia = Trivia()
|
| 425 |
+
|
| 426 |
+
if c == StringType.SLB.value:
|
| 427 |
+
return self._parse_basic_string()
|
| 428 |
+
elif c == StringType.SLL.value:
|
| 429 |
+
return self._parse_literal_string()
|
| 430 |
+
elif c == BoolType.TRUE.value[0]:
|
| 431 |
+
return self._parse_true()
|
| 432 |
+
elif c == BoolType.FALSE.value[0]:
|
| 433 |
+
return self._parse_false()
|
| 434 |
+
elif c == "[":
|
| 435 |
+
return self._parse_array()
|
| 436 |
+
elif c == "{":
|
| 437 |
+
return self._parse_inline_table()
|
| 438 |
+
elif c in "+-" or self._peek(4) in {
|
| 439 |
+
"+inf",
|
| 440 |
+
"-inf",
|
| 441 |
+
"inf",
|
| 442 |
+
"+nan",
|
| 443 |
+
"-nan",
|
| 444 |
+
"nan",
|
| 445 |
+
}:
|
| 446 |
+
# Number
|
| 447 |
+
while self._current not in " \t\n\r#,]}" and self.inc():
|
| 448 |
+
pass
|
| 449 |
+
|
| 450 |
+
raw = self.extract()
|
| 451 |
+
|
| 452 |
+
item = self._parse_number(raw, trivia)
|
| 453 |
+
if item is not None:
|
| 454 |
+
return item
|
| 455 |
+
|
| 456 |
+
raise self.parse_error(InvalidNumberError)
|
| 457 |
+
elif c in string.digits:
|
| 458 |
+
# Integer, Float, Date, Time or DateTime
|
| 459 |
+
while self._current not in " \t\n\r#,]}" and self.inc():
|
| 460 |
+
pass
|
| 461 |
+
|
| 462 |
+
raw = self.extract()
|
| 463 |
+
|
| 464 |
+
m = RFC_3339_LOOSE.match(raw)
|
| 465 |
+
if m:
|
| 466 |
+
if m.group(1) and m.group(5):
|
| 467 |
+
# datetime
|
| 468 |
+
try:
|
| 469 |
+
dt = parse_rfc3339(raw)
|
| 470 |
+
assert isinstance(dt, datetime.datetime)
|
| 471 |
+
return DateTime(
|
| 472 |
+
dt.year,
|
| 473 |
+
dt.month,
|
| 474 |
+
dt.day,
|
| 475 |
+
dt.hour,
|
| 476 |
+
dt.minute,
|
| 477 |
+
dt.second,
|
| 478 |
+
dt.microsecond,
|
| 479 |
+
dt.tzinfo,
|
| 480 |
+
trivia,
|
| 481 |
+
raw,
|
| 482 |
+
)
|
| 483 |
+
except ValueError:
|
| 484 |
+
raise self.parse_error(InvalidDateTimeError) from None
|
| 485 |
+
|
| 486 |
+
if m.group(1):
|
| 487 |
+
try:
|
| 488 |
+
dt = parse_rfc3339(raw)
|
| 489 |
+
assert isinstance(dt, datetime.date)
|
| 490 |
+
date = Date(dt.year, dt.month, dt.day, trivia, raw)
|
| 491 |
+
self.mark()
|
| 492 |
+
while self._current not in "\t\n\r#,]}" and self.inc():
|
| 493 |
+
pass
|
| 494 |
+
|
| 495 |
+
time_raw = self.extract()
|
| 496 |
+
time_part = time_raw.rstrip()
|
| 497 |
+
trivia.comment_ws = time_raw[len(time_part) :]
|
| 498 |
+
if not time_part:
|
| 499 |
+
return date
|
| 500 |
+
|
| 501 |
+
dt = parse_rfc3339(raw + time_part)
|
| 502 |
+
assert isinstance(dt, datetime.datetime)
|
| 503 |
+
return DateTime(
|
| 504 |
+
dt.year,
|
| 505 |
+
dt.month,
|
| 506 |
+
dt.day,
|
| 507 |
+
dt.hour,
|
| 508 |
+
dt.minute,
|
| 509 |
+
dt.second,
|
| 510 |
+
dt.microsecond,
|
| 511 |
+
dt.tzinfo,
|
| 512 |
+
trivia,
|
| 513 |
+
raw + time_part,
|
| 514 |
+
)
|
| 515 |
+
except ValueError:
|
| 516 |
+
raise self.parse_error(InvalidDateError) from None
|
| 517 |
+
|
| 518 |
+
if m.group(5):
|
| 519 |
+
try:
|
| 520 |
+
t = parse_rfc3339(raw)
|
| 521 |
+
assert isinstance(t, datetime.time)
|
| 522 |
+
return Time(
|
| 523 |
+
t.hour,
|
| 524 |
+
t.minute,
|
| 525 |
+
t.second,
|
| 526 |
+
t.microsecond,
|
| 527 |
+
t.tzinfo,
|
| 528 |
+
trivia,
|
| 529 |
+
raw,
|
| 530 |
+
)
|
| 531 |
+
except ValueError:
|
| 532 |
+
raise self.parse_error(InvalidTimeError) from None
|
| 533 |
+
|
| 534 |
+
item = self._parse_number(raw, trivia)
|
| 535 |
+
if item is not None:
|
| 536 |
+
return item
|
| 537 |
+
|
| 538 |
+
raise self.parse_error(InvalidNumberError)
|
| 539 |
+
else:
|
| 540 |
+
raise self.parse_error(UnexpectedCharError, c)
|
| 541 |
+
|
| 542 |
+
def _parse_true(self):
|
| 543 |
+
return self._parse_bool(BoolType.TRUE)
|
| 544 |
+
|
| 545 |
+
def _parse_false(self):
|
| 546 |
+
return self._parse_bool(BoolType.FALSE)
|
| 547 |
+
|
| 548 |
+
def _parse_bool(self, style: BoolType) -> Bool:
|
| 549 |
+
with self._state:
|
| 550 |
+
style = BoolType(style)
|
| 551 |
+
|
| 552 |
+
# only keep parsing for bool if the characters match the style
|
| 553 |
+
# try consuming rest of chars in style
|
| 554 |
+
for c in style:
|
| 555 |
+
self.consume(c, min=1, max=1)
|
| 556 |
+
|
| 557 |
+
return Bool(style, Trivia())
|
| 558 |
+
|
| 559 |
+
def _parse_array(self) -> Array:
|
| 560 |
+
# Consume opening bracket, EOF here is an issue (middle of array)
|
| 561 |
+
self.inc(exception=UnexpectedEofError)
|
| 562 |
+
|
| 563 |
+
elems: list[Item] = []
|
| 564 |
+
prev_value = None
|
| 565 |
+
while True:
|
| 566 |
+
# consume whitespace
|
| 567 |
+
mark = self._idx
|
| 568 |
+
self.consume(TOMLChar.SPACES + TOMLChar.NL)
|
| 569 |
+
indent = self._src[mark : self._idx]
|
| 570 |
+
newline = set(TOMLChar.NL) & set(indent)
|
| 571 |
+
if newline:
|
| 572 |
+
elems.append(Whitespace(indent))
|
| 573 |
+
continue
|
| 574 |
+
|
| 575 |
+
# consume comment
|
| 576 |
+
if self._current == "#":
|
| 577 |
+
cws, comment, trail = self._parse_comment_trail(parse_trail=False)
|
| 578 |
+
elems.append(Comment(Trivia(indent, cws, comment, trail)))
|
| 579 |
+
continue
|
| 580 |
+
|
| 581 |
+
# consume indent
|
| 582 |
+
if indent:
|
| 583 |
+
elems.append(Whitespace(indent))
|
| 584 |
+
continue
|
| 585 |
+
|
| 586 |
+
# consume value
|
| 587 |
+
if not prev_value:
|
| 588 |
+
try:
|
| 589 |
+
elems.append(self._parse_value())
|
| 590 |
+
prev_value = True
|
| 591 |
+
continue
|
| 592 |
+
except UnexpectedCharError:
|
| 593 |
+
pass
|
| 594 |
+
|
| 595 |
+
# consume comma
|
| 596 |
+
if prev_value and self._current == ",":
|
| 597 |
+
self.inc(exception=UnexpectedEofError)
|
| 598 |
+
# If the previous item is Whitespace, add to it
|
| 599 |
+
if isinstance(elems[-1], Whitespace):
|
| 600 |
+
elems[-1]._s = elems[-1].s + ","
|
| 601 |
+
else:
|
| 602 |
+
elems.append(Whitespace(","))
|
| 603 |
+
prev_value = False
|
| 604 |
+
continue
|
| 605 |
+
|
| 606 |
+
# consume closing bracket
|
| 607 |
+
if self._current == "]":
|
| 608 |
+
# consume closing bracket, EOF here doesn't matter
|
| 609 |
+
self.inc()
|
| 610 |
+
break
|
| 611 |
+
|
| 612 |
+
raise self.parse_error(UnexpectedCharError, self._current)
|
| 613 |
+
|
| 614 |
+
try:
|
| 615 |
+
res = Array(elems, Trivia())
|
| 616 |
+
except ValueError:
|
| 617 |
+
pass
|
| 618 |
+
else:
|
| 619 |
+
return res
|
| 620 |
+
|
| 621 |
+
def _parse_inline_table(self) -> InlineTable:
|
| 622 |
+
# consume opening bracket, EOF here is an issue (middle of array)
|
| 623 |
+
self.inc(exception=UnexpectedEofError)
|
| 624 |
+
|
| 625 |
+
elems = Container(True)
|
| 626 |
+
trailing_comma = None
|
| 627 |
+
while True:
|
| 628 |
+
# consume leading whitespace
|
| 629 |
+
mark = self._idx
|
| 630 |
+
self.consume(TOMLChar.SPACES)
|
| 631 |
+
raw = self._src[mark : self._idx]
|
| 632 |
+
if raw:
|
| 633 |
+
elems.add(Whitespace(raw))
|
| 634 |
+
|
| 635 |
+
if not trailing_comma:
|
| 636 |
+
# None: empty inline table
|
| 637 |
+
# False: previous key-value pair was not followed by a comma
|
| 638 |
+
if self._current == "}":
|
| 639 |
+
# consume closing bracket, EOF here doesn't matter
|
| 640 |
+
self.inc()
|
| 641 |
+
break
|
| 642 |
+
|
| 643 |
+
if trailing_comma is False or (
|
| 644 |
+
trailing_comma is None and self._current == ","
|
| 645 |
+
):
|
| 646 |
+
# Either the previous key-value pair was not followed by a comma
|
| 647 |
+
# or the table has an unexpected leading comma.
|
| 648 |
+
raise self.parse_error(UnexpectedCharError, self._current)
|
| 649 |
+
else:
|
| 650 |
+
# True: previous key-value pair was followed by a comma
|
| 651 |
+
if self._current == "}" or self._current == ",":
|
| 652 |
+
raise self.parse_error(UnexpectedCharError, self._current)
|
| 653 |
+
|
| 654 |
+
key, val = self._parse_key_value(False)
|
| 655 |
+
elems.add(key, val)
|
| 656 |
+
|
| 657 |
+
# consume trailing whitespace
|
| 658 |
+
mark = self._idx
|
| 659 |
+
self.consume(TOMLChar.SPACES)
|
| 660 |
+
raw = self._src[mark : self._idx]
|
| 661 |
+
if raw:
|
| 662 |
+
elems.add(Whitespace(raw))
|
| 663 |
+
|
| 664 |
+
# consume trailing comma
|
| 665 |
+
trailing_comma = self._current == ","
|
| 666 |
+
if trailing_comma:
|
| 667 |
+
# consume closing bracket, EOF here is an issue (middle of inline table)
|
| 668 |
+
self.inc(exception=UnexpectedEofError)
|
| 669 |
+
|
| 670 |
+
return InlineTable(elems, Trivia())
|
| 671 |
+
|
| 672 |
+
def _parse_number(self, raw: str, trivia: Trivia) -> Item | None:
|
| 673 |
+
# Leading zeros are not allowed
|
| 674 |
+
sign = ""
|
| 675 |
+
if raw.startswith(("+", "-")):
|
| 676 |
+
sign = raw[0]
|
| 677 |
+
raw = raw[1:]
|
| 678 |
+
|
| 679 |
+
if len(raw) > 1 and (
|
| 680 |
+
(raw.startswith("0") and not raw.startswith(("0.", "0o", "0x", "0b", "0e")))
|
| 681 |
+
or (sign and raw.startswith("."))
|
| 682 |
+
):
|
| 683 |
+
return None
|
| 684 |
+
|
| 685 |
+
if raw.startswith(("0o", "0x", "0b")) and sign:
|
| 686 |
+
return None
|
| 687 |
+
|
| 688 |
+
digits = "[0-9]"
|
| 689 |
+
base = 10
|
| 690 |
+
if raw.startswith("0b"):
|
| 691 |
+
digits = "[01]"
|
| 692 |
+
base = 2
|
| 693 |
+
elif raw.startswith("0o"):
|
| 694 |
+
digits = "[0-7]"
|
| 695 |
+
base = 8
|
| 696 |
+
elif raw.startswith("0x"):
|
| 697 |
+
digits = "[0-9a-f]"
|
| 698 |
+
base = 16
|
| 699 |
+
|
| 700 |
+
# Underscores should be surrounded by digits
|
| 701 |
+
clean = re.sub(f"(?i)(?<={digits})_(?={digits})", "", raw).lower()
|
| 702 |
+
|
| 703 |
+
if "_" in clean:
|
| 704 |
+
return None
|
| 705 |
+
|
| 706 |
+
if clean.endswith(".") or (
|
| 707 |
+
not clean.startswith("0x") and clean.split("e", 1)[0].endswith(".")
|
| 708 |
+
):
|
| 709 |
+
return None
|
| 710 |
+
|
| 711 |
+
try:
|
| 712 |
+
return Integer(int(sign + clean, base), trivia, sign + raw)
|
| 713 |
+
except ValueError:
|
| 714 |
+
try:
|
| 715 |
+
return Float(float(sign + clean), trivia, sign + raw)
|
| 716 |
+
except ValueError:
|
| 717 |
+
return None
|
| 718 |
+
|
| 719 |
+
def _parse_literal_string(self) -> String:
|
| 720 |
+
with self._state:
|
| 721 |
+
return self._parse_string(StringType.SLL)
|
| 722 |
+
|
| 723 |
+
def _parse_basic_string(self) -> String:
|
| 724 |
+
with self._state:
|
| 725 |
+
return self._parse_string(StringType.SLB)
|
| 726 |
+
|
| 727 |
+
def _parse_escaped_char(self, multiline):
|
| 728 |
+
if multiline and self._current.is_ws():
|
| 729 |
+
# When the last non-whitespace character on a line is
|
| 730 |
+
# a \, it will be trimmed along with all whitespace
|
| 731 |
+
# (including newlines) up to the next non-whitespace
|
| 732 |
+
# character or closing delimiter.
|
| 733 |
+
# """\
|
| 734 |
+
# hello \
|
| 735 |
+
# world"""
|
| 736 |
+
tmp = ""
|
| 737 |
+
while self._current.is_ws():
|
| 738 |
+
tmp += self._current
|
| 739 |
+
# consume the whitespace, EOF here is an issue
|
| 740 |
+
# (middle of string)
|
| 741 |
+
self.inc(exception=UnexpectedEofError)
|
| 742 |
+
continue
|
| 743 |
+
|
| 744 |
+
# the escape followed by whitespace must have a newline
|
| 745 |
+
# before any other chars
|
| 746 |
+
if "\n" not in tmp:
|
| 747 |
+
raise self.parse_error(InvalidCharInStringError, self._current)
|
| 748 |
+
|
| 749 |
+
return ""
|
| 750 |
+
|
| 751 |
+
if self._current in _escaped:
|
| 752 |
+
c = _escaped[self._current]
|
| 753 |
+
|
| 754 |
+
# consume this char, EOF here is an issue (middle of string)
|
| 755 |
+
self.inc(exception=UnexpectedEofError)
|
| 756 |
+
|
| 757 |
+
return c
|
| 758 |
+
|
| 759 |
+
if self._current in {"u", "U"}:
|
| 760 |
+
# this needs to be a unicode
|
| 761 |
+
u, ue = self._peek_unicode(self._current == "U")
|
| 762 |
+
if u is not None:
|
| 763 |
+
# consume the U char and the unicode value
|
| 764 |
+
self.inc_n(len(ue) + 1)
|
| 765 |
+
|
| 766 |
+
return u
|
| 767 |
+
|
| 768 |
+
raise self.parse_error(InvalidUnicodeValueError)
|
| 769 |
+
|
| 770 |
+
raise self.parse_error(InvalidCharInStringError, self._current)
|
| 771 |
+
|
| 772 |
+
def _parse_string(self, delim: StringType) -> String:
|
| 773 |
+
# only keep parsing for string if the current character matches the delim
|
| 774 |
+
if self._current != delim.unit:
|
| 775 |
+
raise self.parse_error(
|
| 776 |
+
InternalParserError,
|
| 777 |
+
f"Invalid character for string type {delim}",
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
# consume the opening/first delim, EOF here is an issue
|
| 781 |
+
# (middle of string or middle of delim)
|
| 782 |
+
self.inc(exception=UnexpectedEofError)
|
| 783 |
+
|
| 784 |
+
if self._current == delim.unit:
|
| 785 |
+
# consume the closing/second delim, we do not care if EOF occurs as
|
| 786 |
+
# that would simply imply an empty single line string
|
| 787 |
+
if not self.inc() or self._current != delim.unit:
|
| 788 |
+
# Empty string
|
| 789 |
+
return String(delim, "", "", Trivia())
|
| 790 |
+
|
| 791 |
+
# consume the third delim, EOF here is an issue (middle of string)
|
| 792 |
+
self.inc(exception=UnexpectedEofError)
|
| 793 |
+
|
| 794 |
+
delim = delim.toggle() # convert delim to multi delim
|
| 795 |
+
|
| 796 |
+
self.mark() # to extract the original string with whitespace and all
|
| 797 |
+
value = ""
|
| 798 |
+
|
| 799 |
+
# A newline immediately following the opening delimiter will be trimmed.
|
| 800 |
+
if delim.is_multiline():
|
| 801 |
+
if self._current == "\n":
|
| 802 |
+
# consume the newline, EOF here is an issue (middle of string)
|
| 803 |
+
self.inc(exception=UnexpectedEofError)
|
| 804 |
+
else:
|
| 805 |
+
cur = self._current
|
| 806 |
+
with self._state(restore=True):
|
| 807 |
+
if self.inc():
|
| 808 |
+
cur += self._current
|
| 809 |
+
if cur == "\r\n":
|
| 810 |
+
self.inc_n(2, exception=UnexpectedEofError)
|
| 811 |
+
|
| 812 |
+
escaped = False # whether the previous key was ESCAPE
|
| 813 |
+
while True:
|
| 814 |
+
code = ord(self._current)
|
| 815 |
+
if (
|
| 816 |
+
delim.is_singleline()
|
| 817 |
+
and not escaped
|
| 818 |
+
and (code == CHR_DEL or (code <= CTRL_CHAR_LIMIT and code != CTRL_I))
|
| 819 |
+
) or (
|
| 820 |
+
delim.is_multiline()
|
| 821 |
+
and not escaped
|
| 822 |
+
and (
|
| 823 |
+
code == CHR_DEL
|
| 824 |
+
or (
|
| 825 |
+
code <= CTRL_CHAR_LIMIT and code not in [CTRL_I, CTRL_J, CTRL_M]
|
| 826 |
+
)
|
| 827 |
+
)
|
| 828 |
+
):
|
| 829 |
+
raise self.parse_error(InvalidControlChar, code, "strings")
|
| 830 |
+
elif not escaped and self._current == delim.unit:
|
| 831 |
+
# try to process current as a closing delim
|
| 832 |
+
original = self.extract()
|
| 833 |
+
|
| 834 |
+
close = ""
|
| 835 |
+
if delim.is_multiline():
|
| 836 |
+
# Consume the delimiters to see if we are at the end of the string
|
| 837 |
+
close = ""
|
| 838 |
+
while self._current == delim.unit:
|
| 839 |
+
close += self._current
|
| 840 |
+
self.inc()
|
| 841 |
+
|
| 842 |
+
if len(close) < 3:
|
| 843 |
+
# Not a triple quote, leave in result as-is.
|
| 844 |
+
# Adding back the characters we already consumed
|
| 845 |
+
value += close
|
| 846 |
+
continue
|
| 847 |
+
|
| 848 |
+
if len(close) == 3:
|
| 849 |
+
# We are at the end of the string
|
| 850 |
+
return String(delim, value, original, Trivia())
|
| 851 |
+
|
| 852 |
+
if len(close) >= 6:
|
| 853 |
+
raise self.parse_error(InvalidCharInStringError, self._current)
|
| 854 |
+
|
| 855 |
+
value += close[:-3]
|
| 856 |
+
original += close[:-3]
|
| 857 |
+
|
| 858 |
+
return String(delim, value, original, Trivia())
|
| 859 |
+
else:
|
| 860 |
+
# consume the closing delim, we do not care if EOF occurs as
|
| 861 |
+
# that would simply imply the end of self._src
|
| 862 |
+
self.inc()
|
| 863 |
+
|
| 864 |
+
return String(delim, value, original, Trivia())
|
| 865 |
+
elif delim.is_basic() and escaped:
|
| 866 |
+
# attempt to parse the current char as an escaped value, an exception
|
| 867 |
+
# is raised if this fails
|
| 868 |
+
value += self._parse_escaped_char(delim.is_multiline())
|
| 869 |
+
|
| 870 |
+
# no longer escaped
|
| 871 |
+
escaped = False
|
| 872 |
+
elif delim.is_basic() and self._current == "\\":
|
| 873 |
+
# the next char is being escaped
|
| 874 |
+
escaped = True
|
| 875 |
+
|
| 876 |
+
# consume this char, EOF here is an issue (middle of string)
|
| 877 |
+
self.inc(exception=UnexpectedEofError)
|
| 878 |
+
else:
|
| 879 |
+
# this is either a literal string where we keep everything as is,
|
| 880 |
+
# or this is not a special escaped char in a basic string
|
| 881 |
+
value += self._current
|
| 882 |
+
|
| 883 |
+
# consume this char, EOF here is an issue (middle of string)
|
| 884 |
+
self.inc(exception=UnexpectedEofError)
|
| 885 |
+
|
| 886 |
+
def _parse_table(
|
| 887 |
+
self, parent_name: Key | None = None, parent: Table | None = None
|
| 888 |
+
) -> tuple[Key, Table | AoT]:
|
| 889 |
+
"""
|
| 890 |
+
Parses a table element.
|
| 891 |
+
"""
|
| 892 |
+
if self._current != "[":
|
| 893 |
+
raise self.parse_error(
|
| 894 |
+
InternalParserError, "_parse_table() called on non-bracket character."
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
indent = self.extract()
|
| 898 |
+
self.inc() # Skip opening bracket
|
| 899 |
+
|
| 900 |
+
if self.end():
|
| 901 |
+
raise self.parse_error(UnexpectedEofError)
|
| 902 |
+
|
| 903 |
+
is_aot = False
|
| 904 |
+
if self._current == "[":
|
| 905 |
+
if not self.inc():
|
| 906 |
+
raise self.parse_error(UnexpectedEofError)
|
| 907 |
+
|
| 908 |
+
is_aot = True
|
| 909 |
+
try:
|
| 910 |
+
key = self._parse_key()
|
| 911 |
+
except EmptyKeyError:
|
| 912 |
+
raise self.parse_error(EmptyTableNameError) from None
|
| 913 |
+
if self.end():
|
| 914 |
+
raise self.parse_error(UnexpectedEofError)
|
| 915 |
+
elif self._current != "]":
|
| 916 |
+
raise self.parse_error(UnexpectedCharError, self._current)
|
| 917 |
+
|
| 918 |
+
key.sep = ""
|
| 919 |
+
full_key = key
|
| 920 |
+
name_parts = tuple(key)
|
| 921 |
+
if any(" " in part.key.strip() and part.is_bare() for part in name_parts):
|
| 922 |
+
raise self.parse_error(
|
| 923 |
+
ParseError, f'Invalid table name "{full_key.as_string()}"'
|
| 924 |
+
)
|
| 925 |
+
|
| 926 |
+
missing_table = False
|
| 927 |
+
if parent_name:
|
| 928 |
+
parent_name_parts = tuple(parent_name)
|
| 929 |
+
else:
|
| 930 |
+
parent_name_parts = ()
|
| 931 |
+
|
| 932 |
+
if len(name_parts) > len(parent_name_parts) + 1:
|
| 933 |
+
missing_table = True
|
| 934 |
+
|
| 935 |
+
name_parts = name_parts[len(parent_name_parts) :]
|
| 936 |
+
|
| 937 |
+
values = Container(True)
|
| 938 |
+
|
| 939 |
+
self.inc() # Skip closing bracket
|
| 940 |
+
if is_aot:
|
| 941 |
+
# TODO: Verify close bracket
|
| 942 |
+
self.inc()
|
| 943 |
+
|
| 944 |
+
cws, comment, trail = self._parse_comment_trail()
|
| 945 |
+
|
| 946 |
+
result = Null()
|
| 947 |
+
table = Table(
|
| 948 |
+
values,
|
| 949 |
+
Trivia(indent, cws, comment, trail),
|
| 950 |
+
is_aot,
|
| 951 |
+
name=name_parts[0].key if name_parts else key.key,
|
| 952 |
+
display_name=full_key.as_string(),
|
| 953 |
+
is_super_table=False,
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
+
if len(name_parts) > 1:
|
| 957 |
+
if missing_table:
|
| 958 |
+
# Missing super table
|
| 959 |
+
# i.e. a table initialized like this: [foo.bar]
|
| 960 |
+
# without initializing [foo]
|
| 961 |
+
#
|
| 962 |
+
# So we have to create the parent tables
|
| 963 |
+
table = Table(
|
| 964 |
+
Container(True),
|
| 965 |
+
Trivia("", cws, comment, trail),
|
| 966 |
+
is_aot and name_parts[0] in self._aot_stack,
|
| 967 |
+
is_super_table=True,
|
| 968 |
+
name=name_parts[0].key,
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
result = table
|
| 972 |
+
key = name_parts[0]
|
| 973 |
+
|
| 974 |
+
for i, _name in enumerate(name_parts[1:]):
|
| 975 |
+
child = table.get(
|
| 976 |
+
_name,
|
| 977 |
+
Table(
|
| 978 |
+
Container(True),
|
| 979 |
+
Trivia(indent, cws, comment, trail),
|
| 980 |
+
is_aot and i == len(name_parts) - 2,
|
| 981 |
+
is_super_table=i < len(name_parts) - 2,
|
| 982 |
+
name=_name.key,
|
| 983 |
+
display_name=(
|
| 984 |
+
full_key.as_string() if i == len(name_parts) - 2 else None
|
| 985 |
+
),
|
| 986 |
+
),
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
if is_aot and i == len(name_parts) - 2:
|
| 990 |
+
table.raw_append(_name, AoT([child], name=table.name, parsed=True))
|
| 991 |
+
else:
|
| 992 |
+
table.raw_append(_name, child)
|
| 993 |
+
|
| 994 |
+
table = child
|
| 995 |
+
values = table.value
|
| 996 |
+
else:
|
| 997 |
+
if name_parts:
|
| 998 |
+
key = name_parts[0]
|
| 999 |
+
|
| 1000 |
+
while not self.end():
|
| 1001 |
+
item = self._parse_item()
|
| 1002 |
+
if item:
|
| 1003 |
+
_key, item = item
|
| 1004 |
+
if not self._merge_ws(item, values):
|
| 1005 |
+
table.raw_append(_key, item)
|
| 1006 |
+
else:
|
| 1007 |
+
if self._current == "[":
|
| 1008 |
+
_, key_next = self._peek_table()
|
| 1009 |
+
|
| 1010 |
+
if self._is_child(full_key, key_next):
|
| 1011 |
+
key_next, table_next = self._parse_table(full_key, table)
|
| 1012 |
+
|
| 1013 |
+
table.raw_append(key_next, table_next)
|
| 1014 |
+
|
| 1015 |
+
# Picking up any sibling
|
| 1016 |
+
while not self.end():
|
| 1017 |
+
_, key_next = self._peek_table()
|
| 1018 |
+
|
| 1019 |
+
if not self._is_child(full_key, key_next):
|
| 1020 |
+
break
|
| 1021 |
+
|
| 1022 |
+
key_next, table_next = self._parse_table(full_key, table)
|
| 1023 |
+
|
| 1024 |
+
table.raw_append(key_next, table_next)
|
| 1025 |
+
|
| 1026 |
+
break
|
| 1027 |
+
else:
|
| 1028 |
+
raise self.parse_error(
|
| 1029 |
+
InternalParserError,
|
| 1030 |
+
"_parse_item() returned None on a non-bracket character.",
|
| 1031 |
+
)
|
| 1032 |
+
table.value._validate_out_of_order_table()
|
| 1033 |
+
if isinstance(result, Null):
|
| 1034 |
+
result = table
|
| 1035 |
+
|
| 1036 |
+
if is_aot and (not self._aot_stack or full_key != self._aot_stack[-1]):
|
| 1037 |
+
result = self._parse_aot(result, full_key)
|
| 1038 |
+
|
| 1039 |
+
return key, result
|
| 1040 |
+
|
| 1041 |
+
def _peek_table(self) -> tuple[bool, Key]:
|
| 1042 |
+
"""
|
| 1043 |
+
Peeks ahead non-intrusively by cloning then restoring the
|
| 1044 |
+
initial state of the parser.
|
| 1045 |
+
|
| 1046 |
+
Returns the name of the table about to be parsed,
|
| 1047 |
+
as well as whether it is part of an AoT.
|
| 1048 |
+
"""
|
| 1049 |
+
# we always want to restore after exiting this scope
|
| 1050 |
+
with self._state(save_marker=True, restore=True):
|
| 1051 |
+
if self._current != "[":
|
| 1052 |
+
raise self.parse_error(
|
| 1053 |
+
InternalParserError,
|
| 1054 |
+
"_peek_table() entered on non-bracket character",
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
# AoT
|
| 1058 |
+
self.inc()
|
| 1059 |
+
is_aot = False
|
| 1060 |
+
if self._current == "[":
|
| 1061 |
+
self.inc()
|
| 1062 |
+
is_aot = True
|
| 1063 |
+
try:
|
| 1064 |
+
return is_aot, self._parse_key()
|
| 1065 |
+
except EmptyKeyError:
|
| 1066 |
+
raise self.parse_error(EmptyTableNameError) from None
|
| 1067 |
+
|
| 1068 |
+
def _parse_aot(self, first: Table, name_first: Key) -> AoT:
|
| 1069 |
+
"""
|
| 1070 |
+
Parses all siblings of the provided table first and bundles them into
|
| 1071 |
+
an AoT.
|
| 1072 |
+
"""
|
| 1073 |
+
payload = [first]
|
| 1074 |
+
self._aot_stack.append(name_first)
|
| 1075 |
+
while not self.end():
|
| 1076 |
+
is_aot_next, name_next = self._peek_table()
|
| 1077 |
+
if is_aot_next and name_next == name_first:
|
| 1078 |
+
_, table = self._parse_table(name_first)
|
| 1079 |
+
payload.append(table)
|
| 1080 |
+
else:
|
| 1081 |
+
break
|
| 1082 |
+
|
| 1083 |
+
self._aot_stack.pop()
|
| 1084 |
+
|
| 1085 |
+
return AoT(payload, parsed=True)
|
| 1086 |
+
|
| 1087 |
+
def _peek(self, n: int) -> str:
|
| 1088 |
+
"""
|
| 1089 |
+
Peeks ahead n characters.
|
| 1090 |
+
|
| 1091 |
+
n is the max number of characters that will be peeked.
|
| 1092 |
+
"""
|
| 1093 |
+
# we always want to restore after exiting this scope
|
| 1094 |
+
with self._state(restore=True):
|
| 1095 |
+
buf = ""
|
| 1096 |
+
for _ in range(n):
|
| 1097 |
+
if self._current not in " \t\n\r#,]}" + self._src.EOF:
|
| 1098 |
+
buf += self._current
|
| 1099 |
+
self.inc()
|
| 1100 |
+
continue
|
| 1101 |
+
|
| 1102 |
+
break
|
| 1103 |
+
return buf
|
| 1104 |
+
|
| 1105 |
+
def _peek_unicode(self, is_long: bool) -> tuple[str | None, str | None]:
|
| 1106 |
+
"""
|
| 1107 |
+
Peeks ahead non-intrusively by cloning then restoring the
|
| 1108 |
+
initial state of the parser.
|
| 1109 |
+
|
| 1110 |
+
Returns the unicode value is it's a valid one else None.
|
| 1111 |
+
"""
|
| 1112 |
+
# we always want to restore after exiting this scope
|
| 1113 |
+
with self._state(save_marker=True, restore=True):
|
| 1114 |
+
if self._current not in {"u", "U"}:
|
| 1115 |
+
raise self.parse_error(
|
| 1116 |
+
InternalParserError, "_peek_unicode() entered on non-unicode value"
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
self.inc() # Dropping prefix
|
| 1120 |
+
self.mark()
|
| 1121 |
+
|
| 1122 |
+
if is_long:
|
| 1123 |
+
chars = 8
|
| 1124 |
+
else:
|
| 1125 |
+
chars = 4
|
| 1126 |
+
|
| 1127 |
+
if not self.inc_n(chars):
|
| 1128 |
+
value, extracted = None, None
|
| 1129 |
+
else:
|
| 1130 |
+
extracted = self.extract()
|
| 1131 |
+
|
| 1132 |
+
if extracted[0].lower() == "d" and extracted[1].strip("01234567"):
|
| 1133 |
+
return None, None
|
| 1134 |
+
|
| 1135 |
+
try:
|
| 1136 |
+
value = chr(int(extracted, 16))
|
| 1137 |
+
except (ValueError, OverflowError):
|
| 1138 |
+
value = None
|
| 1139 |
+
|
| 1140 |
+
return value, extracted
|
miniconda3/lib/python3.13/site-packages/tomlkit/py.typed
ADDED
|
File without changes
|
miniconda3/lib/python3.13/site-packages/tomlkit/source.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from copy import copy
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from tomlkit.exceptions import ParseError
|
| 7 |
+
from tomlkit.exceptions import UnexpectedCharError
|
| 8 |
+
from tomlkit.toml_char import TOMLChar
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class _State:
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
source: Source,
|
| 15 |
+
save_marker: bool | None = False,
|
| 16 |
+
restore: bool | None = False,
|
| 17 |
+
) -> None:
|
| 18 |
+
self._source = source
|
| 19 |
+
self._save_marker = save_marker
|
| 20 |
+
self.restore = restore
|
| 21 |
+
|
| 22 |
+
def __enter__(self) -> _State:
|
| 23 |
+
# Entering this context manager - save the state
|
| 24 |
+
self._chars = copy(self._source._chars)
|
| 25 |
+
self._idx = self._source._idx
|
| 26 |
+
self._current = self._source._current
|
| 27 |
+
self._marker = self._source._marker
|
| 28 |
+
|
| 29 |
+
return self
|
| 30 |
+
|
| 31 |
+
def __exit__(self, exception_type, exception_val, trace):
|
| 32 |
+
# Exiting this context manager - restore the prior state
|
| 33 |
+
if self.restore or exception_type:
|
| 34 |
+
self._source._chars = self._chars
|
| 35 |
+
self._source._idx = self._idx
|
| 36 |
+
self._source._current = self._current
|
| 37 |
+
if self._save_marker:
|
| 38 |
+
self._source._marker = self._marker
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class _StateHandler:
|
| 42 |
+
"""
|
| 43 |
+
State preserver for the Parser.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, source: Source) -> None:
|
| 47 |
+
self._source = source
|
| 48 |
+
self._states = []
|
| 49 |
+
|
| 50 |
+
def __call__(self, *args, **kwargs):
|
| 51 |
+
return _State(self._source, *args, **kwargs)
|
| 52 |
+
|
| 53 |
+
def __enter__(self) -> _State:
|
| 54 |
+
state = self()
|
| 55 |
+
self._states.append(state)
|
| 56 |
+
return state.__enter__()
|
| 57 |
+
|
| 58 |
+
def __exit__(self, exception_type, exception_val, trace):
|
| 59 |
+
state = self._states.pop()
|
| 60 |
+
return state.__exit__(exception_type, exception_val, trace)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Source(str):
|
| 64 |
+
EOF = TOMLChar("\0")
|
| 65 |
+
|
| 66 |
+
def __init__(self, _: str) -> None:
|
| 67 |
+
super().__init__()
|
| 68 |
+
|
| 69 |
+
# Collection of TOMLChars
|
| 70 |
+
self._chars = iter([(i, TOMLChar(c)) for i, c in enumerate(self)])
|
| 71 |
+
|
| 72 |
+
self._idx = 0
|
| 73 |
+
self._marker = 0
|
| 74 |
+
self._current = TOMLChar("")
|
| 75 |
+
|
| 76 |
+
self._state = _StateHandler(self)
|
| 77 |
+
|
| 78 |
+
self.inc()
|
| 79 |
+
|
| 80 |
+
def reset(self):
|
| 81 |
+
# initialize both idx and current
|
| 82 |
+
self.inc()
|
| 83 |
+
|
| 84 |
+
# reset marker
|
| 85 |
+
self.mark()
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def state(self) -> _StateHandler:
|
| 89 |
+
return self._state
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def idx(self) -> int:
|
| 93 |
+
return self._idx
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def current(self) -> TOMLChar:
|
| 97 |
+
return self._current
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def marker(self) -> int:
|
| 101 |
+
return self._marker
|
| 102 |
+
|
| 103 |
+
def extract(self) -> str:
|
| 104 |
+
"""
|
| 105 |
+
Extracts the value between marker and index
|
| 106 |
+
"""
|
| 107 |
+
return self[self._marker : self._idx]
|
| 108 |
+
|
| 109 |
+
def inc(self, exception: type[ParseError] | None = None) -> bool:
|
| 110 |
+
"""
|
| 111 |
+
Increments the parser if the end of the input has not been reached.
|
| 112 |
+
Returns whether or not it was able to advance.
|
| 113 |
+
"""
|
| 114 |
+
try:
|
| 115 |
+
self._idx, self._current = next(self._chars)
|
| 116 |
+
|
| 117 |
+
return True
|
| 118 |
+
except StopIteration:
|
| 119 |
+
self._idx = len(self)
|
| 120 |
+
self._current = self.EOF
|
| 121 |
+
if exception:
|
| 122 |
+
raise self.parse_error(exception) from None
|
| 123 |
+
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
def inc_n(self, n: int, exception: type[ParseError] | None = None) -> bool:
|
| 127 |
+
"""
|
| 128 |
+
Increments the parser by n characters
|
| 129 |
+
if the end of the input has not been reached.
|
| 130 |
+
"""
|
| 131 |
+
return all(self.inc(exception=exception) for _ in range(n))
|
| 132 |
+
|
| 133 |
+
def consume(self, chars, min=0, max=-1):
|
| 134 |
+
"""
|
| 135 |
+
Consume chars until min/max is satisfied is valid.
|
| 136 |
+
"""
|
| 137 |
+
while self.current in chars and max != 0:
|
| 138 |
+
min -= 1
|
| 139 |
+
max -= 1
|
| 140 |
+
if not self.inc():
|
| 141 |
+
break
|
| 142 |
+
|
| 143 |
+
# failed to consume minimum number of characters
|
| 144 |
+
if min > 0:
|
| 145 |
+
raise self.parse_error(UnexpectedCharError, self.current)
|
| 146 |
+
|
| 147 |
+
def end(self) -> bool:
|
| 148 |
+
"""
|
| 149 |
+
Returns True if the parser has reached the end of the input.
|
| 150 |
+
"""
|
| 151 |
+
return self._current is self.EOF
|
| 152 |
+
|
| 153 |
+
def mark(self) -> None:
|
| 154 |
+
"""
|
| 155 |
+
Sets the marker to the index's current position
|
| 156 |
+
"""
|
| 157 |
+
self._marker = self._idx
|
| 158 |
+
|
| 159 |
+
def parse_error(
|
| 160 |
+
self,
|
| 161 |
+
exception: type[ParseError] = ParseError,
|
| 162 |
+
*args: Any,
|
| 163 |
+
**kwargs: Any,
|
| 164 |
+
) -> ParseError:
|
| 165 |
+
"""
|
| 166 |
+
Creates a generic "parse error" at the current position.
|
| 167 |
+
"""
|
| 168 |
+
line, col = self._to_linecol()
|
| 169 |
+
|
| 170 |
+
return exception(line, col, *args, **kwargs)
|
| 171 |
+
|
| 172 |
+
def _to_linecol(self) -> tuple[int, int]:
|
| 173 |
+
cur = 0
|
| 174 |
+
for i, line in enumerate(self.splitlines()):
|
| 175 |
+
if cur + len(line) + 1 > self.idx:
|
| 176 |
+
return (i + 1, self.idx - cur)
|
| 177 |
+
|
| 178 |
+
cur += len(line) + 1
|
| 179 |
+
|
| 180 |
+
return len(self.splitlines()), 0
|
miniconda3/lib/python3.13/site-packages/tomlkit/toml_char.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import string
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class TOMLChar(str):
|
| 5 |
+
def __init__(self, c):
|
| 6 |
+
super().__init__()
|
| 7 |
+
|
| 8 |
+
if len(self) > 1:
|
| 9 |
+
raise ValueError("A TOML character must be of length 1")
|
| 10 |
+
|
| 11 |
+
BARE = string.ascii_letters + string.digits + "-_"
|
| 12 |
+
KV = "= \t"
|
| 13 |
+
NUMBER = string.digits + "+-_.e"
|
| 14 |
+
SPACES = " \t"
|
| 15 |
+
NL = "\n\r"
|
| 16 |
+
WS = SPACES + NL
|
| 17 |
+
|
| 18 |
+
def is_bare_key_char(self) -> bool:
|
| 19 |
+
"""
|
| 20 |
+
Whether the character is a valid bare key name or not.
|
| 21 |
+
"""
|
| 22 |
+
return self in self.BARE
|
| 23 |
+
|
| 24 |
+
def is_kv_sep(self) -> bool:
|
| 25 |
+
"""
|
| 26 |
+
Whether the character is a valid key/value separator or not.
|
| 27 |
+
"""
|
| 28 |
+
return self in self.KV
|
| 29 |
+
|
| 30 |
+
def is_int_float_char(self) -> bool:
|
| 31 |
+
"""
|
| 32 |
+
Whether the character if a valid integer or float value character or not.
|
| 33 |
+
"""
|
| 34 |
+
return self in self.NUMBER
|
| 35 |
+
|
| 36 |
+
def is_ws(self) -> bool:
|
| 37 |
+
"""
|
| 38 |
+
Whether the character is a whitespace character or not.
|
| 39 |
+
"""
|
| 40 |
+
return self in self.WS
|
| 41 |
+
|
| 42 |
+
def is_nl(self) -> bool:
|
| 43 |
+
"""
|
| 44 |
+
Whether the character is a new line character or not.
|
| 45 |
+
"""
|
| 46 |
+
return self in self.NL
|
| 47 |
+
|
| 48 |
+
def is_spaces(self) -> bool:
|
| 49 |
+
"""
|
| 50 |
+
Whether the character is a space or not
|
| 51 |
+
"""
|
| 52 |
+
return self in self.SPACES
|
miniconda3/lib/python3.13/site-packages/tomlkit/toml_document.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tomlkit.container import Container
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class TOMLDocument(Container):
|
| 5 |
+
"""
|
| 6 |
+
A TOML document.
|
| 7 |
+
"""
|
miniconda3/lib/python3.13/site-packages/tomlkit/toml_file.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
from typing import TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
from tomlkit.api import loads
|
| 7 |
+
from tomlkit.toml_document import TOMLDocument
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from _typeshed import StrPath as _StrPath
|
| 12 |
+
else:
|
| 13 |
+
from typing import Union
|
| 14 |
+
|
| 15 |
+
_StrPath = Union[str, os.PathLike]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TOMLFile:
|
| 19 |
+
"""
|
| 20 |
+
Represents a TOML file.
|
| 21 |
+
|
| 22 |
+
:param path: path to the TOML file
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, path: _StrPath) -> None:
|
| 26 |
+
self._path = path
|
| 27 |
+
self._linesep = os.linesep
|
| 28 |
+
|
| 29 |
+
def read(self) -> TOMLDocument:
|
| 30 |
+
"""Read the file content as a :class:`tomlkit.toml_document.TOMLDocument`."""
|
| 31 |
+
with open(self._path, encoding="utf-8", newline="") as f:
|
| 32 |
+
content = f.read()
|
| 33 |
+
|
| 34 |
+
# check if consistent line endings
|
| 35 |
+
num_newline = content.count("\n")
|
| 36 |
+
if num_newline > 0:
|
| 37 |
+
num_win_eol = content.count("\r\n")
|
| 38 |
+
if num_win_eol == num_newline:
|
| 39 |
+
self._linesep = "\r\n"
|
| 40 |
+
content = content.replace("\r\n", "\n")
|
| 41 |
+
elif num_win_eol == 0:
|
| 42 |
+
self._linesep = "\n"
|
| 43 |
+
else:
|
| 44 |
+
self._linesep = "mixed"
|
| 45 |
+
|
| 46 |
+
return loads(content)
|
| 47 |
+
|
| 48 |
+
def write(self, data: TOMLDocument) -> None:
|
| 49 |
+
"""Write the TOMLDocument to the file."""
|
| 50 |
+
content = data.as_string()
|
| 51 |
+
|
| 52 |
+
# apply linesep
|
| 53 |
+
if self._linesep == "\n":
|
| 54 |
+
content = content.replace("\r\n", "\n")
|
| 55 |
+
elif self._linesep == "\r\n":
|
| 56 |
+
content = re.sub(r"(?<!\r)\n", "\r\n", content)
|
| 57 |
+
|
| 58 |
+
with open(self._path, "w", encoding="utf-8", newline="") as f:
|
| 59 |
+
f.write(content)
|
miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/METADATA
ADDED
|
@@ -0,0 +1,1595 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: tqdm
|
| 3 |
+
Version: 4.67.3
|
| 4 |
+
Summary: Fast, Extensible Progress Meter
|
| 5 |
+
Maintainer-email: tqdm developers <devs@tqdm.ml>
|
| 6 |
+
License: MPL-2.0 AND MIT
|
| 7 |
+
Project-URL: homepage, https://tqdm.github.io
|
| 8 |
+
Project-URL: repository, https://github.com/tqdm/tqdm
|
| 9 |
+
Project-URL: changelog, https://tqdm.github.io/releases
|
| 10 |
+
Project-URL: wiki, https://github.com/tqdm/tqdm/wiki
|
| 11 |
+
Keywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,time
|
| 12 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 13 |
+
Classifier: Environment :: Console
|
| 14 |
+
Classifier: Environment :: MacOS X
|
| 15 |
+
Classifier: Environment :: Other Environment
|
| 16 |
+
Classifier: Environment :: Win32 (MS Windows)
|
| 17 |
+
Classifier: Environment :: X11 Applications
|
| 18 |
+
Classifier: Framework :: IPython
|
| 19 |
+
Classifier: Framework :: Jupyter
|
| 20 |
+
Classifier: Intended Audience :: Developers
|
| 21 |
+
Classifier: Intended Audience :: Education
|
| 22 |
+
Classifier: Intended Audience :: End Users/Desktop
|
| 23 |
+
Classifier: Intended Audience :: Other Audience
|
| 24 |
+
Classifier: Intended Audience :: System Administrators
|
| 25 |
+
Classifier: Operating System :: MacOS
|
| 26 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
| 27 |
+
Classifier: Operating System :: Microsoft
|
| 28 |
+
Classifier: Operating System :: Microsoft :: MS-DOS
|
| 29 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 30 |
+
Classifier: Operating System :: POSIX
|
| 31 |
+
Classifier: Operating System :: POSIX :: BSD
|
| 32 |
+
Classifier: Operating System :: POSIX :: BSD :: FreeBSD
|
| 33 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 34 |
+
Classifier: Operating System :: POSIX :: SunOS/Solaris
|
| 35 |
+
Classifier: Operating System :: Unix
|
| 36 |
+
Classifier: Programming Language :: Python
|
| 37 |
+
Classifier: Programming Language :: Python :: 3
|
| 38 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 39 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 40 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 41 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 42 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 43 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 44 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 45 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 46 |
+
Classifier: Programming Language :: Python :: Implementation
|
| 47 |
+
Classifier: Programming Language :: Python :: Implementation :: IronPython
|
| 48 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 49 |
+
Classifier: Programming Language :: Unix Shell
|
| 50 |
+
Classifier: Topic :: Desktop Environment
|
| 51 |
+
Classifier: Topic :: Education :: Computer Aided Instruction (CAI)
|
| 52 |
+
Classifier: Topic :: Education :: Testing
|
| 53 |
+
Classifier: Topic :: Office/Business
|
| 54 |
+
Classifier: Topic :: Other/Nonlisted Topic
|
| 55 |
+
Classifier: Topic :: Software Development :: Build Tools
|
| 56 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 57 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 58 |
+
Classifier: Topic :: Software Development :: Pre-processors
|
| 59 |
+
Classifier: Topic :: Software Development :: User Interfaces
|
| 60 |
+
Classifier: Topic :: System :: Installation/Setup
|
| 61 |
+
Classifier: Topic :: System :: Logging
|
| 62 |
+
Classifier: Topic :: System :: Monitoring
|
| 63 |
+
Classifier: Topic :: System :: Shells
|
| 64 |
+
Classifier: Topic :: Terminals
|
| 65 |
+
Classifier: Topic :: Utilities
|
| 66 |
+
Requires-Python: >=3.7
|
| 67 |
+
Description-Content-Type: text/x-rst
|
| 68 |
+
License-File: LICENCE
|
| 69 |
+
Requires-Dist: colorama; platform_system == "Windows"
|
| 70 |
+
Requires-Dist: importlib_metadata; python_version < "3.8"
|
| 71 |
+
Provides-Extra: dev
|
| 72 |
+
Requires-Dist: pytest>=6; extra == "dev"
|
| 73 |
+
Requires-Dist: pytest-cov; extra == "dev"
|
| 74 |
+
Requires-Dist: pytest-timeout; extra == "dev"
|
| 75 |
+
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
|
| 76 |
+
Requires-Dist: nbval; extra == "dev"
|
| 77 |
+
Provides-Extra: discord
|
| 78 |
+
Requires-Dist: requests; extra == "discord"
|
| 79 |
+
Provides-Extra: slack
|
| 80 |
+
Requires-Dist: slack-sdk; extra == "slack"
|
| 81 |
+
Provides-Extra: telegram
|
| 82 |
+
Requires-Dist: requests; extra == "telegram"
|
| 83 |
+
Provides-Extra: notebook
|
| 84 |
+
Requires-Dist: ipywidgets>=6; extra == "notebook"
|
| 85 |
+
Dynamic: license-file
|
| 86 |
+
|
| 87 |
+
|Logo|
|
| 88 |
+
|
| 89 |
+
tqdm
|
| 90 |
+
====
|
| 91 |
+
|
| 92 |
+
|Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft|
|
| 93 |
+
|
| 94 |
+
|Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads|
|
| 95 |
+
|
| 96 |
+
|LICENCE| |OpenHub-Status| |binder-demo| |awesome-python|
|
| 97 |
+
|
| 98 |
+
``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress,"
|
| 99 |
+
and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*).
|
| 100 |
+
|
| 101 |
+
Instantly make your loops show a smart progress meter - just wrap any
|
| 102 |
+
iterable with ``tqdm(iterable)``, and you're done!
|
| 103 |
+
|
| 104 |
+
.. code:: python
|
| 105 |
+
|
| 106 |
+
from tqdm import tqdm
|
| 107 |
+
for i in tqdm(range(10000)):
|
| 108 |
+
...
|
| 109 |
+
|
| 110 |
+
``76%|████████████████████████ | 7568/10000 [00:33<00:10, 229.00it/s]``
|
| 111 |
+
|
| 112 |
+
``trange(N)`` can be also used as a convenient shortcut for
|
| 113 |
+
``tqdm(range(N))``.
|
| 114 |
+
|
| 115 |
+
|Screenshot|
|
| 116 |
+
|Video| |Slides| |Merch|
|
| 117 |
+
|
| 118 |
+
It can also be executed as a module with pipes:
|
| 119 |
+
|
| 120 |
+
.. code:: sh
|
| 121 |
+
|
| 122 |
+
$ seq 9999999 | tqdm --bytes | wc -l
|
| 123 |
+
75.2MB [00:00, 217MB/s]
|
| 124 |
+
9999999
|
| 125 |
+
|
| 126 |
+
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
|
| 127 |
+
> backup.tgz
|
| 128 |
+
32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s]
|
| 129 |
+
|
| 130 |
+
Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and is
|
| 131 |
+
unit tested against performance regression.
|
| 132 |
+
By comparison, the well-established
|
| 133 |
+
`ProgressBar <https://github.com/niltonvolpato/python-progressbar>`__ has
|
| 134 |
+
an 800ns/iter overhead.
|
| 135 |
+
|
| 136 |
+
In addition to its low overhead, ``tqdm`` uses smart algorithms to predict
|
| 137 |
+
the remaining time and to skip unnecessary iteration displays, which allows
|
| 138 |
+
for a negligible overhead in most cases.
|
| 139 |
+
|
| 140 |
+
``tqdm`` works on any platform
|
| 141 |
+
(Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS),
|
| 142 |
+
in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
|
| 143 |
+
|
| 144 |
+
``tqdm`` does not require any dependencies (not even ``curses``!), just
|
| 145 |
+
Python and an environment supporting ``carriage return \r`` and
|
| 146 |
+
``line feed \n`` control characters.
|
| 147 |
+
|
| 148 |
+
------------------------------------------
|
| 149 |
+
|
| 150 |
+
.. contents:: Table of contents
|
| 151 |
+
:backlinks: top
|
| 152 |
+
:local:
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
Installation
|
| 156 |
+
------------
|
| 157 |
+
|
| 158 |
+
Latest PyPI stable release
|
| 159 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 160 |
+
|
| 161 |
+
|Versions| |PyPI-Downloads| |Libraries-Dependents|
|
| 162 |
+
|
| 163 |
+
.. code:: sh
|
| 164 |
+
|
| 165 |
+
pip install tqdm
|
| 166 |
+
|
| 167 |
+
Latest development release on GitHub
|
| 168 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 169 |
+
|
| 170 |
+
|GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated|
|
| 171 |
+
|
| 172 |
+
Pull and install pre-release ``devel`` branch:
|
| 173 |
+
|
| 174 |
+
.. code:: sh
|
| 175 |
+
|
| 176 |
+
pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm"
|
| 177 |
+
|
| 178 |
+
Latest Conda release
|
| 179 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 180 |
+
|
| 181 |
+
|Conda-Forge-Status|
|
| 182 |
+
|
| 183 |
+
.. code:: sh
|
| 184 |
+
|
| 185 |
+
conda install -c conda-forge tqdm
|
| 186 |
+
|
| 187 |
+
Latest Snapcraft release
|
| 188 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 189 |
+
|
| 190 |
+
|Snapcraft|
|
| 191 |
+
|
| 192 |
+
There are 3 channels to choose from:
|
| 193 |
+
|
| 194 |
+
.. code:: sh
|
| 195 |
+
|
| 196 |
+
snap install tqdm # implies --stable, i.e. latest tagged release
|
| 197 |
+
snap install tqdm --candidate # master branch
|
| 198 |
+
snap install tqdm --edge # devel branch
|
| 199 |
+
|
| 200 |
+
Note that ``snap`` binaries are purely for CLI use (not ``import``-able), and
|
| 201 |
+
automatically set up ``bash`` tab-completion.
|
| 202 |
+
|
| 203 |
+
Latest Docker release
|
| 204 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 205 |
+
|
| 206 |
+
|Docker|
|
| 207 |
+
|
| 208 |
+
.. code:: sh
|
| 209 |
+
|
| 210 |
+
docker pull tqdm/tqdm
|
| 211 |
+
docker run -i --rm tqdm/tqdm --help
|
| 212 |
+
|
| 213 |
+
Other
|
| 214 |
+
~~~~~
|
| 215 |
+
|
| 216 |
+
There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use:
|
| 217 |
+
|
| 218 |
+
|Repology|
|
| 219 |
+
|
| 220 |
+
.. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg
|
| 221 |
+
:target: https://repology.org/project/python:tqdm/versions
|
| 222 |
+
|
| 223 |
+
Changelog
|
| 224 |
+
---------
|
| 225 |
+
|
| 226 |
+
The list of all changes is available either on GitHub's Releases:
|
| 227 |
+
|GitHub-Status|, on the
|
| 228 |
+
`wiki <https://github.com/tqdm/tqdm/wiki/Releases>`__, or on the
|
| 229 |
+
`website <https://tqdm.github.io/releases>`__.
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
Usage
|
| 233 |
+
-----
|
| 234 |
+
|
| 235 |
+
``tqdm`` is very versatile and can be used in a number of ways.
|
| 236 |
+
The three main ones are given below.
|
| 237 |
+
|
| 238 |
+
Iterable-based
|
| 239 |
+
~~~~~~~~~~~~~~
|
| 240 |
+
|
| 241 |
+
Wrap ``tqdm()`` around any iterable:
|
| 242 |
+
|
| 243 |
+
.. code:: python
|
| 244 |
+
|
| 245 |
+
from tqdm import tqdm
|
| 246 |
+
from time import sleep
|
| 247 |
+
|
| 248 |
+
text = ""
|
| 249 |
+
for char in tqdm(["a", "b", "c", "d"]):
|
| 250 |
+
sleep(0.25)
|
| 251 |
+
text = text + char
|
| 252 |
+
|
| 253 |
+
``trange(i)`` is a special optimised instance of ``tqdm(range(i))``:
|
| 254 |
+
|
| 255 |
+
.. code:: python
|
| 256 |
+
|
| 257 |
+
from tqdm import trange
|
| 258 |
+
|
| 259 |
+
for i in trange(100):
|
| 260 |
+
sleep(0.01)
|
| 261 |
+
|
| 262 |
+
Instantiation outside of the loop allows for manual control over ``tqdm()``:
|
| 263 |
+
|
| 264 |
+
.. code:: python
|
| 265 |
+
|
| 266 |
+
pbar = tqdm(["a", "b", "c", "d"])
|
| 267 |
+
for char in pbar:
|
| 268 |
+
sleep(0.25)
|
| 269 |
+
pbar.set_description("Processing %s" % char)
|
| 270 |
+
|
| 271 |
+
Manual
|
| 272 |
+
~~~~~~
|
| 273 |
+
|
| 274 |
+
Manual control of ``tqdm()`` updates using a ``with`` statement:
|
| 275 |
+
|
| 276 |
+
.. code:: python
|
| 277 |
+
|
| 278 |
+
with tqdm(total=100) as pbar:
|
| 279 |
+
for i in range(10):
|
| 280 |
+
sleep(0.1)
|
| 281 |
+
pbar.update(10)
|
| 282 |
+
|
| 283 |
+
If the optional variable ``total`` (or an iterable with ``len()``) is
|
| 284 |
+
provided, predictive stats are displayed.
|
| 285 |
+
|
| 286 |
+
``with`` is also optional (you can just assign ``tqdm()`` to a variable,
|
| 287 |
+
but in this case don't forget to ``del`` or ``close()`` at the end:
|
| 288 |
+
|
| 289 |
+
.. code:: python
|
| 290 |
+
|
| 291 |
+
pbar = tqdm(total=100)
|
| 292 |
+
for i in range(10):
|
| 293 |
+
sleep(0.1)
|
| 294 |
+
pbar.update(10)
|
| 295 |
+
pbar.close()
|
| 296 |
+
|
| 297 |
+
Module
|
| 298 |
+
~~~~~~
|
| 299 |
+
|
| 300 |
+
Perhaps the most wonderful use of ``tqdm`` is in a script or on the command
|
| 301 |
+
line. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will pass
|
| 302 |
+
through all ``stdin`` to ``stdout`` while printing progress to ``stderr``.
|
| 303 |
+
|
| 304 |
+
The example below demonstrate counting the number of lines in all Python files
|
| 305 |
+
in the current directory, with timing information included.
|
| 306 |
+
|
| 307 |
+
.. code:: sh
|
| 308 |
+
|
| 309 |
+
$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
|
| 310 |
+
857365
|
| 311 |
+
|
| 312 |
+
real 0m3.458s
|
| 313 |
+
user 0m0.274s
|
| 314 |
+
sys 0m3.325s
|
| 315 |
+
|
| 316 |
+
$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
|
| 317 |
+
857366it [00:03, 246471.31it/s]
|
| 318 |
+
857365
|
| 319 |
+
|
| 320 |
+
real 0m3.585s
|
| 321 |
+
user 0m0.862s
|
| 322 |
+
sys 0m3.358s
|
| 323 |
+
|
| 324 |
+
Note that the usual arguments for ``tqdm`` can also be specified.
|
| 325 |
+
|
| 326 |
+
.. code:: sh
|
| 327 |
+
|
| 328 |
+
$ find . -name '*.py' -type f -exec cat \{} \; |
|
| 329 |
+
tqdm --unit loc --unit_scale --total 857366 >> /dev/null
|
| 330 |
+
100%|█████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]
|
| 331 |
+
|
| 332 |
+
Backing up a large directory?
|
| 333 |
+
|
| 334 |
+
.. code:: sh
|
| 335 |
+
|
| 336 |
+
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
|
| 337 |
+
> backup.tgz
|
| 338 |
+
44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s]
|
| 339 |
+
|
| 340 |
+
This can be beautified further:
|
| 341 |
+
|
| 342 |
+
.. code:: sh
|
| 343 |
+
|
| 344 |
+
$ BYTES=$(du -sb docs/ | cut -f1)
|
| 345 |
+
$ tar -cf - docs/ \
|
| 346 |
+
| tqdm --bytes --total "$BYTES" --desc Processing | gzip \
|
| 347 |
+
| tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \
|
| 348 |
+
> ~/backup.tgz
|
| 349 |
+
Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s]
|
| 350 |
+
Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s]
|
| 351 |
+
|
| 352 |
+
Or done on a file level using 7-zip:
|
| 353 |
+
|
| 354 |
+
.. code:: sh
|
| 355 |
+
|
| 356 |
+
$ 7z a -bd -r backup.7z docs/ | grep Compressing \
|
| 357 |
+
| tqdm --total $(find docs/ -type f | wc -l) --unit files \
|
| 358 |
+
| grep -v Compressing
|
| 359 |
+
100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s]
|
| 360 |
+
|
| 361 |
+
Pre-existing CLI programs already outputting basic progress information will
|
| 362 |
+
benefit from ``tqdm``'s ``--update`` and ``--update_to`` flags:
|
| 363 |
+
|
| 364 |
+
.. code:: sh
|
| 365 |
+
|
| 366 |
+
$ seq 3 0.1 5 | tqdm --total 5 --update_to --null
|
| 367 |
+
100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s]
|
| 368 |
+
$ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations
|
| 369 |
+
55it [00:00, 90006.52it/s]
|
| 370 |
+
|
| 371 |
+
FAQ and Known Issues
|
| 372 |
+
--------------------
|
| 373 |
+
|
| 374 |
+
|GitHub-Issues|
|
| 375 |
+
|
| 376 |
+
The most common issues relate to excessive output on multiple lines, instead
|
| 377 |
+
of a neat one-line progress bar.
|
| 378 |
+
|
| 379 |
+
- Consoles in general: require support for carriage return (``CR``, ``\r``).
|
| 380 |
+
|
| 381 |
+
* Some cloud logging consoles which don't support ``\r`` properly
|
| 382 |
+
(`cloudwatch <https://github.com/tqdm/tqdm/issues/966>`__,
|
| 383 |
+
`K8s <https://github.com/tqdm/tqdm/issues/1319>`__) may benefit from
|
| 384 |
+
``export TQDM_POSITION=-1``.
|
| 385 |
+
|
| 386 |
+
- Nested progress bars:
|
| 387 |
+
|
| 388 |
+
* Consoles in general: require support for moving cursors up to the
|
| 389 |
+
previous line. For example,
|
| 390 |
+
`IDLE <https://github.com/tqdm/tqdm/issues/191#issuecomment-230168030>`__,
|
| 391 |
+
`ConEmu <https://github.com/tqdm/tqdm/issues/254>`__ and
|
| 392 |
+
`PyCharm <https://github.com/tqdm/tqdm/issues/203>`__ (also
|
| 393 |
+
`here <https://github.com/tqdm/tqdm/issues/208>`__,
|
| 394 |
+
`here <https://github.com/tqdm/tqdm/issues/307>`__, and
|
| 395 |
+
`here <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__)
|
| 396 |
+
lack full support.
|
| 397 |
+
* Windows: additionally may require the Python module ``colorama``
|
| 398 |
+
to ensure nested bars stay within their respective lines.
|
| 399 |
+
|
| 400 |
+
- Unicode:
|
| 401 |
+
|
| 402 |
+
* Environments which report that they support unicode will have solid smooth
|
| 403 |
+
progressbars. The fallback is an ``ascii``-only bar.
|
| 404 |
+
* Windows consoles often only partially support unicode and thus
|
| 405 |
+
`often require explicit ascii=True <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__
|
| 406 |
+
(also `here <https://github.com/tqdm/tqdm/issues/499>`__). This is due to
|
| 407 |
+
either normal-width unicode characters being incorrectly displayed as
|
| 408 |
+
"wide", or some unicode characters not rendering.
|
| 409 |
+
|
| 410 |
+
- Wrapping generators:
|
| 411 |
+
|
| 412 |
+
* Generator wrapper functions tend to hide the length of iterables.
|
| 413 |
+
``tqdm`` does not.
|
| 414 |
+
* Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or
|
| 415 |
+
``tqdm(enumerate(x), total=len(x), ...)``.
|
| 416 |
+
The same applies to ``numpy.ndenumerate``.
|
| 417 |
+
* Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even
|
| 418 |
+
``zip(tqdm(a), tqdm(b))``.
|
| 419 |
+
* The same applies to ``itertools``.
|
| 420 |
+
* Some useful convenience functions can be found under ``tqdm.contrib``.
|
| 421 |
+
|
| 422 |
+
- `No intermediate output in docker-compose <https://github.com/tqdm/tqdm/issues/771>`__:
|
| 423 |
+
use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``.
|
| 424 |
+
|
| 425 |
+
- Overriding defaults via environment variables:
|
| 426 |
+
e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam.
|
| 427 |
+
This override logic is handled by the ``tqdm.utils.envwrap`` decorator
|
| 428 |
+
(useful independent of ``tqdm``).
|
| 429 |
+
|
| 430 |
+
If you come across any other difficulties, browse and file |GitHub-Issues|.
|
| 431 |
+
|
| 432 |
+
Documentation
|
| 433 |
+
-------------
|
| 434 |
+
|
| 435 |
+
|Py-Versions| |README-Hits| (Since 19 May 2016)
|
| 436 |
+
|
| 437 |
+
.. code:: python
|
| 438 |
+
|
| 439 |
+
class tqdm():
|
| 440 |
+
"""
|
| 441 |
+
Decorate an iterable object, returning an iterator which acts exactly
|
| 442 |
+
like the original iterable, but prints a dynamically updating
|
| 443 |
+
progressbar every time a value is requested.
|
| 444 |
+
"""
|
| 445 |
+
|
| 446 |
+
@envwrap("TQDM_") # override defaults via env vars
|
| 447 |
+
def __init__(self, iterable=None, desc=None, total=None, leave=True,
|
| 448 |
+
file=None, ncols=None, mininterval=0.1,
|
| 449 |
+
maxinterval=10.0, miniters=None, ascii=None, disable=False,
|
| 450 |
+
unit='it', unit_scale=False, dynamic_ncols=False,
|
| 451 |
+
smoothing=0.3, bar_format=None, initial=0, position=None,
|
| 452 |
+
postfix=None, unit_divisor=1000, write_bytes=False,
|
| 453 |
+
lock_args=None, nrows=None, colour=None, delay=0):
|
| 454 |
+
|
| 455 |
+
Parameters
|
| 456 |
+
~~~~~~~~~~
|
| 457 |
+
|
| 458 |
+
* iterable : iterable, optional
|
| 459 |
+
Iterable to decorate with a progressbar.
|
| 460 |
+
Leave blank to manually manage the updates.
|
| 461 |
+
* desc : str, optional
|
| 462 |
+
Prefix for the progressbar.
|
| 463 |
+
* total : int or float, optional
|
| 464 |
+
The number of expected iterations. If unspecified,
|
| 465 |
+
len(iterable) is used if possible. If float("inf") or as a last
|
| 466 |
+
resort, only basic progress statistics are displayed
|
| 467 |
+
(no ETA, no progressbar).
|
| 468 |
+
If ``gui`` is True and this parameter needs subsequent updating,
|
| 469 |
+
specify an initial arbitrary large positive number,
|
| 470 |
+
e.g. 9e9.
|
| 471 |
+
* leave : bool, optional
|
| 472 |
+
If [default: True], keeps all traces of the progressbar
|
| 473 |
+
upon termination of iteration.
|
| 474 |
+
If ``None``, will leave only if ``position`` is ``0``.
|
| 475 |
+
* file : ``io.TextIOWrapper`` or ``io.StringIO``, optional
|
| 476 |
+
Specifies where to output the progress messages
|
| 477 |
+
(default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()``
|
| 478 |
+
methods. For encoding, see ``write_bytes``.
|
| 479 |
+
* ncols : int, optional
|
| 480 |
+
The width of the entire output message. If specified,
|
| 481 |
+
dynamically resizes the progressbar to stay within this bound.
|
| 482 |
+
If unspecified, attempts to use environment width. The
|
| 483 |
+
fallback is a meter width of 10 and no limit for the counter and
|
| 484 |
+
statistics. If 0, will not print any meter (only stats).
|
| 485 |
+
* mininterval : float, optional
|
| 486 |
+
Minimum progress display update interval [default: 0.1] seconds.
|
| 487 |
+
* maxinterval : float, optional
|
| 488 |
+
Maximum progress display update interval [default: 10] seconds.
|
| 489 |
+
Automatically adjusts ``miniters`` to correspond to ``mininterval``
|
| 490 |
+
after long display update lag. Only works if ``dynamic_miniters``
|
| 491 |
+
or monitor thread is enabled.
|
| 492 |
+
* miniters : int or float, optional
|
| 493 |
+
Minimum progress display update interval, in iterations.
|
| 494 |
+
If 0 and ``dynamic_miniters``, will automatically adjust to equal
|
| 495 |
+
``mininterval`` (more CPU efficient, good for tight loops).
|
| 496 |
+
If > 0, will skip display of specified number of iterations.
|
| 497 |
+
Tweak this and ``mininterval`` to get very efficient loops.
|
| 498 |
+
If your progress is erratic with both fast and slow iterations
|
| 499 |
+
(network, skipping items, etc) you should set miniters=1.
|
| 500 |
+
* ascii : bool or str, optional
|
| 501 |
+
If unspecified or False, use unicode (smooth blocks) to fill
|
| 502 |
+
the meter. The fallback is to use ASCII characters " 123456789#".
|
| 503 |
+
* disable : bool, optional
|
| 504 |
+
Whether to disable the entire progressbar wrapper
|
| 505 |
+
[default: False]. If set to None, disable on non-TTY.
|
| 506 |
+
* unit : str, optional
|
| 507 |
+
String that will be used to define the unit of each iteration
|
| 508 |
+
[default: it].
|
| 509 |
+
* unit_scale : bool or int or float, optional
|
| 510 |
+
If 1 or True, the number of iterations will be reduced/scaled
|
| 511 |
+
automatically and a metric prefix following the
|
| 512 |
+
International System of Units standard will be added
|
| 513 |
+
(kilo, mega, etc.) [default: False]. If any other non-zero
|
| 514 |
+
number, will scale ``total`` and ``n``.
|
| 515 |
+
* dynamic_ncols : bool, optional
|
| 516 |
+
If set, constantly alters ``ncols`` and ``nrows`` to the
|
| 517 |
+
environment (allowing for window resizes) [default: False].
|
| 518 |
+
* smoothing : float, optional
|
| 519 |
+
Exponential moving average smoothing factor for speed estimates
|
| 520 |
+
(ignored in GUI mode). Ranges from 0 (average speed) to 1
|
| 521 |
+
(current/instantaneous speed) [default: 0.3].
|
| 522 |
+
* bar_format : str, optional
|
| 523 |
+
Specify a custom bar string formatting. May impact performance.
|
| 524 |
+
[default: '{l_bar}{bar}{r_bar}'], where
|
| 525 |
+
l_bar='{desc}: {percentage:3.0f}%|' and
|
| 526 |
+
r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
|
| 527 |
+
'{rate_fmt}{postfix}]'
|
| 528 |
+
Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
|
| 529 |
+
percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
|
| 530 |
+
rate, rate_fmt, rate_noinv, rate_noinv_fmt,
|
| 531 |
+
rate_inv, rate_inv_fmt, postfix, unit_divisor,
|
| 532 |
+
remaining, remaining_s, eta.
|
| 533 |
+
Note that a trailing ": " is automatically removed after {desc}
|
| 534 |
+
if the latter is empty.
|
| 535 |
+
* initial : int or float, optional
|
| 536 |
+
The initial counter value. Useful when restarting a progress
|
| 537 |
+
bar [default: 0]. If using float, consider specifying ``{n:.3f}``
|
| 538 |
+
or similar in ``bar_format``, or specifying ``unit_scale``.
|
| 539 |
+
* position : int, optional
|
| 540 |
+
Specify the line offset to print this bar (starting from 0)
|
| 541 |
+
Automatic if unspecified.
|
| 542 |
+
Useful to manage multiple bars at once (eg, from threads).
|
| 543 |
+
* postfix : dict or ``*``, optional
|
| 544 |
+
Specify additional stats to display at the end of the bar.
|
| 545 |
+
Calls ``set_postfix(**postfix)`` if possible (dict).
|
| 546 |
+
* unit_divisor : float, optional
|
| 547 |
+
[default: 1000], ignored unless ``unit_scale`` is True.
|
| 548 |
+
* write_bytes : bool, optional
|
| 549 |
+
Whether to write bytes. If (default: False) will write unicode.
|
| 550 |
+
* lock_args : tuple, optional
|
| 551 |
+
Passed to ``refresh`` for intermediate output
|
| 552 |
+
(initialisation, iterating, and updating).
|
| 553 |
+
* nrows : int, optional
|
| 554 |
+
The screen height. If specified, hides nested bars outside this
|
| 555 |
+
bound. If unspecified, attempts to use environment height.
|
| 556 |
+
The fallback is 20.
|
| 557 |
+
* colour : str, optional
|
| 558 |
+
Bar colour (e.g. 'green', '#00ff00').
|
| 559 |
+
* delay : float, optional
|
| 560 |
+
Don't display until [default: 0] seconds have elapsed.
|
| 561 |
+
|
| 562 |
+
Extra CLI Options
|
| 563 |
+
~~~~~~~~~~~~~~~~~
|
| 564 |
+
|
| 565 |
+
* delim : chr, optional
|
| 566 |
+
Delimiting character [default: '\n']. Use '\0' for null.
|
| 567 |
+
N.B.: on Windows systems, Python converts '\n' to '\r\n'.
|
| 568 |
+
* buf_size : int, optional
|
| 569 |
+
String buffer size in bytes [default: 256]
|
| 570 |
+
used when ``delim`` is specified.
|
| 571 |
+
* bytes : bool, optional
|
| 572 |
+
If true, will count bytes, ignore ``delim``, and default
|
| 573 |
+
``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'.
|
| 574 |
+
* tee : bool, optional
|
| 575 |
+
If true, passes ``stdin`` to both ``stderr`` and ``stdout``.
|
| 576 |
+
* update : bool, optional
|
| 577 |
+
If true, will treat input as newly elapsed iterations,
|
| 578 |
+
i.e. numbers to pass to ``update()``. Note that this is slow
|
| 579 |
+
(~2e5 it/s) since every input must be decoded as a number.
|
| 580 |
+
* update_to : bool, optional
|
| 581 |
+
If true, will treat input as total elapsed iterations,
|
| 582 |
+
i.e. numbers to assign to ``self.n``. Note that this is slow
|
| 583 |
+
(~2e5 it/s) since every input must be decoded as a number.
|
| 584 |
+
* null : bool, optional
|
| 585 |
+
If true, will discard input (no stdout).
|
| 586 |
+
* manpath : str, optional
|
| 587 |
+
Directory in which to install tqdm man pages.
|
| 588 |
+
* comppath : str, optional
|
| 589 |
+
Directory in which to place tqdm completion.
|
| 590 |
+
* log : str, optional
|
| 591 |
+
CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
|
| 592 |
+
|
| 593 |
+
Returns
|
| 594 |
+
~~~~~~~
|
| 595 |
+
|
| 596 |
+
* out : decorated iterator.
|
| 597 |
+
|
| 598 |
+
.. code:: python
|
| 599 |
+
|
| 600 |
+
class tqdm():
|
| 601 |
+
def update(self, n=1):
|
| 602 |
+
"""
|
| 603 |
+
Manually update the progress bar, useful for streams
|
| 604 |
+
such as reading files.
|
| 605 |
+
E.g.:
|
| 606 |
+
>>> t = tqdm(total=filesize) # Initialise
|
| 607 |
+
>>> for current_buffer in stream:
|
| 608 |
+
... ...
|
| 609 |
+
... t.update(len(current_buffer))
|
| 610 |
+
>>> t.close()
|
| 611 |
+
The last line is highly recommended, but possibly not necessary if
|
| 612 |
+
``t.update()`` will be called in such a way that ``filesize`` will be
|
| 613 |
+
exactly reached and printed.
|
| 614 |
+
|
| 615 |
+
Parameters
|
| 616 |
+
----------
|
| 617 |
+
n : int or float, optional
|
| 618 |
+
Increment to add to the internal counter of iterations
|
| 619 |
+
[default: 1]. If using float, consider specifying ``{n:.3f}``
|
| 620 |
+
or similar in ``bar_format``, or specifying ``unit_scale``.
|
| 621 |
+
|
| 622 |
+
Returns
|
| 623 |
+
-------
|
| 624 |
+
out : bool or None
|
| 625 |
+
True if a ``display()`` was triggered.
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
def close(self):
|
| 629 |
+
"""Cleanup and (if leave=False) close the progressbar."""
|
| 630 |
+
|
| 631 |
+
def clear(self, nomove=False):
|
| 632 |
+
"""Clear current bar display."""
|
| 633 |
+
|
| 634 |
+
def refresh(self):
|
| 635 |
+
"""
|
| 636 |
+
Force refresh the display of this bar.
|
| 637 |
+
|
| 638 |
+
Parameters
|
| 639 |
+
----------
|
| 640 |
+
nolock : bool, optional
|
| 641 |
+
If ``True``, does not lock.
|
| 642 |
+
If [default: ``False``]: calls ``acquire()`` on internal lock.
|
| 643 |
+
lock_args : tuple, optional
|
| 644 |
+
Passed to internal lock's ``acquire()``.
|
| 645 |
+
If specified, will only ``display()`` if ``acquire()`` returns ``True``.
|
| 646 |
+
"""
|
| 647 |
+
|
| 648 |
+
def unpause(self):
|
| 649 |
+
"""Restart tqdm timer from last print time."""
|
| 650 |
+
|
| 651 |
+
def reset(self, total=None):
|
| 652 |
+
"""
|
| 653 |
+
Resets to 0 iterations for repeated use.
|
| 654 |
+
|
| 655 |
+
Consider combining with ``leave=True``.
|
| 656 |
+
|
| 657 |
+
Parameters
|
| 658 |
+
----------
|
| 659 |
+
total : int or float, optional. Total to use for the new bar.
|
| 660 |
+
"""
|
| 661 |
+
|
| 662 |
+
def set_description(self, desc=None, refresh=True):
|
| 663 |
+
"""
|
| 664 |
+
Set/modify description of the progress bar.
|
| 665 |
+
|
| 666 |
+
Parameters
|
| 667 |
+
----------
|
| 668 |
+
desc : str, optional
|
| 669 |
+
refresh : bool, optional
|
| 670 |
+
Forces refresh [default: True].
|
| 671 |
+
"""
|
| 672 |
+
|
| 673 |
+
def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs):
|
| 674 |
+
"""
|
| 675 |
+
Set/modify postfix (additional stats)
|
| 676 |
+
with automatic formatting based on datatype.
|
| 677 |
+
|
| 678 |
+
Parameters
|
| 679 |
+
----------
|
| 680 |
+
ordered_dict : dict or OrderedDict, optional
|
| 681 |
+
refresh : bool, optional
|
| 682 |
+
Forces refresh [default: True].
|
| 683 |
+
kwargs : dict, optional
|
| 684 |
+
"""
|
| 685 |
+
|
| 686 |
+
@classmethod
|
| 687 |
+
def write(cls, s, file=sys.stdout, end="\n"):
|
| 688 |
+
"""Print a message via tqdm (without overlap with bars)."""
|
| 689 |
+
|
| 690 |
+
@property
|
| 691 |
+
def format_dict(self):
|
| 692 |
+
"""Public API for read-only member access."""
|
| 693 |
+
|
| 694 |
+
def display(self, msg=None, pos=None):
|
| 695 |
+
"""
|
| 696 |
+
Use ``self.sp`` to display ``msg`` in the specified ``pos``.
|
| 697 |
+
|
| 698 |
+
Consider overloading this function when inheriting to use e.g.:
|
| 699 |
+
``self.some_frontend(**self.format_dict)`` instead of ``self.sp``.
|
| 700 |
+
|
| 701 |
+
Parameters
|
| 702 |
+
----------
|
| 703 |
+
msg : str, optional. What to display (default: ``repr(self)``).
|
| 704 |
+
pos : int, optional. Position to ``moveto``
|
| 705 |
+
(default: ``abs(self.pos)``).
|
| 706 |
+
"""
|
| 707 |
+
|
| 708 |
+
@classmethod
|
| 709 |
+
@contextmanager
|
| 710 |
+
def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
|
| 711 |
+
"""
|
| 712 |
+
stream : file-like object.
|
| 713 |
+
method : str, "read" or "write". The result of ``read()`` and
|
| 714 |
+
the first argument of ``write()`` should have a ``len()``.
|
| 715 |
+
|
| 716 |
+
>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
|
| 717 |
+
... while True:
|
| 718 |
+
... chunk = fobj.read(chunk_size)
|
| 719 |
+
... if not chunk:
|
| 720 |
+
... break
|
| 721 |
+
"""
|
| 722 |
+
|
| 723 |
+
@classmethod
|
| 724 |
+
def pandas(cls, *targs, **tqdm_kwargs):
|
| 725 |
+
"""Registers the current `tqdm` class with `pandas`."""
|
| 726 |
+
|
| 727 |
+
def trange(*args, **tqdm_kwargs):
|
| 728 |
+
"""Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
|
| 729 |
+
|
| 730 |
+
Convenience Functions
|
| 731 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 732 |
+
|
| 733 |
+
.. code:: python
|
| 734 |
+
|
| 735 |
+
def tqdm.contrib.tenumerate(iterable, start=0, total=None,
|
| 736 |
+
tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs):
|
| 737 |
+
"""Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
|
| 738 |
+
|
| 739 |
+
def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs):
|
| 740 |
+
"""Equivalent of builtin `zip`."""
|
| 741 |
+
|
| 742 |
+
def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs):
|
| 743 |
+
"""Equivalent of builtin `map`."""
|
| 744 |
+
|
| 745 |
+
Submodules
|
| 746 |
+
~~~~~~~~~~
|
| 747 |
+
|
| 748 |
+
.. code:: python
|
| 749 |
+
|
| 750 |
+
class tqdm.notebook.tqdm(tqdm.tqdm):
|
| 751 |
+
"""IPython/Jupyter Notebook widget."""
|
| 752 |
+
|
| 753 |
+
class tqdm.auto.tqdm(tqdm.tqdm):
|
| 754 |
+
"""Automatically chooses beween `tqdm.notebook` and `tqdm.tqdm`."""
|
| 755 |
+
|
| 756 |
+
class tqdm.asyncio.tqdm(tqdm.tqdm):
|
| 757 |
+
"""Asynchronous version."""
|
| 758 |
+
@classmethod
|
| 759 |
+
def as_completed(cls, fs, *, loop=None, timeout=None, total=None,
|
| 760 |
+
**tqdm_kwargs):
|
| 761 |
+
"""Wrapper for `asyncio.as_completed`."""
|
| 762 |
+
|
| 763 |
+
class tqdm.gui.tqdm(tqdm.tqdm):
|
| 764 |
+
"""Matplotlib GUI version."""
|
| 765 |
+
|
| 766 |
+
class tqdm.tk.tqdm(tqdm.tqdm):
|
| 767 |
+
"""Tkinter GUI version."""
|
| 768 |
+
|
| 769 |
+
class tqdm.rich.tqdm(tqdm.tqdm):
|
| 770 |
+
"""`rich.progress` version."""
|
| 771 |
+
|
| 772 |
+
class tqdm.keras.TqdmCallback(keras.callbacks.Callback):
|
| 773 |
+
"""Keras callback for epoch and batch progress."""
|
| 774 |
+
|
| 775 |
+
class tqdm.dask.TqdmCallback(dask.callbacks.Callback):
|
| 776 |
+
"""Dask callback for task progress."""
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
``contrib``
|
| 780 |
+
+++++++++++
|
| 781 |
+
|
| 782 |
+
The ``tqdm.contrib`` package also contains experimental modules:
|
| 783 |
+
|
| 784 |
+
- ``tqdm.contrib.itertools``: Thin wrappers around ``itertools``
|
| 785 |
+
- ``tqdm.contrib.concurrent``: Thin wrappers around ``concurrent.futures``
|
| 786 |
+
- ``tqdm.contrib.slack``: Posts to `Slack <https://slack.com>`__ bots
|
| 787 |
+
- ``tqdm.contrib.discord``: Posts to `Discord <https://discord.com>`__ bots
|
| 788 |
+
- ``tqdm.contrib.telegram``: Posts to `Telegram <https://telegram.org>`__ bots
|
| 789 |
+
- ``tqdm.contrib.bells``: Automagically enables all optional features
|
| 790 |
+
|
| 791 |
+
* ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram``
|
| 792 |
+
|
| 793 |
+
Examples and Advanced Usage
|
| 794 |
+
---------------------------
|
| 795 |
+
|
| 796 |
+
- See the `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
|
| 797 |
+
folder;
|
| 798 |
+
- import the module and run ``help()``;
|
| 799 |
+
- consult the `wiki <https://github.com/tqdm/tqdm/wiki>`__;
|
| 800 |
+
|
| 801 |
+
* this has an
|
| 802 |
+
`excellent article <https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar>`__
|
| 803 |
+
on how to make a **great** progressbar;
|
| 804 |
+
|
| 805 |
+
- check out the `slides from PyData London <https://tqdm.github.io/PyData2019/slides.html>`__, or
|
| 806 |
+
- run the |binder-demo|.
|
| 807 |
+
|
| 808 |
+
Description and additional stats
|
| 809 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 810 |
+
|
| 811 |
+
Custom information can be displayed and updated dynamically on ``tqdm`` bars
|
| 812 |
+
with the ``desc`` and ``postfix`` arguments:
|
| 813 |
+
|
| 814 |
+
.. code:: python
|
| 815 |
+
|
| 816 |
+
from tqdm import tqdm, trange
|
| 817 |
+
from random import random, randint
|
| 818 |
+
from time import sleep
|
| 819 |
+
|
| 820 |
+
with trange(10) as t:
|
| 821 |
+
for i in t:
|
| 822 |
+
# Description will be displayed on the left
|
| 823 |
+
t.set_description('GEN %i' % i)
|
| 824 |
+
# Postfix will be displayed on the right,
|
| 825 |
+
# formatted automatically based on argument's datatype
|
| 826 |
+
t.set_postfix(loss=random(), gen=randint(1,999), str='h',
|
| 827 |
+
lst=[1, 2])
|
| 828 |
+
sleep(0.1)
|
| 829 |
+
|
| 830 |
+
with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}",
|
| 831 |
+
postfix=["Batch", {"value": 0}]) as t:
|
| 832 |
+
for i in range(10):
|
| 833 |
+
sleep(0.1)
|
| 834 |
+
t.postfix[1]["value"] = i / 2
|
| 835 |
+
t.update()
|
| 836 |
+
|
| 837 |
+
Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string:
|
| 838 |
+
|
| 839 |
+
- ``postfix`` also needs to be passed as an initial argument in a compatible
|
| 840 |
+
format, and
|
| 841 |
+
- ``postfix`` will be auto-converted to a string if it is a ``dict``-like
|
| 842 |
+
object. To prevent this behaviour, insert an extra item into the dictionary
|
| 843 |
+
where the key is not a string.
|
| 844 |
+
|
| 845 |
+
Additional ``bar_format`` parameters may also be defined by overriding
|
| 846 |
+
``format_dict``, and the bar itself may be modified using ``ascii``:
|
| 847 |
+
|
| 848 |
+
.. code:: python
|
| 849 |
+
|
| 850 |
+
from tqdm import tqdm
|
| 851 |
+
class TqdmExtraFormat(tqdm):
|
| 852 |
+
"""Provides a `total_time` format parameter"""
|
| 853 |
+
@property
|
| 854 |
+
def format_dict(self):
|
| 855 |
+
d = super().format_dict
|
| 856 |
+
total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
|
| 857 |
+
d.update(total_time=self.format_interval(total_time) + " in total")
|
| 858 |
+
return d
|
| 859 |
+
|
| 860 |
+
for i in TqdmExtraFormat(
|
| 861 |
+
range(9), ascii=" .oO0",
|
| 862 |
+
bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"):
|
| 863 |
+
if i == 4:
|
| 864 |
+
break
|
| 865 |
+
|
| 866 |
+
.. code::
|
| 867 |
+
|
| 868 |
+
00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s]
|
| 869 |
+
|
| 870 |
+
Note that ``{bar}`` also supports a format specifier ``[width][type]``.
|
| 871 |
+
|
| 872 |
+
- ``width``
|
| 873 |
+
|
| 874 |
+
* unspecified (default): automatic to fill ``ncols``
|
| 875 |
+
* ``int >= 0``: fixed width overriding ``ncols`` logic
|
| 876 |
+
* ``int < 0``: subtract from the automatic default
|
| 877 |
+
|
| 878 |
+
- ``type``
|
| 879 |
+
|
| 880 |
+
* ``a``: ascii (``ascii=True`` override)
|
| 881 |
+
* ``u``: unicode (``ascii=False`` override)
|
| 882 |
+
* ``b``: blank (``ascii=" "`` override)
|
| 883 |
+
|
| 884 |
+
This means a fixed bar with right-justified text may be created by using:
|
| 885 |
+
``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"``
|
| 886 |
+
|
| 887 |
+
Nested progress bars
|
| 888 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 889 |
+
|
| 890 |
+
``tqdm`` supports nested progress bars. Here's an example:
|
| 891 |
+
|
| 892 |
+
.. code:: python
|
| 893 |
+
|
| 894 |
+
from tqdm.auto import trange
|
| 895 |
+
from time import sleep
|
| 896 |
+
|
| 897 |
+
for i in trange(4, desc='1st loop'):
|
| 898 |
+
for j in trange(5, desc='2nd loop'):
|
| 899 |
+
for k in trange(50, desc='3rd loop', leave=False):
|
| 900 |
+
sleep(0.01)
|
| 901 |
+
|
| 902 |
+
For manual control over positioning (e.g. for multi-processing use),
|
| 903 |
+
you may specify ``position=n`` where ``n=0`` for the outermost bar,
|
| 904 |
+
``n=1`` for the next, and so on.
|
| 905 |
+
However, it's best to check if ``tqdm`` can work without manual ``position``
|
| 906 |
+
first.
|
| 907 |
+
|
| 908 |
+
.. code:: python
|
| 909 |
+
|
| 910 |
+
from time import sleep
|
| 911 |
+
from tqdm import trange, tqdm
|
| 912 |
+
from multiprocessing import Pool, RLock, freeze_support
|
| 913 |
+
|
| 914 |
+
L = list(range(9))
|
| 915 |
+
|
| 916 |
+
def progresser(n):
|
| 917 |
+
interval = 0.001 / (n + 2)
|
| 918 |
+
total = 5000
|
| 919 |
+
text = f"#{n}, est. {interval * total:<04.2}s"
|
| 920 |
+
for _ in trange(total, desc=text, position=n):
|
| 921 |
+
sleep(interval)
|
| 922 |
+
|
| 923 |
+
if __name__ == '__main__':
|
| 924 |
+
freeze_support() # for Windows support
|
| 925 |
+
tqdm.set_lock(RLock()) # for managing output contention
|
| 926 |
+
p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),))
|
| 927 |
+
p.map(progresser, L)
|
| 928 |
+
|
| 929 |
+
Note that in Python 3, ``tqdm.write`` is thread-safe:
|
| 930 |
+
|
| 931 |
+
.. code:: python
|
| 932 |
+
|
| 933 |
+
from time import sleep
|
| 934 |
+
from tqdm import tqdm, trange
|
| 935 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 936 |
+
|
| 937 |
+
L = list(range(9))
|
| 938 |
+
|
| 939 |
+
def progresser(n):
|
| 940 |
+
interval = 0.001 / (n + 2)
|
| 941 |
+
total = 5000
|
| 942 |
+
text = f"#{n}, est. {interval * total:<04.2}s"
|
| 943 |
+
for _ in trange(total, desc=text):
|
| 944 |
+
sleep(interval)
|
| 945 |
+
if n == 6:
|
| 946 |
+
tqdm.write("n == 6 completed.")
|
| 947 |
+
tqdm.write("`tqdm.write()` is thread-safe in py3!")
|
| 948 |
+
|
| 949 |
+
if __name__ == '__main__':
|
| 950 |
+
with ThreadPoolExecutor() as p:
|
| 951 |
+
p.map(progresser, L)
|
| 952 |
+
|
| 953 |
+
Hooks and callbacks
|
| 954 |
+
~~~~~~~~~~~~~~~~~~~
|
| 955 |
+
|
| 956 |
+
``tqdm`` can easily support callbacks/hooks and manual updates.
|
| 957 |
+
Here's an example with ``urllib``:
|
| 958 |
+
|
| 959 |
+
**``urllib.urlretrieve`` documentation**
|
| 960 |
+
|
| 961 |
+
| [...]
|
| 962 |
+
| If present, the hook function will be called once
|
| 963 |
+
| on establishment of the network connection and once after each block read
|
| 964 |
+
| thereafter. The hook will be passed three arguments; a count of blocks
|
| 965 |
+
| transferred so far, a block size in bytes, and the total size of the file.
|
| 966 |
+
| [...]
|
| 967 |
+
|
| 968 |
+
.. code:: python
|
| 969 |
+
|
| 970 |
+
import urllib, os
|
| 971 |
+
from tqdm import tqdm
|
| 972 |
+
urllib = getattr(urllib, 'request', urllib)
|
| 973 |
+
|
| 974 |
+
class TqdmUpTo(tqdm):
|
| 975 |
+
"""Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
|
| 976 |
+
def update_to(self, b=1, bsize=1, tsize=None):
|
| 977 |
+
"""
|
| 978 |
+
b : int, optional
|
| 979 |
+
Number of blocks transferred so far [default: 1].
|
| 980 |
+
bsize : int, optional
|
| 981 |
+
Size of each block (in tqdm units) [default: 1].
|
| 982 |
+
tsize : int, optional
|
| 983 |
+
Total size (in tqdm units). If [default: None] remains unchanged.
|
| 984 |
+
"""
|
| 985 |
+
if tsize is not None:
|
| 986 |
+
self.total = tsize
|
| 987 |
+
return self.update(b * bsize - self.n) # also sets self.n = b * bsize
|
| 988 |
+
|
| 989 |
+
eg_link = "https://caspersci.uk.to/matryoshka.zip"
|
| 990 |
+
with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
|
| 991 |
+
desc=eg_link.split('/')[-1]) as t: # all optional kwargs
|
| 992 |
+
urllib.urlretrieve(eg_link, filename=os.devnull,
|
| 993 |
+
reporthook=t.update_to, data=None)
|
| 994 |
+
t.total = t.n
|
| 995 |
+
|
| 996 |
+
Inspired by `twine#242 <https://github.com/pypa/twine/pull/242>`__.
|
| 997 |
+
Functional alternative in
|
| 998 |
+
`examples/tqdm_wget.py <https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py>`__.
|
| 999 |
+
|
| 1000 |
+
It is recommend to use ``miniters=1`` whenever there is potentially
|
| 1001 |
+
large differences in iteration speed (e.g. downloading a file over
|
| 1002 |
+
a patchy connection).
|
| 1003 |
+
|
| 1004 |
+
**Wrapping read/write methods**
|
| 1005 |
+
|
| 1006 |
+
To measure throughput through a file-like object's ``read`` or ``write``
|
| 1007 |
+
methods, use ``CallbackIOWrapper``:
|
| 1008 |
+
|
| 1009 |
+
.. code:: python
|
| 1010 |
+
|
| 1011 |
+
from tqdm.auto import tqdm
|
| 1012 |
+
from tqdm.utils import CallbackIOWrapper
|
| 1013 |
+
|
| 1014 |
+
with tqdm(total=file_obj.size,
|
| 1015 |
+
unit='B', unit_scale=True, unit_divisor=1024) as t:
|
| 1016 |
+
fobj = CallbackIOWrapper(t.update, file_obj, "read")
|
| 1017 |
+
while True:
|
| 1018 |
+
chunk = fobj.read(chunk_size)
|
| 1019 |
+
if not chunk:
|
| 1020 |
+
break
|
| 1021 |
+
t.reset()
|
| 1022 |
+
# ... continue to use `t` for something else
|
| 1023 |
+
|
| 1024 |
+
Alternatively, use the even simpler ``wrapattr`` convenience function,
|
| 1025 |
+
which would condense both the ``urllib`` and ``CallbackIOWrapper`` examples
|
| 1026 |
+
down to:
|
| 1027 |
+
|
| 1028 |
+
.. code:: python
|
| 1029 |
+
|
| 1030 |
+
import urllib, os
|
| 1031 |
+
from tqdm import tqdm
|
| 1032 |
+
|
| 1033 |
+
eg_link = "https://caspersci.uk.to/matryoshka.zip"
|
| 1034 |
+
response = getattr(urllib, 'request', urllib).urlopen(eg_link)
|
| 1035 |
+
with tqdm.wrapattr(open(os.devnull, "wb"), "write",
|
| 1036 |
+
miniters=1, desc=eg_link.split('/')[-1],
|
| 1037 |
+
total=getattr(response, 'length', None)) as fout:
|
| 1038 |
+
for chunk in response:
|
| 1039 |
+
fout.write(chunk)
|
| 1040 |
+
|
| 1041 |
+
The ``requests`` equivalent is nearly identical:
|
| 1042 |
+
|
| 1043 |
+
.. code:: python
|
| 1044 |
+
|
| 1045 |
+
import requests, os
|
| 1046 |
+
from tqdm import tqdm
|
| 1047 |
+
|
| 1048 |
+
eg_link = "https://caspersci.uk.to/matryoshka.zip"
|
| 1049 |
+
response = requests.get(eg_link, stream=True)
|
| 1050 |
+
with tqdm.wrapattr(open(os.devnull, "wb"), "write",
|
| 1051 |
+
miniters=1, desc=eg_link.split('/')[-1],
|
| 1052 |
+
total=int(response.headers.get('content-length', 0))) as fout:
|
| 1053 |
+
for chunk in response.iter_content(chunk_size=4096):
|
| 1054 |
+
fout.write(chunk)
|
| 1055 |
+
|
| 1056 |
+
**Custom callback**
|
| 1057 |
+
|
| 1058 |
+
``tqdm`` is known for intelligently skipping unnecessary displays. To make a
|
| 1059 |
+
custom callback take advantage of this, simply use the return value of
|
| 1060 |
+
``update()``. This is set to ``True`` if a ``display()`` was triggered.
|
| 1061 |
+
|
| 1062 |
+
.. code:: python
|
| 1063 |
+
|
| 1064 |
+
from tqdm.auto import tqdm as std_tqdm
|
| 1065 |
+
|
| 1066 |
+
def external_callback(*args, **kwargs):
|
| 1067 |
+
...
|
| 1068 |
+
|
| 1069 |
+
class TqdmExt(std_tqdm):
|
| 1070 |
+
def update(self, n=1):
|
| 1071 |
+
displayed = super().update(n)
|
| 1072 |
+
if displayed:
|
| 1073 |
+
external_callback(**self.format_dict)
|
| 1074 |
+
return displayed
|
| 1075 |
+
|
| 1076 |
+
``asyncio``
|
| 1077 |
+
~~~~~~~~~~~
|
| 1078 |
+
|
| 1079 |
+
Note that ``break`` isn't currently caught by asynchronous iterators.
|
| 1080 |
+
This means that ``tqdm`` cannot clean up after itself in this case:
|
| 1081 |
+
|
| 1082 |
+
.. code:: python
|
| 1083 |
+
|
| 1084 |
+
from tqdm.asyncio import tqdm
|
| 1085 |
+
|
| 1086 |
+
async for i in tqdm(range(9)):
|
| 1087 |
+
if i == 2:
|
| 1088 |
+
break
|
| 1089 |
+
|
| 1090 |
+
Instead, either call ``pbar.close()`` manually or use the context manager syntax:
|
| 1091 |
+
|
| 1092 |
+
.. code:: python
|
| 1093 |
+
|
| 1094 |
+
from tqdm.asyncio import tqdm
|
| 1095 |
+
|
| 1096 |
+
with tqdm(range(9)) as pbar:
|
| 1097 |
+
async for i in pbar:
|
| 1098 |
+
if i == 2:
|
| 1099 |
+
break
|
| 1100 |
+
|
| 1101 |
+
Pandas Integration
|
| 1102 |
+
~~~~~~~~~~~~~~~~~~
|
| 1103 |
+
|
| 1104 |
+
Due to popular demand we've added support for ``pandas`` -- here's an example
|
| 1105 |
+
for ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``:
|
| 1106 |
+
|
| 1107 |
+
.. code:: python
|
| 1108 |
+
|
| 1109 |
+
import pandas as pd
|
| 1110 |
+
import numpy as np
|
| 1111 |
+
from tqdm import tqdm
|
| 1112 |
+
|
| 1113 |
+
df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
|
| 1114 |
+
|
| 1115 |
+
# Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
|
| 1116 |
+
# (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.)
|
| 1117 |
+
tqdm.pandas(desc="my bar!")
|
| 1118 |
+
|
| 1119 |
+
# Now you can use `progress_apply` instead of `apply`
|
| 1120 |
+
# and `progress_map` instead of `map`
|
| 1121 |
+
df.progress_apply(lambda x: x**2)
|
| 1122 |
+
# can also groupby:
|
| 1123 |
+
# df.groupby(0).progress_apply(lambda x: x**2)
|
| 1124 |
+
|
| 1125 |
+
In case you're interested in how this works (and how to modify it for your
|
| 1126 |
+
own callbacks), see the
|
| 1127 |
+
`examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
|
| 1128 |
+
folder or import the module and run ``help()``.
|
| 1129 |
+
|
| 1130 |
+
Keras Integration
|
| 1131 |
+
~~~~~~~~~~~~~~~~~
|
| 1132 |
+
|
| 1133 |
+
A ``keras`` callback is also available:
|
| 1134 |
+
|
| 1135 |
+
.. code:: python
|
| 1136 |
+
|
| 1137 |
+
from tqdm.keras import TqdmCallback
|
| 1138 |
+
|
| 1139 |
+
...
|
| 1140 |
+
|
| 1141 |
+
model.fit(..., verbose=0, callbacks=[TqdmCallback()])
|
| 1142 |
+
|
| 1143 |
+
Dask Integration
|
| 1144 |
+
~~~~~~~~~~~~~~~~
|
| 1145 |
+
|
| 1146 |
+
A ``dask`` callback is also available:
|
| 1147 |
+
|
| 1148 |
+
.. code:: python
|
| 1149 |
+
|
| 1150 |
+
from tqdm.dask import TqdmCallback
|
| 1151 |
+
|
| 1152 |
+
with TqdmCallback(desc="compute"):
|
| 1153 |
+
...
|
| 1154 |
+
arr.compute()
|
| 1155 |
+
|
| 1156 |
+
# or use callback globally
|
| 1157 |
+
cb = TqdmCallback(desc="global")
|
| 1158 |
+
cb.register()
|
| 1159 |
+
arr.compute()
|
| 1160 |
+
|
| 1161 |
+
IPython/Jupyter Integration
|
| 1162 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1163 |
+
|
| 1164 |
+
IPython/Jupyter is supported via the ``tqdm.notebook`` submodule:
|
| 1165 |
+
|
| 1166 |
+
.. code:: python
|
| 1167 |
+
|
| 1168 |
+
from tqdm.notebook import trange, tqdm
|
| 1169 |
+
from time import sleep
|
| 1170 |
+
|
| 1171 |
+
for i in trange(3, desc='1st loop'):
|
| 1172 |
+
for j in tqdm(range(100), desc='2nd loop'):
|
| 1173 |
+
sleep(0.01)
|
| 1174 |
+
|
| 1175 |
+
In addition to ``tqdm`` features, the submodule provides a native Jupyter
|
| 1176 |
+
widget (compatible with IPython v1-v4 and Jupyter), fully working nested bars
|
| 1177 |
+
and colour hints (blue: normal, green: completed, red: error/interrupt,
|
| 1178 |
+
light blue: no ETA); as demonstrated below.
|
| 1179 |
+
|
| 1180 |
+
|Screenshot-Jupyter1|
|
| 1181 |
+
|Screenshot-Jupyter2|
|
| 1182 |
+
|Screenshot-Jupyter3|
|
| 1183 |
+
|
| 1184 |
+
The ``notebook`` version supports percentage or pixels for overall width
|
| 1185 |
+
(e.g.: ``ncols='100%'`` or ``ncols='480px'``).
|
| 1186 |
+
|
| 1187 |
+
It is also possible to let ``tqdm`` automatically choose between
|
| 1188 |
+
console or notebook versions by using the ``autonotebook`` submodule:
|
| 1189 |
+
|
| 1190 |
+
.. code:: python
|
| 1191 |
+
|
| 1192 |
+
from tqdm.autonotebook import tqdm
|
| 1193 |
+
tqdm.pandas()
|
| 1194 |
+
|
| 1195 |
+
Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebook
|
| 1196 |
+
since it is not meant to be possible to distinguish between ``jupyter notebook``
|
| 1197 |
+
and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppress
|
| 1198 |
+
this warning.
|
| 1199 |
+
|
| 1200 |
+
Note that notebooks will display the bar in the cell where it was created.
|
| 1201 |
+
This may be a different cell from the one where it is used.
|
| 1202 |
+
If this is not desired, either
|
| 1203 |
+
|
| 1204 |
+
- delay the creation of the bar to the cell where it must be displayed, or
|
| 1205 |
+
- create the bar with ``display=False``, and in a later cell call
|
| 1206 |
+
``display(bar.container)``:
|
| 1207 |
+
|
| 1208 |
+
.. code:: python
|
| 1209 |
+
|
| 1210 |
+
from tqdm.notebook import tqdm
|
| 1211 |
+
pbar = tqdm(..., display=False)
|
| 1212 |
+
|
| 1213 |
+
.. code:: python
|
| 1214 |
+
|
| 1215 |
+
# different cell
|
| 1216 |
+
display(pbar.container)
|
| 1217 |
+
|
| 1218 |
+
The ``keras`` callback has a ``display()`` method which can be used likewise:
|
| 1219 |
+
|
| 1220 |
+
.. code:: python
|
| 1221 |
+
|
| 1222 |
+
from tqdm.keras import TqdmCallback
|
| 1223 |
+
cbk = TqdmCallback(display=False)
|
| 1224 |
+
|
| 1225 |
+
.. code:: python
|
| 1226 |
+
|
| 1227 |
+
# different cell
|
| 1228 |
+
cbk.display()
|
| 1229 |
+
model.fit(..., verbose=0, callbacks=[cbk])
|
| 1230 |
+
|
| 1231 |
+
Another possibility is to have a single bar (near the top of the notebook)
|
| 1232 |
+
which is constantly re-used (using ``reset()`` rather than ``close()``).
|
| 1233 |
+
For this reason, the notebook version (unlike the CLI version) does not
|
| 1234 |
+
automatically call ``close()`` upon ``Exception``.
|
| 1235 |
+
|
| 1236 |
+
.. code:: python
|
| 1237 |
+
|
| 1238 |
+
from tqdm.notebook import tqdm
|
| 1239 |
+
pbar = tqdm()
|
| 1240 |
+
|
| 1241 |
+
.. code:: python
|
| 1242 |
+
|
| 1243 |
+
# different cell
|
| 1244 |
+
iterable = range(100)
|
| 1245 |
+
pbar.reset(total=len(iterable)) # initialise with new `total`
|
| 1246 |
+
for i in iterable:
|
| 1247 |
+
pbar.update()
|
| 1248 |
+
pbar.refresh() # force print final status but don't `close()`
|
| 1249 |
+
|
| 1250 |
+
Custom Integration
|
| 1251 |
+
~~~~~~~~~~~~~~~~~~
|
| 1252 |
+
|
| 1253 |
+
To change the default arguments (such as making ``dynamic_ncols=True``),
|
| 1254 |
+
simply use built-in Python magic:
|
| 1255 |
+
|
| 1256 |
+
.. code:: python
|
| 1257 |
+
|
| 1258 |
+
from functools import partial
|
| 1259 |
+
from tqdm import tqdm as std_tqdm
|
| 1260 |
+
tqdm = partial(std_tqdm, dynamic_ncols=True)
|
| 1261 |
+
|
| 1262 |
+
For further customisation,
|
| 1263 |
+
``tqdm`` may be inherited from to create custom callbacks (as with the
|
| 1264 |
+
``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends
|
| 1265 |
+
(e.g. GUIs such as notebook or plotting packages). In the latter case:
|
| 1266 |
+
|
| 1267 |
+
1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable
|
| 1268 |
+
terminal ``status_printer`` creation.
|
| 1269 |
+
2. Redefine: ``close()``, ``clear()``, ``display()``.
|
| 1270 |
+
|
| 1271 |
+
Consider overloading ``display()`` to use e.g.
|
| 1272 |
+
``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``.
|
| 1273 |
+
|
| 1274 |
+
Some submodule examples of inheritance:
|
| 1275 |
+
|
| 1276 |
+
- `tqdm/notebook.py <https://github.com/tqdm/tqdm/blob/master/tqdm/notebook.py>`__
|
| 1277 |
+
- `tqdm/gui.py <https://github.com/tqdm/tqdm/blob/master/tqdm/gui.py>`__
|
| 1278 |
+
- `tqdm/tk.py <https://github.com/tqdm/tqdm/blob/master/tqdm/tk.py>`__
|
| 1279 |
+
- `tqdm/contrib/slack.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/slack.py>`__
|
| 1280 |
+
- `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__
|
| 1281 |
+
- `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
|
| 1282 |
+
|
| 1283 |
+
Dynamic Monitor/Meter
|
| 1284 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 1285 |
+
|
| 1286 |
+
You can use a ``tqdm`` as a meter which is not monotonically increasing.
|
| 1287 |
+
This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total``
|
| 1288 |
+
changes.
|
| 1289 |
+
|
| 1290 |
+
One example would be recursively searching for files. The ``total`` is the
|
| 1291 |
+
number of objects found so far, while ``n`` is the number of those objects which
|
| 1292 |
+
are files (rather than folders):
|
| 1293 |
+
|
| 1294 |
+
.. code:: python
|
| 1295 |
+
|
| 1296 |
+
from tqdm import tqdm
|
| 1297 |
+
import os.path
|
| 1298 |
+
|
| 1299 |
+
def find_files_recursively(path, show_progress=True):
|
| 1300 |
+
files = []
|
| 1301 |
+
# total=1 assumes `path` is a file
|
| 1302 |
+
t = tqdm(total=1, unit="file", disable=not show_progress)
|
| 1303 |
+
if not os.path.exists(path):
|
| 1304 |
+
raise IOError("Cannot find:" + path)
|
| 1305 |
+
|
| 1306 |
+
def append_found_file(f):
|
| 1307 |
+
files.append(f)
|
| 1308 |
+
t.update()
|
| 1309 |
+
|
| 1310 |
+
def list_found_dir(path):
|
| 1311 |
+
"""returns os.listdir(path) assuming os.path.isdir(path)"""
|
| 1312 |
+
listing = os.listdir(path)
|
| 1313 |
+
# subtract 1 since a "file" we found was actually this directory
|
| 1314 |
+
t.total += len(listing) - 1
|
| 1315 |
+
# fancy way to give info without forcing a refresh
|
| 1316 |
+
t.set_postfix(dir=path[-10:], refresh=False)
|
| 1317 |
+
t.update(0) # may trigger a refresh
|
| 1318 |
+
return listing
|
| 1319 |
+
|
| 1320 |
+
def recursively_search(path):
|
| 1321 |
+
if os.path.isdir(path):
|
| 1322 |
+
for f in list_found_dir(path):
|
| 1323 |
+
recursively_search(os.path.join(path, f))
|
| 1324 |
+
else:
|
| 1325 |
+
append_found_file(path)
|
| 1326 |
+
|
| 1327 |
+
recursively_search(path)
|
| 1328 |
+
t.set_postfix(dir=path)
|
| 1329 |
+
t.close()
|
| 1330 |
+
return files
|
| 1331 |
+
|
| 1332 |
+
Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger a
|
| 1333 |
+
display refresh to avoid console spamming.
|
| 1334 |
+
|
| 1335 |
+
Writing messages
|
| 1336 |
+
~~~~~~~~~~~~~~~~
|
| 1337 |
+
|
| 1338 |
+
This is a work in progress (see
|
| 1339 |
+
`#737 <https://github.com/tqdm/tqdm/issues/737>`__).
|
| 1340 |
+
|
| 1341 |
+
Since ``tqdm`` uses a simple printing mechanism to display progress bars,
|
| 1342 |
+
you should not write any message in the terminal using ``print()`` while
|
| 1343 |
+
a progressbar is open.
|
| 1344 |
+
|
| 1345 |
+
To write messages in the terminal without any collision with ``tqdm`` bar
|
| 1346 |
+
display, a ``.write()`` method is provided:
|
| 1347 |
+
|
| 1348 |
+
.. code:: python
|
| 1349 |
+
|
| 1350 |
+
from tqdm.auto import tqdm, trange
|
| 1351 |
+
from time import sleep
|
| 1352 |
+
|
| 1353 |
+
bar = trange(10)
|
| 1354 |
+
for i in bar:
|
| 1355 |
+
# Print using tqdm class method .write()
|
| 1356 |
+
sleep(0.1)
|
| 1357 |
+
if not (i % 3):
|
| 1358 |
+
tqdm.write("Done task %i" % i)
|
| 1359 |
+
# Can also use bar.write()
|
| 1360 |
+
|
| 1361 |
+
By default, this will print to standard output ``sys.stdout``. but you can
|
| 1362 |
+
specify any file-like object using the ``file`` argument. For example, this
|
| 1363 |
+
can be used to redirect the messages writing to a log file or class.
|
| 1364 |
+
|
| 1365 |
+
Redirecting writing
|
| 1366 |
+
~~~~~~~~~~~~~~~~~~~
|
| 1367 |
+
|
| 1368 |
+
If using a library that can print messages to the console, editing the library
|
| 1369 |
+
by replacing ``print()`` with ``tqdm.write()`` may not be desirable.
|
| 1370 |
+
In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option.
|
| 1371 |
+
|
| 1372 |
+
To redirect ``sys.stdout``, create a file-like class that will write
|
| 1373 |
+
any input string to ``tqdm.write()``, and supply the arguments
|
| 1374 |
+
``file=sys.stdout, dynamic_ncols=True``.
|
| 1375 |
+
|
| 1376 |
+
A reusable canonical example is given below:
|
| 1377 |
+
|
| 1378 |
+
.. code:: python
|
| 1379 |
+
|
| 1380 |
+
from time import sleep
|
| 1381 |
+
import contextlib
|
| 1382 |
+
import sys
|
| 1383 |
+
from tqdm import tqdm
|
| 1384 |
+
from tqdm.contrib import DummyTqdmFile
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
@contextlib.contextmanager
|
| 1388 |
+
def std_out_err_redirect_tqdm():
|
| 1389 |
+
orig_out_err = sys.stdout, sys.stderr
|
| 1390 |
+
try:
|
| 1391 |
+
sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
|
| 1392 |
+
yield orig_out_err[0]
|
| 1393 |
+
# Relay exceptions
|
| 1394 |
+
except Exception as exc:
|
| 1395 |
+
raise exc
|
| 1396 |
+
# Always restore sys.stdout/err if necessary
|
| 1397 |
+
finally:
|
| 1398 |
+
sys.stdout, sys.stderr = orig_out_err
|
| 1399 |
+
|
| 1400 |
+
def some_fun(i):
|
| 1401 |
+
print("Fee, fi, fo,".split()[i])
|
| 1402 |
+
|
| 1403 |
+
# Redirect stdout to tqdm.write() (don't forget the `as save_stdout`)
|
| 1404 |
+
with std_out_err_redirect_tqdm() as orig_stdout:
|
| 1405 |
+
# tqdm needs the original stdout
|
| 1406 |
+
# and dynamic_ncols=True to autodetect console width
|
| 1407 |
+
for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True):
|
| 1408 |
+
sleep(.5)
|
| 1409 |
+
some_fun(i)
|
| 1410 |
+
|
| 1411 |
+
# After the `with`, printing is restored
|
| 1412 |
+
print("Done!")
|
| 1413 |
+
|
| 1414 |
+
Redirecting ``logging``
|
| 1415 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 1416 |
+
|
| 1417 |
+
Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging``
|
| 1418 |
+
may also be redirected to ``tqdm.write()``.
|
| 1419 |
+
|
| 1420 |
+
Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure to
|
| 1421 |
+
redirect ``logging`` first if needed.
|
| 1422 |
+
|
| 1423 |
+
Helper methods are available in ``tqdm.contrib.logging``. For example:
|
| 1424 |
+
|
| 1425 |
+
.. code:: python
|
| 1426 |
+
|
| 1427 |
+
import logging
|
| 1428 |
+
from tqdm import trange
|
| 1429 |
+
from tqdm.contrib.logging import logging_redirect_tqdm
|
| 1430 |
+
|
| 1431 |
+
LOG = logging.getLogger(__name__)
|
| 1432 |
+
|
| 1433 |
+
if __name__ == '__main__':
|
| 1434 |
+
logging.basicConfig(level=logging.INFO)
|
| 1435 |
+
with logging_redirect_tqdm():
|
| 1436 |
+
for i in trange(9):
|
| 1437 |
+
if i == 4:
|
| 1438 |
+
LOG.info("console logging redirected to `tqdm.write()`")
|
| 1439 |
+
# logging restored
|
| 1440 |
+
|
| 1441 |
+
Monitoring thread, intervals and miniters
|
| 1442 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1443 |
+
|
| 1444 |
+
``tqdm`` implements a few tricks to increase efficiency and reduce overhead.
|
| 1445 |
+
|
| 1446 |
+
- Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long
|
| 1447 |
+
to wait between each refresh. ``tqdm`` always gets updated in the background,
|
| 1448 |
+
but it will display only every ``mininterval``.
|
| 1449 |
+
- Reduce number of calls to check system clock/time.
|
| 1450 |
+
- ``mininterval`` is more intuitive to configure than ``miniters``.
|
| 1451 |
+
A clever adjustment system ``dynamic_miniters`` will automatically adjust
|
| 1452 |
+
``miniters`` to the amount of iterations that fit into time ``mininterval``.
|
| 1453 |
+
Essentially, ``tqdm`` will check if it's time to print without actually
|
| 1454 |
+
checking time. This behaviour can be still be bypassed by manually setting
|
| 1455 |
+
``miniters``.
|
| 1456 |
+
|
| 1457 |
+
However, consider a case with a combination of fast and slow iterations.
|
| 1458 |
+
After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to a
|
| 1459 |
+
large number. When iteration rate subsequently slows, ``miniters`` will
|
| 1460 |
+
remain large and thus reduce display update frequency. To address this:
|
| 1461 |
+
|
| 1462 |
+
- ``maxinterval`` defines the maximum time between display refreshes.
|
| 1463 |
+
A concurrent monitoring thread checks for overdue updates and forces one
|
| 1464 |
+
where necessary.
|
| 1465 |
+
|
| 1466 |
+
The monitoring thread should not have a noticeable overhead, and guarantees
|
| 1467 |
+
updates at least every 10 seconds by default.
|
| 1468 |
+
This value can be directly changed by setting the ``monitor_interval`` of
|
| 1469 |
+
any ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``).
|
| 1470 |
+
The monitor thread may be disabled application-wide by setting
|
| 1471 |
+
``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar.
|
| 1472 |
+
|
| 1473 |
+
|
| 1474 |
+
Merch
|
| 1475 |
+
-----
|
| 1476 |
+
|
| 1477 |
+
You can buy `tqdm branded merch <https://tqdm.github.io/merch>`__ now!
|
| 1478 |
+
|
| 1479 |
+
Contributions
|
| 1480 |
+
-------------
|
| 1481 |
+
|
| 1482 |
+
|GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices|
|
| 1483 |
+
|
| 1484 |
+
All source code is hosted on `GitHub <https://github.com/tqdm/tqdm>`__.
|
| 1485 |
+
Contributions are welcome.
|
| 1486 |
+
|
| 1487 |
+
See the
|
| 1488 |
+
`CONTRIBUTING <https://github.com/tqdm/tqdm/blob/master/CONTRIBUTING.md>`__
|
| 1489 |
+
file for more information.
|
| 1490 |
+
|
| 1491 |
+
Developers who have made significant contributions, ranked by *SLoC*
|
| 1492 |
+
(surviving lines of code,
|
| 1493 |
+
`git fame <https://github.com/casperdcl/git-fame>`__ ``-wMC --excl '\.(png|gif|jpg)$'``),
|
| 1494 |
+
are:
|
| 1495 |
+
|
| 1496 |
+
==================== ======================================================== ==== ================================
|
| 1497 |
+
Name ID SLoC Notes
|
| 1498 |
+
==================== ======================================================== ==== ================================
|
| 1499 |
+
Casper da Costa-Luis `casperdcl <https://github.com/casperdcl>`__ ~80% primary maintainer |Gift-Casper|
|
| 1500 |
+
Stephen Larroque `lrq3000 <https://github.com/lrq3000>`__ ~9% team member
|
| 1501 |
+
Martin Zugnoni `martinzugnoni <https://github.com/martinzugnoni>`__ ~3%
|
| 1502 |
+
Daniel Ecer `de-code <https://github.com/de-code>`__ ~2%
|
| 1503 |
+
Richard Sheridan `richardsheridan <https://github.com/richardsheridan>`__ ~1%
|
| 1504 |
+
Guangshuo Chen `chengs <https://github.com/chengs>`__ ~1%
|
| 1505 |
+
Helio Machado `0x2b3bfa0 <https://github.com/0x2b3bfa0>`__ ~1%
|
| 1506 |
+
Kyle Altendorf `altendky <https://github.com/altendky>`__ <1%
|
| 1507 |
+
Noam Yorav-Raphael `noamraph <https://github.com/noamraph>`__ <1% original author
|
| 1508 |
+
Matthew Stevens `mjstevens777 <https://github.com/mjstevens777>`__ <1%
|
| 1509 |
+
Hadrien Mary `hadim <https://github.com/hadim>`__ <1% team member
|
| 1510 |
+
Mikhail Korobov `kmike <https://github.com/kmike>`__ <1% team member
|
| 1511 |
+
==================== ======================================================== ==== ================================
|
| 1512 |
+
|
| 1513 |
+
Ports to Other Languages
|
| 1514 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1515 |
+
|
| 1516 |
+
A list is available on
|
| 1517 |
+
`this wiki page <https://github.com/tqdm/tqdm/wiki/tqdm-ports>`__.
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
LICENCE
|
| 1521 |
+
-------
|
| 1522 |
+
|
| 1523 |
+
Open Source (OSI approved): |LICENCE|
|
| 1524 |
+
|
| 1525 |
+
Citation information: |DOI|
|
| 1526 |
+
|
| 1527 |
+
|README-Hits| (Since 19 May 2016)
|
| 1528 |
+
|
| 1529 |
+
.. |Logo| image:: https://tqdm.github.io/img/logo.gif
|
| 1530 |
+
.. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif
|
| 1531 |
+
.. |Video| image:: https://tqdm.github.io/img/video.jpg
|
| 1532 |
+
:target: https://tqdm.github.io/video
|
| 1533 |
+
.. |Slides| image:: https://tqdm.github.io/img/slides.jpg
|
| 1534 |
+
:target: https://tqdm.github.io/PyData2019/slides.html
|
| 1535 |
+
.. |Merch| image:: https://tqdm.github.io/img/merch.jpg
|
| 1536 |
+
:target: https://tqdm.github.io/merch
|
| 1537 |
+
.. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub
|
| 1538 |
+
:target: https://github.com/tqdm/tqdm/actions/workflows/test.yml
|
| 1539 |
+
.. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls
|
| 1540 |
+
:target: https://coveralls.io/github/tqdm/tqdm
|
| 1541 |
+
.. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg
|
| 1542 |
+
:target: https://codecov.io/gh/tqdm/tqdm
|
| 1543 |
+
.. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177
|
| 1544 |
+
:target: https://www.codacy.com/gh/tqdm/tqdm/dashboard
|
| 1545 |
+
.. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge
|
| 1546 |
+
:target: https://bestpractices.coreinfrastructure.org/projects/3264
|
| 1547 |
+
.. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white
|
| 1548 |
+
:target: https://github.com/tqdm/tqdm/releases
|
| 1549 |
+
.. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1550 |
+
:target: https://github.com/tqdm/tqdm/network
|
| 1551 |
+
.. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1552 |
+
:target: https://github.com/tqdm/tqdm/stargazers
|
| 1553 |
+
.. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white
|
| 1554 |
+
:target: https://github.com/tqdm/tqdm/graphs/commit-activity
|
| 1555 |
+
.. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1556 |
+
:target: https://github.com/tqdm/tqdm/issues?q=
|
| 1557 |
+
.. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1558 |
+
:target: https://github.com/tqdm/tqdm/pulls
|
| 1559 |
+
.. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1560 |
+
:target: https://github.com/tqdm/tqdm/graphs/contributors
|
| 1561 |
+
.. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed
|
| 1562 |
+
:target: https://github.com/tqdm/tqdm/pulse
|
| 1563 |
+
.. |Gift-Casper| image:: https://img.shields.io/badge/dynamic/json.svg?color=ff69b4&label=gifts%20received&prefix=%C2%A3&query=%24..sum&url=https%3A%2F%2Fcaspersci.uk.to%2Fgifts.json
|
| 1564 |
+
:target: https://cdcl.ml/sponsor
|
| 1565 |
+
.. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg
|
| 1566 |
+
:target: https://tqdm.github.io/releases
|
| 1567 |
+
.. |PyPI-Downloads| image:: https://img.shields.io/pypi/dm/tqdm.svg?label=pypi%20downloads&logo=PyPI&logoColor=white
|
| 1568 |
+
:target: https://pepy.tech/project/tqdm
|
| 1569 |
+
.. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white
|
| 1570 |
+
:target: https://pypi.org/project/tqdm
|
| 1571 |
+
.. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge
|
| 1572 |
+
:target: https://anaconda.org/conda-forge/tqdm
|
| 1573 |
+
.. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft
|
| 1574 |
+
:target: https://snapcraft.io/tqdm
|
| 1575 |
+
.. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white
|
| 1576 |
+
:target: https://hub.docker.com/r/tqdm/tqdm
|
| 1577 |
+
.. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white
|
| 1578 |
+
:target: https://libraries.io/pypi/tqdm
|
| 1579 |
+
.. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white
|
| 1580 |
+
:target: https://github.com/tqdm/tqdm/network/dependents
|
| 1581 |
+
.. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif
|
| 1582 |
+
:target: https://www.openhub.net/p/tqdm?ref=Thin+badge
|
| 1583 |
+
.. |awesome-python| image:: https://awesome.re/mentioned-badge.svg
|
| 1584 |
+
:target: https://github.com/vinta/awesome-python
|
| 1585 |
+
.. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg
|
| 1586 |
+
:target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE
|
| 1587 |
+
.. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg
|
| 1588 |
+
:target: https://doi.org/10.5281/zenodo.595120
|
| 1589 |
+
.. |binder-demo| image:: https://mybinder.org/badge_logo.svg
|
| 1590 |
+
:target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb
|
| 1591 |
+
.. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif
|
| 1592 |
+
.. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif
|
| 1593 |
+
.. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif
|
| 1594 |
+
.. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif
|
| 1595 |
+
:target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social
|
miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/RECORD
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
../../../bin/tqdm,sha256=73U48CzPisWZ32FTy_S_gWeTwg0o9rZO6gw1G0ZJkFc,438
|
| 2 |
+
tqdm-4.67.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 3 |
+
tqdm-4.67.3.dist-info/METADATA,sha256=fA6aZiwZCV8zmkt2EgHrBs_5xh-5WBU1svlvROcY7Sk,57679
|
| 4 |
+
tqdm-4.67.3.dist-info/RECORD,,
|
| 5 |
+
tqdm-4.67.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
tqdm-4.67.3.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
|
| 7 |
+
tqdm-4.67.3.dist-info/direct_url.json,sha256=nCuD6POfnL1taF9om0CuWT_e3zbNCW9npT8FZ5govwA,90
|
| 8 |
+
tqdm-4.67.3.dist-info/entry_points.txt,sha256=ReJCH7Ui3Zyh6M16E4OhsZ1oU7WtMXCfbtoyBhGO29Y,39
|
| 9 |
+
tqdm-4.67.3.dist-info/licenses/LICENCE,sha256=_P-Hw6R86AKKhRKqGC1PzwrRyQVE7nXPmzQ2hMrBlN4,1985
|
| 10 |
+
tqdm-4.67.3.dist-info/top_level.txt,sha256=NLiUJNfmc9At15s7JURiwvqMEjUi9G5PMGRrmMYzNSM,5
|
| 11 |
+
tqdm/__init__.py,sha256=9mQNYSSqP99JasubEC1POJLMmhkkBH6cJZxPIR5G2pQ,1572
|
| 12 |
+
tqdm/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
| 13 |
+
tqdm/__pycache__/__init__.cpython-313.pyc,,
|
| 14 |
+
tqdm/__pycache__/__main__.cpython-313.pyc,,
|
| 15 |
+
tqdm/__pycache__/_main.cpython-313.pyc,,
|
| 16 |
+
tqdm/__pycache__/_monitor.cpython-313.pyc,,
|
| 17 |
+
tqdm/__pycache__/_tqdm.cpython-313.pyc,,
|
| 18 |
+
tqdm/__pycache__/_tqdm_gui.cpython-313.pyc,,
|
| 19 |
+
tqdm/__pycache__/_tqdm_notebook.cpython-313.pyc,,
|
| 20 |
+
tqdm/__pycache__/_tqdm_pandas.cpython-313.pyc,,
|
| 21 |
+
tqdm/__pycache__/_utils.cpython-313.pyc,,
|
| 22 |
+
tqdm/__pycache__/asyncio.cpython-313.pyc,,
|
| 23 |
+
tqdm/__pycache__/auto.cpython-313.pyc,,
|
| 24 |
+
tqdm/__pycache__/autonotebook.cpython-313.pyc,,
|
| 25 |
+
tqdm/__pycache__/cli.cpython-313.pyc,,
|
| 26 |
+
tqdm/__pycache__/dask.cpython-313.pyc,,
|
| 27 |
+
tqdm/__pycache__/gui.cpython-313.pyc,,
|
| 28 |
+
tqdm/__pycache__/keras.cpython-313.pyc,,
|
| 29 |
+
tqdm/__pycache__/notebook.cpython-313.pyc,,
|
| 30 |
+
tqdm/__pycache__/rich.cpython-313.pyc,,
|
| 31 |
+
tqdm/__pycache__/std.cpython-313.pyc,,
|
| 32 |
+
tqdm/__pycache__/tk.cpython-313.pyc,,
|
| 33 |
+
tqdm/__pycache__/utils.cpython-313.pyc,,
|
| 34 |
+
tqdm/__pycache__/version.cpython-313.pyc,,
|
| 35 |
+
tqdm/_main.py,sha256=9ySvgmi_2Sw4CAo5UDW0Q2dxfTryboEWGHohfCJz0sA,283
|
| 36 |
+
tqdm/_monitor.py,sha256=Uku-DPWgzJ7dO5CK08xKJK-E_F6qQ-JB3ksuXczSYR0,3699
|
| 37 |
+
tqdm/_tqdm.py,sha256=LfLCuJ6bpsVo9xilmtBXyEm1vGnUCFrliW85j3J-nD4,283
|
| 38 |
+
tqdm/_tqdm_gui.py,sha256=03Hc8KayxJveieI5-0-2NGiDpLvw9jZekofJUV7CCwk,287
|
| 39 |
+
tqdm/_tqdm_notebook.py,sha256=BuHiLuxu6uEfZFaPJW3RPpPaxaVctEQA3kdSJSDL1hw,307
|
| 40 |
+
tqdm/_tqdm_pandas.py,sha256=c9jptUgigN6axRDhRd4Rif98Tmxeopc1nFNFhIpbFUE,888
|
| 41 |
+
tqdm/_utils.py,sha256=_4E73bfDj4f1s3sM42NLHNrZDOkijZoWq-n6xWLkdZ8,553
|
| 42 |
+
tqdm/asyncio.py,sha256=Kp2rSkNRf9KRqa3d9YpgeZQ7L7EZf2Ki4bSc7UPIyoo,2757
|
| 43 |
+
tqdm/auto.py,sha256=nDZflj6p2zKkjBCNBourrhS81zYfZy1_dQvbckrdW8o,871
|
| 44 |
+
tqdm/autonotebook.py,sha256=Yb9F5uaiBPhfbDDFpbtoG8I2YUw3uQJ89rUDLbfR6ws,956
|
| 45 |
+
tqdm/cli.py,sha256=orEaahqDEBGZR1uCcTW8BkhSPEhBlSO0BKYbJ1Qgc6k,10994
|
| 46 |
+
tqdm/completion.sh,sha256=j79KbSmpIj_E11jfTfBXrGnUTzKXVpQ1vGVQvsyDRl4,946
|
| 47 |
+
tqdm/contrib/__init__.py,sha256=1GMYYE866WCvlHg5MdmzOvPsQj4ZuMlXzz8xcRcJD60,2479
|
| 48 |
+
tqdm/contrib/__pycache__/__init__.cpython-313.pyc,,
|
| 49 |
+
tqdm/contrib/__pycache__/bells.cpython-313.pyc,,
|
| 50 |
+
tqdm/contrib/__pycache__/concurrent.cpython-313.pyc,,
|
| 51 |
+
tqdm/contrib/__pycache__/discord.cpython-313.pyc,,
|
| 52 |
+
tqdm/contrib/__pycache__/itertools.cpython-313.pyc,,
|
| 53 |
+
tqdm/contrib/__pycache__/logging.cpython-313.pyc,,
|
| 54 |
+
tqdm/contrib/__pycache__/slack.cpython-313.pyc,,
|
| 55 |
+
tqdm/contrib/__pycache__/telegram.cpython-313.pyc,,
|
| 56 |
+
tqdm/contrib/__pycache__/utils_worker.cpython-313.pyc,,
|
| 57 |
+
tqdm/contrib/bells.py,sha256=Yx1HqGCmHrESCAO700j5wE__JCleNODJxedh1ijPLD0,837
|
| 58 |
+
tqdm/contrib/concurrent.py,sha256=K1yjloKS5WRNFyjLRth0DmU5PAnDbF0A-GD27N-J4a8,3986
|
| 59 |
+
tqdm/contrib/discord.py,sha256=MtVIL1s_dxH21G4sL8FBgQ4Wei23ho9Ek5T-AommvNc,5243
|
| 60 |
+
tqdm/contrib/itertools.py,sha256=WdKKQU5eSzsqHu29SN_oH12huYZo0Jihqoi9-nVhwz4,774
|
| 61 |
+
tqdm/contrib/logging.py,sha256=NsYtnKttj2mMrGm58mEdo5a9DP_2vv8pZyrimSuWulA,3760
|
| 62 |
+
tqdm/contrib/slack.py,sha256=eP_Mr5sQonYniHxxQNGue3jk2JkIPmPWFZqIYxnOui0,4007
|
| 63 |
+
tqdm/contrib/telegram.py,sha256=vn_9SATMbbwn2PAbzSDyOX6av3eBB01QBug11P4H-Og,5008
|
| 64 |
+
tqdm/contrib/utils_worker.py,sha256=vaxyJyagYwOCQXLUMd86bCbI4sPqZysuMGbDSGmvEWo,1199
|
| 65 |
+
tqdm/dask.py,sha256=9Ei58eVqTossRLhAfWyUFCduXYKjmLmwkaXIy-CHYfs,1319
|
| 66 |
+
tqdm/gui.py,sha256=STIB3K8iDzDgkNUqWIpvcI_u0OGtbGNy5NwpALXhfWs,5479
|
| 67 |
+
tqdm/keras.py,sha256=op9sBkb6q6c6dw2wJ0SD2ZwpPK7yM1Vbg4l1Qiy3MIo,4373
|
| 68 |
+
tqdm/notebook.py,sha256=scgzRQmDYzIFag_1gRh98LhtZdu3ig2yrmZdqvlgops,10802
|
| 69 |
+
tqdm/rich.py,sha256=YyMPkEHVyYUVUR3adJKbVX26iTmNKpNMf3DEqmm-m60,5021
|
| 70 |
+
tqdm/std.py,sha256=Sk24SwOd59hpNbb0UL8Y3_8ueRmL3_5O72Vy2XKasjE,57510
|
| 71 |
+
tqdm/tk.py,sha256=Gu0uwXwLCGPRGHORdi3WvBLGiseUp_xxX_h_gp9VpK0,6701
|
| 72 |
+
tqdm/tqdm.1,sha256=cDyo6hSykXedJ3Pcx5tkogR1ai3QXRnrJ0MbR2Gd9-s,7581
|
| 73 |
+
tqdm/utils.py,sha256=dpGZUeqoLPinM-kEsULTSe2E3jzp8wUunL6eKzkYOgk,11810
|
| 74 |
+
tqdm/version.py,sha256=oBM1eCOTDZDGZHffNqlehXTeQdKdracckNAEaMRmPjM,337
|
miniconda3/lib/python3.13/site-packages/tqdm-4.67.3.dist-info/REQUESTED
ADDED
|
File without changes
|