m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

897 lines
30 KiB

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