get list of callable methods

Alex Martelli aleaxit at yahoo.com
Sat Oct 16 06:17:33 EDT 2004


John Hunter <jdhunter at ace.bsd.uchicago.edu> wrote:

>     >>   __all__ is the best indicator.  Since not all modules define
>     >> it, though, inspect.getsourcefile() is a reasonable fallback to
>     >> filter things based on the file of their definition.
> 
> Great - this seems to get the job done
> 
> import sys, inspect
> import matplotlib.matlab
> 
> class defined_in:
>     def __init__(self, modname):
>         self.modname = modname
>         
>     def __call__(self, o):
>         return (inspect.isfunction(o) and
>                 o.__module__==self.modname and
>                 not o.__name__.startswith('_'))
> 
> modname = 'matplotlib.matlab'
> members = inspect.getmembers(sys.modules[modname], defined_in(modname))
> for name, o in members:
>     print name

Very nice!  I'd slightly prefer one tiny difference...:

def defined_in(modname):
    def check(o):
        return ( inspect.isfunction(o) and
                 o.__module__ == modname and
                 not o.__name__.startswith('_') )
    return check

A matter of taste, of course, but I prefer to write such things as
closures rather than classes -- classes are more powerful and versatile,
and exactly because of this, when I don't need the power, I think it
expresses my design idea better to use a closure.  Not a criticism at
all, mind you, just pointing out a possible alternative.


Alex



More information about the Python-list mailing list