module functions list

D

Diez B. Roggisch

Hi,

this strikes me as a pretty basic question, but google didn't help, so I'm
asking it here:

How do I get a list of functions defined in a module in the module itself?
Like this:

--- module functions.py
def foo():
return 1

def bar():
return 1


def all_functions():
return <some magic code that yields [foo, bar]>

---

The application for this is that I want a bunch of predefined functions for
a small expression interpreter of mine to be collected in one module and
get them all without an explicit "registration" process.

Any ideas?
 
M

mark hellewell

Hi,

You could use a list comprehension coupled with a filter:

functionList = [function for function in dir(objectName) \
if callable(getattr(objectName,function))]

mark
 
D

Diez B. Roggisch

Hi,
You could use a list comprehension coupled with a filter:

functionList = [function for function in dir(objectName) \
if callable(getattr(objectName,function))]

That works if objectName is my module - but how do I get a reference to the
current module _inside_ my module? Thats the hart part (at least for
me ...)
 
M

Michel Claveau - abstraction méta-galactique non t

dir(MODULE)

print type(dir(MODULE)) #===>>> <type 'list'>
 
P

Peter Otten

Diez said:
Hi,
You could use a list comprehension coupled with a filter:

functionList = [function for function in dir(objectName) \
if callable(getattr(objectName,function))]

Note that callable() will not filter out classes. If you want to exclude
classes from your list, have a look at inspect.isfunction() or
inspect.isroutine().
That works if objectName is my module - but how do I get a reference to
the current module _inside_ my module? Thats the hart part (at least for
me ...)

sys.modules[__name__]

Peter
 
D

Diez B. Roggisch

sys.modules[__name__]

Ahh, that did it. Thanks. So far I don't care for classes vs. functions, but
the introspect tip will eventually come to use one day...
 

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

Forum statistics

Threads
474,204
Messages
2,571,063
Members
47,670
Latest member
micheljon

Latest Threads

Top