Leif K-Brooks wrote:
Michael Spencer wrote:

if hasattr(item,"__iter__"): # Avoids iterating over strings


That's probably the cleanest way to avoid strings, but it's unfortunately not a good idea IMHO. Many objects (IndexedCatalog's Result objects are what I'm concerned about, but there are undoubtedly others) still rely entirely on the old-style sequence iteration protocol even though they're proper containers, so checking for __iter__ wouldn't work on them. Explicitly doing isinstance(item, basestring) is probably the best option until older objects move to the new iteration protocol.
Sure, the preceding part of my post:

One issue is specifying iterable types which should be atomic (notably strings). This uses a simple hardwired test for that.

...makes it clear that 'hasattr(item,"__iter__")' is not claiming to be a general atomicity test.


Using something like:
if not isinstance(item, basestring):
    try:
        iterator = iter(item)
    etc...

...defines a rule that works for your case, but it also means that any non-basestring class that implements __getitem__ gets flattened. That may be what you want...or not.

I think flatten is a special-case function, and it is therefore most practical to define its atomicity rules on a case-by-case basis.

Michael






-- http://mail.python.org/mailman/listinfo/python-list

Reply via email to