How to access a function's formal signature?

kj no.email at please.post
Tue Aug 11 23:30:24 CEST 2009



In the standard Python interactive interpreter, the string printed
by the help command when applied to a function includes the function's
formal signature.  E.g.:

>>> def foo(bar, *baz, **frobozz):
...   pass
... 
>>> help(foo)
Help on function foo in module __main__:

foo(bar, *baz, **frobozz)


Here by "signature" I'm referring to the substring "bar, *baz,
**frobozz" shown above (or, equivalently, any other object from
which this string could be deduced).  (I figured out that I can
retrieve this signature using methods in the inspect module.)

OK, now, is there a way to modify a function so that pydoc (and
presumably also the interactive interpreter's help function, etc.)
will print out a desired specific signature for this function?

For example, is there some way that I can modify foo above so that
help(foo) will print out

foo(x, y=None)

I tried mucking with foo.func_code's co_argcount, co_varnames, and
co_flags attributes, but as it turns out, they are read-only,
unfortunately.

The context here is the problem of writing a signature-changing
decorator in such a way that documentation facilities like help
and pydoc will print out the signature of the *original* undecorated
code (with some modifications), rather than the signature of the
decorated method.

TIA!

kynn



More information about the Python-list mailing list