Get a list of functions in a file

Aaron Brady castironpi at gmail.com
Mon Dec 29 08:40:42 EST 2008


On Dec 29, 3:50 am, "Chris Rebert" <c... at rebertia.com> wrote:
> On Sun, Dec 28, 2008 at 11:26 PM, member Basu <b... at archlinux.us> wrote:
> > I'm putting some utility functions in a file and then building a simple
> > shell interface to them. Is their some way I can automatically get a list of
> > all the functions in the file? I could wrap them in a class and then use
> > attributes, but I'd rather leave them as simple functions.
>
> Assuming you've already imported the module as 'mod':
>
> func_names = [name for name in dir(mod) if callable(getattr(mod, name))]
> funcs = [getattr(mod, name) for name in dir(mod) if
> callable(getattr(mod, name))]
>
> Note that such lists will also include classes (as they too are
> callable). There are ways of excluding classes (and other objects that
> implement __call__), but it makes the code a bit more complicated.

No, not in general.  It's a weakness of one of the strengths of
Python.  For instance, if you define a function in a string, or return
one from another function, there's no way to get at it.

If you do want to import it, you can put any executable code inside an
'if __name__== "__main__"' block, so it won't get executed while
you're trying to index/catalog it.

If you're interested in something more hard-core, you might like the
'tokenize' module.  And I think the pattern you're looking for is
'every "def" outside a string, and even some in one.'

P.S.  Did not receive the original message on Google Groups.



More information about the Python-list mailing list