bpo-39865: Don't lose exception context when __getattr__ is present #19303
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When a class has a
__getattr__
hook, it attempts to retrieve the attribute (e.g through a descriptor or the__dict__
). If this initial attempt fails withAttributeError
then a fallback is attempted on__getattr__
. In turn, if the__getattr__
raises anotherAttributeError
, then the original exception that caused the fallback is lost. This PR attempts to surface that information to avoid subtle bugs that might be caused by this.The motivating example for this, as taken from the test is:
In this case, this class supports
a.foo
through a descriptor/property but has a bug in it. Previously attempting to accessa.foo
would lead to this traceback:This masks the original exception that caused the lookup to be delegated to
__getattr__
. However with the right cause set, the error message now looks like:which makes the real root cause of the bug a lot easier to diagnose. There's also external reason to believe that this might be a problem:
The code to set the cause could definitely use a helper in the
PyErr_
namespace. It's pretty ugly as it stands now.https://bugs.python.org/issue39865