six.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. """Utilities for writing code that runs on Python 2 and 3"""
  2. # Copyright (c) 2010-2012 Benjamin Peterson
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. # this software and associated documentation files (the "Software"), to deal in
  6. # the Software without restriction, including without limitation the rights to
  7. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  8. # the Software, and to permit persons to whom the Software is furnished to do so,
  9. # 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, FITNESS
  16. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  17. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  18. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. import operator
  21. import sys
  22. import types
  23. __author__ = "Benjamin Peterson <benjamin@python.org>"
  24. __version__ = "1.2.0"
  25. # True if we are running on Python 3.
  26. PY3 = sys.version_info[0] == 3
  27. if PY3:
  28. string_types = str,
  29. integer_types = int,
  30. class_types = type,
  31. text_type = str
  32. binary_type = bytes
  33. MAXSIZE = sys.maxsize
  34. else:
  35. string_types = basestring,
  36. integer_types = (int, long)
  37. class_types = (type, types.ClassType)
  38. text_type = unicode
  39. binary_type = str
  40. if sys.platform.startswith("java"):
  41. # Jython always uses 32 bits.
  42. MAXSIZE = int((1 << 31) - 1)
  43. else:
  44. # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
  45. class X(object):
  46. def __len__(self):
  47. return 1 << 31
  48. try:
  49. len(X())
  50. except OverflowError:
  51. # 32-bit
  52. MAXSIZE = int((1 << 31) - 1)
  53. else:
  54. # 64-bit
  55. MAXSIZE = int((1 << 63) - 1)
  56. del X
  57. def _add_doc(func, doc):
  58. """Add documentation to a function."""
  59. func.__doc__ = doc
  60. def _import_module(name):
  61. """Import module, returning the module after the last dot."""
  62. __import__(name)
  63. return sys.modules[name]
  64. # Replacement for lazy loading stuff in upstream six. See gh-2764
  65. if PY3:
  66. import builtins
  67. import functools
  68. reduce = functools.reduce
  69. zip = builtins.zip
  70. xrange = builtins.range
  71. else:
  72. import __builtin__
  73. import itertools
  74. builtins = __builtin__
  75. reduce = __builtin__.reduce
  76. zip = itertools.izip
  77. xrange = __builtin__.xrange
  78. if PY3:
  79. _meth_func = "__func__"
  80. _meth_self = "__self__"
  81. _func_code = "__code__"
  82. _func_defaults = "__defaults__"
  83. _iterkeys = "keys"
  84. _itervalues = "values"
  85. _iteritems = "items"
  86. else:
  87. _meth_func = "im_func"
  88. _meth_self = "im_self"
  89. _func_code = "func_code"
  90. _func_defaults = "func_defaults"
  91. _iterkeys = "iterkeys"
  92. _itervalues = "itervalues"
  93. _iteritems = "iteritems"
  94. try:
  95. advance_iterator = next
  96. except NameError:
  97. def advance_iterator(it):
  98. return it.next()
  99. next = advance_iterator
  100. if PY3:
  101. def get_unbound_function(unbound):
  102. return unbound
  103. Iterator = object
  104. def callable(obj):
  105. return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
  106. else:
  107. def get_unbound_function(unbound):
  108. return unbound.im_func
  109. class Iterator(object):
  110. def next(self):
  111. return type(self).__next__(self)
  112. callable = callable
  113. _add_doc(get_unbound_function,
  114. """Get the function out of a possibly unbound function""")
  115. get_method_function = operator.attrgetter(_meth_func)
  116. get_method_self = operator.attrgetter(_meth_self)
  117. get_function_code = operator.attrgetter(_func_code)
  118. get_function_defaults = operator.attrgetter(_func_defaults)
  119. def iterkeys(d):
  120. """Return an iterator over the keys of a dictionary."""
  121. return iter(getattr(d, _iterkeys)())
  122. def itervalues(d):
  123. """Return an iterator over the values of a dictionary."""
  124. return iter(getattr(d, _itervalues)())
  125. def iteritems(d):
  126. """Return an iterator over the (key, value) pairs of a dictionary."""
  127. return iter(getattr(d, _iteritems)())
  128. if PY3:
  129. def b(s):
  130. return s.encode("latin-1")
  131. def u(s):
  132. return s
  133. if sys.version_info[1] <= 1:
  134. def int2byte(i):
  135. return bytes((i,))
  136. else:
  137. # This is about 2x faster than the implementation above on 3.2+
  138. int2byte = operator.methodcaller("to_bytes", 1, "big")
  139. import io
  140. StringIO = io.StringIO
  141. BytesIO = io.BytesIO
  142. else:
  143. def b(s):
  144. return s
  145. def u(s):
  146. return unicode(s, "unicode_escape")
  147. int2byte = chr
  148. import StringIO
  149. StringIO = BytesIO = StringIO.StringIO
  150. _add_doc(b, """Byte literal""")
  151. _add_doc(u, """Text literal""")
  152. if PY3:
  153. import builtins
  154. exec_ = getattr(builtins, "exec")
  155. def reraise(tp, value, tb=None):
  156. if value.__traceback__ is not tb:
  157. raise value.with_traceback(tb)
  158. raise value
  159. print_ = getattr(builtins, "print")
  160. del builtins
  161. else:
  162. def exec_(code, globs=None, locs=None):
  163. """Execute code in a namespace."""
  164. if globs is None:
  165. frame = sys._getframe(1)
  166. globs = frame.f_globals
  167. if locs is None:
  168. locs = frame.f_locals
  169. del frame
  170. elif locs is None:
  171. locs = globs
  172. exec("""exec code in globs, locs""")
  173. exec_("""def reraise(tp, value, tb=None):
  174. raise tp, value, tb
  175. """)
  176. def print_(*args, **kwargs):
  177. """The new-style print function."""
  178. fp = kwargs.pop("file", sys.stdout)
  179. if fp is None:
  180. return
  181. def write(data):
  182. if not isinstance(data, basestring):
  183. data = str(data)
  184. fp.write(data)
  185. want_unicode = False
  186. sep = kwargs.pop("sep", None)
  187. if sep is not None:
  188. if isinstance(sep, unicode):
  189. want_unicode = True
  190. elif not isinstance(sep, str):
  191. raise TypeError("sep must be None or a string")
  192. end = kwargs.pop("end", None)
  193. if end is not None:
  194. if isinstance(end, unicode):
  195. want_unicode = True
  196. elif not isinstance(end, str):
  197. raise TypeError("end must be None or a string")
  198. if kwargs:
  199. raise TypeError("invalid keyword arguments to print()")
  200. if not want_unicode:
  201. for arg in args:
  202. if isinstance(arg, unicode):
  203. want_unicode = True
  204. break
  205. if want_unicode:
  206. newline = unicode("\n")
  207. space = unicode(" ")
  208. else:
  209. newline = "\n"
  210. space = " "
  211. if sep is None:
  212. sep = space
  213. if end is None:
  214. end = newline
  215. for i, arg in enumerate(args):
  216. if i:
  217. write(sep)
  218. write(arg)
  219. write(end)
  220. _add_doc(reraise, """Reraise an exception.""")
  221. def with_metaclass(meta, base=object):
  222. """Create a base class with a metaclass."""
  223. return meta("NewBase", (base,), {})