six.py 27 KB

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