1 # Copyright (c) 2010-2020 Benjamin Peterson
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:
10 # The above copyright notice and this permission notice shall be included in all
11 # copies or substantial portions of the Software.
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
21 """Utilities for writing code that runs on Python 2 and 3"""
23 from __future__
import absolute_import
31 __author__
= "Benjamin Peterson <benjamin@python.org>"
32 __version__
= "1.16.0"
35 # Useful for very coarse version differentiation.
36 PY2
= sys
.version_info
[0] == 2
37 PY3
= sys
.version_info
[0] == 3
38 PY34
= sys
.version_info
[0:2] >= (3, 4)
42 integer_types
= (int,)
49 string_types
= (basestring
,)
50 integer_types
= (int, long)
51 class_types
= (type, types
.ClassType
)
55 if sys
.platform
.startswith("java"):
56 # Jython always uses 32 bits.
57 MAXSIZE
= int((1 << 31) - 1)
59 # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
68 MAXSIZE
= int((1 << 31) - 1)
71 MAXSIZE
= int((1 << 63) - 1)
75 from importlib
.util
import spec_from_loader
77 spec_from_loader
= None
80 def _add_doc(func
, doc
):
81 """Add documentation to a function."""
85 def _import_module(name
):
86 """Import module, returning the module after the last dot."""
88 return sys
.modules
[name
]
91 class _LazyDescr(object):
92 def __init__(self
, name
):
95 def __get__(self
, obj
, tp
):
96 result
= self
._resolve
()
97 setattr(obj
, self
.name
, result
) # Invokes __set__.
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:
107 class MovedModule(_LazyDescr
):
108 def __init__(self
, name
, old
, new
=None):
109 super(MovedModule
, self
).__init
__(name
)
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
)
127 class _LazyModule(types
.ModuleType
):
128 def __init__(self
, name
):
129 super(_LazyModule
, self
).__init
__(name
)
130 self
.__doc
__ = self
.__class
__.__doc
__
133 attrs
= ["__doc__", "__name__"]
134 attrs
+= [attr
.name
for attr
in self
._moved
_attributes
]
137 # Subclasses should override this
138 _moved_attributes
= []
141 class MovedAttribute(_LazyDescr
):
142 def __init__(self
, name
, old_mod
, new_mod
, old_attr
=None, new_attr
=None):
143 super(MovedAttribute
, self
).__init
__(name
)
161 module
= _import_module(self
.mod
)
162 return getattr(module
, self
.attr
)
165 class _SixMetaPathImporter(object):
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
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
:
190 def find_spec(self
, fullname
, path
, target
=None):
191 if fullname
in self
.known_modules
:
192 return spec_from_loader(fullname
, self
)
195 def __get_module(self
, fullname
):
197 return self
.known_modules
[fullname
]
199 raise ImportError("This loader does not know module " + fullname
)
201 def load_module(self
, fullname
):
203 # in case of a reload
204 return sys
.modules
[fullname
]
207 mod
= self
.__get
_module
(fullname
)
208 if isinstance(mod
, MovedModule
):
211 mod
.__loader
__ = self
212 sys
.modules
[fullname
] = mod
215 def is_package(self
, fullname
):
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)
222 return hasattr(self
.__get
_module
(fullname
), "__path__")
224 def get_code(self
, fullname
):
227 Required, if is_package is implemented"""
228 self
.__get
_module
(fullname
) # eventually raises ImportError
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
):
240 _importer
= _SixMetaPathImporter(__name__
)
243 class _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"),
254 "filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"
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"),
264 "reload_module", "__builtin__", "importlib" if PY34
else "imp", "reload"
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"),
275 "zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"
277 MovedModule("builtins", "__builtin__"),
278 MovedModule("configparser", "ConfigParser"),
282 "collections.abc" if sys
.version_info
>= (3, 3) else "collections",
284 MovedModule("copyreg", "copy_reg"),
285 MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
286 MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),
290 "_dummy_thread" if sys
.version_info
< (3, 9) else "_thread",
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"),
301 "email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"
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"),
334 # Add windows specific modules.
335 if sys
.platform
== "win32":
336 _moved_attributes
+= [
337 MovedModule("winreg", "_winreg"),
340 for attr
in _moved_attributes
:
341 setattr(_MovedItems
, attr
.name
, attr
)
342 if isinstance(attr
, MovedModule
):
343 _importer
._add
_module
(attr
, "moves." + attr
.name
)
346 _MovedItems
._moved
_attributes
= _moved_attributes
348 moves
= _MovedItems(__name__
+ ".moves")
349 _importer
._add
_module
(moves
, "moves")
352 class 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"),
373 "unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"
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"),
386 for attr
in _urllib_parse_moved_attributes
:
387 setattr(Module_six_moves_urllib_parse
, attr
.name
, attr
)
390 Module_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",
399 class 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"),
409 for attr
in _urllib_error_moved_attributes
:
410 setattr(Module_six_moves_urllib_error
, attr
.name
, attr
)
413 Module_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",
422 class 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"),
464 for attr
in _urllib_request_moved_attributes
:
465 setattr(Module_six_moves_urllib_request
, attr
.name
, attr
)
468 Module_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",
477 class 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"),
488 for attr
in _urllib_response_moved_attributes
:
489 setattr(Module_six_moves_urllib_response
, attr
.name
, attr
)
492 Module_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",
501 class 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"),
509 for attr
in _urllib_robotparser_moved_attributes
:
510 setattr(Module_six_moves_urllib_robotparser
, attr
.name
, attr
)
513 Module_six_moves_urllib_robotparser
._moved
_attributes
= (
514 _urllib_robotparser_moved_attributes
517 _importer
._add
_module
(
518 Module_six_moves_urllib_robotparser(__name__
+ ".moves.urllib.robotparser"),
519 "moves.urllib_robotparser",
520 "moves.urllib.robotparser",
524 class 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")
536 return ["parse", "error", "request", "response", "robotparser"]
539 _importer
._add
_module
(
540 Module_six_moves_urllib(__name__
+ ".moves.urllib"), "moves.urllib"
545 """Add an item to six.moves."""
546 setattr(_MovedItems
, move
.name
, move
)
549 def remove_move(name
):
550 """Remove item from six.moves."""
552 delattr(_MovedItems
, name
)
553 except AttributeError:
555 del moves
.__dict
__[name
]
557 raise AttributeError("no such move, %r" % (name
,))
561 _meth_func
= "__func__"
562 _meth_self
= "__self__"
564 _func_closure
= "__closure__"
565 _func_code
= "__code__"
566 _func_defaults
= "__defaults__"
567 _func_globals
= "__globals__"
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"
579 advance_iterator
= next
582 def advance_iterator(it
):
586 next
= advance_iterator
594 return any("__call__" in klass
.__dict
__ for klass
in type(obj
).__mro
__)
599 def get_unbound_function(unbound
):
602 create_bound_method
= types
.MethodType
604 def create_unbound_method(func
, cls
):
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):
621 return type(self
).__next
__(self
)
625 get_unbound_function
, """Get the function out of a possibly unbound function"""
629 get_method_function
= operator
.attrgetter(_meth_func
)
630 get_method_self
= operator
.attrgetter(_meth_self
)
631 get_function_closure
= operator
.attrgetter(_func_closure
)
632 get_function_code
= operator
.attrgetter(_func_code
)
633 get_function_defaults
= operator
.attrgetter(_func_defaults
)
634 get_function_globals
= operator
.attrgetter(_func_globals
)
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")
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.")
680 iterlists
, "Return an iterator over the (key, [values]) pairs of a dictionary."
687 return s
.encode("latin-1")
695 int2byte
= struct
.Struct(">B").pack
697 byte2int
= operator
.itemgetter(0)
698 indexbytes
= operator
.getitem
702 StringIO
= io
.StringIO
705 _assertCountEqual
= "assertCountEqual"
706 if sys
.version_info
[1] <= 1:
707 _assertRaisesRegex
= "assertRaisesRegexp"
708 _assertRegex
= "assertRegexpMatches"
709 _assertNotRegex
= "assertNotRegexpMatches"
711 _assertRaisesRegex
= "assertRaisesRegex"
712 _assertRegex
= "assertRegex"
713 _assertNotRegex
= "assertNotRegex"
719 # Workaround for standalone backslash
722 return unicode(s
.replace(r
"\\", r
"\\\\"), "unicode_escape")
730 def indexbytes(buf
, i
):
733 iterbytes
= functools
.partial(itertools
.imap
, ord)
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""")
745 def assertCountEqual(self
, *args
, **kwargs
):
746 return getattr(self
, _assertCountEqual
)(*args
, **kwargs
)
749 def assertRaisesRegex(self
, *args
, **kwargs
):
750 return getattr(self
, _assertRaisesRegex
)(*args
, **kwargs
)
753 def assertRegex(self
, *args
, **kwargs
):
754 return getattr(self
, _assertRegex
)(*args
, **kwargs
)
757 def assertNotRegex(self
, *args
, **kwargs
):
758 return getattr(self
, _assertNotRegex
)(*args
, **kwargs
)
762 exec_
= getattr(moves
.builtins
, "exec")
764 def reraise(tp
, value
, tb
=None):
768 if value
.__traceback
__ is not tb
:
769 raise value
.with_traceback(tb
)
777 def exec_(_code_
, _globs_
=None, _locs_
=None):
778 """Execute code in a namespace."""
780 frame
= sys
._getframe
(1)
781 _globs_
= frame
.f_globals
783 _locs_
= frame
.f_locals
787 exec ("""exec _code_ in _globs_, _locs_""")
790 """def reraise(tp, value, tb=None):
799 if sys
.version_info
[:2] > (3,):
801 """def raise_from(value, from_value):
803 raise value from from_value
810 def raise_from(value
, from_value
):
814 print_
= getattr(moves
.builtins
, "print", None)
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
)
824 if not isinstance(data
, basestring
):
826 # If the file has an encoding, encode unicode with it.
829 and isinstance(data
, unicode)
830 and fp
.encoding
is not None
832 errors
= getattr(fp
, "errors", None)
835 data
= data
.encode(fp
.encoding
, errors
)
839 sep
= kwargs
.pop("sep", None)
841 if isinstance(sep
, unicode):
843 elif not isinstance(sep
, str):
844 raise TypeError("sep must be None or a string")
845 end
= kwargs
.pop("end", None)
847 if isinstance(end
, unicode):
849 elif not isinstance(end
, str):
850 raise TypeError("end must be None or a string")
852 raise TypeError("invalid keyword arguments to print()")
855 if isinstance(arg
, unicode):
859 newline
= unicode("\n")
868 for i
, arg
in enumerate(args
):
875 if sys
.version_info
[:2] < (3, 3):
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:
886 _add_doc(reraise
, """Reraise an exception.""")
888 if sys
.version_info
[0:2] < (3, 4):
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.
897 assigned
=functools
.WRAPPER_ASSIGNMENTS
,
898 updated
=functools
.WRAPPER_UPDATES
,
900 for attr
in assigned
:
902 value
= getattr(wrapped
, attr
)
903 except AttributeError:
906 setattr(wrapper
, attr
, value
)
908 getattr(wrapper
, attr
).update(getattr(wrapped
, attr
, {}))
909 wrapper
.__wrapped
__ = wrapped
912 _update_wrapper
.__doc
__ = functools
.update_wrapper
.__doc
__
916 assigned
=functools
.WRAPPER_ASSIGNMENTS
,
917 updated
=functools
.WRAPPER_UPDATES
,
919 return functools
.partial(
920 _update_wrapper
, wrapped
=wrapped
, assigned
=assigned
, updated
=updated
923 wraps
.__doc
__ = functools
.wraps
.__doc
__
926 wraps
= functools
.wraps
929 def 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
943 resolved_bases
= bases
944 return meta(name
, resolved_bases
, d
)
947 def __prepare__(cls
, name
, this_bases
):
948 return meta
.__prepare
__(name
, bases
)
950 return type.__new
__(metaclass
, "temporary_class", (), {})
953 def add_metaclass(metaclass
):
954 """Class decorator for creating a class with a metaclass."""
957 orig_vars
= cls
.__dict
__.copy()
958 slots
= orig_vars
.get("__slots__")
959 if slots
is not None:
960 if isinstance(slots
, str):
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__"):
967 orig_vars
["__qualname__"] = cls
.__qualname
__
968 return metaclass(cls
.__name
__, cls
.__bases
__, orig_vars
)
973 def ensure_binary(s
, encoding
="utf-8", errors
="strict"):
974 """Coerce **s** to six.binary_type.
977 - `unicode` -> encoded to `str`
981 - `str` -> encoded to `bytes`
984 if isinstance(s
, binary_type
):
986 if isinstance(s
, text_type
):
987 return s
.encode(encoding
, errors
)
988 raise TypeError("not expecting type '%s'" % type(s
))
991 def ensure_str(s
, encoding
="utf-8", errors
="strict"):
992 """Coerce *s* to `str`.
995 - `unicode` -> encoded to `str`
1000 - `bytes` -> decoded to `str`
1002 # Optimization: Fast return for the common case.
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
))
1014 def ensure_text(s
, encoding
="utf-8", errors
="strict"):
1015 """Coerce *s* to six.text_type.
1018 - `unicode` -> `unicode`
1019 - `str` -> `unicode`
1023 - `bytes` -> decoded to `str`
1025 if isinstance(s
, binary_type
):
1026 return s
.decode(encoding
, errors
)
1027 elif isinstance(s
, text_type
):
1030 raise TypeError("not expecting type '%s'" % type(s
))
1033 def python_2_unicode_compatible(klass
):
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.
1042 if "__str__" not in klass
.__dict
__:
1044 "@python_2_unicode_compatible cannot be applied "
1045 "to %s because it doesn't define __str__()." % klass
.__name
__
1047 klass
.__unicode
__ = klass
.__str
__
1048 klass
.__str
__ = lambda self
: self
.__unicode
__().encode("utf-8")
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
1057 if globals().get("__spec__") is not None:
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.)
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.
1069 type(importer
).__name
__ == "_SixMetaPathImporter"
1070 and importer
.name
== __name__
1072 del sys
.meta_path
[i
]
1075 # Finally, add the importer to the meta path import hook.
1076 sys
.meta_path
.append(_importer
)