andreasblixt

andreasblixt t1_izo7j6o wrote

For the fun of it, I asked ChatGPT to generate the solution for creating the output above, and it didn't get it 100% but it's a pretty good start! One of my favorite things is how it implicitly got that it should do sorted(line_numbers) because set does not have a defined iteration order, or how it should make the line numbers right-aligned.


Here is some sample code that demonstrates how you can write a Python program that turns a raised exception into the desired output. This code is not complete, but it should give you a good starting point:

import traceback

def turn_exception_into_output():
  try:
    # Code that may raise an exception goes here
    pass
  except Exception as e:
    # Aggregate the lines of code surrounding the trace in a map
    lines = {}

    # Get the traceback object
    tb = traceback.extract_tb(e.__traceback__)

    # Loop through the traceback object
    for t in tb:
      file_name, line_number, _, _ = t

      # Initialize the set of line numbers for this file
      if file_name not in lines:
        lines[file_name] = set()

      # Update the set of line numbers with the range of relevant lines
      lines[file_name].update(range(line_number - 5, line_number + 5))

    # Print the error message
    print("Please explain concisely why this error in my Python code happened:")

    # Print the traceback
    print("\n".join(traceback.format_exception(e.__class__, e, e.__traceback__)))

    # Print the relevant lines of code
    print("\nBased on these lines of code surrounding the trace:")
    for file_name, line_numbers in lines.items():
      print(file_name)
      for line_number in sorted(line_numbers):
        print("{:>3} ...".format(line_number))

To use this code, you would call the turn_exception_into_output function whenever you want to handle an exception and print the desired output. For example:

try:
  # Code that may raise an exception goes here
  pass
except:
  turn_exception_into_output()

You could also use this code as part of a custom exception handler. For example:

import sys

def custom_exception_handler(exception_type, exception, traceback):
  turn_exception_into_output()

# Set the custom exception handler
sys.excepthook = custom_exception_handler

With this code, whenever an unhandled exception is raised, the custom_exception_handler function will be called, which will turn the exception into the desired output.

13

andreasblixt t1_izntugx wrote

Nice! I think its answer would be much more contextual if you made the prompt something like this:

Please explain concisely why this error in my Python code happened:

    Traceback ...
    ...

Based on these lines of code surrounding the trace:

    broken.py
     1 ...
     2 ...
    ...
    11 ...

I would aggregate those lines in a map of file_name: str -> line_numbers: set where you basically do lines["broken.py"].update(range(error_lineno - 5, error_lineno + 5)) (with boundary checking etc ofc) so that you can then aggregate all the relevant lines with context, without overlap.

24