Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The return of __iter__() and __contains__() change after accessing of an index with no error #1328

Open
candleindark opened this issue Jan 22, 2025 · 2 comments
Labels
Bug Something doesn't work the way it should.

Comments

@candleindark
Copy link

candleindark commented Jan 22, 2025

The following example illustrate that accessing of an index in an ErrorTree object that has no error can added the index to the collection of indices considered having errors.

from jsonschema import Draft202012Validator
from jsonschema.exceptions import ErrorTree

schema = {
    "type" : "array",
    "items" : {"type" : "number", "enum" : [1, 2, 3]},
    "minItems" : 3,
}
instance = ["spam", 2]

v = Draft202012Validator(schema)
for error in sorted(v.iter_errors(instance), key=str):
    print(error.message)

print("\n====================================")
tree = ErrorTree(v.iter_errors(instance))

print(f"correct value of list(tree): {list(tree)}")
"correct value of list(tree): [0]"
print(f"correct value of `1 in tree`: {1 in tree}")
"correct value of `1 in tree`: False"

# Accessing the 1 index changes the iteration of the tree
tree[1]

print("\n ===== after accessing the 1 index of the tree =====")
print(f"incorrect value of list(tree): {list(tree)}")
"incorrect value of list(tree): [0, 1]"
print(f"incorrect value of `1 in tree`: {1 in tree}")
"incorrect value of `1 in tree`: True"

This behavior contradicts with the documentation at https://python-jsonschema.readthedocs.io/en/latest/errors/#errortrees and is a bug.

@Julian
Copy link
Member

Julian commented Jan 28, 2025

Thanks, this looks like a simple misuse of defaultdict -- a PR is welcome if you'd like, otherwise this may be easier to fix when v5 is out as we currently support (deprecated) modification of error trees.

@Julian Julian added the Bug Something doesn't work the way it should. label Jan 28, 2025
@candleindark
Copy link
Author

@Julian I think wait for V5 then. I have no immediate use of this feature. Thanks for the follow up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something doesn't work the way it should.
Projects
None yet
Development

No branches or pull requests

2 participants