[Python-Dev] Iterable String Redux (aka String ABC)
Terry Reedy
tjreedy at udel.edu
Wed May 28 00:58:14 CEST 2008
"Armin Ronacher" <armin.ronacher at active-4.com> wrote in message
news:loom.20080527T192243-415 at post.gmane.org...
| Basically *the* problematic situation with iterable strings is something
like
| a `flatten` function that flattens out every iterable object except of
strings.
In most real cases I can imagine, this is way too broad. For instance,
trying to 'flatten' an infinite iterable makes the flatten output one also.
Flattening a set imposes an arbitrary order (but that is ok if one feeds
the output to set(), which de-orders it). Flattening a dict decouples keys
and values. Flattening iterable set-theoretic numbers (0={}, n = {n-1,
{n-1}}, or something like that) would literaly yield nothing.
| Imagine it's implemented in a way similar to that::
|
| def flatten(iterable):
| for item in iterable:
| try:
| if isinstance(item, basestring):
| raise TypeError()
| iterator = iter(item)
| except TypeError:
| yield item
| else:
| for i in flatten(iterator):
| yield i
I can more easily imagine wanting to flatten only certain classes, such and
tuples and lists, or frozensets and sets.
def flatten(iterable, classes):
for item in iterable:
if type(item) in classes:
for i in flatten(item, classes):
yield i
else:
yield item
| A problem comes up as soon as user defined strings (such as UserString)
is
| passed to the function. In my opinion a good solution would be a
"String"
| ABC one could test against.
This might be a good idea regardless of my comments.
tjr
More information about the Python-Dev
mailing list