1

In python, I want to create logging function such as returning function's name, its arguments,and the value of function. The output I want with sys.stderr like "test: f(arg='1', arg2='a')\ntest: f -> '1a'"

The code is like below ```

def log(prefix):
def decorator(func):
  @functools.wraps(func)
   def wrapper(*args, **kws):
     code *here
    return wrapper
 return decorator
@log
function(arg="1", arg2="a")
 return arg + arg2

```

I thought of some code like below, but it won't work especially at arg="1" arg2="a". I dont know how to unpack kws arguments ( dict here) at just one time.

1.

print("{}: {}({})\n{}: {} -> {}".format(prefix, func.__name__, kws, prefix, func.__name__, func(**kws)), file=sys.stderr)

2.

print("{}: {}({})\n{}: {} -> {}".format(prefix, func.__name__, **kws, prefix, func.__name__, func(**kws)), file=sys.stderr)

If you are familiar with this, could you give me some solutions or hint?

yy224
  • 11
  • 1
  • This isn't a duplicate, but [this question and its answers](https://stackoverflow.com/q/10724495/3814202) may have some useful tools. I don't really understand what you're doing with `func(**kws)`, I think you're calling the function twice here? Anyway, something like `",".join("{0}={1}".format(arg, kws[arg]) for arg in kws)` might also be useful here. AKA it's probably easier to just iterate through things – svenevs Oct 08 '17 at 02:41

0 Answers0