list of all functions defined in the current module

F

Fernando Rodriguez

Hi,

How can I get the list of all the functions defined in the current module?
 
?

=?ISO-8859-1?Q?Gerhard_H=E4ring?=

Fernando said:
Hi,

How can I get the list of all the functions defined in the current module?

If you have

def getfunctions(module):
import types
l = []
for key, value in module.__dict__.items():
if type(value) is FunctionType:
l.append(value)
return l

Then you can call this function with getfunctions(sys.modules[__name__])
to get a list of functions in the current module.

Perhaps you could also use the builtin 'inspect' module for this task.

-- Gerhard
 
A

anton muhin

Fernando said:
Hi,

How can I get the list of all the functions defined in the current module?

Here's what I managed to do:

<listfunc.py>
import inspect

def listfunc():
me = __import__(inspect.getmodulename(__file__))
for name in dir(me):
obj = getattr(me, name)
if inspect.isfunction(obj):
yield obj

def foo(): pass

def bar(): pass
</lisfunc.py>

<d.py>
import listfunc

for func in listfunc.listfunc():
print func
</d.py>

It prints:
<function bar at 0x008ECAF0>
<function foo at 0x008ECAB0>
<function listfunc at 0x008F3430>

regards,
anton.
 
D

David Eppstein

Gerhard Haring said:
Fernando said:
Hi,

How can I get the list of all the functions defined in the current module?

If you have

def getfunctions(module):
import types
l = []
for key, value in module.__dict__.items():
if type(value) is FunctionType:
l.append(value)
return l

Then you can call this function with getfunctions(sys.modules[__name__])
to get a list of functions in the current module.

Perhaps you could also use the builtin 'inspect' module for this task.

If you just want a list of a module's globals, what's wrong with
dir(modulename)
?

Of course it will tell you about globals that are not functions (e.g.
classes) but maybe that's what the original poster wanted anyway.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top