phillipstack phillipstack - 2 months ago 23
Python Question

Loop through object functions

dir(object)
returns a list of object attributes and functions. How can I iterate over all callable functions and get the output of the functions? (ASSUMING NO FUNCTION ARGS)

for a in dir(obj) if not a.startswith('__') and callable(getattr(obj,a)):
response = obj.a()


This does not work as python is treating a as the attribute name. Is there any way to do this?

Answer

you need to use getattr to actually get the callable and then call it ...

do this

fn = getattr(obj,a)
fn()

not this

obj.a()

of coarse you are not checking if the callable has any required arguments or anything like that ... im not sure what you are actually trying to accomplish... but im skeptical that this is the right technique

additionally you need one more ) on this line callable(getattr(obj,a):