view configmix/py.py @ 428:090a25f36a3d

FIX: Allow jailed configurations to use correctly use base configurations that use a different "default" marker object. Jailed configurations assumed that their "default" marker object is identical to the "default" marker object in the unjailed base configuration. This is not always true, especially if "_JailedConfiguration.rebind()" is used. Removed the explicit "default" keyword argument and passed the complete keywords argument dictionary to the base instead. This triggers correct default handling in the base.
author Franz Glasner <f.glasner@feldmann-mg.com>
date Thu, 09 Dec 2021 13:02:17 +0100
parents eed16a1ec8f3
children f454889e41fa
line wrap: on
line source

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

"""

from __future__ import division, absolute_import, print_function


__all__ = ["load"]


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

from .compat import PY2, u2fs


def load(filename, extract=None):
    """Load Python-style configuration files.

    Files are loaded and **executed** with :func:`exec` using an empty
    dict as global and local context.#

    :param filename: the path to the configuration file
    :param extract: an optional list of variable names (keys) to extract
                    into the resulting configuration dictionary
    :returns: the configuration as dictionary
    :rtype: collections.OrderedDict or ordereddict.OrderedDict or dict

    """
    if extract is not None:
        if not isinstance(extract, (type([]), type(tuple()), type(set()), )):
            raise TypeError("`extract' must be a sequence")
    gcontext = DictImpl()
    lcontext = DictImpl()
    if PY2:
        execfile(u2fs(filename, True), gcontext, lcontext)      # noqa: F821
    else:
        # "rb" mode allows Python to derive the encoding automatically
        with open(filename, "rb") as vf:
            code = compile(vf.read(), filename, "exec")
            exec(code, gcontext, lcontext)
    if extract is None:
        if "__all__" in lcontext:
            extract = lcontext["__all__"]
        else:
            extract = [k for k in lcontext if not k.startswith('_')]
    #
    # Don't bail on non-existing keys and (implicitly) convert to an
    # ordered list
    #
    extract = [v for v in extract if v in lcontext]
    return DictImpl(zip(extract, [lcontext[v] for v in extract]))