six.py 29 KB

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