Characters contain themselves?

Kent Johnson kent at kentsjohnson.com
Sat Apr 8 09:10:58 EDT 2006


WENDUM Denis 47.76.11 (agent) wrote:
> While testing recursive algoritms dealing with generic lists I stumbled 
> on infinite loops which were triggered by the fact that (at least for my 
> version of Pyton) characters contain themselves.See session:

Strings are sequences and this is a problem for recursive functions that 
process nested lists. You do need to test for stringiness somehow. IIRC 
the usual solutions are

- explicit test for string: isinstance(xx, basestring)

- explicit test for list: isinstance(xx, list) - this fails for 
user-defined sequences that don't subclass list

- test for __iter__ attribute. IIUC this relies on an implementation 
detail that strings don't define __iter__:

In [6]: hasattr('aa', '__iter__')
Out[6]: False

In [7]: hasattr([], '__iter__')
Out[7]: True

Kent



More information about the Python-list mailing list