[Tutor] Using type
Dave Angel
d at davea.name
Fri Aug 12 12:07:06 CEST 2011
On 08/12/2011 05:31 AM, ALAN GAULD wrote:
>
>
>> It'll work on lists and tuples, for simple examples. But beware that
>> when you iterate through strings, the individual characters are also
>> strings, and this function will fail with an error like:
>> RuntimeError: maximum recursion depth exceeded
>
> Oh, good catch Dave.
>
> So you'd want to add an explicit check for a string.
> And in fact you probably don't want to "flatten" a string into
> individual characters anyway!
>
> Alan G.
>
I agree with you about probably not wanting to flatten a string. So I'd
add an isinstance() for strings and unicode. But the following is an
interesting problem.
I like duck typing in general. But I dislike having negative
isinstance() checks just for such a case. For example, one might
remember to check for a string, but not unicode or byte, which have the
same problem. Not to mention a user written iterable that might also
behave the same way.
For many functions, I'd simply document which types it's known to work
for, and let the caller beware. But infinite recursion is a
particularly nasty failure mode.
Any suggestions how to solve a problem of this kind without having an
explicit list of exceptions?
The usual rule for avoiding infinite recursion is to assure that each
recursion "reduces" the problem in some way, so that the termination
condition can be assured. The following is the best I could come up to
implement that. It refuses to recurse if the iterable won't change.
def flatten(my_data):
gut = []
for item in my_data:
try:
iter(item) # test for iterability
if len(item) == 1 and item == item[0]:
gut.append(item)
else:
gut = gut + flatten(item)
except TypeError:
gut.append(item)
return gut
--
DaveA
More information about the Tutor
mailing list