1 """Utilities for writing code that runs on Python 2 and 3"""
23 from __future__
import absolute_import
31 __author__ =
"Benjamin Peterson <benjamin@python.org>"
36 PY2 = sys.version_info[0] == 2
37 PY3 = sys.version_info[0] == 3
48 string_types = basestring,
49 integer_types = (int, long)
50 class_types = (type, types.ClassType)
54 if sys.platform.startswith(
"java"):
56 MAXSIZE =
int((1 << 31) - 1)
67 MAXSIZE =
int((1 << 31) - 1)
70 MAXSIZE =
int((1 << 63) - 1)
75 """Add documentation to a function."""
80 """Import module, returning the module after the last dot."""
82 return sys.modules[name]
91 result = self._resolve()
92 setattr(obj, self.
name, result)
96 delattr(obj.__class__, self.
name)
97 except AttributeError:
105 super(MovedModule, self).
__init__(name)
118 value = getattr(_module, attr)
119 setattr(self, attr, value)
126 super(_LazyModule, self).
__init__(name)
130 attrs = [
"__doc__",
"__name__"]
135 _moved_attributes = []
140 def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
141 super(MovedAttribute, self).
__init__(name)
160 return getattr(module, self.
attr)
166 A meta path importer to import six.moves and its submodules.
168 This class implements a PEP302 finder and loader. It should be compatible
169 with Python 2.5 and all existing versions of Python3
177 for fullname
in fullnames:
192 raise ImportError(
"This loader does not know module " + fullname)
197 return sys.modules[fullname]
201 if isinstance(mod, MovedModule):
204 mod.__loader__ = self
205 sys.modules[fullname] = mod
210 Return true, if the named module is a package.
212 We need this method to get correct spec objects with
213 Python 3.4 (see PEP451)
220 Required, if is_package is implemented"""
223 get_source = get_code
230 """Lazy loading of moved objects"""
234 _moved_attributes = [
236 MovedAttribute(
"filter",
"itertools",
"builtins",
"ifilter",
"filter"),
237 MovedAttribute(
"filterfalse",
"itertools",
"itertools",
"ifilterfalse",
"filterfalse"),
238 MovedAttribute(
"input",
"__builtin__",
"builtins",
"raw_input",
"input"),
241 MovedAttribute(
"range",
"__builtin__",
"builtins",
"xrange",
"range"),
249 MovedAttribute(
"xrange",
"__builtin__",
"builtins",
"xrange",
"range"),
251 MovedAttribute(
"zip_longest",
"itertools",
"itertools",
"izip_longest",
"zip_longest"),
257 MovedModule(
"_dummy_thread",
"dummy_thread",
"_dummy_thread"),
258 MovedModule(
"http_cookiejar",
"cookielib",
"http.cookiejar"),
259 MovedModule(
"http_cookies",
"Cookie",
"http.cookies"),
260 MovedModule(
"html_entities",
"htmlentitydefs",
"html.entities"),
261 MovedModule(
"html_parser",
"HTMLParser",
"html.parser"),
262 MovedModule(
"http_client",
"httplib",
"http.client"),
263 MovedModule(
"email_mime_multipart",
"email.MIMEMultipart",
"email.mime.multipart"),
264 MovedModule(
"email_mime_nonmultipart",
"email.MIMENonMultipart",
"email.mime.nonmultipart"),
265 MovedModule(
"email_mime_text",
"email.MIMEText",
"email.mime.text"),
266 MovedModule(
"email_mime_base",
"email.MIMEBase",
"email.mime.base"),
267 MovedModule(
"BaseHTTPServer",
"BaseHTTPServer",
"http.server"),
268 MovedModule(
"CGIHTTPServer",
"CGIHTTPServer",
"http.server"),
269 MovedModule(
"SimpleHTTPServer",
"SimpleHTTPServer",
"http.server"),
276 MovedModule(
"tkinter_dialog",
"Dialog",
"tkinter.dialog"),
277 MovedModule(
"tkinter_filedialog",
"FileDialog",
"tkinter.filedialog"),
278 MovedModule(
"tkinter_scrolledtext",
"ScrolledText",
"tkinter.scrolledtext"),
279 MovedModule(
"tkinter_simpledialog",
"SimpleDialog",
"tkinter.simpledialog"),
282 MovedModule(
"tkinter_constants",
"Tkconstants",
"tkinter.constants"),
283 MovedModule(
"tkinter_dnd",
"Tkdnd",
"tkinter.dnd"),
284 MovedModule(
"tkinter_colorchooser",
"tkColorChooser",
285 "tkinter.colorchooser"),
286 MovedModule(
"tkinter_commondialog",
"tkCommonDialog",
287 "tkinter.commondialog"),
288 MovedModule(
"tkinter_tkfiledialog",
"tkFileDialog",
"tkinter.filedialog"),
289 MovedModule(
"tkinter_font",
"tkFont",
"tkinter.font"),
290 MovedModule(
"tkinter_messagebox",
"tkMessageBox",
"tkinter.messagebox"),
291 MovedModule(
"tkinter_tksimpledialog",
"tkSimpleDialog",
292 "tkinter.simpledialog"),
293 MovedModule(
"urllib_parse", __name__ +
".moves.urllib_parse",
"urllib.parse"),
294 MovedModule(
"urllib_error", __name__ +
".moves.urllib_error",
"urllib.error"),
295 MovedModule(
"urllib", __name__ +
".moves.urllib", __name__ +
".moves.urllib"),
296 MovedModule(
"urllib_robotparser",
"robotparser",
"urllib.robotparser"),
297 MovedModule(
"xmlrpc_client",
"xmlrpclib",
"xmlrpc.client"),
298 MovedModule(
"xmlrpc_server",
"SimpleXMLRPCServer",
"xmlrpc.server"),
301 for attr
in _moved_attributes:
302 setattr(_MovedItems, attr.name, attr)
303 if isinstance(attr, MovedModule):
304 _importer._add_module(attr,
"moves." + attr.name)
307 _MovedItems._moved_attributes = _moved_attributes
310 _importer._add_module(moves,
"moves")
315 """Lazy loading of moved objects in six.moves.urllib_parse"""
318 _urllib_parse_moved_attributes = [
319 MovedAttribute(
"ParseResult",
"urlparse",
"urllib.parse"),
320 MovedAttribute(
"SplitResult",
"urlparse",
"urllib.parse"),
321 MovedAttribute(
"parse_qs",
"urlparse",
"urllib.parse"),
322 MovedAttribute(
"parse_qsl",
"urlparse",
"urllib.parse"),
323 MovedAttribute(
"urldefrag",
"urlparse",
"urllib.parse"),
324 MovedAttribute(
"urljoin",
"urlparse",
"urllib.parse"),
325 MovedAttribute(
"urlparse",
"urlparse",
"urllib.parse"),
326 MovedAttribute(
"urlsplit",
"urlparse",
"urllib.parse"),
327 MovedAttribute(
"urlunparse",
"urlparse",
"urllib.parse"),
328 MovedAttribute(
"urlunsplit",
"urlparse",
"urllib.parse"),
329 MovedAttribute(
"quote",
"urllib",
"urllib.parse"),
330 MovedAttribute(
"quote_plus",
"urllib",
"urllib.parse"),
331 MovedAttribute(
"unquote",
"urllib",
"urllib.parse"),
332 MovedAttribute(
"unquote_plus",
"urllib",
"urllib.parse"),
333 MovedAttribute(
"urlencode",
"urllib",
"urllib.parse"),
334 MovedAttribute(
"splitquery",
"urllib",
"urllib.parse"),
335 MovedAttribute(
"splittag",
"urllib",
"urllib.parse"),
336 MovedAttribute(
"splituser",
"urllib",
"urllib.parse"),
337 MovedAttribute(
"uses_fragment",
"urlparse",
"urllib.parse"),
338 MovedAttribute(
"uses_netloc",
"urlparse",
"urllib.parse"),
339 MovedAttribute(
"uses_params",
"urlparse",
"urllib.parse"),
340 MovedAttribute(
"uses_query",
"urlparse",
"urllib.parse"),
341 MovedAttribute(
"uses_relative",
"urlparse",
"urllib.parse"),
343 for attr
in _urllib_parse_moved_attributes:
344 setattr(Module_six_moves_urllib_parse, attr.name, attr)
347 Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
349 _importer._add_module(Module_six_moves_urllib_parse(__name__ +
".moves.urllib_parse"),
350 "moves.urllib_parse",
"moves.urllib.parse")
355 """Lazy loading of moved objects in six.moves.urllib_error"""
358 _urllib_error_moved_attributes = [
359 MovedAttribute(
"URLError",
"urllib2",
"urllib.error"),
360 MovedAttribute(
"HTTPError",
"urllib2",
"urllib.error"),
361 MovedAttribute(
"ContentTooShortError",
"urllib",
"urllib.error"),
363 for attr
in _urllib_error_moved_attributes:
364 setattr(Module_six_moves_urllib_error, attr.name, attr)
367 Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
369 _importer._add_module(Module_six_moves_urllib_error(__name__ +
".moves.urllib.error"),
370 "moves.urllib_error",
"moves.urllib.error")
375 """Lazy loading of moved objects in six.moves.urllib_request"""
378 _urllib_request_moved_attributes = [
379 MovedAttribute(
"urlopen",
"urllib2",
"urllib.request"),
380 MovedAttribute(
"install_opener",
"urllib2",
"urllib.request"),
381 MovedAttribute(
"build_opener",
"urllib2",
"urllib.request"),
382 MovedAttribute(
"pathname2url",
"urllib",
"urllib.request"),
383 MovedAttribute(
"url2pathname",
"urllib",
"urllib.request"),
384 MovedAttribute(
"getproxies",
"urllib",
"urllib.request"),
385 MovedAttribute(
"Request",
"urllib2",
"urllib.request"),
386 MovedAttribute(
"OpenerDirector",
"urllib2",
"urllib.request"),
387 MovedAttribute(
"HTTPDefaultErrorHandler",
"urllib2",
"urllib.request"),
388 MovedAttribute(
"HTTPRedirectHandler",
"urllib2",
"urllib.request"),
389 MovedAttribute(
"HTTPCookieProcessor",
"urllib2",
"urllib.request"),
390 MovedAttribute(
"ProxyHandler",
"urllib2",
"urllib.request"),
391 MovedAttribute(
"BaseHandler",
"urllib2",
"urllib.request"),
392 MovedAttribute(
"HTTPPasswordMgr",
"urllib2",
"urllib.request"),
393 MovedAttribute(
"HTTPPasswordMgrWithDefaultRealm",
"urllib2",
"urllib.request"),
394 MovedAttribute(
"AbstractBasicAuthHandler",
"urllib2",
"urllib.request"),
395 MovedAttribute(
"HTTPBasicAuthHandler",
"urllib2",
"urllib.request"),
396 MovedAttribute(
"ProxyBasicAuthHandler",
"urllib2",
"urllib.request"),
397 MovedAttribute(
"AbstractDigestAuthHandler",
"urllib2",
"urllib.request"),
398 MovedAttribute(
"HTTPDigestAuthHandler",
"urllib2",
"urllib.request"),
399 MovedAttribute(
"ProxyDigestAuthHandler",
"urllib2",
"urllib.request"),
400 MovedAttribute(
"HTTPHandler",
"urllib2",
"urllib.request"),
401 MovedAttribute(
"HTTPSHandler",
"urllib2",
"urllib.request"),
402 MovedAttribute(
"FileHandler",
"urllib2",
"urllib.request"),
403 MovedAttribute(
"FTPHandler",
"urllib2",
"urllib.request"),
404 MovedAttribute(
"CacheFTPHandler",
"urllib2",
"urllib.request"),
405 MovedAttribute(
"UnknownHandler",
"urllib2",
"urllib.request"),
406 MovedAttribute(
"HTTPErrorProcessor",
"urllib2",
"urllib.request"),
407 MovedAttribute(
"urlretrieve",
"urllib",
"urllib.request"),
408 MovedAttribute(
"urlcleanup",
"urllib",
"urllib.request"),
409 MovedAttribute(
"URLopener",
"urllib",
"urllib.request"),
410 MovedAttribute(
"FancyURLopener",
"urllib",
"urllib.request"),
411 MovedAttribute(
"proxy_bypass",
"urllib",
"urllib.request"),
413 for attr
in _urllib_request_moved_attributes:
414 setattr(Module_six_moves_urllib_request, attr.name, attr)
417 Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
419 _importer._add_module(Module_six_moves_urllib_request(__name__ +
".moves.urllib.request"),
420 "moves.urllib_request",
"moves.urllib.request")
425 """Lazy loading of moved objects in six.moves.urllib_response"""
428 _urllib_response_moved_attributes = [
429 MovedAttribute(
"addbase",
"urllib",
"urllib.response"),
430 MovedAttribute(
"addclosehook",
"urllib",
"urllib.response"),
431 MovedAttribute(
"addinfo",
"urllib",
"urllib.response"),
432 MovedAttribute(
"addinfourl",
"urllib",
"urllib.response"),
434 for attr
in _urllib_response_moved_attributes:
435 setattr(Module_six_moves_urllib_response, attr.name, attr)
438 Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
440 _importer._add_module(Module_six_moves_urllib_response(__name__ +
".moves.urllib.response"),
441 "moves.urllib_response",
"moves.urllib.response")
446 """Lazy loading of moved objects in six.moves.urllib_robotparser"""
449 _urllib_robotparser_moved_attributes = [
450 MovedAttribute(
"RobotFileParser",
"robotparser",
"urllib.robotparser"),
452 for attr
in _urllib_robotparser_moved_attributes:
453 setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
456 Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
458 _importer._add_module(Module_six_moves_urllib_robotparser(__name__ +
".moves.urllib.robotparser"),
459 "moves.urllib_robotparser",
"moves.urllib.robotparser")
464 """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
466 parse = _importer._get_module(
"moves.urllib_parse")
467 error = _importer._get_module(
"moves.urllib_error")
468 request = _importer._get_module(
"moves.urllib_request")
469 response = _importer._get_module(
"moves.urllib_response")
470 robotparser = _importer._get_module(
"moves.urllib_robotparser")
473 return [
'parse',
'error',
'request',
'response',
'robotparser']
480 """Add an item to six.moves."""
481 setattr(_MovedItems, move.name, move)
485 """Remove item from six.moves."""
487 delattr(_MovedItems, name)
488 except AttributeError:
490 del moves.__dict__[name]
492 raise AttributeError(
"no such move, %r" % (name,))
496 _meth_func =
"__func__"
497 _meth_self =
"__self__"
499 _func_closure =
"__closure__"
500 _func_code =
"__code__"
501 _func_defaults =
"__defaults__"
502 _func_globals =
"__globals__"
504 _meth_func =
"im_func"
505 _meth_self =
"im_self"
507 _func_closure =
"func_closure"
508 _func_code =
"func_code"
509 _func_defaults =
"func_defaults"
510 _func_globals =
"func_globals"
514 advance_iterator = next
518 next = advance_iterator
525 return any(
"__call__" in klass.__dict__
for klass
in type(obj).__mro__)
532 create_bound_method = types.MethodType
537 return unbound.im_func
540 return types.MethodType(func, obj, obj.__class__)
545 return type(self).__next__(self)
549 """Get the function out of a possibly unbound function""")
552 get_method_function = operator.attrgetter(_meth_func)
553 get_method_self = operator.attrgetter(_meth_self)
554 get_function_closure = operator.attrgetter(_func_closure)
555 get_function_code = operator.attrgetter(_func_code)
556 get_function_defaults = operator.attrgetter(_func_defaults)
557 get_function_globals = operator.attrgetter(_func_globals)
562 return iter(d.keys(**kw))
565 return iter(d.values(**kw))
568 return iter(d.items(**kw))
571 return iter(d.lists(**kw))
573 viewkeys = operator.methodcaller(
"keys")
575 viewvalues = operator.methodcaller(
"values")
577 viewitems = operator.methodcaller(
"items")
580 return iter(d.iterkeys(**kw))
583 return iter(d.itervalues(**kw))
586 return iter(d.iteritems(**kw))
589 return iter(d.iterlists(**kw))
591 viewkeys = operator.methodcaller(
"viewkeys")
593 viewvalues = operator.methodcaller(
"viewvalues")
595 viewitems = operator.methodcaller(
"viewitems")
597 _add_doc(iterkeys,
"Return an iterator over the keys of a dictionary.")
598 _add_doc(itervalues,
"Return an iterator over the values of a dictionary.")
600 "Return an iterator over the (key, value) pairs of a dictionary.")
602 "Return an iterator over the (key, [values]) pairs of a dictionary.")
607 return s.encode(
"latin-1")
612 if sys.version_info[1] <= 1:
617 int2byte = operator.methodcaller(
"to_bytes", 1,
"big")
618 byte2int = operator.itemgetter(0)
619 indexbytes = operator.getitem
622 StringIO = io.StringIO
624 _assertCountEqual =
"assertCountEqual"
625 _assertRaisesRegex =
"assertRaisesRegex"
626 _assertRegex =
"assertRegex"
633 return unicode(s.replace(
r'\\',
r'\\\\'),
"unicode_escape")
642 iterbytes = functools.partial(itertools.imap, ord)
644 StringIO = BytesIO = StringIO.StringIO
645 _assertCountEqual =
"assertItemsEqual"
646 _assertRaisesRegex =
"assertRaisesRegexp"
647 _assertRegex =
"assertRegexpMatches"
653 return getattr(self, _assertCountEqual)(*args, **kwargs)
657 return getattr(self, _assertRaisesRegex)(*args, **kwargs)
661 return getattr(self, _assertRegex)(*args, **kwargs)
665 exec_ = getattr(moves.builtins,
"exec")
670 if value.__traceback__
is not tb:
671 raise value.with_traceback(tb)
675 def exec_(_code_, _globs_=None, _locs_=None):
676 """Execute code in a namespace."""
678 frame = sys._getframe(1)
679 _globs_ = frame.f_globals
681 _locs_ = frame.f_locals
685 exec(
"""exec _code_ in _globs_, _locs_""")
687 exec_(
"""def reraise(tp, value, tb=None):
692 if sys.version_info[:2] == (3, 2):
693 exec_(
"""def raise_from(value, from_value):
694 if from_value is None:
696 raise value from from_value
698 elif sys.version_info[:2] > (3, 2):
699 exec_(
"""def raise_from(value, from_value):
700 raise value from from_value
707 print_ = getattr(moves.builtins,
"print",
None)
710 """The new-style print function for Python 2.4 and 2.5."""
711 fp = kwargs.pop(
"file", sys.stdout)
716 if not isinstance(data, basestring):
719 if (isinstance(fp, file)
and
720 isinstance(data, unicode)
and
721 fp.encoding
is not None):
722 errors = getattr(fp,
"errors",
None)
725 data = data.encode(fp.encoding, errors)
728 sep = kwargs.pop(
"sep",
None)
730 if isinstance(sep, unicode):
732 elif not isinstance(sep, str):
733 raise TypeError(
"sep must be None or a string")
734 end = kwargs.pop(
"end",
None)
736 if isinstance(end, unicode):
738 elif not isinstance(end, str):
739 raise TypeError(
"end must be None or a string")
741 raise TypeError(
"invalid keyword arguments to print()")
744 if isinstance(arg, unicode):
757 for i, arg
in enumerate(args):
762 if sys.version_info[:2] < (3, 3):
765 def print_(*args, **kwargs):
766 fp = kwargs.get(
"file", sys.stdout)
767 flush = kwargs.pop(
"flush",
False)
769 if flush
and fp
is not None:
772 _add_doc(reraise,
"""Reraise an exception.""")
774 if sys.version_info[0:2] < (3, 4):
775 def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
776 updated=functools.WRAPPER_UPDATES):
778 f = functools.wraps(wrapped, assigned, updated)(f)
779 f.__wrapped__ = wrapped
783 wraps = functools.wraps
787 """Create a base class with a metaclass."""
791 class metaclass(meta):
793 def __new__(cls, name, this_bases, d):
794 return meta(name, bases, d)
795 return type.__new__(metaclass,
'temporary_class', (), {})
799 """Class decorator for creating a class with a metaclass."""
801 orig_vars = cls.__dict__.
copy()
802 slots = orig_vars.get(
'__slots__')
803 if slots
is not None:
804 if isinstance(slots, str):
806 for slots_var
in slots:
807 orig_vars.pop(slots_var)
808 orig_vars.pop(
'__dict__',
None)
809 orig_vars.pop(
'__weakref__',
None)
810 return metaclass(cls.__name__, cls.__bases__, orig_vars)
816 A decorator that defines __unicode__ and __str__ methods under Python 2.
817 Under Python 3 it does nothing.
819 To support Python 2 and 3 with a single code base, define a __str__ method
820 returning text and apply this decorator to the class.
823 if '__str__' not in klass.__dict__:
824 raise ValueError(
"@python_2_unicode_compatible cannot be applied "
825 "to %s because it doesn't define __str__()." %
827 klass.__unicode__ = klass.__str__
828 klass.__str__ =
lambda self: self.__unicode__().
encode(
'utf-8')
836 __package__ = __name__
837 if globals().get(
"__spec__")
is not None:
838 __spec__.submodule_search_locations = []
843 for i, importer
in enumerate(sys.meta_path):
848 if (
type(importer).__name__ ==
"_SixMetaPathImporter" and
849 importer.name == __name__):
854 sys.meta_path.append(_importer)