Applying a function recursively

Ben Finney ben+python at
Sat Sep 10 04:13:18 EDT 2011

hetchkay <hetchkay at> writes:

> 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.

That smells like a bad design. Why are you using the same function for
al of those different behaviours?

That's not merely rhetorical; the design isn't absolutely wrong. But
it's wrong often enough that you need to have a compelling reason to
make such a complex behaviour in a single function.

I suspect, if you can be explicit about the goal you're aiming for with
this code, a better design can be found that doesn't require all those
polymorphism-breaking type checks.

 \      “An expert is a man who has made all the mistakes which can be |
  `\                         made in a very narrow field.” —Niels Bohr |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list