PageRenderTime 46ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/mako/compat.py

https://bitbucket.org/zzzeek/mako
Python | 177 lines | 115 code | 48 blank | 14 comment | 20 complexity | 9a58a61efa22660bfd66d20eadbc6207 MD5 | raw file
  1. # mako/compat.py
  2. # Copyright 2006-2020 the Mako authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of Mako and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. import collections
  7. import inspect
  8. import sys
  9. py3k = sys.version_info >= (3, 0)
  10. py2k = sys.version_info < (3,)
  11. py27 = sys.version_info >= (2, 7)
  12. jython = sys.platform.startswith("java")
  13. win32 = sys.platform.startswith("win")
  14. pypy = hasattr(sys, "pypy_version_info")
  15. ArgSpec = collections.namedtuple(
  16. "ArgSpec", ["args", "varargs", "keywords", "defaults"]
  17. )
  18. def inspect_getargspec(func):
  19. """getargspec based on fully vendored getfullargspec from Python 3.3."""
  20. if inspect.ismethod(func):
  21. func = func.__func__
  22. if not inspect.isfunction(func):
  23. raise TypeError("{!r} is not a Python function".format(func))
  24. co = func.__code__
  25. if not inspect.iscode(co):
  26. raise TypeError("{!r} is not a code object".format(co))
  27. nargs = co.co_argcount
  28. names = co.co_varnames
  29. nkwargs = co.co_kwonlyargcount if py3k else 0
  30. args = list(names[:nargs])
  31. nargs += nkwargs
  32. varargs = None
  33. if co.co_flags & inspect.CO_VARARGS:
  34. varargs = co.co_varnames[nargs]
  35. nargs = nargs + 1
  36. varkw = None
  37. if co.co_flags & inspect.CO_VARKEYWORDS:
  38. varkw = co.co_varnames[nargs]
  39. return ArgSpec(args, varargs, varkw, func.__defaults__)
  40. if py3k:
  41. from io import StringIO
  42. import builtins as compat_builtins
  43. from urllib.parse import quote_plus, unquote_plus
  44. from html.entities import codepoint2name, name2codepoint
  45. string_types = (str,)
  46. binary_type = bytes
  47. text_type = str
  48. from io import BytesIO as byte_buffer
  49. def u(s):
  50. return s
  51. def b(s):
  52. return s.encode("latin-1")
  53. def octal(lit):
  54. return eval("0o" + lit)
  55. else:
  56. import __builtin__ as compat_builtins # noqa
  57. try:
  58. from cStringIO import StringIO
  59. except:
  60. from StringIO import StringIO
  61. byte_buffer = StringIO
  62. from urllib import quote_plus, unquote_plus # noqa
  63. from htmlentitydefs import codepoint2name, name2codepoint # noqa
  64. string_types = (basestring,) # noqa
  65. binary_type = str
  66. text_type = unicode # noqa
  67. def u(s):
  68. return unicode(s, "utf-8") # noqa
  69. def b(s):
  70. return s
  71. def octal(lit):
  72. return eval("0" + lit)
  73. if py3k:
  74. from importlib import machinery, util
  75. if hasattr(util, 'module_from_spec'):
  76. # Python 3.5+
  77. def load_module(module_id, path):
  78. spec = util.spec_from_file_location(module_id, path)
  79. module = util.module_from_spec(spec)
  80. spec.loader.exec_module(module)
  81. return module
  82. else:
  83. def load_module(module_id, path):
  84. module = machinery.SourceFileLoader(module_id, path).load_module()
  85. del sys.modules[module_id]
  86. return module
  87. else:
  88. import imp
  89. def load_module(module_id, path):
  90. fp = open(path, "rb")
  91. try:
  92. module = imp.load_source(module_id, path, fp)
  93. del sys.modules[module_id]
  94. return module
  95. finally:
  96. fp.close()
  97. if py3k:
  98. def reraise(tp, value, tb=None, cause=None):
  99. if cause is not None:
  100. value.__cause__ = cause
  101. if value.__traceback__ is not tb:
  102. raise value.with_traceback(tb)
  103. raise value
  104. else:
  105. exec(
  106. "def reraise(tp, value, tb=None, cause=None):\n"
  107. " raise tp, value, tb\n"
  108. )
  109. def exception_as():
  110. return sys.exc_info()[1]
  111. all = all # noqa
  112. def exception_name(exc):
  113. return exc.__class__.__name__
  114. ################################################
  115. # cross-compatible metaclass implementation
  116. # Copyright (c) 2010-2012 Benjamin Peterson
  117. def with_metaclass(meta, base=object):
  118. """Create a base class with a metaclass."""
  119. return meta("%sBase" % meta.__name__, (base,), {})
  120. ################################################
  121. def arg_stringname(func_arg):
  122. """Gets the string name of a kwarg or vararg
  123. In Python3.4 a function's args are
  124. of _ast.arg type not _ast.name
  125. """
  126. if hasattr(func_arg, "arg"):
  127. return func_arg.arg
  128. else:
  129. return str(func_arg)