Advertisement
GoodiesHQ

Debug Decorator

Mar 7th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. from functools import wraps
  2. from time import perf_counter
  3. import types
  4.  
  5.  
  6. class debug(object):
  7.     def __init__(self, Time=False, Parameters=False, Doc=False, Value=False):
  8.         self.t = Time
  9.         self.p = Parameters
  10.         self.d = Doc
  11.         self.v = Value
  12.  
  13.     def __call__(self, func):
  14.         @wraps(func)
  15.         def run(*args, **kwargs):
  16.             @wraps(func)
  17.             def gen(g):
  18.                 print("\tDebug Generator: '{}'".format(func.__name__))
  19.                 step = 0
  20.                 while True:
  21.                     try:
  22.                         if self.t:
  23.                             gt1 = perf_counter()
  24.                         genval = next(g)
  25.                         if self.t:
  26.                             gt2 = perf_counter()
  27.                             print("\tGenerator Time: {:.3e} seconds".format(gt2 - gt1))
  28.                         print("\tGenerator Step #{}: {}".format(step, genval if self.v else type(genval).__name__))
  29.                         step += 1
  30.                         yield genval
  31.                     except GeneratorExit:
  32.                         break
  33.                 print("\tGeneratpr {} is finsihed.".format(func.__name__))
  34.             params = ""
  35.             if self.p:
  36.                 params = ", ".join(["{}".format(arg) for arg in args] + ["{}={}".format(k, v) for k, v in kwargs.items()])
  37.             print("\n\tDebug output for '{}({})'".format(func.__name__, params))
  38.             if self.d:
  39.                 print('\tDocstring: "{}"'.format(func.__doc__))
  40.             if self.t:
  41.                 t1 = perf_counter()
  42.             val = func(*args, **kwargs)
  43.             if self.t:
  44.                 t2 = perf_counter()
  45.                 print("\tTime Taken: {:.3e} seconds".format(t2 - t1))
  46.             print("\tReturn: '{}'\n".format(val if self.v else type(val).__name__))
  47.             return gen(val) if isinstance(val, types.GeneratorType) else run
  48.         return run
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement