six.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. import operator
  22. import sys
  23. import types
  24. __author__ = "Benjamin Peterson <benjamin@python.org>"
  25. __version__ = "1.6.1"
  26. # Useful for very coarse version differentiation.
  27. PY2 = sys.version_info[0] == 2
  28. PY3 = sys.version_info[0] == 3
  29. if PY3:
  30. string_types = str,
  31. integer_types = int,
  32. class_types = type,
  33. text_type = str
  34. binary_type = bytes
  35. MAXSIZE = sys.maxsize
  36. else:
  37. string_types = basestring,
  38. integer_types = (int, long)
  39. class_types = (type, types.ClassType)
  40. text_type = unicode
  41. binary_type = str
  42. if sys.platform.startswith("java"):
  43. # Jython always uses 32 bits.
  44. MAXSIZE = int((1 << 31) - 1)
  45. else:
  46. # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
  47. class X(object):
  48. def __len__(self):
  49. return 1 << 31
  50. try:
  51. len(X())
  52. except OverflowError:
  53. # 32-bit
  54. MAXSIZE = int((1 << 31) - 1)
  55. else:
  56. # 64-bit
  57. MAXSIZE = int((1 << 63) - 1)
  58. del X
  59. def _add_doc(func, doc):
  60. """Add documentation to a function."""
  61. func.__doc__ = doc
  62. def _import_module(name):
  63. """Import module, returning the module after the last dot."""
  64. __import__(name)
  65. return sys.modules[name]
  66. class _LazyDescr(object):
  67. def __init__(self, name):
  68. self.name = name
  69. def __get__(self, obj, tp):
  70. try:
  71. result = self._resolve()
  72. except ImportError:
  73. # See the nice big comment in MovedModule.__getattr__.
  74. raise AttributeError("%s could not be imported " % self.name)
  75. setattr(obj, self.name, result) # Invokes __set__.
  76. # This is a bit ugly, but it avoids running this again.
  77. delattr(obj.__class__, self.name)
  78. return result
  79. class MovedModule(_LazyDescr):
  80. def __init__(self, name, old, new=None):
  81. super(MovedModule, self).__init__(name)
  82. if PY3:
  83. if new is None:
  84. new = name
  85. self.mod = new
  86. else:
  87. self.mod = old
  88. def _resolve(self):
  89. return _import_module(self.mod)
  90. def __getattr__(self, attr):
  91. # It turns out many Python frameworks like to traverse sys.modules and
  92. # try to load various attributes. This causes problems if this is a
  93. # platform-specific module on the wrong platform, like _winreg on
  94. # Unixes. Therefore, we silently pretend unimportable modules do not
  95. # have any attributes. See issues #51, #53, #56, and #63 for the full
  96. # tales of woe.
  97. #
  98. # First, if possible, avoid loading the module just to look at __file__,
  99. # __name__, or __path__.
  100. if (attr in ("__file__", "__name__", "__path__") and
  101. self.mod not in sys.modules):
  102. raise AttributeError(attr)
  103. try:
  104. _module = self._resolve()
  105. except ImportError:
  106. raise AttributeError(attr)
  107. value = getattr(_module, attr)
  108. setattr(self, attr, value)
  109. return value
  110. class _LazyModule(types.ModuleType):
  111. def __init__(self, name):
  112. super(_LazyModule, self).__init__(name)
  113. self.__doc__ = self.__class__.__doc__
  114. def __dir__(self):
  115. attrs = ["__doc__", "__name__"]
  116. attrs += [attr.name for attr in self._moved_attributes]
  117. return attrs
  118. # Subclasses should override this
  119. _moved_attributes = []
  120. class MovedAttribute(_LazyDescr):
  121. def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
  122. super(MovedAttribute, self).__init__(name)
  123. if PY3:
  124. if new_mod is None:
  125. new_mod = name
  126. self.mod = new_mod
  127. if new_attr is None:
  128. if old_attr is None:
  129. new_attr = name
  130. else:
  131. new_attr = old_attr
  132. self.attr = new_attr
  133. else:
  134. self.mod = old_mod
  135. if old_attr is None:
  136. old_attr = name
  137. self.attr = old_attr
  138. def _resolve(self):
  139. module = _import_module(self.mod)
  140. return getattr(module, self.attr)
  141. class _MovedItems(_LazyModule):
  142. """Lazy loading of moved objects"""
  143. _moved_attributes = [
  144. MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
  145. MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
  146. MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
  147. MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
  148. MovedAttribute("map", "itertools", "builtins", "imap", "map"),
  149. MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
  150. MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
  151. MovedAttribute("reduce", "__builtin__", "functools"),
  152. MovedAttribute("StringIO", "StringIO", "io"),
  153. MovedAttribute("UserString", "UserString", "collections"),
  154. MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
  155. MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
  156. MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
  157. MovedModule("builtins", "__builtin__"),
  158. MovedModule("configparser", "ConfigParser"),
  159. MovedModule("copyreg", "copy_reg"),
  160. MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
  161. MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
  162. MovedModule("http_cookies", "Cookie", "http.cookies"),
  163. MovedModule("html_entities", "htmlentitydefs", "html.entities"),
  164. MovedModule("html_parser", "HTMLParser", "html.parser"),
  165. MovedModule("http_client", "httplib", "http.client"),
  166. MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
  167. MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
  168. MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
  169. MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
  170. MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
  171. MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
  172. MovedModule("cPickle", "cPickle", "pickle"),
  173. MovedModule("queue", "Queue"),
  174. MovedModule("reprlib", "repr"),
  175. MovedModule("socketserver", "SocketServer"),
  176. MovedModule("_thread", "thread", "_thread"),
  177. MovedModule("tkinter", "Tkinter"),
  178. MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
  179. MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
  180. MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
  181. MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
  182. MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
  183. MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
  184. MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
  185. MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
  186. MovedModule("tkinter_colorchooser", "tkColorChooser",
  187. "tkinter.colorchooser"),
  188. MovedModule("tkinter_commondialog", "tkCommonDialog",
  189. "tkinter.commondialog"),
  190. MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
  191. MovedModule("tkinter_font", "tkFont", "tkinter.font"),
  192. MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
  193. MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
  194. "tkinter.simpledialog"),
  195. MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
  196. MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
  197. MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
  198. MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
  199. MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
  200. MovedModule("xmlrpc_server", "xmlrpclib", "xmlrpc.server"),
  201. MovedModule("winreg", "_winreg"),
  202. ]
  203. for attr in _moved_attributes:
  204. setattr(_MovedItems, attr.name, attr)
  205. if isinstance(attr, MovedModule):
  206. sys.modules[__name__ + ".moves." + attr.name] = attr
  207. del attr
  208. _MovedItems._moved_attributes = _moved_attributes
  209. moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves")
  210. class Module_six_moves_urllib_parse(_LazyModule):
  211. """Lazy loading of moved objects in six.moves.urllib_parse"""
  212. _urllib_parse_moved_attributes = [
  213. MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
  214. MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
  215. MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
  216. MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
  217. MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
  218. MovedAttribute("urljoin", "urlparse", "urllib.parse"),
  219. MovedAttribute("urlparse", "urlparse", "urllib.parse"),
  220. MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
  221. MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
  222. MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
  223. MovedAttribute("quote", "urllib", "urllib.parse"),
  224. MovedAttribute("quote_plus", "urllib", "urllib.parse"),
  225. MovedAttribute("unquote", "urllib", "urllib.parse"),
  226. MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
  227. MovedAttribute("urlencode", "urllib", "urllib.parse"),
  228. MovedAttribute("splitquery", "urllib", "urllib.parse"),
  229. ]
  230. for attr in _urllib_parse_moved_attributes:
  231. setattr(Module_six_moves_urllib_parse, attr.name, attr)
  232. del attr
  233. Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
  234. sys.modules[__name__ + ".moves.urllib_parse"] = sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse")
  235. class Module_six_moves_urllib_error(_LazyModule):
  236. """Lazy loading of moved objects in six.moves.urllib_error"""
  237. _urllib_error_moved_attributes = [
  238. MovedAttribute("URLError", "urllib2", "urllib.error"),
  239. MovedAttribute("HTTPError", "urllib2", "urllib.error"),
  240. MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
  241. ]
  242. for attr in _urllib_error_moved_attributes:
  243. setattr(Module_six_moves_urllib_error, attr.name, attr)
  244. del attr
  245. Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
  246. sys.modules[__name__ + ".moves.urllib_error"] = sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error")
  247. class Module_six_moves_urllib_request(_LazyModule):
  248. """Lazy loading of moved objects in six.moves.urllib_request"""
  249. _urllib_request_moved_attributes = [
  250. MovedAttribute("urlopen", "urllib2", "urllib.request"),
  251. MovedAttribute("install_opener", "urllib2", "urllib.request"),
  252. MovedAttribute("build_opener", "urllib2", "urllib.request"),
  253. MovedAttribute("pathname2url", "urllib", "urllib.request"),
  254. MovedAttribute("url2pathname", "urllib", "urllib.request"),
  255. MovedAttribute("getproxies", "urllib", "urllib.request"),
  256. MovedAttribute("Request", "urllib2", "urllib.request"),
  257. MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
  258. MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
  259. MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
  260. MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
  261. MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
  262. MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
  263. MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
  264. MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
  265. MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
  266. MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
  267. MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
  268. MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
  269. MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
  270. MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
  271. MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
  272. MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
  273. MovedAttribute("FileHandler", "urllib2", "urllib.request"),
  274. MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
  275. MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
  276. MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
  277. MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
  278. MovedAttribute("urlretrieve", "urllib", "urllib.request"),
  279. MovedAttribute("urlcleanup", "urllib", "urllib.request"),
  280. MovedAttribute("URLopener", "urllib", "urllib.request"),
  281. MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
  282. MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
  283. ]
  284. for attr in _urllib_request_moved_attributes:
  285. setattr(Module_six_moves_urllib_request, attr.name, attr)
  286. del attr
  287. Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
  288. sys.modules[__name__ + ".moves.urllib_request"] = sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request")
  289. class Module_six_moves_urllib_response(_LazyModule):
  290. """Lazy loading of moved objects in six.moves.urllib_response"""
  291. _urllib_response_moved_attributes = [
  292. MovedAttribute("addbase", "urllib", "urllib.response"),
  293. MovedAttribute("addclosehook", "urllib", "urllib.response"),
  294. MovedAttribute("addinfo", "urllib", "urllib.response"),
  295. MovedAttribute("addinfourl", "urllib", "urllib.response"),
  296. ]
  297. for attr in _urllib_response_moved_attributes:
  298. setattr(Module_six_moves_urllib_response, attr.name, attr)
  299. del attr
  300. Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
  301. sys.modules[__name__ + ".moves.urllib_response"] = sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response")
  302. class Module_six_moves_urllib_robotparser(_LazyModule):
  303. """Lazy loading of moved objects in six.moves.urllib_robotparser"""
  304. _urllib_robotparser_moved_attributes = [
  305. MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
  306. ]
  307. for attr in _urllib_robotparser_moved_attributes:
  308. setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
  309. del attr
  310. Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
  311. sys.modules[__name__ + ".moves.urllib_robotparser"] = sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser")
  312. class Module_six_moves_urllib(types.ModuleType):
  313. """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
  314. parse = sys.modules[__name__ + ".moves.urllib_parse"]
  315. error = sys.modules[__name__ + ".moves.urllib_error"]
  316. request = sys.modules[__name__ + ".moves.urllib_request"]
  317. response = sys.modules[__name__ + ".moves.urllib_response"]
  318. robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"]
  319. def __dir__(self):
  320. return ['parse', 'error', 'request', 'response', 'robotparser']
  321. sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib")
  322. def add_move(move):
  323. """Add an item to six.moves."""
  324. setattr(_MovedItems, move.name, move)
  325. def remove_move(name):
  326. """Remove item from six.moves."""
  327. try:
  328. delattr(_MovedItems, name)
  329. except AttributeError:
  330. try:
  331. del moves.__dict__[name]
  332. except KeyError:
  333. raise AttributeError("no such move, %r" % (name,))
  334. if PY3:
  335. _meth_func = "__func__"
  336. _meth_self = "__self__"
  337. _func_closure = "__closure__"
  338. _func_code = "__code__"
  339. _func_defaults = "__defaults__"
  340. _func_globals = "__globals__"
  341. _iterkeys = "keys"
  342. _itervalues = "values"
  343. _iteritems = "items"
  344. _iterlists = "lists"
  345. else:
  346. _meth_func = "im_func"
  347. _meth_self = "im_self"
  348. _func_closure = "func_closure"
  349. _func_code = "func_code"
  350. _func_defaults = "func_defaults"
  351. _func_globals = "func_globals"
  352. _iterkeys = "iterkeys"
  353. _itervalues = "itervalues"
  354. _iteritems = "iteritems"
  355. _iterlists = "iterlists"
  356. try:
  357. advance_iterator = next
  358. except NameError:
  359. def advance_iterator(it):
  360. return it.next()
  361. next = advance_iterator
  362. try:
  363. callable = callable
  364. except NameError:
  365. def callable(obj):
  366. return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
  367. if PY3:
  368. def get_unbound_function(unbound):
  369. return unbound
  370. create_bound_method = types.MethodType
  371. Iterator = object
  372. else:
  373. def get_unbound_function(unbound):
  374. return unbound.im_func
  375. def create_bound_method(func, obj):
  376. return types.MethodType(func, obj, obj.__class__)
  377. class Iterator(object):
  378. def next(self):
  379. return type(self).__next__(self)
  380. callable = callable
  381. _add_doc(get_unbound_function,
  382. """Get the function out of a possibly unbound function""")
  383. get_method_function = operator.attrgetter(_meth_func)
  384. get_method_self = operator.attrgetter(_meth_self)
  385. get_function_closure = operator.attrgetter(_func_closure)
  386. get_function_code = operator.attrgetter(_func_code)
  387. get_function_defaults = operator.attrgetter(_func_defaults)
  388. get_function_globals = operator.attrgetter(_func_globals)
  389. def iterkeys(d, **kw):
  390. """Return an iterator over the keys of a dictionary."""
  391. return iter(getattr(d, _iterkeys)(**kw))
  392. def itervalues(d, **kw):
  393. """Return an iterator over the values of a dictionary."""
  394. return iter(getattr(d, _itervalues)(**kw))
  395. def iteritems(d, **kw):
  396. """Return an iterator over the (key, value) pairs of a dictionary."""
  397. return iter(getattr(d, _iteritems)(**kw))
  398. def iterlists(d, **kw):
  399. """Return an iterator over the (key, [values]) pairs of a dictionary."""
  400. return iter(getattr(d, _iterlists)(**kw))
  401. if PY3:
  402. def b(s):
  403. return s.encode("latin-1")
  404. def u(s):
  405. return s
  406. unichr = chr
  407. if sys.version_info[1] <= 1:
  408. def int2byte(i):
  409. return bytes((i,))
  410. else:
  411. # This is about 2x faster than the implementation above on 3.2+
  412. int2byte = operator.methodcaller("to_bytes", 1, "big")
  413. byte2int = operator.itemgetter(0)
  414. indexbytes = operator.getitem
  415. iterbytes = iter
  416. import io
  417. StringIO = io.StringIO
  418. BytesIO = io.BytesIO
  419. else:
  420. def b(s):
  421. return s
  422. # Workaround for standalone backslash
  423. def u(s):
  424. return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
  425. unichr = unichr
  426. int2byte = chr
  427. def byte2int(bs):
  428. return ord(bs[0])
  429. def indexbytes(buf, i):
  430. return ord(buf[i])
  431. def iterbytes(buf):
  432. return (ord(byte) for byte in buf)
  433. import StringIO
  434. StringIO = BytesIO = StringIO.StringIO
  435. _add_doc(b, """Byte literal""")
  436. _add_doc(u, """Text literal""")
  437. if PY3:
  438. exec_ = getattr(moves.builtins, "exec")
  439. def reraise(tp, value, tb=None):
  440. if value.__traceback__ is not tb:
  441. raise value.with_traceback(tb)
  442. raise value
  443. else:
  444. def exec_(_code_, _globs_=None, _locs_=None):
  445. """Execute code in a namespace."""
  446. if _globs_ is None:
  447. frame = sys._getframe(1)
  448. _globs_ = frame.f_globals
  449. if _locs_ is None:
  450. _locs_ = frame.f_locals
  451. del frame
  452. elif _locs_ is None:
  453. _locs_ = _globs_
  454. exec("""exec _code_ in _globs_, _locs_""")
  455. exec_("""def reraise(tp, value, tb=None):
  456. raise tp, value, tb
  457. """)
  458. print_ = getattr(moves.builtins, "print", None)
  459. if print_ is None:
  460. def print_(*args, **kwargs):
  461. """The new-style print function for Python 2.4 and 2.5."""
  462. fp = kwargs.pop("file", sys.stdout)
  463. if fp is None:
  464. return
  465. def write(data):
  466. if not isinstance(data, basestring):
  467. data = str(data)
  468. # If the file has an encoding, encode unicode with it.
  469. if (isinstance(fp, file) and
  470. isinstance(data, unicode) and
  471. fp.encoding is not None):
  472. errors = getattr(fp, "errors", None)
  473. if errors is None:
  474. errors = "strict"
  475. data = data.encode(fp.encoding, errors)
  476. fp.write(data)
  477. want_unicode = False
  478. sep = kwargs.pop("sep", None)
  479. if sep is not None:
  480. if isinstance(sep, unicode):
  481. want_unicode = True
  482. elif not isinstance(sep, str):
  483. raise TypeError("sep must be None or a string")
  484. end = kwargs.pop("end", None)
  485. if end is not None:
  486. if isinstance(end, unicode):
  487. want_unicode = True
  488. elif not isinstance(end, str):
  489. raise TypeError("end must be None or a string")
  490. if kwargs:
  491. raise TypeError("invalid keyword arguments to print()")
  492. if not want_unicode:
  493. for arg in args:
  494. if isinstance(arg, unicode):
  495. want_unicode = True
  496. break
  497. if want_unicode:
  498. newline = unicode("\n")
  499. space = unicode(" ")
  500. else:
  501. newline = "\n"
  502. space = " "
  503. if sep is None:
  504. sep = space
  505. if end is None:
  506. end = newline
  507. for i, arg in enumerate(args):
  508. if i:
  509. write(sep)
  510. write(arg)
  511. write(end)
  512. _add_doc(reraise, """Reraise an exception.""")
  513. def with_metaclass(meta, *bases):
  514. """Create a base class with a metaclass."""
  515. # This requires a bit of explanation: the basic idea is to make a
  516. # dummy metaclass for one level of class instantiation that replaces
  517. # itself with the actual metaclass. Because of internal type checks
  518. # we also need to make sure that we downgrade the custom metaclass
  519. # for one level to something closer to type (that's why __call__ and
  520. # __init__ comes back from type etc.).
  521. class metaclass(meta):
  522. __call__ = type.__call__
  523. __init__ = type.__init__
  524. def __new__(cls, name, this_bases, d):
  525. if this_bases is None:
  526. return type.__new__(cls, name, (), d)
  527. return meta(name, bases, d)
  528. return metaclass('temporary_class', None, {})
  529. def add_metaclass(metaclass):
  530. """Class decorator for creating a class with a metaclass."""
  531. def wrapper(cls):
  532. orig_vars = cls.__dict__.copy()
  533. orig_vars.pop('__dict__', None)
  534. orig_vars.pop('__weakref__', None)
  535. slots = orig_vars.get('__slots__')
  536. if slots is not None:
  537. if isinstance(slots, str):
  538. slots = [slots]
  539. for slots_var in slots:
  540. orig_vars.pop(slots_var)
  541. return metaclass(cls.__name__, cls.__bases__, orig_vars)
  542. return wrapper
  543. ### Additional customizations for Django ###
  544. if PY3:
  545. _assertRaisesRegex = "assertRaisesRegex"
  546. _assertRegex = "assertRegex"
  547. memoryview = memoryview
  548. buffer_types = (bytes, bytearray, memoryview)
  549. else:
  550. _assertRaisesRegex = "assertRaisesRegexp"
  551. _assertRegex = "assertRegexpMatches"
  552. # memoryview and buffer are not strictly equivalent, but should be fine for
  553. # django core usage (mainly BinaryField). However, Jython doesn't support
  554. # buffer (see http://bugs.jython.org/issue1521), so we have to be careful.
  555. if sys.platform.startswith('java'):
  556. memoryview = memoryview
  557. else:
  558. memoryview = buffer
  559. buffer_types = (bytearray, memoryview)
  560. def assertRaisesRegex(self, *args, **kwargs):
  561. return getattr(self, _assertRaisesRegex)(*args, **kwargs)
  562. def assertRegex(self, *args, **kwargs):
  563. return getattr(self, _assertRegex)(*args, **kwargs)
  564. add_move(MovedModule("_dummy_thread", "dummy_thread"))
  565. add_move(MovedModule("_thread", "thread"))