comparison configmix/py.py @ 19:04505a8dbfc0

Use ordered dictionaries (if available) when reading Python configuration files
author Franz Glasner <f.glasner@feldmann-mg.com>
date Thu, 10 Mar 2016 11:11:17 +0100
parents caaaddb11db1
children aa8345dae995
comparison
equal deleted inserted replaced
18:a04fa81e10ae 19:04505a8dbfc0
4 """ 4 """
5 5
6 from __future__ import division, absolute_import, print_function 6 from __future__ import division, absolute_import, print_function
7 7
8 import locale 8 import locale
9 try:
10 from collections import OrderedDict as DictImpl
11 except ImportError:
12 try:
13 from ordereddict import OrderedDict as DictImpl
14 except ImportError:
15 DictImpl = dict
9 16
10 from .compat import PY2 17 from .compat import PY2
11 18
12 19
13 __all__ = ["load"] 20 __all__ = ["load"]
15 22
16 def load(filename, extract=None): 23 def load(filename, extract=None):
17 if extract is not None: 24 if extract is not None:
18 if not isinstance(extract, (type([]), type(tuple()), type(set()), )): 25 if not isinstance(extract, (type([]), type(tuple()), type(set()), )):
19 raise TypeError("`extract' must be a sequence") 26 raise TypeError("`extract' must be a sequence")
20 gcontext = dict() 27 gcontext = DictImpl()
21 lcontext = dict() 28 lcontext = DictImpl()
22 if PY2: 29 if PY2:
23 filename2 = filename.encode(locale.getpreferredencoding()) 30 filename2 = filename.encode(locale.getpreferredencoding())
24 if PY2: 31 if PY2:
25 execfile(filename2, gcontext, lcontext) 32 execfile(filename2, gcontext, lcontext)
26 else: 33 else:
31 if extract is None: 38 if extract is None:
32 if "__all__" in lcontext: 39 if "__all__" in lcontext:
33 extract = lcontext["__all__"] 40 extract = lcontext["__all__"]
34 else: 41 else:
35 extract = [k for k in lcontext if not k.startswith('_')] 42 extract = [k for k in lcontext if not k.startswith('_')]
36 # don't bail on non-existing keys 43 #
44 # Don't bail on non-existing keys and (implicitly) convert to an
45 # ordered list
46 #
37 extract = [v for v in extract if v in lcontext] 47 extract = [v for v in extract if v in lcontext]
38 return dict(zip(extract, [lcontext[v] for v in extract])) 48 return DictImpl(zip(extract, [lcontext[v] for v in extract]))