changeset 654:0d6673d06c2c

Add support for using "tomllib" (in Python's stdlib since 3.11) and "tomli" TOML packages. They are preferred if they are found to be installed. But note that the declared dependency for the "toml" extra nevertheless is the "toml" package. Because it is available for all supported Python versions. So use Python 3.11+ or install "tomli" manually if you want to use the alternate packages.
author Franz Glasner <fzglas.hg@dom66.de>
date Thu, 19 May 2022 22:10:59 +0200
parents 211288645f02
children b74f20e19c01
files CHANGES.txt configmix/toml.py
diffstat 2 files changed, 42 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/CHANGES.txt	Thu May 19 21:17:39 2022 +0200
+++ b/CHANGES.txt	Thu May 19 22:10:59 2022 +0200
@@ -18,6 +18,17 @@
 - **[feature]**
   Allow to enable and disable the internal caching
 
+- **[feature]**
+  Add support for using :py:mod:`tomllib` (in Python's stdlib since 3.11)
+  and :py:mod:`tomli` TOML packages. They are preferred if they are found
+  to be installed.
+
+  But note that the declared dependency for the ``toml`` extra nevertheless
+  is the :py:mod:`toml` package. Because it is available for all supported
+  Python versions.
+  So use Python 3.11+ or install :py:mod:`tomli` manually if you want to
+  use the alternate packages.
+
 - **[bugfix]**
   For better consistency: use `.getvarl_s()` instead of `.getvarl()`
   in the implementation of `__len__()` in jailed configurations.
--- a/configmix/toml.py	Thu May 19 21:17:39 2022 +0200
+++ b/configmix/toml.py	Thu May 19 22:10:59 2022 +0200
@@ -22,7 +22,22 @@
     except ImportError:
         DictImpl = dict
 
-import toml
+try:
+    import tomllib
+except ImportError:
+    tomllib = None
+    try:
+        import tomli
+    except ImportError:
+        tomli = None
+        try:
+            import toml
+        except ImportError:
+            toml = None
+    else:
+        toml = None
+else:
+    toml = tomli = None
 
 from .compat import u2fs
 
@@ -34,6 +49,18 @@
               encoded.
 
     """
-    with io.open(
-            u2fs(filename), mode="rt", encoding=encoding, newline="") as tfp:
-        return toml.loads(tfp.read(), _dict=DictImpl)
+    if tomllib:
+        with open(u2fs(filename), mode="rb") as tfp:
+            return tomllib.load(tfp)
+    elif tomli:
+        with open(u2fs(filename), mode="rb") as tfp:
+            return tomli.load(tfp)
+    elif toml:
+        with io.open(
+                u2fs(filename),
+                mode="rt",
+                encoding=encoding,
+                newline="") as tfp:
+            return toml.loads(tfp.read(), _dict=DictImpl)
+    else:
+        assert False