Skip to content
Myr

further

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 786dfdd · Browse files · 8 files+518 added−435 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+518 added−435 removed

  • other:+518 added−435 removed

8 files+518 added−435 removed

added:requests/packages/urllib3/packages/mimetools_choose_boundary/__init__.py+47 added
1"""The function mimetools.choose_boundary() from Python 2.7, which seems to2have disappeared in Python 3 (although email.generator._make_boundary() might3work as a replacement?).45Tweaked to use lock from threading rather than thread.6"""7import os8from threading import Lock9_counter_lock = Lock()1011_counter = 012def _get_next_counter():13 global _counter14 with _counter_lock:15 _counter += 116 return _counter1718_prefix = None1920def choose_boundary():21 """Return a string usable as a multipart boundary.2223 The string chosen is unique within a single program run, and24 incorporates the user id (if available), process id (if available),25 and current time. So it's very unlikely the returned string appears26 in message text, but there's no guarantee.2728 The boundary contains dots so you have to quote it in the header."""2930 global _prefix31 import time32 if _prefix is None:33 import socket34 try:35 hostid = socket.gethostbyname(socket.gethostname())36 except socket.gaierror:37 hostid = '127.0.0.1'38 try:39 uid = repr(os.getuid())40 except AttributeError:41 uid = '1'42 try:43 pid = repr(os.getpid())44 except AttributeError:45 pid = '1'46 _prefix = hostid + '.' + uid + '.' + pid47 return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())
added:requests/packages/urllib3/packages/six.py+372 added
1"""Utilities for writing code that runs on Python 2 and 3"""23#Copyright (c) 2010-2011 Benjamin Peterson45#Permission is hereby granted, free of charge, to any person obtaining a copy of6#this software and associated documentation files (the "Software"), to deal in7#the Software without restriction, including without limitation the rights to8#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of9#the Software, and to permit persons to whom the Software is furnished to do so,10#subject to the following conditions:1112#The above copyright notice and this permission notice shall be included in all13#copies or substantial portions of the Software.1415#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS17#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR18#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER19#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.2122import operator23import sys24import types2526__author__ = "Benjamin Peterson <benjamin@python.org>"27__version__ = "1.1.0"282930# True if we are running on Python 3.31PY3 = sys.version_info[0] == 33233if PY3:34 string_types = str,35 integer_types = int,36 class_types = type,37 text_type = str38 binary_type = bytes3940 MAXSIZE = sys.maxsize41else:42 string_types = basestring,43 integer_types = (int, long)44 class_types = (type, types.ClassType)45 text_type = unicode46 binary_type = str4748 # It's possible to have sizeof(long) != sizeof(Py_ssize_t).49 class X(object):50 def __len__(self):51 return 1 << 3152 try:53 len(X())54 except OverflowError:55 # 32-bit56 MAXSIZE = int((1 << 31) - 1)57 else:58 # 64-bit59 MAXSIZE = int((1 << 63) - 1)60 del X616263def _add_doc(func, doc):64 """Add documentation to a function."""65 func.__doc__ = doc666768def _import_module(name):69 """Import module, returning the module after the last dot."""70 __import__(name)71 return sys.modules[name]727374class _LazyDescr(object):7576 def __init__(self, name):77 self.name = name7879 def __get__(self, obj, tp):80 result = self._resolve()81 setattr(obj, self.name, result)82 # This is a bit ugly, but it avoids running this again.83 delattr(tp, self.name)84 return result858687class MovedModule(_LazyDescr):8889 def __init__(self, name, old, new=None):90 super(MovedModule, self).__init__(name)91 if PY3:92 if new is None:93 new = name94 self.mod = new95 else:96 self.mod = old9798 def _resolve(self):99 return _import_module(self.mod)100101102class MovedAttribute(_LazyDescr):103104 def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):105 super(MovedAttribute, self).__init__(name)106 if PY3:107 if new_mod is None:108 new_mod = name109 self.mod = new_mod110 if new_attr is None:111 if old_attr is None:112 new_attr = name113 else:114 new_attr = old_attr115 self.attr = new_attr116 else:117 self.mod = old_mod118 if old_attr is None:119 old_attr = name120 self.attr = old_attr121122 def _resolve(self):123 module = _import_module(self.mod)124 return getattr(module, self.attr)125126127128class _MovedItems(types.ModuleType):129 """Lazy loading of moved objects"""130131132_moved_attributes = [133 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),134 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),135 MovedAttribute("map", "itertools", "builtins", "imap", "map"),136 MovedAttribute("reload_module", "__builtin__", "imp", "reload"),137 MovedAttribute("reduce", "__builtin__", "functools"),138 MovedAttribute("StringIO", "StringIO", "io"),139 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),140 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),141142 MovedModule("builtins", "__builtin__"),143 MovedModule("configparser", "ConfigParser"),144 MovedModule("copyreg", "copy_reg"),145 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),146 MovedModule("http_cookies", "Cookie", "http.cookies"),147 MovedModule("html_entities", "htmlentitydefs", "html.entities"),148 MovedModule("html_parser", "HTMLParser", "html.parser"),149 MovedModule("http_client", "httplib", "http.client"),150 MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),151 MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),152 MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),153 MovedModule("cPickle", "cPickle", "pickle"),154 MovedModule("queue", "Queue"),155 MovedModule("reprlib", "repr"),156 MovedModule("socketserver", "SocketServer"),157 MovedModule("tkinter", "Tkinter"),158 MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),159 MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),160 MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),161 MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),162 MovedModule("tkinter_tix", "Tix", "tkinter.tix"),163 MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),164 MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),165 MovedModule("tkinter_colorchooser", "tkColorChooser",166 "tkinter.colorchooser"),167 MovedModule("tkinter_commondialog", "tkCommonDialog",168 "tkinter.commondialog"),169 MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),170 MovedModule("tkinter_font", "tkFont", "tkinter.font"),171 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),172 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",173 "tkinter.simpledialog"),174 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),175 MovedModule("winreg", "_winreg"),176]177for attr in _moved_attributes:178 setattr(_MovedItems, attr.name, attr)179del attr180181moves = sys.modules["six.moves"] = _MovedItems("moves")182183184def add_move(move):185 """Add an item to six.moves."""186 setattr(_MovedItems, move.name, move)187188189def remove_move(name):190 """Remove item from six.moves."""191 try:192 delattr(_MovedItems, name)193 except AttributeError:194 try:195 del moves.__dict__[name]196 except KeyError:197 raise AttributeError("no such move, %r" % (name,))198199200if PY3:201 _meth_func = "__func__"202 _meth_self = "__self__"203204 _func_code = "__code__"205 _func_defaults = "__defaults__"206207 _iterkeys = "keys"208 _itervalues = "values"209 _iteritems = "items"210else:211 _meth_func = "im_func"212 _meth_self = "im_self"213214 _func_code = "func_code"215 _func_defaults = "func_defaults"216217 _iterkeys = "iterkeys"218 _itervalues = "itervalues"219 _iteritems = "iteritems"220221222if PY3:223 def get_unbound_function(unbound):224 return unbound225226227 advance_iterator = next228229 def callable(obj):230 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)231else:232 def get_unbound_function(unbound):233 return unbound.im_func234235236 def advance_iterator(it):237 return it.next()238239 callable = callable240_add_doc(get_unbound_function,241 """Get the function out of a possibly unbound function""")242243244get_method_function = operator.attrgetter(_meth_func)245get_method_self = operator.attrgetter(_meth_self)246get_function_code = operator.attrgetter(_func_code)247get_function_defaults = operator.attrgetter(_func_defaults)248249250def iterkeys(d):251 """Return an iterator over the keys of a dictionary."""252 return getattr(d, _iterkeys)()253254def itervalues(d):255 """Return an iterator over the values of a dictionary."""256 return getattr(d, _itervalues)()257258def iteritems(d):259 """Return an iterator over the (key, value) pairs of a dictionary."""260 return getattr(d, _iteritems)()261262263if PY3:264 def b(s):265 return s.encode("latin-1")266 def u(s):267 return s268 if sys.version_info[1] <= 1:269 def int2byte(i):270 return bytes((i,))271 else:272 # This is about 2x faster than the implementation above on 3.2+273 int2byte = operator.methodcaller("to_bytes", 1, "big")274 import io275 StringIO = io.StringIO276 BytesIO = io.BytesIO277else:278 def b(s):279 return s280 def u(s):281 return unicode(s, "unicode_escape")282 int2byte = chr283 import StringIO284 StringIO = BytesIO = StringIO.StringIO285_add_doc(b, """Byte literal""")286_add_doc(u, """Text literal""")287288289if PY3:290 import builtins291 exec_ = getattr(builtins, "exec")292293294 def reraise(tp, value, tb=None):295 if value.__traceback__ is not tb:296 raise value.with_traceback(tb)297 raise value298299300 print_ = getattr(builtins, "print")301 del builtins302303else:304 def exec_(code, globs=None, locs=None):305 """Execute code in a namespace."""306 if globs is None:307 frame = sys._getframe(1)308 globs = frame.f_globals309 if locs is None:310 locs = frame.f_locals311 del frame312 elif locs is None:313 locs = globs314 exec("""exec code in globs, locs""")315316317 exec_("""def reraise(tp, value, tb=None):318 raise tp, value, tb319""")320321322 def print_(*args, **kwargs):323 """The new-style print function."""324 fp = kwargs.pop("file", sys.stdout)325 if fp is None:326 return327 def write(data):328 if not isinstance(data, basestring):329 data = str(data)330 fp.write(data)331 want_unicode = False332 sep = kwargs.pop("sep", None)333 if sep is not None:334 if isinstance(sep, unicode):335 want_unicode = True336 elif not isinstance(sep, str):337 raise TypeError("sep must be None or a string")338 end = kwargs.pop("end", None)339 if end is not None:340 if isinstance(end, unicode):341 want_unicode = True342 elif not isinstance(end, str):343 raise TypeError("end must be None or a string")344 if kwargs:345 raise TypeError("invalid keyword arguments to print()")346 if not want_unicode:347 for arg in args:348 if isinstance(arg, unicode):349 want_unicode = True350 break351 if want_unicode:352 newline = unicode("\n")353 space = unicode(" ")354 else:355 newline = "\n"356 space = " "357 if sep is None:358 sep = space359 if end is None:360 end = newline361 for i, arg in enumerate(args):362 if i:363 write(sep)364 write(arg)365 write(end)366367_add_doc(reraise, """Reraise an exception.""")368369370def with_metaclass(meta, base=object):371 """Create a base class with a metaclass."""372 return meta("NewBase", (base,), {})
modified:requests/packages/urllib3/connectionpool.py+56 added-20 removed
5 unmodified lines
67import logging8import socket910from select import poll, POLLIN11from socket import error as SocketError, timeout as SocketTimeout121314try: # Python 315 from http.client import HTTPConnection, HTTPSConnection, HTTPException16 from http.client import HTTP_PORT, HTTPS_PORT17except ImportError:18 from httplib import HTTPConnection, HTTPSConnection, HTTPException19 from httplib import HTTP_PORT, HTTPS_PORT2021try: # Python 322 from queue import Queue, Empty, Full23except ImportError:24 from Queue import Queue, Empty, Full19 20from select import select21from socket import error as SocketError, timeout as SocketTimeout2523from .packages.ssl_match_hostname import match_hostname, CertificateError2425try:26try: # Compiled with SSL?27 import ssl28 BaseSSLError = ssl.SSLError29except ImportError:30 ssl = None
1 unmodified line
323334from .request import RequestMethods35from .response import HTTPResponse35from .exceptions import (36 SSLError,36from .exceptions import (SSLError,37 MaxRetryError,38 TimeoutError,39 HostChangedError,40 EmptyPoolError,41)4243from . import six43from urllib3.packages.ssl_match_hostname import match_hostname, CertificateError44from urllib3.packages import six4546xrange = six.moves.xrange474648log = logging.getLogger(__name__)4950_Default = object()5152port_by_scheme = {53 'http': HTTP_PORT,54 'https': HTTPS_PORT,55}5657## Connection objects (extension of httplib)5859class VerifiedHTTPSConnection(HTTPSConnection):
35 unmodified lines
95 """96 Base class for all connection pools, such as97 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.98 """94 pass99100 scheme = None101102 def __init__(self, host, port=None):103 self.host = host104 self.port = port105106 def __str__(self):107 return '%s(host=%r, port=%r)' % (type(self).__name__,108 self.host, self.port)109110111class HTTPConnectionPool(ConnectionPool, RequestMethods):112 """113 Thread-safe connection pool for one host.114
77 unmodified lines
192 try:193 conn = self.pool.get(block=self.block, timeout=timeout)194195 # If this is a persistent connection, check if it got disconnected182 if conn and conn.sock and select([conn.sock], [], [], 0.0)[0]:183 # Either data is buffered (bad), or the connection is dropped.196 if conn and conn.sock and is_connection_dropped(conn):197 log.info("Resetting dropped connection: %s" % self.host)198 conn.close()199200 except Empty:201 if self.block:189 raise EmptyPoolError("Pool reached maximum size and no more "202 raise EmptyPoolError(self,203 "Pool reached maximum size and no more "204 "connections are allowed.")205 pass # Oh well, we'll create a new connection then206207 return conn or self._new_conn()
44 unmodified lines
252253 def is_same_host(self, url):254 """255 Check if the given ``url`` is a member of the same host as this242 conncetion pool.256 connection pool.257 """258 # TODO: Add optional support for socket.gethostbyname checking.259 scheme, host, port = get_host(url)260261 if self.port and not port:262 # Use explicit default port for comparison when none is given.263 port = port_by_scheme.get(scheme)264265 return (url.startswith('/') or246 get_host(url) == (self.scheme, self.host, self.port))266 (scheme, host, port) == (self.scheme, self.host, self.port))267268 def urlopen(self, method, url, body=None, headers=None, retries=3,269 redirect=True, assert_same_host=True, timeout=_Default,270 pool_timeout=None, release_conn=None, **response_kw):
64 unmodified lines
335 if headers is None:336 headers = self.headers337338 if retries < 0:319 raise MaxRetryError(url)339 raise MaxRetryError(self, url)340341 if timeout is _Default:342 timeout = self.timeout343
5 unmodified lines
349 host = "%s://%s" % (self.scheme, self.host)350 if self.port:351 host = "%s:%d" % (host, self.port)352333 raise HostChangedError(host, url, retries - 1)353 raise HostChangedError(self, url, retries - 1)354355 conn = None356357 try:
24 unmodified lines
382 # ``response.read()``)383384 except Empty as e:385 # Timed out by queue366 raise TimeoutError("Request timed out. (pool_timeout=%s)" %386 raise TimeoutError(self, "Request timed out. (pool_timeout=%s)" %387 pool_timeout)388389 except SocketTimeout as e:390 # Timed out by socket371 raise TimeoutError("Request timed out. (timeout=%s)" %391 raise TimeoutError(self, "Request timed out. (timeout=%s)" %392 timeout)393394 except BaseSSLError as e:395 # SSL certificate error
181 unmodified lines
577 if scheme == 'https':578 return HTTPSConnectionPool(host, port=port, **kw)579 else:580 return HTTPConnectionPool(host, port=port, **kw)581582583def is_connection_dropped(conn):584 """585 Returns True if the connection is dropped and should be closed.586587 :param conn:588 ``HTTPConnection`` object.589 """590 # poll-based replacement to select([conn.sock], [], [], 0.0)[0]:591 p = poll()592 p.register(conn.sock, POLLIN)593 for (fno, ev) in p.poll(0.0):594 if fno == conn.sock.fileno():595 # Either data is buffered (bad), or the connection is dropped.596 return True
modified:requests/packages/urllib3/exceptions.py+27 added-18 removed
2 unmodified lines
3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php67## Exceptions7## Base Exceptions89class HTTPError(Exception):10 "Base exception used by this module."11 pass121314class SSLError(Exception):14class PoolError(HTTPError):15 "Base exception for errors caused within a pool."16 def __init__(self, pool, message):17 self.pool = pool18 HTTPError.__init__(self, "%s: %s" % (pool, message))192021class SSLError(HTTPError):22 "Raised when SSL certificate fails in an HTTPS connection."23 pass242526## Leaf Exceptions2719class MaxRetryError(HTTPError):28class MaxRetryError(PoolError):29 "Raised when the maximum number of retries is exceeded."21 def __init__(self, url):22 HTTPError.__init__(self, "Max retries exceeded for url: %s" % url)30 def __init__(self, pool, url):31 PoolError.__init__(self, pool,32 "Max retries exceeded with url: %s" % url)3334 self.url = url353626class TimeoutError(HTTPError):27 "Raised when a socket timeout occurs."28 pass293031class HostChangedError(HTTPError):37class HostChangedError(PoolError):38 "Raised when an existing pool gets a request for a foreign host."33 def __init__(self, original_host, new_url, retries=3):34 HTTPError.__init__(self,35 "Connection pool with host '%s' tried to open a foreign host: %s" %36 (original_host, new_url))39 def __init__(self, pool, url, retries=3):40 PoolError.__init__(self, pool,41 "Tried to open a foreign host with url: %s" % url)4238 self.original_host = original_host39 self.new_url = new_url43 self.url = url44 self.retries = retries454643class EmptyPoolError(HTTPError):47class TimeoutError(PoolError):48 "Raised when a socket timeout occurs."49 pass505152class EmptyPoolError(PoolError):53 "Raised when a pool runs out of connections and no more are allowed."54 pass
modified:requests/packages/urllib3/filepost.py+3 added-4 removed
8 unmodified lines
910try:11 from mimetools import choose_boundary12except ImportError:13 # I don't like using an undocumented function, but I don't yet know what it does14 from email.generator import _make_boundary as choose_boundary13 from .packages.mimetools_choose_boundary import choose_boundary1415from io import BytesIO1618from . import six19from .six import b17from .packages import six18from .packages.six import b1920writer = codecs.lookup('utf-8')[3]2122
52 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+2 added-7 removed
6 unmodified lines
7import logging89from ._collections import RecentlyUsedContainer10from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool11from .connectionpool import get_host, connection_from_url11from .connectionpool import get_host, connection_from_url, port_by_scheme12from .exceptions import HostChangedError13from .request import RequestMethods1415
4 unmodified lines
20 'http': HTTPConnectionPool,21 'https': HTTPSConnectionPool,22}2324port_by_scheme = {25 'http': 80,26 'https': 443,27}2824log = logging.getLogger(__name__)252627class PoolManager(RequestMethods):
76 unmodified lines
104 return conn.urlopen(method, url, **kw)105106 except HostChangedError as e:107 kw['retries'] = e.retries # Persist retries countdown113 return self.urlopen(method, e.new_url, **kw)108 return self.urlopen(method, e.url, **kw)109110111class ProxyManager(RequestMethods):112 """
16 unmodified lines
modified:requests/packages/urllib3/response.py+11 added-14 removed
65 unmodified lines
66 self.reason = reason67 self.strict = strict6869 self._decode_content = decode_content70 self._body = None70 self._body = body if body and isinstance(body, basestring) else None71 self._fp = None72 self._original_response = original_response7374 self._pool = pool
1 unmodified line
7677 if hasattr(body, 'read'):78 self._fp = body7980 if preload_content:80 if preload_content and not self._body:81 self._body = self.read(decode_content=decode_content)8283 def get_redirect_location(self):84 """
49 unmodified lines
134 decoder = self.CONTENT_DECODERS.get(content_encoding)135 if decode_content is None:136 decode_content = self._decode_content137138 data = self._fp and self._fp.read(amt)138 if self._fp is None:139 return140141 try:142 if amt is None:143 # cStringIO doesn't like amt=None144 data = self._fp.read()145 else:146 return self._fp.read(amt)147142 if amt:143 return data144145 if not decode_content or not decoder:146 if cache_content:147 self._body = data148149 return data150148 try:149 if decode_content and decoder:152 data = decoder(data)150 data = decoder(data)151 except IOError:152 raise HTTPError("Received response with content-encoding: %s, but "153 "failed to decode it." % content_encoding)154
2 unmodified lines
157158 return data159160 finally:163161 if self._original_response and self._original_response.isclosed():162 self.release_conn()163164 @classmethod
27 unmodified lines
deleted:requests/packages/urllib3/six.py-372 removed
1"""Utilities for writing code that runs on Python 2 and 3"""23#Copyright (c) 2010-2011 Benjamin Peterson45#Permission is hereby granted, free of charge, to any person obtaining a copy of6#this software and associated documentation files (the "Software"), to deal in7#the Software without restriction, including without limitation the rights to8#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of9#the Software, and to permit persons to whom the Software is furnished to do so,10#subject to the following conditions:1112#The above copyright notice and this permission notice shall be included in all13#copies or substantial portions of the Software.1415#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS17#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR18#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER19#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.2122import operator23import sys24import types2526__author__ = "Benjamin Peterson <benjamin@python.org>"27__version__ = "1.1.0"282930# True if we are running on Python 3.31PY3 = sys.version_info[0] == 33233if PY3:34 string_types = str,35 integer_types = int,36 class_types = type,37 text_type = str38 binary_type = bytes3940 MAXSIZE = sys.maxsize41else:42 string_types = basestring,43 integer_types = (int, long)44 class_types = (type, types.ClassType)45 text_type = unicode46 binary_type = str4748 # It's possible to have sizeof(long) != sizeof(Py_ssize_t).49 class X(object):50 def __len__(self):51 return 1 << 3152 try:53 len(X())54 except OverflowError:55 # 32-bit56 MAXSIZE = int((1 << 31) - 1)57 else:58 # 64-bit59 MAXSIZE = int((1 << 63) - 1)60 del X616263def _add_doc(func, doc):64 """Add documentation to a function."""65 func.__doc__ = doc666768def _import_module(name):69 """Import module, returning the module after the last dot."""70 __import__(name)71 return sys.modules[name]727374class _LazyDescr(object):7576 def __init__(self, name):77 self.name = name7879 def __get__(self, obj, tp):80 result = self._resolve()81 setattr(obj, self.name, result)82 # This is a bit ugly, but it avoids running this again.83 delattr(tp, self.name)84 return result858687class MovedModule(_LazyDescr):8889 def __init__(self, name, old, new=None):90 super(MovedModule, self).__init__(name)91 if PY3:92 if new is None:93 new = name94 self.mod = new95 else:96 self.mod = old9798 def _resolve(self):99 return _import_module(self.mod)100101102class MovedAttribute(_LazyDescr):103104 def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):105 super(MovedAttribute, self).__init__(name)106 if PY3:107 if new_mod is None:108 new_mod = name109 self.mod = new_mod110 if new_attr is None:111 if old_attr is None:112 new_attr = name113 else:114 new_attr = old_attr115 self.attr = new_attr116 else:117 self.mod = old_mod118 if old_attr is None:119 old_attr = name120 self.attr = old_attr121122 def _resolve(self):123 module = _import_module(self.mod)124 return getattr(module, self.attr)125126127128class _MovedItems(types.ModuleType):129 """Lazy loading of moved objects"""130131132_moved_attributes = [133 MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),134 MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),135 MovedAttribute("map", "itertools", "builtins", "imap", "map"),136 MovedAttribute("reload_module", "__builtin__", "imp", "reload"),137 MovedAttribute("reduce", "__builtin__", "functools"),138 MovedAttribute("StringIO", "StringIO", "io"),139 MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),140 MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),141142 MovedModule("builtins", "__builtin__"),143 MovedModule("configparser", "ConfigParser"),144 MovedModule("copyreg", "copy_reg"),145 MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),146 MovedModule("http_cookies", "Cookie", "http.cookies"),147 MovedModule("html_entities", "htmlentitydefs", "html.entities"),148 MovedModule("html_parser", "HTMLParser", "html.parser"),149 MovedModule("http_client", "httplib", "http.client"),150 MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),151 MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),152 MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),153 MovedModule("cPickle", "cPickle", "pickle"),154 MovedModule("queue", "Queue"),155 MovedModule("reprlib", "repr"),156 MovedModule("socketserver", "SocketServer"),157 MovedModule("tkinter", "Tkinter"),158 MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),159 MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),160 MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),161 MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),162 MovedModule("tkinter_tix", "Tix", "tkinter.tix"),163 MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),164 MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),165 MovedModule("tkinter_colorchooser", "tkColorChooser",166 "tkinter.colorchooser"),167 MovedModule("tkinter_commondialog", "tkCommonDialog",168 "tkinter.commondialog"),169 MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),170 MovedModule("tkinter_font", "tkFont", "tkinter.font"),171 MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),172 MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",173 "tkinter.simpledialog"),174 MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),175 MovedModule("winreg", "_winreg"),176]177for attr in _moved_attributes:178 setattr(_MovedItems, attr.name, attr)179del attr180181moves = sys.modules["six.moves"] = _MovedItems("moves")182183184def add_move(move):185 """Add an item to six.moves."""186 setattr(_MovedItems, move.name, move)187188189def remove_move(name):190 """Remove item from six.moves."""191 try:192 delattr(_MovedItems, name)193 except AttributeError:194 try:195 del moves.__dict__[name]196 except KeyError:197 raise AttributeError("no such move, %r" % (name,))198199200if PY3:201 _meth_func = "__func__"202 _meth_self = "__self__"203204 _func_code = "__code__"205 _func_defaults = "__defaults__"206207 _iterkeys = "keys"208 _itervalues = "values"209 _iteritems = "items"210else:211 _meth_func = "im_func"212 _meth_self = "im_self"213214 _func_code = "func_code"215 _func_defaults = "func_defaults"216217 _iterkeys = "iterkeys"218 _itervalues = "itervalues"219 _iteritems = "iteritems"220221222if PY3:223 def get_unbound_function(unbound):224 return unbound225226227 advance_iterator = next228229 def callable(obj):230 return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)231else:232 def get_unbound_function(unbound):233 return unbound.im_func234235236 def advance_iterator(it):237 return it.next()238239 callable = callable240_add_doc(get_unbound_function,241 """Get the function out of a possibly unbound function""")242243244get_method_function = operator.attrgetter(_meth_func)245get_method_self = operator.attrgetter(_meth_self)246get_function_code = operator.attrgetter(_func_code)247get_function_defaults = operator.attrgetter(_func_defaults)248249250def iterkeys(d):251 """Return an iterator over the keys of a dictionary."""252 return getattr(d, _iterkeys)()253254def itervalues(d):255 """Return an iterator over the values of a dictionary."""256 return getattr(d, _itervalues)()257258def iteritems(d):259 """Return an iterator over the (key, value) pairs of a dictionary."""260 return getattr(d, _iteritems)()261262263if PY3:264 def b(s):265 return s.encode("latin-1")266 def u(s):267 return s268 if sys.version_info[1] <= 1:269 def int2byte(i):270 return bytes((i,))271 else:272 # This is about 2x faster than the implementation above on 3.2+273 int2byte = operator.methodcaller("to_bytes", 1, "big")274 import io275 StringIO = io.StringIO276 BytesIO = io.BytesIO277else:278 def b(s):279 return s280 def u(s):281 return unicode(s, "unicode_escape")282 int2byte = chr283 import StringIO284 StringIO = BytesIO = StringIO.StringIO285_add_doc(b, """Byte literal""")286_add_doc(u, """Text literal""")287288289if PY3:290 import builtins291 exec_ = getattr(builtins, "exec")292293294 def reraise(tp, value, tb=None):295 if value.__traceback__ is not tb:296 raise value.with_traceback(tb)297 raise value298299300 print_ = getattr(builtins, "print")301 del builtins302303else:304 def exec_(code, globs=None, locs=None):305 """Execute code in a namespace."""306 if globs is None:307 frame = sys._getframe(1)308 globs = frame.f_globals309 if locs is None:310 locs = frame.f_locals311 del frame312 elif locs is None:313 locs = globs314 exec("""exec code in globs, locs""")315316317 exec_("""def reraise(tp, value, tb=None):318 raise tp, value, tb319""")320321322 def print_(*args, **kwargs):323 """The new-style print function."""324 fp = kwargs.pop("file", sys.stdout)325 if fp is None:326 return327 def write(data):328 if not isinstance(data, basestring):329 data = str(data)330 fp.write(data)331 want_unicode = False332 sep = kwargs.pop("sep", None)333 if sep is not None:334 if isinstance(sep, unicode):335 want_unicode = True336 elif not isinstance(sep, str):337 raise TypeError("sep must be None or a string")338 end = kwargs.pop("end", None)339 if end is not None:340 if isinstance(end, unicode):341 want_unicode = True342 elif not isinstance(end, str):343 raise TypeError("end must be None or a string")344 if kwargs:345 raise TypeError("invalid keyword arguments to print()")346 if not want_unicode:347 for arg in args:348 if isinstance(arg, unicode):349 want_unicode = True350 break351 if want_unicode:352 newline = unicode("\n")353 space = unicode(" ")354 else:355 newline = "\n"356 space = " "357 if sep is None:358 sep = space359 if end is None:360 end = newline361 for i, arg in enumerate(args):362 if i:363 write(sep)364 write(arg)365 write(end)366367_add_doc(reraise, """Reraise an exception.""")368369370def with_metaclass(meta, base=object):371 """Create a base class with a metaclass."""372 return meta("NewBase", (base,), {})