Applying a function recursively

hetchkay hetchkay at gmail.com
Sat Sep 10 03:19:42 EDT 2011


Hi,
I want to apply a "convert" function on an object as follows:
If the object is of MyType type, invoke the passed in function.
If the object is a dictionary, apply on the keys and values of the
dictionary recursively.
If the object is a set, list or tuple, apply on each element
recursively.
Else, leave the object as is.

I wrote the following code:
def convert(obj, func):
   if isinstance(obj, MyType):
      return func(obj)
   elif isinstance(obj, dict):
      return dict((convert(key, func), convert(value, func)) for key,
value in obj.iteritems())
   elif isinstance(obj, (list, tuple, set)):
      return obj.__class__(convert(x, func) for x in obj)
   else:
      return obj

Is there a better way to do this?
Is there any way I can make this code faster?

Regards,
Krishnan



More information about the Python-list mailing list