Separate diagnostic hints from exception messages

Motivation

Built-in error messages have become considerably more detailed.

For example, Python 3.14 gives me this:

>>> [a, b for a, b in ()]
SyntaxError: did you forget parentheses around the comprehension target?
>>> random
NameError: name 'random' is not defined. Did you forget to import 'random'?
>>> tupl
NameError: name 'tupl' is not defined. Did you mean: 'tuple'?
>>> [1, 2 3]
SyntaxError: invalid syntax. Perhaps you forgot a comma?
>>> {1: 2, 3}
SyntaxError: ':' expected after dictionary key

Python 3.15 added further improvements, for example:

>>> [1, 2, 3].push(4)
AttributeError: 'list' object has no attribute 'push'. Did you mean '.append'?
>>> {}.put("a", 1)
AttributeError: 'dict' object has no attribute 'put'. Use d[k] = v.

In my opinion, this is an excellent direction and makes the messages much more helpful. However, I find the way these messages are currently phrased somewhat surprising and inconsistent. I see three main reasons for this:

  1. Mixing errors and hints: The messages tend to combine a description of the actual error with a suggestion about what might help to address it. The suggestions are speculative and often more verbose, which can be distracting.
  2. Phrasing: The suggestions are phrased differently from one message to another. Sometimes they are direct questions (Did you mean x?), sometimes possibilities (Perhaps you forgot y?), and sometimes instructions (Use z.).
  3. Style: Suggestions tend to be phrased as complete sentences, which deviates from the compact style of traditional error messages. In particular, trailing periods and question marks feel a bit out of place.

Proposal

To address this, I would like to propose the following idea:

  1. Establish a convention for composing error messages. For example, stipulate that they should describe the actual error that occurred, without mixing in suggestions, and preferably without trailing periods or question marks.
  2. Provide a way to attach additional diagnostic hints to exceptions, separately from their actual messages. For example, a hints attribute holding zero or more strings could be added to Exception.

REPLs could then display errors like this, for instance:

>>> random
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    random
NameError: name 'random' is not defined
  Hint: consider importing 'random'
>>> {}.put("a", 1)
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    {}.put("a", 1)
    ^^^^^^
AttributeError: 'dict' object has no attribute 'put'
  Hint: use item assignment (d[k] = v)

It would also allow other environments, such as IDEs and applications, to decide whether and how to display these hints.

I am interested in hearing your thoughts. Would this direction be feasible and worth pursuing?

Related discussions

2 Likes

What you want already exists. Hints are added by the default handling of caught exceptions, which involved the default value of sys.excepthook, which adds the hint. I don’t know the details, but look carefully at the following.

>>> try:
...     random
... except Exception as e:
...     e.args[0]
...     hasattr(e, '__notes__')
...     e.add_note('Hint')
...     e.__notes__  # Added by add_note
... 
"name 'random' is not defined"
False
['Hint']

IDLE invokes the default handling via the traceback module, but could customize, as other REPL replacements do.

I’m not convinced separating error and hint adds enough benefit.

Based on which condition would you show or hide the hints? The language and execution environment can’t decide this because they lack context. It could only be a user setting, which should be on by default: Having to know that you can activate additional error hints and needing to rerun to get these would significantly reduce the utility and usability of hints. OTOH I doubt people would care to deactivate hints. In other words str(e) must continue to contain the hints.

So the only advantage would be that you have more structured data, which tooling could use to format the message differently than just str(e) - e.g. separate to new line or color.

Giving users an opportunity to deactivate hints is not really what I’m trying to propose. Sorry for the misunderstanding. Let me clarify: I find hints incredibly useful, and I would love to see more in the language. To allow them to scale without sacrificing consistency, however, I think there should be a better strategy than simply adding them to str(e).

I absolutely agree about the first part: the main advantage would be to expose more structured data about errors. In my opinion, the benefits would go beyond formatting, though. It would allow an arbitrary number of hints to be attached to an exception, while delegating their presentation to the environment. Among other things, I think this would encourage a more consistent presentation of error messages and hints.

For example, consider this hypothetical output:

>>> def fetch():
...     await something()
...     
  File "<python-input-10>", line 2
    await something()
    ^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside async function
  Hint: to use await, declare 'fetch' with 'async def'
  Hint: to call 'something' synchronously, use asyncio.run()

Thanks for bringing that up. I am aware of PEP 678, but I didn’t mention it because its motivation is described as “add[ing] information after the exception was caught.” If you think the mechanism would nevertheless be suitable, great! That would still leave the question of how tooling could distinguish diagnostic hints from arbitrarily added notes, though.