rich
rich copied to clipboard
[REQUEST] PEP657 error code ranges in tracebacks
Python 3.11 implements code position ranges in tracebacks.
from rich.traceback import install
install(show_locals=True)
data = [
{
"person": {
"friends": [
{"name": "Sally",
"age": 32},
{"name": "Yuri",
"age": 43}
],
"location": "Warsaw, Poland"
}
}
]
print(data[0]["person"]["friends"][2]["name"])
The default exception handler will print the position of the offending error in the traceback:
Traceback (most recent call last):
File "/Users/anthonyshaw/projects/python-3.11-demos/error_messages.py", line 15, in <module>
print(data[0]["person"]["friends"][2]["name"])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range
Rich does not use this data (but still looks very pretty)

IT would be great to get the trace messages with arrows.
Note: TracebackException now has the offset and end_offset attributes which expose the information needed to print the arrows.
https://github.com/python/cpython/blob/3.11/Lib/traceback.py#L852-L864
This is very much a drive-by comment: I wonder if there's Unicode characters that could be used for this.
I'd love to implement this. Not certain how to render it yet. Rich shows a few lines before and after the highlighted line, and I wouldn't want to break that up with the ~~~~~~~^^^ characters.
But there are other ways we could emphasize those error columns, with underline or reverse video perhaps. We can experiment a little.
@darrenburns @DrBenton Any suggestions?
Inline emphasis looks to be a good way to manage this indeed, at least for a first iteration :slightly_smiling_face:
Note: TracebackException now has the offset and end_offset attributes which expose the information needed to print the arrows. https://github.com/python/cpython/blob/3.11/Lib/traceback.py#L852-L864
It seems that the offset and end_offset attributes are set only for SyntaxErrors, if I'm not wrong?
It seems that FrameSummary instances, generated via StackSummary.extract(walk_tb(traceback)) , now have a colno and end_colno attributes, which I guess we could potentially use to report the exact location of the error on the line.
However, in my few tests these 2 attributes' values seem to always be None? :thinking:
For highlighting, may I suggest something similar to what I have shown in https://github.com/Textualize/rich/issues/1829?
We have the ability to highlight additional ranges within Syntax now. So this might be a good point to tackle this.