Applying a function recursively
ben+python at benfinney.id.au
Sat Sep 10 10:13:18 CEST 2011
hetchkay <hetchkay at gmail.com> writes:
> 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
> 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 |
More information about the Python-list