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

1

25

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?

Bureaucracy answered 19/2, 2014 at 16:1 Comment(1)
I don't think that's a duplicate. In that question the OP only wanted information, in this one he actually wants to call the functions.Chivalry
C
42

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',
 ...]
Chivalry answered 19/2, 2014 at 16:5 Comment(2)
being new to python am a bit confused on how to implement this: [f for , f in foo.__dict_.iteritems() if callable(f)]. I get AttributeError: 'dict' object has no attribute 'iteritems'Bureaucracy
@wakamdr Seems you're using Python 3, try with __dict__.items()Chivalry

© 2022 - 2024 — McMap. All rights reserved.