-2

I am using Python to write a function decorator that logs the arguments and returns value of the function when it is called

    def logfunc(prefix)

The output should be to sys.stderr in the format:

"{prefix}: {function name}({positional args}..., {keyword=args}, ...)" 

and

"{prefix}: {function name} -> {return value}"

respectively for call and return.

This is how it is used:

@logfunc("test")
def f(arg)
    return arg

I dont quiet understand it? Can someone show me a pointer?

Anto
  • 6,806
  • 8
  • 43
  • 65
user2756325
  • 39
  • 3
  • 6

2 Answers2

2
import logging

logger = logging.getLogger(__name__)

def logging_decorator(fn):
    def func(*a, **kw):
       logger.info('%s(%s, %s)', fn, a, kw)
       return fn(*a, **kw)
    return func

if you want to print to stderr instead you can use import sys and then sys.stderr.write('%s(%s, %s)' % (fn, a, kw))

mjallday
  • 9,796
  • 9
  • 51
  • 71
2

I found the question to be interesting, even if it is badly asked :-(

The easy part, if that there are examples of decorators without arguments in Python documentation, but it took me some time to understand that a decorator taking arguments is in fact a function taking arguments and returning a decorator. Once this point is clear, the answer is almost evident :

def logger(prefix):
    def decorate(f):
        def wrapper(*args, **kwargs):
            print(prefix, f.__name__, "args", args, "kwargs", kwargs)
            cr = f(*args, **kwargs)
            print(prefix, f.__name__, "result", cr)
            return cr
        return wrapper
    return decorate

Usage :

>>> @logger("test")
def zut(a, b, foo='FOO'):
    return a+b

>>> zut(2,3)
test zut args (2, 3) kwargs {}
test zut cr 5
5
>>> zut(2,3, foo = 'FEE')
test zut args (2, 3) kwargs {'foo': 'FEE'}
test zut cr 5
5
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252