_reflect.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # -*- test-case-name: twisted.test.test_reflect -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Standardized versions of various cool and/or strange things that you can do
  6. with Python's reflection capabilities.
  7. """
  8. import sys
  9. from jsonschema.compat import PY3
  10. class _NoModuleFound(Exception):
  11. """
  12. No module was found because none exists.
  13. """
  14. class InvalidName(ValueError):
  15. """
  16. The given name is not a dot-separated list of Python objects.
  17. """
  18. class ModuleNotFound(InvalidName):
  19. """
  20. The module associated with the given name doesn't exist and it can't be
  21. imported.
  22. """
  23. class ObjectNotFound(InvalidName):
  24. """
  25. The object associated with the given name doesn't exist and it can't be
  26. imported.
  27. """
  28. if PY3:
  29. def reraise(exception, traceback):
  30. raise exception.with_traceback(traceback)
  31. else:
  32. exec("""def reraise(exception, traceback):
  33. raise exception.__class__, exception, traceback""")
  34. reraise.__doc__ = """
  35. Re-raise an exception, with an optional traceback, in a way that is compatible
  36. with both Python 2 and Python 3.
  37. Note that on Python 3, re-raised exceptions will be mutated, with their
  38. C{__traceback__} attribute being set.
  39. @param exception: The exception instance.
  40. @param traceback: The traceback to use, or C{None} indicating a new traceback.
  41. """
  42. def _importAndCheckStack(importName):
  43. """
  44. Import the given name as a module, then walk the stack to determine whether
  45. the failure was the module not existing, or some code in the module (for
  46. example a dependent import) failing. This can be helpful to determine
  47. whether any actual application code was run. For example, to distiguish
  48. administrative error (entering the wrong module name), from programmer
  49. error (writing buggy code in a module that fails to import).
  50. @param importName: The name of the module to import.
  51. @type importName: C{str}
  52. @raise Exception: if something bad happens. This can be any type of
  53. exception, since nobody knows what loading some arbitrary code might
  54. do.
  55. @raise _NoModuleFound: if no module was found.
  56. """
  57. try:
  58. return __import__(importName)
  59. except ImportError:
  60. excType, excValue, excTraceback = sys.exc_info()
  61. while excTraceback:
  62. execName = excTraceback.tb_frame.f_globals["__name__"]
  63. # in Python 2 execName is None when an ImportError is encountered,
  64. # where in Python 3 execName is equal to the importName.
  65. if execName is None or execName == importName:
  66. reraise(excValue, excTraceback)
  67. excTraceback = excTraceback.tb_next
  68. raise _NoModuleFound()
  69. def namedAny(name):
  70. """
  71. Retrieve a Python object by its fully qualified name from the global Python
  72. module namespace. The first part of the name, that describes a module,
  73. will be discovered and imported. Each subsequent part of the name is
  74. treated as the name of an attribute of the object specified by all of the
  75. name which came before it. For example, the fully-qualified name of this
  76. object is 'twisted.python.reflect.namedAny'.
  77. @type name: L{str}
  78. @param name: The name of the object to return.
  79. @raise InvalidName: If the name is an empty string, starts or ends with
  80. a '.', or is otherwise syntactically incorrect.
  81. @raise ModuleNotFound: If the name is syntactically correct but the
  82. module it specifies cannot be imported because it does not appear to
  83. exist.
  84. @raise ObjectNotFound: If the name is syntactically correct, includes at
  85. least one '.', but the module it specifies cannot be imported because
  86. it does not appear to exist.
  87. @raise AttributeError: If an attribute of an object along the way cannot be
  88. accessed, or a module along the way is not found.
  89. @return: the Python object identified by 'name'.
  90. """
  91. if not name:
  92. raise InvalidName('Empty module name')
  93. names = name.split('.')
  94. # if the name starts or ends with a '.' or contains '..', the __import__
  95. # will raise an 'Empty module name' error. This will provide a better error
  96. # message.
  97. if '' in names:
  98. raise InvalidName(
  99. "name must be a string giving a '.'-separated list of Python "
  100. "identifiers, not %r" % (name,))
  101. topLevelPackage = None
  102. moduleNames = names[:]
  103. while not topLevelPackage:
  104. if moduleNames:
  105. trialname = '.'.join(moduleNames)
  106. try:
  107. topLevelPackage = _importAndCheckStack(trialname)
  108. except _NoModuleFound:
  109. moduleNames.pop()
  110. else:
  111. if len(names) == 1:
  112. raise ModuleNotFound("No module named %r" % (name,))
  113. else:
  114. raise ObjectNotFound('%r does not name an object' % (name,))
  115. obj = topLevelPackage
  116. for n in names[1:]:
  117. obj = getattr(obj, n)
  118. return obj