How to get method's arguments

Alex Martelli aleaxit at yahoo.com
Fri Jan 19 09:00:36 EST 2001


"Victor Black" <muk_pr at yahoo.com> wrote in message
news:t6gedbl259o724 at corp.supernews.com...
> 1.How does IDLE show the argument list of a method or procedure.
> e.g when you write "dir(" a hint writing "dir([object]) -> list of
strings"
> pops up.
> (The sources are available but overwhelming)

Python's reflection/introspection powers are good, but, here, what
is involved is rather the documentation-string that gets attached
to each Python function (and several other objects) if the author
bothers to put it in.

A function object has an attribute named __doc__, containing its
documentation-string (or None, if no docstring).  E.g.:

def foo(bar):
    "foo(number) -> a bigger number"
    return bar+1

Now, foo.__doc__ is bound to the string
"foo(number) -> a bigger number".  The same string is also bound
to attribute foo.func_doc (I don't know why in this case there
are two ways to access the same data -- I may be missing something!).

If you wish, you can also truly find out about a function's
arguments from within Python.

foo.func_code is bound to the code-object which the funtion
runs.  Each code-object X has some useful attributes, such as:
    X.co_argcount    number of arguments
    X.co_varnames    local variable names; the first X.co_argcount
                     ones are the names of the *arguments*
    X.co_flags       has bit 4 set if X accepts arbitrary args
                     with the *args syntax; bit 8 set, if it
                     accepts arbitrary named args with **kwds syntax

And, back to the function-object we mentioned, foo.func_defaults
is bound to the tuple of default values for the function's
arguments, so you also know which ones are optional!  Note that
the optional arguments, if any, are always the _last_ (rightmost)
len(foo.func_defaults) ones.

But I don't think IDLE really needs to get into these introspection
issues -- I suspect it can get away with just the docstring (I have
not checked its sources to check exactly what it _does_ do for
tip-displaying purposes).


Alex






More information about the Python-list mailing list