What's the use of the else in try/except/else?

ma mabdelkader at gmail.com
Thu May 14 00:39:35 EDT 2009


A really great use for try/except/else would be if an object is
implementing its own __getitem__ method, so you would have something
like this:

class SomeObj(object):
    def __getitem__(self, key):
		try:
			#sometype of assertion here based on key type
		except AssertionError, e:
			raise TypeError, e #invalid type
		else:
			#continue processing, etc.. return some index, which will auto throw
			#an index error if you have some type of indexable datastructure



More information about the Python-list mailing list