jsonschema icon indicating copy to clipboard operation
jsonschema copied to clipboard

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

Open candleindark opened this issue 11 months ago • 2 comments

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.

candleindark avatar Jan 22 '25 06:01 candleindark

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 avatar Jan 28 '25 09:01 Julian

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

candleindark avatar Jan 28 '25 20:01 candleindark