comparison planemo/lib/python3.7/site-packages/backports/configparser/helpers.py @ 0:d30785e31577 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:18:57 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:d30785e31577
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from __future__ import absolute_import
5 from __future__ import division
6 from __future__ import print_function
7 from __future__ import unicode_literals
8
9 import abc
10 import os
11
12 try:
13 from collections.abc import MutableMapping
14 except ImportError:
15 from collections import MutableMapping
16
17 try:
18 from collections import UserDict
19 except ImportError:
20 from UserDict import UserDict
21
22 try:
23 from collections import OrderedDict
24 except ImportError:
25 from ordereddict import OrderedDict
26
27 try:
28 import pathlib
29 except ImportError:
30 pathlib = None
31
32 from io import open
33 import sys
34
35 try:
36 from thread import get_ident
37 except ImportError:
38 try:
39 from _thread import get_ident
40 except ImportError:
41 from _dummy_thread import get_ident
42
43
44 __all__ = ['UserDict', 'OrderedDict', 'open']
45
46
47 PY2 = sys.version_info[0] == 2
48 PY3 = sys.version_info[0] == 3
49
50 native_str = str
51 str = type('str')
52
53
54 def from_none(exc):
55 """raise from_none(ValueError('a')) == raise ValueError('a') from None"""
56 exc.__cause__ = None
57 exc.__suppress_context__ = True
58 return exc
59
60
61 # from reprlib 3.2.1
62 def recursive_repr(fillvalue='...'):
63 'Decorator to make a repr function return fillvalue for a recursive call'
64
65 def decorating_function(user_function):
66 repr_running = set()
67
68 def wrapper(self):
69 key = id(self), get_ident()
70 if key in repr_running:
71 return fillvalue
72 repr_running.add(key)
73 try:
74 result = user_function(self)
75 finally:
76 repr_running.discard(key)
77 return result
78
79 # Can't use functools.wraps() here because of bootstrap issues
80 wrapper.__module__ = getattr(user_function, '__module__')
81 wrapper.__doc__ = getattr(user_function, '__doc__')
82 wrapper.__name__ = getattr(user_function, '__name__')
83 wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
84 return wrapper
85
86 return decorating_function
87
88
89 # from collections 3.2.1
90 class _ChainMap(MutableMapping):
91 ''' A ChainMap groups multiple dicts (or other mappings) together
92 to create a single, updateable view.
93
94 The underlying mappings are stored in a list. That list is public and can
95 accessed or updated using the *maps* attribute. There is no other state.
96
97 Lookups search the underlying mappings successively until a key is found.
98 In contrast, writes, updates, and deletions only operate on the first
99 mapping.
100
101 '''
102
103 def __init__(self, *maps):
104 '''Initialize a ChainMap by setting *maps* to the given mappings.
105 If no mappings are provided, a single empty dictionary is used.
106
107 '''
108 self.maps = list(maps) or [{}] # always at least one map
109
110 def __missing__(self, key):
111 raise KeyError(key)
112
113 def __getitem__(self, key):
114 for mapping in self.maps:
115 try:
116 # can't use 'key in mapping' with defaultdict
117 return mapping[key]
118 except KeyError:
119 pass
120 # support subclasses that define __missing__
121 return self.__missing__(key)
122
123 def get(self, key, default=None):
124 return self[key] if key in self else default
125
126 def __len__(self):
127 # reuses stored hash values if possible
128 return len(set().union(*self.maps))
129
130 def __iter__(self):
131 return iter(set().union(*self.maps))
132
133 def __contains__(self, key):
134 return any(key in m for m in self.maps)
135
136 @recursive_repr()
137 def __repr__(self):
138 return '{0.__class__.__name__}({1})'.format(
139 self, ', '.join(map(repr, self.maps))
140 )
141
142 @classmethod
143 def fromkeys(cls, iterable, *args):
144 'Create a ChainMap with a single dict created from the iterable.'
145 return cls(dict.fromkeys(iterable, *args))
146
147 def copy(self):
148 """
149 New ChainMap or subclass with a new copy of
150 maps[0] and refs to maps[1:]
151 """
152 return self.__class__(self.maps[0].copy(), *self.maps[1:])
153
154 __copy__ = copy
155
156 def new_child(self): # like Django's Context.push()
157 'New ChainMap with a new dict followed by all previous maps.'
158 return self.__class__({}, *self.maps)
159
160 @property
161 def parents(self): # like Django's Context.pop()
162 'New ChainMap from maps[1:].'
163 return self.__class__(*self.maps[1:])
164
165 def __setitem__(self, key, value):
166 self.maps[0][key] = value
167
168 def __delitem__(self, key):
169 try:
170 del self.maps[0][key]
171 except KeyError:
172 raise KeyError('Key not found in the first mapping: {!r}'.format(key))
173
174 def popitem(self):
175 """
176 Remove and return an item pair from maps[0].
177 Raise KeyError is maps[0] is empty.
178 """
179 try:
180 return self.maps[0].popitem()
181 except KeyError:
182 raise KeyError('No keys found in the first mapping.')
183
184 def pop(self, key, *args):
185 """
186 Remove *key* from maps[0] and return its value.
187 Raise KeyError if *key* not in maps[0].
188 """
189
190 try:
191 return self.maps[0].pop(key, *args)
192 except KeyError:
193 raise KeyError('Key not found in the first mapping: {!r}'.format(key))
194
195 def clear(self):
196 'Clear maps[0], leaving maps[1:] intact.'
197 self.maps[0].clear()
198
199
200 try:
201 from collections import ChainMap
202 except ImportError:
203 ChainMap = _ChainMap
204
205
206 _ABC = getattr(
207 abc,
208 'ABC',
209 # Python 3.3 compatibility
210 abc.ABCMeta(native_str('__ABC'), (object,), dict(__metaclass__=abc.ABCMeta)),
211 )
212
213
214 class _PathLike(_ABC):
215
216 """Abstract base class for implementing the file system path protocol."""
217
218 @abc.abstractmethod
219 def __fspath__(self):
220 """Return the file system path representation of the object."""
221 raise NotImplementedError
222
223 @classmethod
224 def __subclasshook__(cls, subclass):
225 return bool(
226 hasattr(subclass, '__fspath__')
227 # workaround for Python 3.5
228 or pathlib
229 and issubclass(subclass, pathlib.Path)
230 )
231
232
233 PathLike = getattr(os, 'PathLike', _PathLike)
234
235
236 def _fspath(path):
237 """Return the path representation of a path-like object.
238
239 If str or bytes is passed in, it is returned unchanged. Otherwise the
240 os.PathLike interface is used to get the path representation. If the
241 path representation is not str or bytes, TypeError is raised. If the
242 provided path is not str, bytes, or os.PathLike, TypeError is raised.
243 """
244 if isinstance(path, (str, bytes)):
245 return path
246
247 if not hasattr(path, '__fspath__') and isinstance(path, pathlib.Path):
248 # workaround for Python 3.5
249 return str(path)
250
251 # Work from the object's type to match method resolution of other magic
252 # methods.
253 path_type = type(path)
254 try:
255 path_repr = path_type.__fspath__(path)
256 except AttributeError:
257
258 if hasattr(path_type, '__fspath__'):
259 raise
260 else:
261 raise TypeError(
262 "expected str, bytes or os.PathLike object, "
263 "not " + path_type.__name__
264 )
265 if isinstance(path_repr, (str, bytes)):
266 return path_repr
267 else:
268 raise TypeError(
269 "expected {}.__fspath__() to return str or bytes, "
270 "not {}".format(path_type.__name__, type(path_repr).__name__)
271 )
272
273
274 fspath = getattr(os, 'fspath', _fspath)