python-jsonschema / jsonschema

An implementation of the JSON Schema specification for Python
https://python-jsonschema.readthedocs.io
MIT License
4.61k stars 581 forks source link

Preserve $ref history. #1144

Closed atsuoishimoto closed 1 year ago

atsuoishimoto commented 1 year ago

In large schemas, understanding which $ref is being referenced when an error occurs can be helpful in debugging. We used to refer to the history of $ref with code like this:

for error in validator.iter_errors(instance):
    print(validator.resolver._scopes_stack)
    print(error)

However, with the current version of jsonschema, validator.resolver is deprecated, and it will be not possible to refer to it.

In this PR, I have made changes so that the history of $ref is recorded in the exception object when an error occurs, and the $ref from the root to the part where the error occurred can be referred to with error.refs. I believe this feature will be useful not only for us, but for many users as well.

Julian commented 1 year ago

Your original code clearly touched something private :)

But for this one, I'm willing to consider such a thing, especially given it's required to support #1008, but not precisely in his way.

We'd also need to handle $dynamicRef and $recursiveRef, so some extra thought is needed.

But the objects used within the referencing library were written partially to support this (referencing's Resolver.dynamic_scope essentially contains this information).

I'm going to close this PR given the above but please open an issue and we can discuss some other way to do this.

atsuoishimoto commented 1 year ago

Thank you for the comment!

I filed the #1146. Thanks!