view configmix/toml.py @ 676:e1fd2fca8694

>>>>> Tag v0.21.2 for changeset 2ca35f4b03a5
author Franz Glasner <fzglas.hg@dom66.de>
date Wed, 12 Apr 2023 09:27:20 +0200
parents 0d6673d06c2c
children
line wrap: on
line source

# -*- coding: utf-8 -*-
# :-
# :Copyright: (c) 2015-2022, Franz Glasner. All rights reserved.
# :License:   BSD-3-Clause. See LICENSE.txt for details.
# :-
"""Read TOML style configuration files.

"""

from __future__ import division, absolute_import, print_function


__all__ = ["load"]


import io
try:
    from collections import OrderedDict as DictImpl
except ImportError:
    try:
        from ordereddict import OrderedDict as DictImpl
    except ImportError:
        DictImpl = dict

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


def load(filename, encoding="utf-8"):
    """Load a single TOML file with name `filename` and encoding `encoding`.

    .. note:: The TOML standard requires that all TOML files are UTF-8
              encoded.

    """
    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