decorating functions with generic signatures (not for the faint of heart)
Thomas Heller
theller at python.net
Fri Apr 8 07:21:52 EDT 2005
"Michele Simionato" <michele.simionato at gmail.com> writes:
> I have realized today that defining decorators for functions
> with generic signatures is pretty non-trivial.
I've not completely read your post ;-), but I assume you're trying to do
something that I've also done some time ago. Maybe the following code
snippet is useful for you - it creates a source code string which can
than be compiled.
The code prints this when run:
"""
def f(a, b=42, c='spam', d=None):
'docstring'
return f._api_(a, b, c, d)
def g(*args, **kw):
''
return g._api_(*args, **kw)
"""
Thomas
<code>
def make_codestring(func):
import inspect
args, varargs, varkw, defaults = inspect.getargspec(func)
return "def %s%s:\n %r\n return %s._api_%s" % \
(func.func_name,
inspect.formatargspec(args, varargs, varkw, defaults),
func.func_doc or "",
func.func_name,
inspect.formatargspec(args, varargs, varkw))
def f(a, b=42, c="spam", d=None):
"docstring"
def g(*args, **kw):
pass
print make_codestring(f)
print make_codestring(g)
</code>
More information about the Python-list
mailing list