Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 934
sam Avatar asked Dec 07 '10 08:12

sam


2 Answers

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
like image 63
kevpie Avatar answered Oct 24 '22 17:10

kevpie


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)
like image 1
Karl Knechtel Avatar answered Oct 24 '22 16:10

Karl Knechtel