# HG changeset patch # User Franz Glasner # Date 1457481106 -3600 # Node ID caaaddb11db19864fd598679777ab9497c2e2955 # Parent dc058099a4cb7776350798d8bba0285746e420f8 Evaluating Python configuration files diff -r dc058099a4cb -r caaaddb11db1 configmix/py.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/configmix/py.py Wed Mar 09 00:51:46 2016 +0100 @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +r"""Read configuration settings from Python files + +""" + +from __future__ import division, absolute_import, print_function + +import locale + +from .compat import PY2 + + +__all__ = ["load"] + + +def load(filename, extract=None): + if extract is not None: + if not isinstance(extract, (type([]), type(tuple()), type(set()), )): + raise TypeError("`extract' must be a sequence") + gcontext = dict() + lcontext = dict() + if PY2: + filename2 = filename.encode(locale.getpreferredencoding()) + if PY2: + execfile(filename2, gcontext, lcontext) + 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 + extract = [v for v in extract if v in lcontext] + return dict(zip(extract, [lcontext[v] for v in extract]))