[Tutor] How to use introspection to discover parameters?

Jerry Hill malaclypse2 at gmail.com
Thu Jul 26 16:39:36 CEST 2012


On Thu, Jul 26, 2012 at 9:48 AM, David <bouncingcats at gmail.com> wrote:
> A related question:
> help() seems to do the introspection for me. Does python allow me to do it in
> my own code? Specifically, how might I write my own function to mimic line 3 of
> help(), appearing like so:
>
>>>> my_function(logging.log)
> "log(level, msg, *args, **kwargs)"
>
> If I knew how to do that, it might help me understand how to do "introspection"
> better.

The inspect module probably has all the tools you need:
http://docs.python.org/library/inspect.html .  In particular,
inspect.getargspec() will get you the argument specification of a
function, like this:

>>> inspect.getargspec(logging.log)
ArgSpec(args=['level', 'msg'], varargs='args', keywords='kwargs', defaults=None)
>>>

Then you just have to format those results the way you like.

Also, the help object itself is written in python.  You can look at
the source in pydoc.py
(http://hg.python.org/cpython/file/2.7/Lib/pydoc.py) to see exactly
what it does.

-- 
Jerry


More information about the Tutor mailing list