_builtin.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import sys
  2. # Passthrough for builtins supported with py27.
  3. BaseException = BaseException
  4. GeneratorExit = GeneratorExit
  5. _sysex = (KeyboardInterrupt, SystemExit, MemoryError, GeneratorExit)
  6. all = all
  7. any = any
  8. callable = callable
  9. enumerate = enumerate
  10. reversed = reversed
  11. set, frozenset = set, frozenset
  12. sorted = sorted
  13. if sys.version_info >= (3, 0):
  14. exec("print_ = print ; exec_=exec")
  15. import builtins
  16. # some backward compatibility helpers
  17. _basestring = str
  18. def _totext(obj, encoding=None, errors=None):
  19. if isinstance(obj, bytes):
  20. if errors is None:
  21. obj = obj.decode(encoding)
  22. else:
  23. obj = obj.decode(encoding, errors)
  24. elif not isinstance(obj, str):
  25. obj = str(obj)
  26. return obj
  27. def _isbytes(x):
  28. return isinstance(x, bytes)
  29. def _istext(x):
  30. return isinstance(x, str)
  31. text = str
  32. bytes = bytes
  33. def _getimself(function):
  34. return getattr(function, '__self__', None)
  35. def _getfuncdict(function):
  36. return getattr(function, "__dict__", None)
  37. def _getcode(function):
  38. return getattr(function, "__code__", None)
  39. def execfile(fn, globs=None, locs=None):
  40. if globs is None:
  41. back = sys._getframe(1)
  42. globs = back.f_globals
  43. locs = back.f_locals
  44. del back
  45. elif locs is None:
  46. locs = globs
  47. fp = open(fn, "r")
  48. try:
  49. source = fp.read()
  50. finally:
  51. fp.close()
  52. co = compile(source, fn, "exec", dont_inherit=True)
  53. exec_(co, globs, locs)
  54. else:
  55. import __builtin__ as builtins
  56. _totext = unicode
  57. _basestring = basestring
  58. text = unicode
  59. bytes = str
  60. execfile = execfile
  61. callable = callable
  62. def _isbytes(x):
  63. return isinstance(x, str)
  64. def _istext(x):
  65. return isinstance(x, unicode)
  66. def _getimself(function):
  67. return getattr(function, 'im_self', None)
  68. def _getfuncdict(function):
  69. return getattr(function, "__dict__", None)
  70. def _getcode(function):
  71. try:
  72. return getattr(function, "__code__")
  73. except AttributeError:
  74. return getattr(function, "func_code", None)
  75. def print_(*args, **kwargs):
  76. """ minimal backport of py3k print statement. """
  77. sep = ' '
  78. if 'sep' in kwargs:
  79. sep = kwargs.pop('sep')
  80. end = '\n'
  81. if 'end' in kwargs:
  82. end = kwargs.pop('end')
  83. file = 'file' in kwargs and kwargs.pop('file') or sys.stdout
  84. if kwargs:
  85. args = ", ".join([str(x) for x in kwargs])
  86. raise TypeError("invalid keyword arguments: %s" % args)
  87. at_start = True
  88. for x in args:
  89. if not at_start:
  90. file.write(sep)
  91. file.write(str(x))
  92. at_start = False
  93. file.write(end)
  94. def exec_(obj, globals=None, locals=None):
  95. """ minimal backport of py3k exec statement. """
  96. __tracebackhide__ = True
  97. if globals is None:
  98. frame = sys._getframe(1)
  99. globals = frame.f_globals
  100. if locals is None:
  101. locals = frame.f_locals
  102. elif locals is None:
  103. locals = globals
  104. exec2(obj, globals, locals)
  105. if sys.version_info >= (3, 0):
  106. def _reraise(cls, val, tb):
  107. __tracebackhide__ = True
  108. assert hasattr(val, '__traceback__')
  109. raise cls.with_traceback(val, tb)
  110. else:
  111. exec ("""
  112. def _reraise(cls, val, tb):
  113. __tracebackhide__ = True
  114. raise cls, val, tb
  115. def exec2(obj, globals, locals):
  116. __tracebackhide__ = True
  117. exec obj in globals, locals
  118. """)
  119. def _tryimport(*names):
  120. """ return the first successfully imported module. """
  121. assert names
  122. for name in names:
  123. try:
  124. __import__(name)
  125. except ImportError:
  126. excinfo = sys.exc_info()
  127. else:
  128. return sys.modules[name]
  129. _reraise(*excinfo)