How do you use co_positions (PEP 657)?

v3.11 introduced fine grained errors (FGEs), with positional information of the underlying code in codeobject.co_positions(). These FGEs are not produced with exceptions occurring during REPL interaction. But co_positions() is indeed set in this case.

The question is, how do you make use of co_positions()? There is traceback.tb_lasti, which seem like it would be an index into tb_frame.f_code.co_positions(), but this doesn’t seem to match up. What am I missing?

Update: the error position within he line can apparently be computed using:

list(t.tb_frame.f_code.co_positions())[t.tb_lasti // 2]

I wonder if that’s always valid, and also how to compute the context (~~~) vs. error site (^^^) regions?

co_positions is used by the internal builtin excepthook function, which is the initial value of sys.excepthook (which should never be changed) and sys.excepthook, which is called by the REPL and which users can change to alter exception handling. I am also curious about the context region.

1 Like

It seems like there is some custom AST examination, with two hard-coded cases: binary operators and subscripts. It would be nice if the results of this were exposed to the python API.

1 Like