Quantify over all functions of a module

Fredrik Lundh fredrik at pythonware.com
Mon Dec 8 08:23:15 EST 2003


Joerg Schuster wrote:

> The following code comes closest to what I am trying to do.
> It does not work, because dir() does not return functions, but
> function names as strings.
>
> ##### test2.py #####
> def plus_2(_int):
>     return _int + 2
>
> def plus_3(_int):
>     return _int + 3
>
>
> #### test.py #####
> #!/usr/bin/env python
>
> import re
> import test2
>
> func_list = []
>
> for func in dir(test2):
>     test = re.search("^__", func)
>     if not test:
>         func_list.append(func)
>
> for func in func_list:
>     print apply(func, (2,))
>
>
> I failed to find a solution by searching the net, probably because I
> didn't know the right keywords. And I suppose that searching
> would not be necessary, if I knew the right keywords.

if you look up "dir" in the documentation, you'll find related functions
including:

    getattr(module, name) => object

and

    vars(module) => dictionary mapping names to objects

something like this might work:

    for name, func in vars(test2):
        if not name.startswith("__") and callable(func):
            func_list.append(func)

</F>








More information about the Python-list mailing list