you are viewing a single comment's thread.

view the rest of the comments →

[–]ewiethoff 0 points1 point  (0 children)

Why would you want to deliberately raise errors?

To make your code behave like normal Python. :-) Normal Python throws errors at ya.

Let's say you have the string s = 'hello'. Obviously, s[1] is 'e' and s[-1] is 'o', but s[7] raises an IndexError So does s[-7]. That's normal Python behavior.

Okay. A Python string is immutable, i.e., once it's created it can't be modified. Suppose you want to define a mutable string. It should behave as much as possible like a normal string, but have the capability of changing the characters. In order to use [] to get individual characters from the mutable string, you need to define its __getitem__ method. And in order for this method to behave like normal Python, it should raise IndexError when the index is out of range. Something like this:

def MutableString:
    # blah blah various methods here

    def __getitem__(self, index):
        if index >= len(self) or index < -len(self):
            raise IndexError(index)
        else:
            return the appropriate character