invoke method on many instances

Steven D'Aprano steve at
Fri Jul 17 03:45:08 EDT 2009

On Fri, 17 Jul 2009 05:19:50 +0000, Alan G Isaac wrote:

> As a recurrent situation, I need to invoke the same method on many
> instances.  Speed matters, but the solution should be pure Python.  Is
> the following convenience function a reasonable approach?
> def apply2(itr, methodname, *args, **kwargs):
>     f = operator.methodcaller(methodname, *args, **kwargs)
>     for item in itr:
>         f(item)

I don't particularly like your naming conventions, but never mind.

You could also try this:

for obj in objects:
    getattr(obj, methodname)(*args, **kwargs)

See also these recipes from the "Python Cookbook":


More information about the Python-list mailing list