Quantify over all functions of a module

J

Joerg Schuster

Hello,

I want to refer to all functions of a module, say test2.py, without
having to manually enumerate them.

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.


Jörg
 
F

Fredrik Lundh

Joerg said:
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>
 
F

Fredrik Lundh

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

ahem. better make that:

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

</F>
 
A

Aahz

ahem. better make that:

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

....and if you wanna show off your Python 2.2+ knowledge, make that
iteritems(). ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top