|
| 1 | +# Created by Peter Norvig |
| 2 | + |
| 3 | +# TODO: need to somehow enable sys._getframe() |
| 4 | +# even though 'sys' is technically locked down |
| 5 | + |
| 6 | +#import inspect # old and really slow! |
| 7 | +import sys |
| 8 | + |
| 9 | +class watchedlist(list): |
| 10 | + """A class that wraps a list, and monitors sets and gets. |
| 11 | + Optionally monitors local variables.""" |
| 12 | + def __setitem__(self, i, val): |
| 13 | + print 'setting A[{}] = {}'.format(i, val) |
| 14 | + self.watchlocals() |
| 15 | + return list.__setitem__(self, i, val) |
| 16 | + def __getitem__(self, i): |
| 17 | + print('fetching A[{}]; value is {};'.format( |
| 18 | + self, i, list.__getitem__(self, i))) |
| 19 | + self.watchlocals() |
| 20 | + return list.__getitem__(self, i) |
| 21 | + |
| 22 | + def watchlocals(self): |
| 23 | + if hasattr(self, 'watchedlocals'): |
| 24 | + #D = inspect.stack()[2][0].f_locals # old and really slow! |
| 25 | + D = sys._getframe(2).f_locals |
| 26 | + print(' watched locals: {}'.format( |
| 27 | + {var: D[var] for var in self.watchedlocals})) |
| 28 | + |
| 29 | + |
| 30 | +def watch(object, watchedspec): |
| 31 | + """Wrap object with a wrapper class (like watchedlist). |
| 32 | + watchedspec is either None or a callable (like watchedlist), or |
| 33 | + a 2-tuple of (callable, local_var_names), where local_var_names |
| 34 | + can be a string or a sequence of strings.""" |
| 35 | + if not watchedspec: |
| 36 | + return object |
| 37 | + kind, locals = (watchedspec if isinstance(watchedspec, (tuple, list)) else |
| 38 | + (watchedspec, ())) |
| 39 | + if isinstance(locals, str): locals = locals.split() |
| 40 | + watched = kind(object) |
| 41 | + watched.watchedlocals = locals |
| 42 | + return watched |
| 43 | + |
| 44 | + |
| 45 | +class watchfn(object): |
| 46 | + """Decorator that watches the arguments of a function. |
| 47 | + Specify watchedspecs for each positional argument, and optionally |
| 48 | + for keyword arguments.""" |
| 49 | + def __init__(self, *args, **kwargs): |
| 50 | + self.args, self.kwargs = args, kwargs |
| 51 | + |
| 52 | + def __call__(self, fn): |
| 53 | + def wrapped_fn(*args, **kwargs): |
| 54 | + args = [watch(obj, spec) for (obj, spec) in zip(args, self.args)] |
| 55 | + kwargs = {k: watch(kwargs[k], self.args.get(k, None)) for k in kwargs} |
| 56 | + return fn(*args, **kwargs) |
| 57 | + #wrapped_fn.__name__ = fn.__name__ |
| 58 | + return wrapped_fn |
| 59 | + |
0 commit comments