You can test the type of an object (e.g., a list entry) with the type operator (to use symbolic names for builtin types, you may also import module types, but it's often just as clear to test against, e.g., type(0) for integers, type(0L) for long integers, type([]) for lists, and so on). Thus, one way to do it could be:
def printType(t): if t==type([]): return "list" elif t==type(''): return "string" elif t==type(0): return "integer" elif t==type(()): return "tuple" else: return "something else" for i in range(len(list)): print "element %d has type %s" % (i, printType(type(list[i])))
However, this kind of approach has some huge flaws - the number of built-in
types (plus types that could be added by the user importing C-written
modules...) is enormous, and all the _classes_ get lumped into one 'type',
which you may not want to keep as one lump...
- Alex Martelli
try:
try:
print "foo"
except:
print "errors"
finally
print "clean up"
I
do agree that an optionally finally-clause after 1 or more except clauses (and
possibly an else clause too) on a try would make for a nice alternative to this
rather cumbersome nested syntax where except (& maybe else) and finally are
mutually exclusive.
"Why you'd want to do this" seems rather obvious -- catch errors AND also
guarantee some finalization.
- Alex Martelli
Version : 1.65 Mise à jour : 11/11/00