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