Improve instantiate
handling of exceptions raised by user code
#1916
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.
This PR fixes a bug that arises when
instantiate
is invoked on a callable that raises a custom exception that has a non-standard signature.Background info about the bug:
This PR closes #1911.
A call to
instantiate({"_target_": target_callable, **kwargs})
works by locating thetarget_callable
and calling it on the given arguments**kwargs
.The call to
target_callable
is performed inside of thehydra._internal.instantiate._instantiate2._call_target
function:This
_call_target
function has atry
/except
block that catches exceptions that might be raisd by thetarget_callable
.In the
_call_target
function'sexcept
block, another exception is raised with an error message giving context about the exception. The exception raised in theexcept
block is of the same type as the exception that was originally caught.This is problematic because we must assume that the exception class
type(e)
can be called with one argument; we are making the assumption here thattype(e).__init__
accepts a string error message as it's first and only argument.This assumption fails if the user's code raises a custom exception whose
__init__
function takes a non-standard number of arguments (as was the case in bug report #1911).Proposed Changes
This PR fixes the reported bug by not raising an exception of
type(e)
if something goes wrong with the call to_target_
.Instead, an instance of
hydra.errors.InstantiationException
is raised frome
(a lá exception chaining).Since this PR changes the type of exception that will be raised if user code throws an exception, it should be considered an API change.
Commits:
I'm not planning to merge this PR until after #1905 and #1915 are finished, as those PRs also touch code related to
instantiate
.