six.py 34 KB

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