six.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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.
  20. """Utilities for writing code that runs on Python 2 and 3"""
  21. from __future__ import absolute_import
  22. import functools
  23. import itertools
  24. import operator
  25. import sys
  26. import types
  27. __author__ = "Benjamin Peterson <benjamin@python.org>"
  28. __version__ = "1.15.0"
  29. # Useful for very coarse version differentiation.
  30. PY2 = sys.version_info[0] == 2
  31. PY3 = sys.version_info[0] == 3
  32. PY34 = sys.version_info[0:2] >= (3, 4)
  33. if PY3:
  34. string_types = str,
  35. integer_types = int,
  36. class_types = type,
  37. text_type = str
  38. binary_type = bytes
  39. MAXSIZE = sys.maxsize
  40. else:
  41. string_types = basestring,
  42. integer_types = (int, long)
  43. class_types = (type, types.ClassType)
  44. text_type = unicode
  45. binary_type = str
  46. if sys.platform.startswith("java"):
  47. # Jython always uses 32 bits.
  48. MAXSIZE = int((1 << 31) - 1)
  49. else:
  50. # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
  51. class X(object):
  52. def __len__(self):
  53. return 1 << 31
  54. try:
  55. len(X())
  56. except OverflowError:
  57. # 32-bit
  58. MAXSIZE = int((1 << 31) - 1)
  59. else:
  60. # 64-bit
  61. MAXSIZE = int((1 << 63) - 1)
  62. del X
  63. def _add_doc(func, doc):
  64. """Add documentation to a function."""
  65. func.__doc__ = doc
  66. def _import_module(name):
  67. """Import module, returning the module after the last dot."""
  68. __import__(name)
  69. return sys.modules[name]
  70. class _LazyDescr(object):
  71. def __init__(self, name):
  72. self.name = name
  73. def __get__(self, obj, tp):
  74. result = self._resolve()
  75. setattr(obj, self.name, result) # Invokes __set__.
  76. try:
  77. # This is a bit ugly, but it avoids running this again by
  78. # removing this descriptor.
  79. delattr(obj.__class__, self.name)
  80. except AttributeError:
  81. pass
  82. return result
  83. class MovedModule(_LazyDescr):
  84. def __init__(self, name, old, new=None):
  85. super(MovedModule, self).__init__(name)
  86. if PY3:
  87. if new is None:
  88. new = name
  89. self.mod = new
  90. else:
  91. self.mod = old
  92. def _resolve(self):
  93. return _import_module(self.mod)
  94. def __getattr__(self, attr):
  95. _module = self._resolve()
  96. value = getattr(_module, attr)
  97. setattr(self, attr, value)
  98. return value
  99. class _LazyModule(types.ModuleType):
  100. def __init__(self, name):
  101. super(_LazyModule, self).__init__(name)
  102. self.__doc__ = self.__class__.__doc__
  103. def __dir__(self):
  104. attrs = ["__doc__", "__name__"]
  105. attrs += [attr.name for attr in self._moved_attributes]
  106. return attrs
  107. # Subclasses should override this
  108. _moved_attributes = []
  109. class MovedAttribute(_LazyDescr):
  110. def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
  111. super(MovedAttribute, self).__init__(name)
  112. if PY3:
  113. if new_mod is None:
  114. new_mod = name
  115. self.mod = new_mod
  116. if new_attr is None:
  117. if old_attr is None:
  118. new_attr = name
  119. else:
  120. new_attr = old_attr
  121. self.attr = new_attr
  122. else:
  123. self.mod = old_mod
  124. if old_attr is None:
  125. old_attr = name
  126. self.attr = old_attr
  127. def _resolve(self):
  128. module = _import_module(self.mod)
  129. return getattr(module, self.attr)
  130. class _SixMetaPathImporter(object):
  131. """
  132. A meta path importer to import six.moves and its submodules.
  133. This class implements a PEP302 finder and loader. It should be compatible
  134. with Python 2.5 and all existing versions of Python3
  135. """
  136. def __init__(self, six_module_name):
  137. self.name = six_module_name
  138. self.known_modules = {}
  139. def _add_module(self, mod, *fullnames):
  140. for fullname in fullnames:
  141. self.known_modules[self.name + "." + fullname] = mod
  142. def _get_module(self, fullname):
  143. return self.known_modules[self.name + "." + fullname]
  144. def find_module(self, fullname, path=None):
  145. if fullname in self.known_modules:
  146. return self
  147. return None
  148. def __get_module(self, fullname):
  149. try:
  150. return self.known_modules[fullname]
  151. except KeyError:
  152. raise ImportError("This loader does not know module " + fullname)
  153. def load_module(self, fullname):
  154. try:
  155. # in case of a reload
  156. return sys.modules[fullname]
  157. except KeyError:
  158. pass
  159. mod = self.__get_module(fullname)
  160. if isinstance(mod, MovedModule):
  161. mod = mod._resolve()
  162. else:
  163. mod.__loader__ = self
  164. sys.modules[fullname] = mod
  165. return mod
  166. def is_package(self, fullname):
  167. """
  168. Return true, if the named module is a package.
  169. We need this method to get correct spec objects with
  170. Python 3.4 (see PEP451)
  171. """
  172. return hasattr(self.__get_module(fullname), "__path__")
  173. def get_code(self, fullname):
  174. """Return None
  175. Required, if is_package is implemented"""
  176. self.__get_module(fullname) # eventually raises ImportError
  177. return None
  178. get_source = get_code # same as get_code
  179. _importer = _SixMetaPathImporter(__name__)
  180. class _MovedItems(_LazyModule):
  181. """Lazy loading of moved objects"""
  182. __path__ = [] # mark as package
  183. _moved_attributes = [
  184. MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
  185. MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
  186. MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
  187. MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
  188. MovedAttribute("intern", "__builtin__", "sys"),
  189. MovedAttribute("map", "itertools", "builtins", "imap", "map"),
  190. MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),
  191. MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),
  192. MovedAttribute("getoutput", "commands", "subprocess"),
  193. MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
  194. MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),
  195. MovedAttribute("reduce", "__builtin__", "functools"),
  196. MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
  197. MovedAttribute("StringIO", "StringIO", "io"),
  198. MovedAttribute("UserDict", "UserDict", "collections"),
  199. MovedAttribute("UserList", "UserList", "collections"),
  200. MovedAttribute("UserString", "UserString", "collections"),
  201. MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
  202. MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
  203. MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
  204. MovedModule("builtins", "__builtin__"),
  205. MovedModule("configparser", "ConfigParser"),
  206. MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"),
  207. MovedModule("copyreg", "copy_reg"),
  208. MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
  209. MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),
  210. MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"),
  211. MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
  212. MovedModule("http_cookies", "Cookie", "http.cookies"),
  213. MovedModule("html_entities", "htmlentitydefs", "html.entities"),
  214. MovedModule("html_parser", "HTMLParser", "html.parser"),
  215. MovedModule("http_client", "httplib", "http.client"),
  216. MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
  217. MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),
  218. MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
  219. MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
  220. MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
  221. MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
  222. MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
  223. MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
  224. MovedModule("cPickle", "cPickle", "pickle"),
  225. MovedModule("queue", "Queue"),
  226. MovedModule("reprlib", "repr"),
  227. MovedModule("socketserver", "SocketServer"),
  228. MovedModule("_thread", "thread", "_thread"),
  229. MovedModule("tkinter", "Tkinter"),
  230. MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
  231. MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
  232. MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
  233. MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
  234. MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
  235. MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
  236. MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
  237. MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
  238. MovedModule("tkinter_colorchooser", "tkColorChooser",
  239. "tkinter.colorchooser"),
  240. MovedModule("tkinter_commondialog", "tkCommonDialog",
  241. "tkinter.commondialog"),
  242. MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
  243. MovedModule("tkinter_font", "tkFont", "tkinter.font"),
  244. MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
  245. MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
  246. "tkinter.simpledialog"),
  247. MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
  248. MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
  249. MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
  250. MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
  251. MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
  252. MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
  253. ]
  254. # Add windows specific modules.
  255. if sys.platform == "win32":
  256. _moved_attributes += [
  257. MovedModule("winreg", "_winreg"),
  258. ]
  259. for attr in _moved_attributes:
  260. setattr(_MovedItems, attr.name, attr)
  261. if isinstance(attr, MovedModule):
  262. _importer._add_module(attr, "moves." + attr.name)
  263. del attr
  264. _MovedItems._moved_attributes = _moved_attributes
  265. moves = _MovedItems(__name__ + ".moves")
  266. _importer._add_module(moves, "moves")
  267. class Module_six_moves_urllib_parse(_LazyModule):
  268. """Lazy loading of moved objects in six.moves.urllib_parse"""
  269. _urllib_parse_moved_attributes = [
  270. MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
  271. MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
  272. MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
  273. MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
  274. MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
  275. MovedAttribute("urljoin", "urlparse", "urllib.parse"),
  276. MovedAttribute("urlparse", "urlparse", "urllib.parse"),
  277. MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
  278. MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
  279. MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
  280. MovedAttribute("quote", "urllib", "urllib.parse"),
  281. MovedAttribute("quote_plus", "urllib", "urllib.parse"),
  282. MovedAttribute("unquote", "urllib", "urllib.parse"),
  283. MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
  284. MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"),
  285. MovedAttribute("urlencode", "urllib", "urllib.parse"),
  286. MovedAttribute("splitquery", "urllib", "urllib.parse"),
  287. MovedAttribute("splittag", "urllib", "urllib.parse"),
  288. MovedAttribute("splituser", "urllib", "urllib.parse"),
  289. MovedAttribute("splitvalue", "urllib", "urllib.parse"),
  290. MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
  291. MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
  292. MovedAttribute("uses_params", "urlparse", "urllib.parse"),
  293. MovedAttribute("uses_query", "urlparse", "urllib.parse"),
  294. MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
  295. ]
  296. for attr in _urllib_parse_moved_attributes:
  297. setattr(Module_six_moves_urllib_parse, attr.name, attr)
  298. del attr
  299. Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
  300. _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
  301. "moves.urllib_parse", "moves.urllib.parse")
  302. class Module_six_moves_urllib_error(_LazyModule):
  303. """Lazy loading of moved objects in six.moves.urllib_error"""
  304. _urllib_error_moved_attributes = [
  305. MovedAttribute("URLError", "urllib2", "urllib.error"),
  306. MovedAttribute("HTTPError", "urllib2", "urllib.error"),
  307. MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
  308. ]
  309. for attr in _urllib_error_moved_attributes:
  310. setattr(Module_six_moves_urllib_error, attr.name, attr)
  311. del attr
  312. Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
  313. _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
  314. "moves.urllib_error", "moves.urllib.error")
  315. class Module_six_moves_urllib_request(_LazyModule):
  316. """Lazy loading of moved objects in six.moves.urllib_request"""
  317. _urllib_request_moved_attributes = [
  318. MovedAttribute("urlopen", "urllib2", "urllib.request"),
  319. MovedAttribute("install_opener", "urllib2", "urllib.request"),
  320. MovedAttribute("build_opener", "urllib2", "urllib.request"),
  321. MovedAttribute("pathname2url", "urllib", "urllib.request"),
  322. MovedAttribute("url2pathname", "urllib", "urllib.request"),
  323. MovedAttribute("getproxies", "urllib", "urllib.request"),
  324. MovedAttribute("Request", "urllib2", "urllib.request"),
  325. MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
  326. MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
  327. MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
  328. MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
  329. MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
  330. MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
  331. MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
  332. MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
  333. MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
  334. MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
  335. MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
  336. MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
  337. MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
  338. MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
  339. MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
  340. MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
  341. MovedAttribute("FileHandler", "urllib2", "urllib.request"),
  342. MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
  343. MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
  344. MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
  345. MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
  346. MovedAttribute("urlretrieve", "urllib", "urllib.request"),
  347. MovedAttribute("urlcleanup", "urllib", "urllib.request"),
  348. MovedAttribute("URLopener", "urllib", "urllib.request"),
  349. MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
  350. MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
  351. MovedAttribute("parse_http_list", "urllib2", "urllib.request"),
  352. MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),
  353. ]
  354. for attr in _urllib_request_moved_attributes:
  355. setattr(Module_six_moves_urllib_request, attr.name, attr)
  356. del attr
  357. Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
  358. _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
  359. "moves.urllib_request", "moves.urllib.request")
  360. class Module_six_moves_urllib_response(_LazyModule):
  361. """Lazy loading of moved objects in six.moves.urllib_response"""
  362. _urllib_response_moved_attributes = [
  363. MovedAttribute("addbase", "urllib", "urllib.response"),
  364. MovedAttribute("addclosehook", "urllib", "urllib.response"),
  365. MovedAttribute("addinfo", "urllib", "urllib.response"),
  366. MovedAttribute("addinfourl", "urllib", "urllib.response"),
  367. ]
  368. for attr in _urllib_response_moved_attributes:
  369. setattr(Module_six_moves_urllib_response, attr.name, attr)
  370. del attr
  371. Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
  372. _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
  373. "moves.urllib_response", "moves.urllib.response")
  374. class Module_six_moves_urllib_robotparser(_LazyModule):
  375. """Lazy loading of moved objects in six.moves.urllib_robotparser"""
  376. _urllib_robotparser_moved_attributes = [
  377. MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
  378. ]
  379. for attr in _urllib_robotparser_moved_attributes:
  380. setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
  381. del attr
  382. Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
  383. _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
  384. "moves.urllib_robotparser", "moves.urllib.robotparser")
  385. class Module_six_moves_urllib(types.ModuleType):
  386. """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
  387. __path__ = [] # mark as package
  388. parse = _importer._get_module("moves.urllib_parse")
  389. error = _importer._get_module("moves.urllib_error")
  390. request = _importer._get_module("moves.urllib_request")
  391. response = _importer._get_module("moves.urllib_response")
  392. robotparser = _importer._get_module("moves.urllib_robotparser")
  393. def __dir__(self):
  394. return ['parse', 'error', 'request', 'response', 'robotparser']
  395. _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
  396. "moves.urllib")
  397. def add_move(move):
  398. """Add an item to six.moves."""
  399. setattr(_MovedItems, move.name, move)
  400. def remove_move(name):
  401. """Remove item from six.moves."""
  402. try:
  403. delattr(_MovedItems, name)
  404. except AttributeError:
  405. try:
  406. del moves.__dict__[name]
  407. except KeyError:
  408. raise AttributeError("no such move, %r" % (name,))
  409. if PY3:
  410. _meth_func = "__func__"
  411. _meth_self = "__self__"
  412. _func_closure = "__closure__"
  413. _func_code = "__code__"
  414. _func_defaults = "__defaults__"
  415. _func_globals = "__globals__"
  416. else:
  417. _meth_func = "im_func"
  418. _meth_self = "im_self"
  419. _func_closure = "func_closure"
  420. _func_code = "func_code"
  421. _func_defaults = "func_defaults"
  422. _func_globals = "func_globals"
  423. try:
  424. advance_iterator = next
  425. except NameError:
  426. def advance_iterator(it):
  427. return it.next()
  428. next = advance_iterator
  429. try:
  430. callable = callable
  431. except NameError:
  432. def callable(obj):
  433. return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
  434. if PY3:
  435. def get_unbound_function(unbound):
  436. return unbound
  437. create_bound_method = types.MethodType
  438. def create_unbound_method(func, cls):
  439. return func
  440. Iterator = object
  441. else:
  442. def get_unbound_function(unbound):
  443. return unbound.im_func
  444. def create_bound_method(func, obj):
  445. return types.MethodType(func, obj, obj.__class__)
  446. def create_unbound_method(func, cls):
  447. return types.MethodType(func, None, cls)
  448. class Iterator(object):
  449. def next(self):
  450. return type(self).__next__(self)
  451. callable = callable
  452. _add_doc(get_unbound_function,
  453. """Get the function out of a possibly unbound function""")
  454. get_method_function = operator.attrgetter(_meth_func)
  455. get_method_self = operator.attrgetter(_meth_self)
  456. get_function_closure = operator.attrgetter(_func_closure)
  457. get_function_code = operator.attrgetter(_func_code)
  458. get_function_defaults = operator.attrgetter(_func_defaults)
  459. get_function_globals = operator.attrgetter(_func_globals)
  460. if PY3:
  461. def iterkeys(d, **kw):
  462. return iter(d.keys(**kw))
  463. def itervalues(d, **kw):
  464. return iter(d.values(**kw))
  465. def iteritems(d, **kw):
  466. return iter(d.items(**kw))
  467. def iterlists(d, **kw):
  468. return iter(d.lists(**kw))
  469. viewkeys = operator.methodcaller("keys")
  470. viewvalues = operator.methodcaller("values")
  471. viewitems = operator.methodcaller("items")
  472. else:
  473. def iterkeys(d, **kw):
  474. return d.iterkeys(**kw)
  475. def itervalues(d, **kw):
  476. return d.itervalues(**kw)
  477. def iteritems(d, **kw):
  478. return d.iteritems(**kw)
  479. def iterlists(d, **kw):
  480. return d.iterlists(**kw)
  481. viewkeys = operator.methodcaller("viewkeys")
  482. viewvalues = operator.methodcaller("viewvalues")
  483. viewitems = operator.methodcaller("viewitems")
  484. _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
  485. _add_doc(itervalues, "Return an iterator over the values of a dictionary.")
  486. _add_doc(iteritems,
  487. "Return an iterator over the (key, value) pairs of a dictionary.")
  488. _add_doc(iterlists,
  489. "Return an iterator over the (key, [values]) pairs of a dictionary.")
  490. if PY3:
  491. def b(s):
  492. return s.encode("latin-1")
  493. def u(s):
  494. return s
  495. unichr = chr
  496. import struct
  497. int2byte = struct.Struct(">B").pack
  498. del struct
  499. byte2int = operator.itemgetter(0)
  500. indexbytes = operator.getitem
  501. iterbytes = iter
  502. import io
  503. StringIO = io.StringIO
  504. BytesIO = io.BytesIO
  505. del io
  506. _assertCountEqual = "assertCountEqual"
  507. if sys.version_info[1] <= 1:
  508. _assertRaisesRegex = "assertRaisesRegexp"
  509. _assertRegex = "assertRegexpMatches"
  510. _assertNotRegex = "assertNotRegexpMatches"
  511. else:
  512. _assertRaisesRegex = "assertRaisesRegex"
  513. _assertRegex = "assertRegex"
  514. _assertNotRegex = "assertNotRegex"
  515. else:
  516. def b(s):
  517. return s
  518. # Workaround for standalone backslash
  519. def u(s):
  520. return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
  521. unichr = unichr
  522. int2byte = chr
  523. def byte2int(bs):
  524. return ord(bs[0])
  525. def indexbytes(buf, i):
  526. return ord(buf[i])
  527. iterbytes = functools.partial(itertools.imap, ord)
  528. import StringIO
  529. StringIO = BytesIO = StringIO.StringIO
  530. _assertCountEqual = "assertItemsEqual"
  531. _assertRaisesRegex = "assertRaisesRegexp"
  532. _assertRegex = "assertRegexpMatches"
  533. _assertNotRegex = "assertNotRegexpMatches"
  534. _add_doc(b, """Byte literal""")
  535. _add_doc(u, """Text literal""")
  536. def assertCountEqual(self, *args, **kwargs):
  537. return getattr(self, _assertCountEqual)(*args, **kwargs)
  538. def assertRaisesRegex(self, *args, **kwargs):
  539. return getattr(self, _assertRaisesRegex)(*args, **kwargs)
  540. def assertRegex(self, *args, **kwargs):
  541. return getattr(self, _assertRegex)(*args, **kwargs)
  542. def assertNotRegex(self, *args, **kwargs):
  543. return getattr(self, _assertNotRegex)(*args, **kwargs)
  544. if PY3:
  545. exec_ = getattr(moves.builtins, "exec")
  546. def reraise(tp, value, tb=None):
  547. try:
  548. if value is None:
  549. value = tp()
  550. if value.__traceback__ is not tb:
  551. raise value.with_traceback(tb)
  552. raise value
  553. finally:
  554. value = None
  555. tb = None
  556. else:
  557. def exec_(_code_, _globs_=None, _locs_=None):
  558. """Execute code in a namespace."""
  559. if _globs_ is None:
  560. frame = sys._getframe(1)
  561. _globs_ = frame.f_globals
  562. if _locs_ is None:
  563. _locs_ = frame.f_locals
  564. del frame
  565. elif _locs_ is None:
  566. _locs_ = _globs_
  567. exec("""exec _code_ in _globs_, _locs_""")
  568. exec_("""def reraise(tp, value, tb=None):
  569. try:
  570. raise tp, value, tb
  571. finally:
  572. tb = None
  573. """)
  574. if sys.version_info[:2] > (3,):
  575. exec_("""def raise_from(value, from_value):
  576. try:
  577. raise value from from_value
  578. finally:
  579. value = None
  580. """)
  581. else:
  582. def raise_from(value, from_value):
  583. raise value
  584. print_ = getattr(moves.builtins, "print", None)
  585. if print_ is None:
  586. def print_(*args, **kwargs):
  587. """The new-style print function for Python 2.4 and 2.5."""
  588. fp = kwargs.pop("file", sys.stdout)
  589. if fp is None:
  590. return
  591. def write(data):
  592. if not isinstance(data, basestring):
  593. data = str(data)
  594. # If the file has an encoding, encode unicode with it.
  595. if (isinstance(fp, file) and
  596. isinstance(data, unicode) and
  597. fp.encoding is not None):
  598. errors = getattr(fp, "errors", None)
  599. if errors is None:
  600. errors = "strict"
  601. data = data.encode(fp.encoding, errors)
  602. fp.write(data)
  603. want_unicode = False
  604. sep = kwargs.pop("sep", None)
  605. if sep is not None:
  606. if isinstance(sep, unicode):
  607. want_unicode = True
  608. elif not isinstance(sep, str):
  609. raise TypeError("sep must be None or a string")
  610. end = kwargs.pop("end", None)
  611. if end is not None:
  612. if isinstance(end, unicode):
  613. want_unicode = True
  614. elif not isinstance(end, str):
  615. raise TypeError("end must be None or a string")
  616. if kwargs:
  617. raise TypeError("invalid keyword arguments to print()")
  618. if not want_unicode:
  619. for arg in args:
  620. if isinstance(arg, unicode):
  621. want_unicode = True
  622. break
  623. if want_unicode:
  624. newline = unicode("\n")
  625. space = unicode(" ")
  626. else:
  627. newline = "\n"
  628. space = " "
  629. if sep is None:
  630. sep = space
  631. if end is None:
  632. end = newline
  633. for i, arg in enumerate(args):
  634. if i:
  635. write(sep)
  636. write(arg)
  637. write(end)
  638. if sys.version_info[:2] < (3, 3):
  639. _print = print_
  640. def print_(*args, **kwargs):
  641. fp = kwargs.get("file", sys.stdout)
  642. flush = kwargs.pop("flush", False)
  643. _print(*args, **kwargs)
  644. if flush and fp is not None:
  645. fp.flush()
  646. _add_doc(reraise, """Reraise an exception.""")
  647. if sys.version_info[0:2] < (3, 4):
  648. # This does exactly the same what the :func:`py3:functools.update_wrapper`
  649. # function does on Python versions after 3.2. It sets the ``__wrapped__``
  650. # attribute on ``wrapper`` object and it doesn't raise an error if any of
  651. # the attributes mentioned in ``assigned`` and ``updated`` are missing on
  652. # ``wrapped`` object.
  653. def _update_wrapper(wrapper, wrapped,
  654. assigned=functools.WRAPPER_ASSIGNMENTS,
  655. updated=functools.WRAPPER_UPDATES):
  656. for attr in assigned:
  657. try:
  658. value = getattr(wrapped, attr)
  659. except AttributeError:
  660. continue
  661. else:
  662. setattr(wrapper, attr, value)
  663. for attr in updated:
  664. getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
  665. wrapper.__wrapped__ = wrapped
  666. return wrapper
  667. _update_wrapper.__doc__ = functools.update_wrapper.__doc__
  668. def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
  669. updated=functools.WRAPPER_UPDATES):
  670. return functools.partial(_update_wrapper, wrapped=wrapped,
  671. assigned=assigned, updated=updated)
  672. wraps.__doc__ = functools.wraps.__doc__
  673. else:
  674. wraps = functools.wraps
  675. def with_metaclass(meta, *bases):
  676. """Create a base class with a metaclass."""
  677. # This requires a bit of explanation: the basic idea is to make a dummy
  678. # metaclass for one level of class instantiation that replaces itself with
  679. # the actual metaclass.
  680. class metaclass(type):
  681. def __new__(cls, name, this_bases, d):
  682. if sys.version_info[:2] >= (3, 7):
  683. # This version introduced PEP 560 that requires a bit
  684. # of extra care (we mimic what is done by __build_class__).
  685. resolved_bases = types.resolve_bases(bases)
  686. if resolved_bases is not bases:
  687. d['__orig_bases__'] = bases
  688. else:
  689. resolved_bases = bases
  690. return meta(name, resolved_bases, d)
  691. @classmethod
  692. def __prepare__(cls, name, this_bases):
  693. return meta.__prepare__(name, bases)
  694. return type.__new__(metaclass, 'temporary_class', (), {})
  695. def add_metaclass(metaclass):
  696. """Class decorator for creating a class with a metaclass."""
  697. def wrapper(cls):
  698. orig_vars = cls.__dict__.copy()
  699. slots = orig_vars.get('__slots__')
  700. if slots is not None:
  701. if isinstance(slots, str):
  702. slots = [slots]
  703. for slots_var in slots:
  704. orig_vars.pop(slots_var)
  705. orig_vars.pop('__dict__', None)
  706. orig_vars.pop('__weakref__', None)
  707. if hasattr(cls, '__qualname__'):
  708. orig_vars['__qualname__'] = cls.__qualname__
  709. return metaclass(cls.__name__, cls.__bases__, orig_vars)
  710. return wrapper
  711. def ensure_binary(s, encoding='utf-8', errors='strict'):
  712. """Coerce **s** to six.binary_type.
  713. For Python 2:
  714. - `unicode` -> encoded to `str`
  715. - `str` -> `str`
  716. For Python 3:
  717. - `str` -> encoded to `bytes`
  718. - `bytes` -> `bytes`
  719. """
  720. if isinstance(s, binary_type):
  721. return s
  722. if isinstance(s, text_type):
  723. return s.encode(encoding, errors)
  724. raise TypeError("not expecting type '%s'" % type(s))
  725. def ensure_str(s, encoding='utf-8', errors='strict'):
  726. """Coerce *s* to `str`.
  727. For Python 2:
  728. - `unicode` -> encoded to `str`
  729. - `str` -> `str`
  730. For Python 3:
  731. - `str` -> `str`
  732. - `bytes` -> decoded to `str`
  733. """
  734. # Optimization: Fast return for the common case.
  735. if type(s) is str:
  736. return s
  737. if PY2 and isinstance(s, text_type):
  738. return s.encode(encoding, errors)
  739. elif PY3 and isinstance(s, binary_type):
  740. return s.decode(encoding, errors)
  741. elif not isinstance(s, (text_type, binary_type)):
  742. raise TypeError("not expecting type '%s'" % type(s))
  743. return s
  744. def ensure_text(s, encoding='utf-8', errors='strict'):
  745. """Coerce *s* to six.text_type.
  746. For Python 2:
  747. - `unicode` -> `unicode`
  748. - `str` -> `unicode`
  749. For Python 3:
  750. - `str` -> `str`
  751. - `bytes` -> decoded to `str`
  752. """
  753. if isinstance(s, binary_type):
  754. return s.decode(encoding, errors)
  755. elif isinstance(s, text_type):
  756. return s
  757. else:
  758. raise TypeError("not expecting type '%s'" % type(s))
  759. def python_2_unicode_compatible(klass):
  760. """
  761. A class decorator that defines __unicode__ and __str__ methods under Python 2.
  762. Under Python 3 it does nothing.
  763. To support Python 2 and 3 with a single code base, define a __str__ method
  764. returning text and apply this decorator to the class.
  765. """
  766. if PY2:
  767. if '__str__' not in klass.__dict__:
  768. raise ValueError("@python_2_unicode_compatible cannot be applied "
  769. "to %s because it doesn't define __str__()." %
  770. klass.__name__)
  771. klass.__unicode__ = klass.__str__
  772. klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
  773. return klass
  774. # Complete the moves implementation.
  775. # This code is at the end of this module to speed up module loading.
  776. # Turn this module into a package.
  777. __path__ = [] # required for PEP 302 and PEP 451
  778. __package__ = __name__ # see PEP 366 @ReservedAssignment
  779. if globals().get("__spec__") is not None:
  780. __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
  781. # Remove other six meta path importers, since they cause problems. This can
  782. # happen if six is removed from sys.modules and then reloaded. (Setuptools does
  783. # this for some reason.)
  784. if sys.meta_path:
  785. for i, importer in enumerate(sys.meta_path):
  786. # Here's some real nastiness: Another "instance" of the six module might
  787. # be floating around. Therefore, we can't use isinstance() to check for
  788. # the six meta path importer, since the other six instance will have
  789. # inserted an importer with different class.
  790. if (type(importer).__name__ == "_SixMetaPathImporter" and
  791. importer.name == __name__):
  792. del sys.meta_path[i]
  793. break
  794. del i, importer
  795. # Finally, add the importer to the meta path import hook.
  796. sys.meta_path.append(_importer)