compat.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # mako/compat.py
  2. # Copyright 2006-2025 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. from importlib import metadata as importlib_metadata
  8. from importlib import util
  9. import inspect
  10. import sys
  11. win32 = sys.platform.startswith("win")
  12. pypy = hasattr(sys, "pypy_version_info")
  13. ArgSpec = collections.namedtuple(
  14. "ArgSpec", ["args", "varargs", "keywords", "defaults"]
  15. )
  16. def inspect_getargspec(func):
  17. """getargspec based on fully vendored getfullargspec from Python 3.3."""
  18. if inspect.ismethod(func):
  19. func = func.__func__
  20. if not inspect.isfunction(func):
  21. raise TypeError(f"{func!r} is not a Python function")
  22. co = func.__code__
  23. if not inspect.iscode(co):
  24. raise TypeError(f"{co!r} is not a code object")
  25. nargs = co.co_argcount
  26. names = co.co_varnames
  27. nkwargs = co.co_kwonlyargcount
  28. args = list(names[:nargs])
  29. nargs += nkwargs
  30. varargs = None
  31. if co.co_flags & inspect.CO_VARARGS:
  32. varargs = co.co_varnames[nargs]
  33. nargs = nargs + 1
  34. varkw = None
  35. if co.co_flags & inspect.CO_VARKEYWORDS:
  36. varkw = co.co_varnames[nargs]
  37. return ArgSpec(args, varargs, varkw, func.__defaults__)
  38. def load_module(module_id, path):
  39. spec = util.spec_from_file_location(module_id, path)
  40. module = util.module_from_spec(spec)
  41. spec.loader.exec_module(module)
  42. return module
  43. def exception_as():
  44. return sys.exc_info()[1]
  45. def exception_name(exc):
  46. return exc.__class__.__name__
  47. def importlib_metadata_get(group):
  48. ep = importlib_metadata.entry_points()
  49. if hasattr(ep, "select"):
  50. return ep.select(group=group)
  51. else:
  52. return ep.get(group, ())