Note that there are some explanatory texts on larger screens.

plurals
  1. POPython logging using a decorator
    text
    copied!<p>This is the first example we meet when we face with decorators. But I'm not able to realize what exactly I would like.</p> <p>A simple decorator named LOG. It should work like this:</p> <pre><code>@LOG def f(a, b=2, *c, **d): pass </code></pre> <p>And the result should be something like:</p> <pre><code>f(1, pippo=4, paperino='luca') ===== Enter f ===== a = 1 b = 2 pippo = 4 paperino = luca ===== Exit f ===== </code></pre> <p>Where every argument passed as a parameter to the function is showed with its value.</p> <p>I discovered that the problem is harder than I thought, mainly because of the many different ways you can pass arguments to a function (think about tuples with *c or dictionaries with **d).</p> <p>I tried a solution but I'm not sure it's correct. It' somethink like this:</p> <pre><code>def LOG(fn): import inspect varList, _, _, default = inspect.getargspec(fn) d = {} if default is not None: d = dict((varList[-len(default):][i], v) for i, v in enumerate(default)) def f(*argt, **argd): print ('Enter %s' % fn).center(100, '=') d.update(dict((varList[i], v) for i, v in enumerate(argt))) d.update(argd) for c in d.iteritems(): print '%s = %s' % c ret = fn(*argt, **argd) print 'return: %s' % ret print ('Exit %s' % fn).center(100, '=') return ret return f </code></pre> <p>I think it's not so easy as I expected, but it's strange I didn't found what I wanted on Google.</p> <p>Can you tell me if my solution is ok? Or can you suggest a better solution to the problem I proposed?</p> <p>Thank you to everybody.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload