comparison configmix/toml.py @ 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
comparison
equal deleted inserted replaced
653:211288645f02 654:0d6673d06c2c
20 try: 20 try:
21 from ordereddict import OrderedDict as DictImpl 21 from ordereddict import OrderedDict as DictImpl
22 except ImportError: 22 except ImportError:
23 DictImpl = dict 23 DictImpl = dict
24 24
25 import toml 25 try:
26 import tomllib
27 except ImportError:
28 tomllib = None
29 try:
30 import tomli
31 except ImportError:
32 tomli = None
33 try:
34 import toml
35 except ImportError:
36 toml = None
37 else:
38 toml = None
39 else:
40 toml = tomli = None
26 41
27 from .compat import u2fs 42 from .compat import u2fs
28 43
29 44
30 def load(filename, encoding="utf-8"): 45 def load(filename, encoding="utf-8"):
32 47
33 .. note:: The TOML standard requires that all TOML files are UTF-8 48 .. note:: The TOML standard requires that all TOML files are UTF-8
34 encoded. 49 encoded.
35 50
36 """ 51 """
37 with io.open( 52 if tomllib:
38 u2fs(filename), mode="rt", encoding=encoding, newline="") as tfp: 53 with open(u2fs(filename), mode="rb") as tfp:
39 return toml.loads(tfp.read(), _dict=DictImpl) 54 return tomllib.load(tfp)
55 elif tomli:
56 with open(u2fs(filename), mode="rb") as tfp:
57 return tomli.load(tfp)
58 elif toml:
59 with io.open(
60 u2fs(filename),
61 mode="rt",
62 encoding=encoding,
63 newline="") as tfp:
64 return toml.loads(tfp.read(), _dict=DictImpl)
65 else:
66 assert False