3

In the following example, I purposefully give wrong types to the parameters of the methods that are chained after a string:

"foo".rsplit(1).join(3) # purposefully wrong input on both methods

The error raised when calling python on a file containing the above looks like this:

$ python test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    "foo".rsplit(1).join(3)
TypeError: must be str or None, not int

I find it surprising that Python doesn't give me more info about where the error occurred. Instead, it seems like it is down to the developer - if I replace rsplit with rstrip, the error raised includes text informing that rstrip doesn't take an int.

"foo".rstrip(1).join(3) # ignore the fact that rstrip doesn't return a list
# raises `TypeError: rstrip arg must be None or str`

I would have expected either a top-hat pointing to the method in question:

    "foo".rsplit(1).join(3)
                 ^error here                           <-- Here
TypeError: must be str or None, not int

Or a more explicit error message:

  File "test.py", line 1, in <module>, in str.rsplit() <-- Here
    "foo".rsplit(1).join(3)
TypeError: must be str or None, not int

Why is it that Python doesn't (or isn't able to) give such error messages?

TomNorway
  • 2,584
  • 1
  • 19
  • 26
  • This annoys me as well. I can only assume it is an oversight. – quamrana Jan 14 '21 at 17:18
  • 1
    Because the cpython byte code does not include the col_offset. Thus compiler only knows about the line_no.(and not the offset) – 1v3m Jan 14 '21 at 17:21
  • Since CPython can't tell you the exact line function call that's erroring in a chain of calls, you can instead get the exact line of the error by breaking up the chain: `foo = "foo"; split_line = foo.rsplit(1); joined_line = split_line.join(3)`. While that code is more verbose, it's potentially more readable, and has the benefit of showing you exactly where any errors happened. – Random Davis Jan 14 '21 at 17:31

0 Answers0