Python: Call all methods of an object with a given set of arguments


Question

I'd like to call all methods of a python object instance with a given set of arguments, i.e. for an object like

class Test():
    def a(input):
        print "a: " + input
    def b(input):
        print "b: " + input
    def c(input):
        print "c: " + input

I would like to write a dynamic method allowing me to run

myMethod('test')

resulting in

a: test
b: test
c: test

by iterating over all test()-methods. Thanks in advance for your help!

1
5
12/7/2010 8:45:53 AM

Accepted Answer

Not exactly sure why you want to do this. Normally in something like unittest you would provide an input on your class then reference it inside each test method.

Using inspect and dir.

from inspect import ismethod

def call_all(obj, *args, **kwargs):
    for name in dir(obj):
        attribute = getattr(obj, name)
        if ismethod(attribute):
            attribute(*args, **kwargs)

class Test():
    def a(self, input):
        print "a: " + input
    def b(self, input):
        print "b: " + input
    def c(self, input):
        print "c: " + input

call_all(Test(), 'my input')

Output:

a: my input
b: my input
c: my input
11
12/7/2010 8:34:44 AM

You really don't want to do this. Python ships with two very nice testing frameworks: see the unittest and doctest modules in the documentation.

But you could try something like:

def call_everything_in(an_object, *args, **kwargs):
    for item in an_object.__dict__:
        to_call = getattr(an_object, item)
        if callable(to_call): to_call(*args, **kwargs)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon