Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a module's functions [duplicate]

I have this function call after importing foo.py. Foo has several methods that I need to call e.g. foo.paint, foo.draw:

import foo

code

if foo:
    getattr(foo, 'paint')()

I need to use a while loop to call and iterate through all the functions foo.paint, foo.draw etc. How do i go about it?

like image 877
lobjc Avatar asked Feb 19 '14 16:02

lobjc


People also ask

How to iterate functions in Python?

You can create an iterator object by applying the iter() built-in function to an iterable. You can use an iterator to manually loop over the iterable it came from. A repeated passing of iterator to the built-in function next() returns successive items in the stream.


1 Answers

You can use foo.__dict__ somehow like this:

for name, val in foo.__dict__.iteritems(): # iterate through every module's attributes
    if callable(val):                      # check if callable (normally functions)
        val()                              # call it

But watch out, this will execute every function (callable) in the module. If some specific function receives any arguments it will fail.

A more elegant (functional) way to get functions would be:

[f for _, f in foo.__dict__.iteritems() if callable(f)]

For example, this will list all functions in the math method:

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
like image 186
Paulo Bu Avatar answered Sep 25 '22 03:09

Paulo Bu