I’m not good enough with decorators yet to do this … Is it possible to define a decorator live_doc that allows me to get an interpolated doc string after a method or function call, filled in with the actual arguments and return value.
@live_doc("f was called with %d, %s and returned %d")
def f(x, y):
x + len(y)
After the code below:
f(3, "marty")
d = f.doc
d should be “f was called with 3, “marty”, and returned 8″. I would prefer to not build up the strings until f.doc is accessed, but would surely need to squirrel away the call args & return value somewhere.
Here’s a somewhat generalised solution that will treat your original docstring
as a template, and maintain other information about the decorated function
(like its name):
Before
fis first called,help(f)in the interactive interpreter gives you:After it’s called, you get:
Or with a more general function, showing off
kwargs:Obviously you could create whatever variables you wanted to use in the template inside
wrapper.