Type Hierarchies

Burkhard Kloss bk at xk7.com
Wed Feb 14 10:35:51 EST 2001


Thanks to all the people who reminded me that len() also works on mappings
...

> def am_i_a_sequence(ob):
>     return type(ob) in
> [types.StringType,types.ListType,types.TupleType,types.XRangeType]

Yes, this works great for the built-in types - but not for user defined
types, which is specifically what I'm after.

> ['t','e','e','p']
:)

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)

Which IMHO looks marginally cleaner than

for item in sequence:
    try:
        for it in sequence:
            process (it)
    except:
        process (item)

Although I guess what I should really do is

for item in flatten(sequence):
    process (item)

Hmmm.... now how do I effectively flatten a sequence ?





More information about the Python-list mailing list