Skip to content

Commit

Permalink
refactor: pure intersection and union of compound paths
Browse files Browse the repository at this point in the history
  • Loading branch information
jg-rp committed Jul 18, 2023
1 parent 9884a71 commit 317d462
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Version 0.9.0 (unreleased)

**Breaking Changes**

- `CompoundJSONPath` instances are no longer updated in-place when using `.union()` and `.intersection()`. Instead, a new `CompoundJSONPath` is returned. `CompoundJSONPath.paths` is now a tuple instead of a list.

**Fixes**

- Fixed a bug with the parsing of JSON Pointers. When given an arbitrary string without slashes, `JSONPointer` would resolve to the document root. The empty string is the only valid pointer that should resolve to the document root. We now raise a `JSONPointerError` in such cases. See [#27](https://github.com/jg-rp/python-jsonpath/issues/27).
Expand Down
4 changes: 2 additions & 2 deletions jsonpath/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,15 @@ def compile(self, path: str) -> Union[JSONPath, CompoundJSONPath]: # noqa: A003

if stream.current.kind == TOKEN_UNION:
stream.next_token()
_path.union(
_path = _path.union(
JSONPath(
env=self,
selectors=self.parser.parse(stream),
)
)
elif stream.current.kind == TOKEN_INTERSECTION:
stream.next_token()
_path.intersection(
_path = _path.intersection(
JSONPath(
env=self,
selectors=self.parser.parse(stream),
Expand Down
21 changes: 14 additions & 7 deletions jsonpath/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,10 +223,11 @@ def __init__(
*,
env: JSONPathEnvironment,
path: Union[JSONPath, CompoundJSONPath],
paths: Iterable[Tuple[str, JSONPath]] = (),
) -> None:
self.env = env
self.path = path
self.paths: List[Tuple[(str, JSONPath)]] = []
self.paths = tuple(paths)

def __str__(self) -> str:
buf: List[str] = [str(self.path)]
Expand Down Expand Up @@ -381,14 +382,20 @@ async def finditer_async(
return matches

def union(self, path: JSONPath) -> CompoundJSONPath:
"""In-place union of this path and another path."""
self.paths.append((self.env.union_token, path))
return self
"""Union of this path and another path."""
return self.__class__(
env=self.env,
path=self.path,
paths=self.paths + ((self.env.union_token, path),),
)

def intersection(self, path: JSONPath) -> CompoundJSONPath:
"""In-place intersection of this path and another path."""
self.paths.append((self.env.intersection_token, path))
return self
"""Intersection of this path and another path."""
return self.__class__(
env=self.env,
path=self.path,
paths=self.paths + ((self.env.intersection_token, path),),
)


T = TypeVar("T")
Expand Down

0 comments on commit 317d462

Please sign in to comment.