Skip to content

Commit

Permalink
Convert empty node lists to _Nothing_.
Browse files Browse the repository at this point in the history
  • Loading branch information
jg-rp committed Dec 28, 2023
1 parent 5feb71d commit 6436db6
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 6 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Python JSONPath Change Log

## Version 0.10.3 (unreleased)

**Fixes**

- Fixed handling of relative and root queries when used as arguments to filter functions. Previously, when those queries resulted in an empty node list, we were converting them to an empty regular list before passing it to functions that accept _ValueType_ arguments. Now, in such cases, we convert empty node lists to the special result _Nothing_, which is required by the spec.

## Version 0.10.2

**Fixes**
Expand Down
14 changes: 13 additions & 1 deletion jsonpath/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,19 @@ def _unpack_node_lists(
if func.arg_types[idx] != ExpressionType.NODES and isinstance(
arg, NodeList
):
_args.append(arg.values_or_singular())
if len(arg) == 0:
# If the query results in an empty nodelist, the
# argument is the special result Nothing.
_args.append(UNDEFINED)
elif len(arg) == 1:
# If the query results in a nodelist consisting of a
# single node, the argument is the value of the node
_args.append(arg[0].obj)
else:
# This should not be possible as a non-singular query
# would have been rejected when checking function
# well-typedness.
_args.append(arg)
else:
_args.append(arg)
return _args
Expand Down
14 changes: 10 additions & 4 deletions jsonpath/function_extensions/length.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""The standard `length` function extension."""
from collections.abc import Sized
from typing import Optional
from typing import Union

from jsonpath.filter import UNDEFINED
from jsonpath.filter import _Undefined
from jsonpath.function_extensions import ExpressionType
from jsonpath.function_extensions import FilterFunction

Expand All @@ -12,9 +14,13 @@ class Length(FilterFunction):
arg_types = [ExpressionType.VALUE]
return_type = ExpressionType.VALUE

def __call__(self, obj: Sized) -> Optional[int]:
"""Return an object's length, or `None` if the object does not have a length."""
def __call__(self, obj: Sized) -> Union[int, _Undefined]:
"""Return an object's length.
If the object does not have a length, the special _Nothing_ value is
returned.
"""
try:
return len(obj)
except TypeError:
return None
return UNDEFINED
2 changes: 1 addition & 1 deletion tests/cts

0 comments on commit 6436db6

Please sign in to comment.