|
| 1 | +class _Context: |
| 2 | + """ |
| 3 | + Stash contextual information in an exception. As we don't know exactly when an exception |
| 4 | + is displayed to a user, this class tries to keep it always up to date. |
| 5 | +
|
| 6 | + This class subclasses string (to be compatible) and tracks an insertion point. |
| 7 | + """ |
| 8 | + |
| 9 | + __slots__ = ("original", "context", "lead") |
| 10 | + |
| 11 | + def __init__(self, original, lead, context): |
| 12 | + self.original = original |
| 13 | + self.lead = lead |
| 14 | + self.context = [context] |
| 15 | + |
| 16 | + def __str__(self): |
| 17 | + return "{}{}{}".format( |
| 18 | + self.original, self.lead, "".join(map(str, reversed(self.context))) |
| 19 | + ) |
| 20 | + |
| 21 | + def __repr__(self): |
| 22 | + return repr(self.__str__()) |
| 23 | + |
| 24 | + @classmethod |
| 25 | + def add(cls, exc, context): |
| 26 | + args = exc.args |
| 27 | + if args and isinstance(args[0], cls): |
| 28 | + args[0].context.append(context) |
| 29 | + return |
| 30 | + args = list(exc.args) |
| 31 | + if args: |
| 32 | + args[0] = cls(args[0], "; at ", context) |
| 33 | + else: |
| 34 | + args.append(cls("", "At ", context)) |
| 35 | + exc.args = tuple(args) |
| 36 | + |
| 37 | + |
| 38 | +class ErrorContext: |
| 39 | + """ |
| 40 | + Inject contextual information into an exception message. This won't work for some |
| 41 | + exceptions like OSError that ignore changes to `args`; likely not an issue for this |
| 42 | + library. There is a neglible performance hit if there is no exception. |
| 43 | +
|
| 44 | + >>> with ErrorContext('.foo'): |
| 45 | + ... with ErrorContext('[0]'): |
| 46 | + ... with ErrorContext('.qux'): |
| 47 | + ... 1 / 0 |
| 48 | + Traceback (most recent call last): |
| 49 | + ZeroDivisionError: division by zero; at .foo[0].qux |
| 50 | +
|
| 51 | + The `__exit__` method will catch the exception and look for a `_context` attribute |
| 52 | + assigned to it. If none exists, it appends `; at ` and the context string to the first |
| 53 | + string argument. |
| 54 | +
|
| 55 | + As the exception walks up the stack, outer ErrorContexts will be called. They will see |
| 56 | + the `_context` attribute and insert their context immediately after `; at ` and before |
| 57 | + the existing context. |
| 58 | +
|
| 59 | + Thus, in the example above: |
| 60 | +
|
| 61 | + ('division by zero',) -- the original message |
| 62 | + ('division by zero; at .qux',) -- the innermost context |
| 63 | + ('division by zero; at [0].qux',) |
| 64 | + ('division by zero; at .foo[0].qux',) -- the outermost context |
| 65 | +
|
| 66 | + For simplicity, the method doesn't attempt to inject whitespace. To represent names, |
| 67 | + consider surrounding them with angle brackets, e.g. `<Class>` |
| 68 | + """ |
| 69 | + |
| 70 | + def __init__(self, *context): |
| 71 | + self.context = context |
| 72 | + |
| 73 | + def __enter__(self): |
| 74 | + pass |
| 75 | + |
| 76 | + def __exit__(self, exc_type, exc_value, traceback): |
| 77 | + if exc_value is not None: |
| 78 | + _Context.add(exc_value, "".join(self.context)) |
| 79 | + |
| 80 | + |
| 81 | +def err_ctx(context, func): |
| 82 | + """ |
| 83 | + Execute a callable, decorating exceptions raised with error context. |
| 84 | +
|
| 85 | + ``err_ctx(context, func)`` has the same effect as: |
| 86 | +
|
| 87 | + with ErrorContext(context): |
| 88 | + return func() |
| 89 | + """ |
| 90 | + try: |
| 91 | + return func() |
| 92 | + except Exception as exc: |
| 93 | + _Context.add(exc, context) |
| 94 | + raise |
0 commit comments