remove agw
[iramuteq] / configparser_helpers.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from collections import MutableMapping
5 try:
6     from thread import get_ident
7 except ImportError:
8     try:
9         from _thread import get_ident
10     except ImportError:
11         from _dummy_thread import get_ident
12
13 # from reprlib 3.2.1
14 def recursive_repr(fillvalue=u'...'):
15     u'Decorator to make a repr function return fillvalue for a recursive call'
16
17     def decorating_function(user_function):
18         repr_running = set()
19
20         def wrapper(self):
21             key = id(self), get_ident()
22             if key in repr_running:
23                 return fillvalue
24             repr_running.add(key)
25             try:
26                 result = user_function(self)
27             finally:
28                 repr_running.discard(key)
29             return result
30
31         # Can't use functools.wraps() here because of bootstrap issues
32         wrapper.__module__ = getattr(user_function, u'__module__')
33         wrapper.__doc__ = getattr(user_function, u'__doc__')
34         wrapper.__name__ = getattr(user_function, u'__name__')
35         wrapper.__annotations__ = getattr(user_function, u'__annotations__', {})
36         return wrapper
37
38     return decorating_function
39
40 # from collections 3.2.1
41 class _ChainMap(MutableMapping):
42     u''' A ChainMap groups multiple dicts (or other mappings) together
43     to create a single, updateable view.
44
45     The underlying mappings are stored in a list.  That list is public and can
46     accessed or updated using the *maps* attribute.  There is no other state.
47
48     Lookups search the underlying mappings successively until a key is found.
49     In contrast, writes, updates, and deletions only operate on the first
50     mapping.
51
52     '''
53
54     def __init__(self, *maps):
55         u'''Initialize a ChainMap by setting *maps* to the given mappings.
56         If no mappings are provided, a single empty dictionary is used.
57
58         '''
59         self.maps = list(maps) or [{}]          # always at least one map
60
61     def __missing__(self, key):
62         raise KeyError(key)
63
64     def __getitem__(self, key):
65         for mapping in self.maps:
66             try:
67                 return mapping[key]             # can't use 'key in mapping' with defaultdict
68             except KeyError:
69                 pass
70         return self.__missing__(key)            # support subclasses that define __missing__
71
72     def get(self, key, default=None):
73         return self[key] if key in self else default
74
75     def __len__(self):
76         return len(set().union(*self.maps))     # reuses stored hash values if possible
77
78     def __iter__(self):
79         return iter(set().union(*self.maps))
80
81     def __contains__(self, key):
82         return any(key in m for m in self.maps)
83
84     @recursive_repr()
85     def __repr__(self):
86         return u'{0.__class__.__name__}({1})'.format(
87             self, u', '.join(map(repr, self.maps)))
88
89     @classmethod
90     def fromkeys(cls, iterable, *args):
91         u'Create a ChainMap with a single dict created from the iterable.'
92         return cls(dict.fromkeys(iterable, *args))
93
94     def copy(self):
95         u'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
96         return self.__class__(self.maps[0].copy(), *self.maps[1:])
97
98     __copy__ = copy
99
100     def new_child(self):                        # like Django's Context.push()
101         u'New ChainMap with a new dict followed by all previous maps.'
102         return self.__class__({}, *self.maps)
103
104     @property
105     def parents(self):                          # like Django's Context.pop()
106         u'New ChainMap from maps[1:].'
107         return self.__class__(*self.maps[1:])
108
109     def __setitem__(self, key, value):
110         self.maps[0][key] = value
111
112     def __delitem__(self, key):
113         try:
114             del self.maps[0][key]
115         except KeyError:
116             raise KeyError(u'Key not found in the first mapping: {!r}'.format(key))
117
118     def popitem(self):
119         u'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
120         try:
121             return self.maps[0].popitem()
122         except KeyError:
123             raise KeyError(u'No keys found in the first mapping.')
124
125     def pop(self, key, *args):
126         u'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
127         try:
128             return self.maps[0].pop(key, *args)
129         except KeyError:
130             raise KeyError(u'Key not found in the first mapping: {!r}'.format(key))
131
132     def clear(self):
133         u'Clear maps[0], leaving maps[1:] intact.'
134         self.maps[0].clear()