Handle import errors more cleanly #226
Merged
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 uses a WrapValidator to improve the handling of errors in an ImportString.
The problem, identified in #222, is that
TypeErrorandValueErrorare treated specially bypydantic. This means that if either of those exceptions are raised during module import, we get a confusing validation error.My wrap validator ensures that we get either a sensible import-related error (e.g. module not found, name not found in module) or a single clear error stating that an error occurred during module import.
This does not dump a traceback, because doing so during validation tends to lead to very confusing messages. However, it should make it obvious that the problem is an unimportable module, and point someone in the right direction.
Had this been implemented last week, I hope it might have saved @julianstirling some head-scratching.
For example:
This does not come across quite as nicely if we use the shorthand:
The first error is due to the way
pydantichandles union types. It might be possible to improve on that, though I'm not 100% sure how - possibly by annotating the union, rather than just the ImportString.