Type Hierarchies

Cliff Crawford cjc26 at nospam.cornell.edu
Wed Feb 14 15:26:55 EST 2001


* Burkhard Kloss <bk at xk7.com> menulis:
| 
| I guess concretely, the problem I'm trying to solve is iterating over a
| sequence which may contain sequences or items, e.g.
| 
| [1, [2,3], 4, 5, [6,7,8,9]]
| 
| and I was hoping to write something along the lines of
| 
| for item in sequence:
|     if is_sequence (item):
|         for it in sequence:
|             process (it)
|     else:
|         process (item)

Well, 'for' uses the __getitem__ method to iterate through the items of
its sequence, so what you could do is check if the object has a
__getitem__ method:

for item in sequence:
    if hasattr(item, "__getitem__"):
        for it in item:
            process(it)
    else:
        process(item)

You'll run into problems though if the object implements a __getitem__
which doesn't ever throw an IndexError, because then the loop will go on
forever.

Also, I just tried this out on built-in sequences (lists and tuples),
and apparently they don't have __getitem__()...?


| Which IMHO looks marginally cleaner than
| 
| for item in sequence:
|     try:
|         for it in sequence:
|             process (it)
|     except:
|         process (item)

This is kind of unsafe, because the "except:" will catch any exception,
not just TypeError (which is what gets raised when you try to iterate
over a non-sequence).


-- 
Cliff Crawford                 http://www.people.cornell.edu/pages/cjc26/
"huh?  Are you all there?  You missing some key parts up there?  Becoming  
a English major or an minor?   Do you need a annual report?  Are you slow
today, eh?  Did someone sever you parietal lobe?" - Mark



More information about the Python-list mailing list