1 | initial version |
I agree with the other responders on using 'map'. As to the other issue, detecting if x is a collection: are you attempting to construct a very general tool that can be used in just about any context, or just something that will work for the solution of a particular problem? If it's the latter, then (depending on your particular context) you might only encounter certain types of collections. For example, if the only kinds of collections you expect to see are lists, tuples, or sets, you could define
itertypes = ["<type 'tuple'>", " <type 'list'>", " <class 'sage.sets.set.Set_object_enumerated_with_category'>"]
then just test if str(type(x)) is in itertypes.
I did a smidge of benchmarking, using a few basic examples, comparing this approach to your "try... except TypeError" approach. (I only tested the step where you determine whether x is a collection or not, omitting the step where you actually apply 'simplefunc'.) When x is a list/tuple/set, my method is only about half as fast as yours, but otherwise it's 3 times as fast. So which is faster might depend on the proportion of the time you expect to encounter collections.
By the way, this may not be a worry for you, but I don't think that Sage would raise any objection if you ask it to iterate over an infinite set like ZZ. It just wouldn't terminate.