Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/urllib3/packages/six.py: 48%
500 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1# Copyright (c) 2010-2020 Benjamin Peterson
2#
3# Permission is hereby granted, free of charge, to any person obtaining a copy
4# of this software and associated documentation files (the "Software"), to deal
5# in the Software without restriction, including without limitation the rights
6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7# copies of the Software, and to permit persons to whom the Software is
8# furnished to do so, subject to the following conditions:
9#
10# The above copyright notice and this permission notice shall be included in all
11# copies or substantial portions of the Software.
12#
13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19# SOFTWARE.
21"""Utilities for writing code that runs on Python 2 and 3"""
23from __future__ import absolute_import
25import functools
26import itertools
27import operator
28import sys
29import types
31__author__ = "Benjamin Peterson <benjamin@python.org>"
32__version__ = "1.16.0"
35# Useful for very coarse version differentiation.
36PY2 = sys.version_info[0] == 2
37PY3 = sys.version_info[0] == 3
38PY34 = sys.version_info[0:2] >= (3, 4)
40if PY3: 40 ↛ 49line 40 didn't jump to line 49, because the condition on line 40 was never false
41 string_types = (str,)
42 integer_types = (int,)
43 class_types = (type,)
44 text_type = str
45 binary_type = bytes
47 MAXSIZE = sys.maxsize
48else:
49 string_types = (basestring,)
50 integer_types = (int, long)
51 class_types = (type, types.ClassType)
52 text_type = unicode
53 binary_type = str
55 if sys.platform.startswith("java"):
56 # Jython always uses 32 bits.
57 MAXSIZE = int((1 << 31) - 1)
58 else:
59 # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
60 class X(object):
61 def __len__(self):
62 return 1 << 31
64 try:
65 len(X())
66 except OverflowError:
67 # 32-bit
68 MAXSIZE = int((1 << 31) - 1)
69 else:
70 # 64-bit
71 MAXSIZE = int((1 << 63) - 1)
72 del X
74if PY34: 74 ↛ 77line 74 didn't jump to line 77, because the condition on line 74 was never false
75 from importlib.util import spec_from_loader
76else:
77 spec_from_loader = None
80def _add_doc(func, doc):
81 """Add documentation to a function."""
82 func.__doc__ = doc
85def _import_module(name):
86 """Import module, returning the module after the last dot."""
87 __import__(name)
88 return sys.modules[name]
91class _LazyDescr(object):
92 def __init__(self, name):
93 self.name = name
95 def __get__(self, obj, tp):
96 result = self._resolve()
97 setattr(obj, self.name, result) # Invokes __set__.
98 try:
99 # This is a bit ugly, but it avoids running this again by
100 # removing this descriptor.
101 delattr(obj.__class__, self.name)
102 except AttributeError:
103 pass
104 return result
107class MovedModule(_LazyDescr):
108 def __init__(self, name, old, new=None):
109 super(MovedModule, self).__init__(name)
110 if PY3: 110 ↛ 115line 110 didn't jump to line 115, because the condition on line 110 was never false
111 if new is None:
112 new = name
113 self.mod = new
114 else:
115 self.mod = old
117 def _resolve(self):
118 return _import_module(self.mod)
120 def __getattr__(self, attr):
121 _module = self._resolve()
122 value = getattr(_module, attr)
123 setattr(self, attr, value)
124 return value
127class _LazyModule(types.ModuleType):
128 def __init__(self, name):
129 super(_LazyModule, self).__init__(name)
130 self.__doc__ = self.__class__.__doc__
132 def __dir__(self):
133 attrs = ["__doc__", "__name__"]
134 attrs += [attr.name for attr in self._moved_attributes]
135 return attrs
137 # Subclasses should override this
138 _moved_attributes = []
141class MovedAttribute(_LazyDescr):
142 def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
143 super(MovedAttribute, self).__init__(name)
144 if PY3: 144 ↛ 155line 144 didn't jump to line 155, because the condition on line 144 was never false
145 if new_mod is None: 145 ↛ 146line 145 didn't jump to line 146, because the condition on line 145 was never true
146 new_mod = name
147 self.mod = new_mod
148 if new_attr is None:
149 if old_attr is None:
150 new_attr = name
151 else:
152 new_attr = old_attr
153 self.attr = new_attr
154 else:
155 self.mod = old_mod
156 if old_attr is None:
157 old_attr = name
158 self.attr = old_attr
160 def _resolve(self):
161 module = _import_module(self.mod)
162 return getattr(module, self.attr)
165class _SixMetaPathImporter(object):
167 """
168 A meta path importer to import six.moves and its submodules.
170 This class implements a PEP302 finder and loader. It should be compatible
171 with Python 2.5 and all existing versions of Python3
172 """
174 def __init__(self, six_module_name):
175 self.name = six_module_name
176 self.known_modules = {}
178 def _add_module(self, mod, *fullnames):
179 for fullname in fullnames:
180 self.known_modules[self.name + "." + fullname] = mod
182 def _get_module(self, fullname):
183 return self.known_modules[self.name + "." + fullname]
185 def find_module(self, fullname, path=None):
186 if fullname in self.known_modules:
187 return self
188 return None
190 def find_spec(self, fullname, path, target=None):
191 if fullname in self.known_modules:
192 return spec_from_loader(fullname, self)
193 return None
195 def __get_module(self, fullname):
196 try:
197 return self.known_modules[fullname]
198 except KeyError:
199 raise ImportError("This loader does not know module " + fullname)
201 def load_module(self, fullname):
202 try:
203 # in case of a reload
204 return sys.modules[fullname]
205 except KeyError:
206 pass
207 mod = self.__get_module(fullname)
208 if isinstance(mod, MovedModule):
209 mod = mod._resolve()
210 else:
211 mod.__loader__ = self
212 sys.modules[fullname] = mod
213 return mod
215 def is_package(self, fullname):
216 """
217 Return true, if the named module is a package.
219 We need this method to get correct spec objects with
220 Python 3.4 (see PEP451)
221 """
222 return hasattr(self.__get_module(fullname), "__path__")
224 def get_code(self, fullname):
225 """Return None
227 Required, if is_package is implemented"""
228 self.__get_module(fullname) # eventually raises ImportError
229 return None
231 get_source = get_code # same as get_code
233 def create_module(self, spec):
234 return self.load_module(spec.name)
236 def exec_module(self, module):
237 pass
240_importer = _SixMetaPathImporter(__name__)
243class _MovedItems(_LazyModule):
245 """Lazy loading of moved objects"""
247 __path__ = [] # mark as package
250_moved_attributes = [
251 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
252 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
253 MovedAttribute(
254 "filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"
255 ),
256 MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
257 MovedAttribute("intern", "__builtin__", "sys"),
258 MovedAttribute("map", "itertools", "builtins", "imap", "map"),
259 MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),
260 MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),
261 MovedAttribute("getoutput", "commands", "subprocess"),
262 MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
263 MovedAttribute(
264 "reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"
265 ),
266 MovedAttribute("reduce", "__builtin__", "functools"),
267 MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
268 MovedAttribute("StringIO", "StringIO", "io"),
269 MovedAttribute("UserDict", "UserDict", "collections"),
270 MovedAttribute("UserList", "UserList", "collections"),
271 MovedAttribute("UserString", "UserString", "collections"),
272 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
273 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
274 MovedAttribute(
275 "zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"
276 ),
277 MovedModule("builtins", "__builtin__"),
278 MovedModule("configparser", "ConfigParser"),
279 MovedModule(
280 "collections_abc",
281 "collections",
282 "collections.abc" if sys.version_info >= (3, 3) else "collections",
283 ),
284 MovedModule("copyreg", "copy_reg"),
285 MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
286 MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),
287 MovedModule(
288 "_dummy_thread",
289 "dummy_thread",
290 "_dummy_thread" if sys.version_info < (3, 9) else "_thread",
291 ),
292 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
293 MovedModule("http_cookies", "Cookie", "http.cookies"),
294 MovedModule("html_entities", "htmlentitydefs", "html.entities"),
295 MovedModule("html_parser", "HTMLParser", "html.parser"),
296 MovedModule("http_client", "httplib", "http.client"),
297 MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
298 MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),
299 MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
300 MovedModule(
301 "email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"
302 ),
303 MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
304 MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
305 MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
306 MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
307 MovedModule("cPickle", "cPickle", "pickle"),
308 MovedModule("queue", "Queue"),
309 MovedModule("reprlib", "repr"),
310 MovedModule("socketserver", "SocketServer"),
311 MovedModule("_thread", "thread", "_thread"),
312 MovedModule("tkinter", "Tkinter"),
313 MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
314 MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
315 MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
316 MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
317 MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
318 MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
319 MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
320 MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
321 MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"),
322 MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"),
323 MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
324 MovedModule("tkinter_font", "tkFont", "tkinter.font"),
325 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
326 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"),
327 MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
328 MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
329 MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
330 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
331 MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
332 MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
333]
334# Add windows specific modules.
335if sys.platform == "win32": 335 ↛ 336line 335 didn't jump to line 336, because the condition on line 335 was never true
336 _moved_attributes += [
337 MovedModule("winreg", "_winreg"),
338 ]
340for attr in _moved_attributes:
341 setattr(_MovedItems, attr.name, attr)
342 if isinstance(attr, MovedModule):
343 _importer._add_module(attr, "moves." + attr.name)
344del attr
346_MovedItems._moved_attributes = _moved_attributes
348moves = _MovedItems(__name__ + ".moves")
349_importer._add_module(moves, "moves")
352class Module_six_moves_urllib_parse(_LazyModule):
354 """Lazy loading of moved objects in six.moves.urllib_parse"""
357_urllib_parse_moved_attributes = [
358 MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
359 MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
360 MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
361 MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
362 MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
363 MovedAttribute("urljoin", "urlparse", "urllib.parse"),
364 MovedAttribute("urlparse", "urlparse", "urllib.parse"),
365 MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
366 MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
367 MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
368 MovedAttribute("quote", "urllib", "urllib.parse"),
369 MovedAttribute("quote_plus", "urllib", "urllib.parse"),
370 MovedAttribute("unquote", "urllib", "urllib.parse"),
371 MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
372 MovedAttribute(
373 "unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"
374 ),
375 MovedAttribute("urlencode", "urllib", "urllib.parse"),
376 MovedAttribute("splitquery", "urllib", "urllib.parse"),
377 MovedAttribute("splittag", "urllib", "urllib.parse"),
378 MovedAttribute("splituser", "urllib", "urllib.parse"),
379 MovedAttribute("splitvalue", "urllib", "urllib.parse"),
380 MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
381 MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
382 MovedAttribute("uses_params", "urlparse", "urllib.parse"),
383 MovedAttribute("uses_query", "urlparse", "urllib.parse"),
384 MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
385]
386for attr in _urllib_parse_moved_attributes:
387 setattr(Module_six_moves_urllib_parse, attr.name, attr)
388del attr
390Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
392_importer._add_module(
393 Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
394 "moves.urllib_parse",
395 "moves.urllib.parse",
396)
399class Module_six_moves_urllib_error(_LazyModule):
401 """Lazy loading of moved objects in six.moves.urllib_error"""
404_urllib_error_moved_attributes = [
405 MovedAttribute("URLError", "urllib2", "urllib.error"),
406 MovedAttribute("HTTPError", "urllib2", "urllib.error"),
407 MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
408]
409for attr in _urllib_error_moved_attributes:
410 setattr(Module_six_moves_urllib_error, attr.name, attr)
411del attr
413Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
415_importer._add_module(
416 Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
417 "moves.urllib_error",
418 "moves.urllib.error",
419)
422class Module_six_moves_urllib_request(_LazyModule):
424 """Lazy loading of moved objects in six.moves.urllib_request"""
427_urllib_request_moved_attributes = [
428 MovedAttribute("urlopen", "urllib2", "urllib.request"),
429 MovedAttribute("install_opener", "urllib2", "urllib.request"),
430 MovedAttribute("build_opener", "urllib2", "urllib.request"),
431 MovedAttribute("pathname2url", "urllib", "urllib.request"),
432 MovedAttribute("url2pathname", "urllib", "urllib.request"),
433 MovedAttribute("getproxies", "urllib", "urllib.request"),
434 MovedAttribute("Request", "urllib2", "urllib.request"),
435 MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
436 MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
437 MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
438 MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
439 MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
440 MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
441 MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
442 MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
443 MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
444 MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
445 MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
446 MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
447 MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
448 MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
449 MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
450 MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
451 MovedAttribute("FileHandler", "urllib2", "urllib.request"),
452 MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
453 MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
454 MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
455 MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
456 MovedAttribute("urlretrieve", "urllib", "urllib.request"),
457 MovedAttribute("urlcleanup", "urllib", "urllib.request"),
458 MovedAttribute("URLopener", "urllib", "urllib.request"),
459 MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
460 MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
461 MovedAttribute("parse_http_list", "urllib2", "urllib.request"),
462 MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),
463]
464for attr in _urllib_request_moved_attributes:
465 setattr(Module_six_moves_urllib_request, attr.name, attr)
466del attr
468Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
470_importer._add_module(
471 Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
472 "moves.urllib_request",
473 "moves.urllib.request",
474)
477class Module_six_moves_urllib_response(_LazyModule):
479 """Lazy loading of moved objects in six.moves.urllib_response"""
482_urllib_response_moved_attributes = [
483 MovedAttribute("addbase", "urllib", "urllib.response"),
484 MovedAttribute("addclosehook", "urllib", "urllib.response"),
485 MovedAttribute("addinfo", "urllib", "urllib.response"),
486 MovedAttribute("addinfourl", "urllib", "urllib.response"),
487]
488for attr in _urllib_response_moved_attributes:
489 setattr(Module_six_moves_urllib_response, attr.name, attr)
490del attr
492Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
494_importer._add_module(
495 Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
496 "moves.urllib_response",
497 "moves.urllib.response",
498)
501class Module_six_moves_urllib_robotparser(_LazyModule):
503 """Lazy loading of moved objects in six.moves.urllib_robotparser"""
506_urllib_robotparser_moved_attributes = [
507 MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
508]
509for attr in _urllib_robotparser_moved_attributes:
510 setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
511del attr
513Module_six_moves_urllib_robotparser._moved_attributes = (
514 _urllib_robotparser_moved_attributes
515)
517_importer._add_module(
518 Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
519 "moves.urllib_robotparser",
520 "moves.urllib.robotparser",
521)
524class Module_six_moves_urllib(types.ModuleType):
526 """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
528 __path__ = [] # mark as package
529 parse = _importer._get_module("moves.urllib_parse")
530 error = _importer._get_module("moves.urllib_error")
531 request = _importer._get_module("moves.urllib_request")
532 response = _importer._get_module("moves.urllib_response")
533 robotparser = _importer._get_module("moves.urllib_robotparser")
535 def __dir__(self):
536 return ["parse", "error", "request", "response", "robotparser"]
539_importer._add_module(
540 Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib"
541)
544def add_move(move):
545 """Add an item to six.moves."""
546 setattr(_MovedItems, move.name, move)
549def remove_move(name):
550 """Remove item from six.moves."""
551 try:
552 delattr(_MovedItems, name)
553 except AttributeError:
554 try:
555 del moves.__dict__[name]
556 except KeyError:
557 raise AttributeError("no such move, %r" % (name,))
560if PY3: 560 ↛ 569line 560 didn't jump to line 569, because the condition on line 560 was never false
561 _meth_func = "__func__"
562 _meth_self = "__self__"
564 _func_closure = "__closure__"
565 _func_code = "__code__"
566 _func_defaults = "__defaults__"
567 _func_globals = "__globals__"
568else:
569 _meth_func = "im_func"
570 _meth_self = "im_self"
572 _func_closure = "func_closure"
573 _func_code = "func_code"
574 _func_defaults = "func_defaults"
575 _func_globals = "func_globals"
578try:
579 advance_iterator = next
580except NameError:
582 def advance_iterator(it):
583 return it.next()
586next = advance_iterator
589try:
590 callable = callable
591except NameError:
593 def callable(obj):
594 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
597if PY3: 597 ↛ 610line 597 didn't jump to line 610, because the condition on line 597 was never false
599 def get_unbound_function(unbound):
600 return unbound
602 create_bound_method = types.MethodType
604 def create_unbound_method(func, cls):
605 return func
607 Iterator = object
608else:
610 def get_unbound_function(unbound):
611 return unbound.im_func
613 def create_bound_method(func, obj):
614 return types.MethodType(func, obj, obj.__class__)
616 def create_unbound_method(func, cls):
617 return types.MethodType(func, None, cls)
619 class Iterator(object):
620 def next(self):
621 return type(self).__next__(self)
623 callable = callable
624_add_doc(
625 get_unbound_function, """Get the function out of a possibly unbound function"""
626)
629get_method_function = operator.attrgetter(_meth_func)
630get_method_self = operator.attrgetter(_meth_self)
631get_function_closure = operator.attrgetter(_func_closure)
632get_function_code = operator.attrgetter(_func_code)
633get_function_defaults = operator.attrgetter(_func_defaults)
634get_function_globals = operator.attrgetter(_func_globals)
637if PY3: 637 ↛ 658line 637 didn't jump to line 658, because the condition on line 637 was never false
639 def iterkeys(d, **kw):
640 return iter(d.keys(**kw))
642 def itervalues(d, **kw):
643 return iter(d.values(**kw))
645 def iteritems(d, **kw):
646 return iter(d.items(**kw))
648 def iterlists(d, **kw):
649 return iter(d.lists(**kw))
651 viewkeys = operator.methodcaller("keys")
653 viewvalues = operator.methodcaller("values")
655 viewitems = operator.methodcaller("items")
656else:
658 def iterkeys(d, **kw):
659 return d.iterkeys(**kw)
661 def itervalues(d, **kw):
662 return d.itervalues(**kw)
664 def iteritems(d, **kw):
665 return d.iteritems(**kw)
667 def iterlists(d, **kw):
668 return d.iterlists(**kw)
670 viewkeys = operator.methodcaller("viewkeys")
672 viewvalues = operator.methodcaller("viewvalues")
674 viewitems = operator.methodcaller("viewitems")
676_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
677_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
678_add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.")
679_add_doc(
680 iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary."
681)
684if PY3: 684 ↛ 716line 684 didn't jump to line 716, because the condition on line 684 was never false
686 def b(s):
687 return s.encode("latin-1")
689 def u(s):
690 return s
692 unichr = chr
693 import struct
695 int2byte = struct.Struct(">B").pack
696 del struct
697 byte2int = operator.itemgetter(0)
698 indexbytes = operator.getitem
699 iterbytes = iter
700 import io
702 StringIO = io.StringIO
703 BytesIO = io.BytesIO
704 del io
705 _assertCountEqual = "assertCountEqual"
706 if sys.version_info[1] <= 1: 706 ↛ 707line 706 didn't jump to line 707, because the condition on line 706 was never true
707 _assertRaisesRegex = "assertRaisesRegexp"
708 _assertRegex = "assertRegexpMatches"
709 _assertNotRegex = "assertNotRegexpMatches"
710 else:
711 _assertRaisesRegex = "assertRaisesRegex"
712 _assertRegex = "assertRegex"
713 _assertNotRegex = "assertNotRegex"
714else:
716 def b(s):
717 return s
719 # Workaround for standalone backslash
721 def u(s):
722 return unicode(s.replace(r"\\", r"\\\\"), "unicode_escape")
724 unichr = unichr
725 int2byte = chr
727 def byte2int(bs):
728 return ord(bs[0])
730 def indexbytes(buf, i):
731 return ord(buf[i])
733 iterbytes = functools.partial(itertools.imap, ord)
734 import StringIO
736 StringIO = BytesIO = StringIO.StringIO
737 _assertCountEqual = "assertItemsEqual"
738 _assertRaisesRegex = "assertRaisesRegexp"
739 _assertRegex = "assertRegexpMatches"
740 _assertNotRegex = "assertNotRegexpMatches"
741_add_doc(b, """Byte literal""")
742_add_doc(u, """Text literal""")
745def assertCountEqual(self, *args, **kwargs):
746 return getattr(self, _assertCountEqual)(*args, **kwargs)
749def assertRaisesRegex(self, *args, **kwargs):
750 return getattr(self, _assertRaisesRegex)(*args, **kwargs)
753def assertRegex(self, *args, **kwargs):
754 return getattr(self, _assertRegex)(*args, **kwargs)
757def assertNotRegex(self, *args, **kwargs):
758 return getattr(self, _assertNotRegex)(*args, **kwargs)
761if PY3: 761 ↛ 777line 761 didn't jump to line 777, because the condition on line 761 was never false
762 exec_ = getattr(moves.builtins, "exec")
764 def reraise(tp, value, tb=None):
765 try:
766 if value is None:
767 value = tp()
768 if value.__traceback__ is not tb:
769 raise value.with_traceback(tb)
770 raise value
771 finally:
772 value = None
773 tb = None
775else:
777 def exec_(_code_, _globs_=None, _locs_=None):
778 """Execute code in a namespace."""
779 if _globs_ is None:
780 frame = sys._getframe(1)
781 _globs_ = frame.f_globals
782 if _locs_ is None:
783 _locs_ = frame.f_locals
784 del frame
785 elif _locs_ is None:
786 _locs_ = _globs_
787 exec ("""exec _code_ in _globs_, _locs_""")
789 exec_(
790 """def reraise(tp, value, tb=None):
791 try:
792 raise tp, value, tb
793 finally:
794 tb = None
795"""
796 )
799if sys.version_info[:2] > (3,): 799 ↛ 810line 799 didn't jump to line 810, because the condition on line 799 was never false
800 exec_(
801 """def raise_from(value, from_value):
802 try:
803 raise value from from_value
804 finally:
805 value = None
806"""
807 )
808else:
810 def raise_from(value, from_value):
811 raise value
814print_ = getattr(moves.builtins, "print", None)
815if print_ is None: 815 ↛ 817line 815 didn't jump to line 817, because the condition on line 815 was never true
817 def print_(*args, **kwargs):
818 """The new-style print function for Python 2.4 and 2.5."""
819 fp = kwargs.pop("file", sys.stdout)
820 if fp is None:
821 return
823 def write(data):
824 if not isinstance(data, basestring):
825 data = str(data)
826 # If the file has an encoding, encode unicode with it.
827 if (
828 isinstance(fp, file)
829 and isinstance(data, unicode)
830 and fp.encoding is not None
831 ):
832 errors = getattr(fp, "errors", None)
833 if errors is None:
834 errors = "strict"
835 data = data.encode(fp.encoding, errors)
836 fp.write(data)
838 want_unicode = False
839 sep = kwargs.pop("sep", None)
840 if sep is not None:
841 if isinstance(sep, unicode):
842 want_unicode = True
843 elif not isinstance(sep, str):
844 raise TypeError("sep must be None or a string")
845 end = kwargs.pop("end", None)
846 if end is not None:
847 if isinstance(end, unicode):
848 want_unicode = True
849 elif not isinstance(end, str):
850 raise TypeError("end must be None or a string")
851 if kwargs:
852 raise TypeError("invalid keyword arguments to print()")
853 if not want_unicode:
854 for arg in args:
855 if isinstance(arg, unicode):
856 want_unicode = True
857 break
858 if want_unicode:
859 newline = unicode("\n")
860 space = unicode(" ")
861 else:
862 newline = "\n"
863 space = " "
864 if sep is None:
865 sep = space
866 if end is None:
867 end = newline
868 for i, arg in enumerate(args):
869 if i:
870 write(sep)
871 write(arg)
872 write(end)
875if sys.version_info[:2] < (3, 3): 875 ↛ 876line 875 didn't jump to line 876, because the condition on line 875 was never true
876 _print = print_
878 def print_(*args, **kwargs):
879 fp = kwargs.get("file", sys.stdout)
880 flush = kwargs.pop("flush", False)
881 _print(*args, **kwargs)
882 if flush and fp is not None:
883 fp.flush()
886_add_doc(reraise, """Reraise an exception.""")
888if sys.version_info[0:2] < (3, 4): 888 ↛ 894line 888 didn't jump to line 894, because the condition on line 888 was never true
889 # This does exactly the same what the :func:`py3:functools.update_wrapper`
890 # function does on Python versions after 3.2. It sets the ``__wrapped__``
891 # attribute on ``wrapper`` object and it doesn't raise an error if any of
892 # the attributes mentioned in ``assigned`` and ``updated`` are missing on
893 # ``wrapped`` object.
894 def _update_wrapper(
895 wrapper,
896 wrapped,
897 assigned=functools.WRAPPER_ASSIGNMENTS,
898 updated=functools.WRAPPER_UPDATES,
899 ):
900 for attr in assigned:
901 try:
902 value = getattr(wrapped, attr)
903 except AttributeError:
904 continue
905 else:
906 setattr(wrapper, attr, value)
907 for attr in updated:
908 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
909 wrapper.__wrapped__ = wrapped
910 return wrapper
912 _update_wrapper.__doc__ = functools.update_wrapper.__doc__
914 def wraps(
915 wrapped,
916 assigned=functools.WRAPPER_ASSIGNMENTS,
917 updated=functools.WRAPPER_UPDATES,
918 ):
919 return functools.partial(
920 _update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated
921 )
923 wraps.__doc__ = functools.wraps.__doc__
925else:
926 wraps = functools.wraps
929def with_metaclass(meta, *bases):
930 """Create a base class with a metaclass."""
931 # This requires a bit of explanation: the basic idea is to make a dummy
932 # metaclass for one level of class instantiation that replaces itself with
933 # the actual metaclass.
934 class metaclass(type):
935 def __new__(cls, name, this_bases, d):
936 if sys.version_info[:2] >= (3, 7):
937 # This version introduced PEP 560 that requires a bit
938 # of extra care (we mimic what is done by __build_class__).
939 resolved_bases = types.resolve_bases(bases)
940 if resolved_bases is not bases:
941 d["__orig_bases__"] = bases
942 else:
943 resolved_bases = bases
944 return meta(name, resolved_bases, d)
946 @classmethod
947 def __prepare__(cls, name, this_bases):
948 return meta.__prepare__(name, bases)
950 return type.__new__(metaclass, "temporary_class", (), {})
953def add_metaclass(metaclass):
954 """Class decorator for creating a class with a metaclass."""
956 def wrapper(cls):
957 orig_vars = cls.__dict__.copy()
958 slots = orig_vars.get("__slots__")
959 if slots is not None: 959 ↛ 960line 959 didn't jump to line 960, because the condition on line 959 was never true
960 if isinstance(slots, str):
961 slots = [slots]
962 for slots_var in slots:
963 orig_vars.pop(slots_var)
964 orig_vars.pop("__dict__", None)
965 orig_vars.pop("__weakref__", None)
966 if hasattr(cls, "__qualname__"): 966 ↛ 968line 966 didn't jump to line 968, because the condition on line 966 was never false
967 orig_vars["__qualname__"] = cls.__qualname__
968 return metaclass(cls.__name__, cls.__bases__, orig_vars)
970 return wrapper
973def ensure_binary(s, encoding="utf-8", errors="strict"):
974 """Coerce **s** to six.binary_type.
976 For Python 2:
977 - `unicode` -> encoded to `str`
978 - `str` -> `str`
980 For Python 3:
981 - `str` -> encoded to `bytes`
982 - `bytes` -> `bytes`
983 """
984 if isinstance(s, binary_type):
985 return s
986 if isinstance(s, text_type):
987 return s.encode(encoding, errors)
988 raise TypeError("not expecting type '%s'" % type(s))
991def ensure_str(s, encoding="utf-8", errors="strict"):
992 """Coerce *s* to `str`.
994 For Python 2:
995 - `unicode` -> encoded to `str`
996 - `str` -> `str`
998 For Python 3:
999 - `str` -> `str`
1000 - `bytes` -> decoded to `str`
1001 """
1002 # Optimization: Fast return for the common case.
1003 if type(s) is str:
1004 return s
1005 if PY2 and isinstance(s, text_type):
1006 return s.encode(encoding, errors)
1007 elif PY3 and isinstance(s, binary_type):
1008 return s.decode(encoding, errors)
1009 elif not isinstance(s, (text_type, binary_type)):
1010 raise TypeError("not expecting type '%s'" % type(s))
1011 return s
1014def ensure_text(s, encoding="utf-8", errors="strict"):
1015 """Coerce *s* to six.text_type.
1017 For Python 2:
1018 - `unicode` -> `unicode`
1019 - `str` -> `unicode`
1021 For Python 3:
1022 - `str` -> `str`
1023 - `bytes` -> decoded to `str`
1024 """
1025 if isinstance(s, binary_type):
1026 return s.decode(encoding, errors)
1027 elif isinstance(s, text_type):
1028 return s
1029 else:
1030 raise TypeError("not expecting type '%s'" % type(s))
1033def python_2_unicode_compatible(klass):
1034 """
1035 A class decorator that defines __unicode__ and __str__ methods under Python 2.
1036 Under Python 3 it does nothing.
1038 To support Python 2 and 3 with a single code base, define a __str__ method
1039 returning text and apply this decorator to the class.
1040 """
1041 if PY2:
1042 if "__str__" not in klass.__dict__:
1043 raise ValueError(
1044 "@python_2_unicode_compatible cannot be applied "
1045 "to %s because it doesn't define __str__()." % klass.__name__
1046 )
1047 klass.__unicode__ = klass.__str__
1048 klass.__str__ = lambda self: self.__unicode__().encode("utf-8")
1049 return klass
1052# Complete the moves implementation.
1053# This code is at the end of this module to speed up module loading.
1054# Turn this module into a package.
1055__path__ = [] # required for PEP 302 and PEP 451
1056__package__ = __name__ # see PEP 366 @ReservedAssignment
1057if globals().get("__spec__") is not None: 1057 ↛ 1062line 1057 didn't jump to line 1062, because the condition on line 1057 was never false
1058 __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
1059# Remove other six meta path importers, since they cause problems. This can
1060# happen if six is removed from sys.modules and then reloaded. (Setuptools does
1061# this for some reason.)
1062if sys.meta_path: 1062 ↛ 1076line 1062 didn't jump to line 1076, because the condition on line 1062 was never false
1063 for i, importer in enumerate(sys.meta_path):
1064 # Here's some real nastiness: Another "instance" of the six module might
1065 # be floating around. Therefore, we can't use isinstance() to check for
1066 # the six meta path importer, since the other six instance will have
1067 # inserted an importer with different class.
1068 if ( 1068 ↛ 1072line 1068 didn't jump to line 1072
1069 type(importer).__name__ == "_SixMetaPathImporter"
1070 and importer.name == __name__
1071 ):
1072 del sys.meta_path[i]
1073 break
1074 del i, importer
1075# Finally, add the importer to the meta path import hook.
1076sys.meta_path.append(_importer)