| Total Complexity | 9 |
| Total Lines | 56 |
| Duplicated Lines | 0 % |
| 1 | from __future__ import absolute_import |
||
| 8 | class Tracer(object): |
||
| 9 | """ |
||
| 10 | Trace object. |
||
| 11 | |||
| 12 | """ |
||
| 13 | |||
| 14 | def __init__(self): |
||
| 15 | self._handler = None |
||
| 16 | |||
| 17 | def __str__(self): |
||
| 18 | return "Tracer(_handler={})".format( |
||
| 19 | "<stopped>" if self._handler is None else self._handler, |
||
| 20 | ) |
||
| 21 | |||
| 22 | def __call__(self, frame, kind, arg): |
||
| 23 | """ |
||
| 24 | The settrace function. |
||
| 25 | |||
| 26 | .. note:: |
||
| 27 | |||
| 28 | This always returns self (drills down) - as opposed to only drilling down when predicate(event) is True |
||
| 29 | because it might |
||
| 30 | match further inside. |
||
| 31 | """ |
||
| 32 | if self._handler is None: |
||
| 33 | raise RuntimeError("Tracer is stopped.") |
||
| 34 | |||
| 35 | self._handler(Event(frame, kind, arg, self)) |
||
| 36 | return self |
||
| 37 | |||
| 38 | def trace(self, predicate): |
||
| 39 | """ |
||
| 40 | Starts tracing. Can be used as a context manager (with slightly incorrect semantics - it starts tracing |
||
| 41 | before ``__enter__`` is |
||
| 42 | called). |
||
| 43 | |||
| 44 | Args: |
||
| 45 | predicates (:class:`hunter.Q` instances): Runs actions if any of the given predicates match. |
||
| 46 | options: Keyword arguments that are passed to :class:`hunter.Q`, for convenience. |
||
| 47 | """ |
||
| 48 | self._handler = predicate |
||
| 49 | sys.settrace(self) |
||
| 50 | return self |
||
| 51 | |||
| 52 | def stop(self): |
||
| 53 | """ |
||
| 54 | Stop tracing. |
||
| 55 | """ |
||
| 56 | sys.settrace(None) |
||
| 57 | self._handler = None |
||
| 58 | |||
| 59 | def __enter__(self): |
||
| 60 | return self |
||
| 61 | |||
| 62 | def __exit__(self, exc_type, exc_val, exc_tb): |
||
| 63 | self.stop() |
||
| 64 |