Skip to content

Commit a7974cf

Browse files
committed
Lint with Ruff.
1 parent bed21d3 commit a7974cf

26 files changed

Lines changed: 354 additions & 430 deletions

‎.flake8‎

Lines changed: 0 additions & 2 deletions
This file was deleted.

‎README.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ pipx install python-jsonpath
8989

9090
Find all objects in `data` matching the given JSONPath `path`. If data is a string, it will be loaded using `json.loads()` and the default `JSONDecoder`.
9191

92-
Returns a list of matched objects, or an empty list if there were not matches.
92+
Returns a list of matched objects, or an empty list if there were no matches.
9393

9494
### jsonpath.finditer
9595

@@ -103,11 +103,11 @@ Return an iterator yielding a `JSONPathMatch` instance for each match of the `pa
103103

104104
Prepare a path for repeated matching against different data. `jsonpath.findall()` and `jsonpath.finditer()` are convenience functions that call `compile()` for you.
105105

106-
`JSONPath` and `CompoundJSONPath` both have `findall()` and `finditer()` methods that behave the same as `jsonpath.findall()` and `jsonpath.finditer()`, just without taking a path string argument.
106+
`JSONPath` and `CompoundJSONPath` both have `findall()` and `finditer()` methods that behave the same as `jsonpath.findall()` and `jsonpath.finditer()`, just without the path argument.
107107

108108
### async
109109

110-
`findall_async()` and `finditer_async` are async equivalents of `findall()` and `finditer()`. They are used when integrating Python JSONPath with [Python Liquid](https://github.com/jg-rp/liquid) and use Python Liquid's [async protocol](https://jg-rp.github.io/liquid/introduction/async-support).
110+
`findall_async()` and `finditer_async()` are async equivalents of `findall()` and `finditer()`. They are used when integrating Python JSONPath with [Python Liquid](https://github.com/jg-rp/liquid) and use Python Liquid's [async protocol](https://jg-rp.github.io/liquid/introduction/async-support).
111111

112112
### Extra filter context
113113

@@ -119,7 +119,7 @@ Use `#` to query extra filter data, similar to how one might use `@` or `$`.
119119

120120
Python JSONPath's default syntax is an opinionated combination of JSONPath features from existing, popular implementations, and much of the [IETF JSONPath draft](https://datatracker.ietf.org/doc/html/draft-ietf-jsonpath-base-11). If you're already familiar with JSONPath syntax, skip to [notable differences](#notable-differences).
121121

122-
TODO: tree analogy / target document
122+
TODO: tree analogy / target document
123123
TODO: use "node" terminology
124124
TODO: mention JSON and Python equivalency
125125

@@ -235,7 +235,7 @@ Comparison operators include `==`, `!=`, `<`, `>`, `<=` and `>=`. Plus `<>` as a
235235

236236
`&&` and `||` are logical operators, `and` and `or` work too.
237237

238-
`=~` matches the left value with a regular expression literal. Regular expressions use a similar syntax to that found in JavaScript, where the pattern to match is surrounded by slashes, optionally followed by flags.
238+
`=~` matches the left value with a regular expression literal. Regular expressions use a syntax similar to that found in JavaScript, where the pattern to match is surrounded by slashes, optionally followed by flags.
239239

240240
```text
241241
$..products.*[?(@.description =~ /.*trainers/i)]
@@ -263,7 +263,7 @@ And this is a list of areas where we deviate from the [IETF JSONPath draft](http
263263
- Nested filters are not supported.
264264
- When a filter is applied to an object (mapping) value, we do not silently apply that filter to the object's values. See the "Existence of non-singular queries" example in the IETF JSONPath draft.
265265
- `|` is a union operator, where matches from two or more JSONPaths are combined.
266-
- `&` is an intersection operator, where we output matches that exist in two paths.
266+
- `&` is an intersection operator, where we exclude matches that don't exist in both left and right paths.
267267

268268
## License
269269

‎compliance.py‎

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,12 @@
1010
import json
1111
import operator
1212
import unittest
13-
1413
from dataclasses import dataclass
15-
16-
from typing import Any
17-
from typing import List
18-
from typing import Mapping
19-
from typing import Optional
20-
from typing import Sequence
21-
from typing import Union
14+
from typing import Any, List, Mapping, Optional, Sequence, Union
2215

2316
import pytest
24-
import jsonpath
2517

26-
# pylint: disable=missing-function-docstring, missing-class-docstring
18+
import jsonpath
2719

2820

2921
@dataclass
@@ -53,9 +45,8 @@ def cases() -> List[Case]:
5345
def valid_cases() -> List[Case]:
5446
def mangle_filter(case: Case) -> Case:
5547
# XXX: Insert parentheses around filter expression :(
56-
if case.name.startswith("filter"):
57-
if case.selector.count("]") == 1:
58-
case.selector = case.selector.replace("[?", "[?(").replace("]", ")]")
48+
if case.name.startswith("filter") and case.selector.count("]") == 1:
49+
case.selector = case.selector.replace("[?", "[?(").replace("]", ")]")
5950

6051
# XXX: Insert wildcard in front of root :(
6152
if (
@@ -79,7 +70,6 @@ def mangle_filter(case: Case) -> Case:
7970
]
8071

8172

82-
# pylint: disable=redefined-outer-name
8373
@pytest.mark.parametrize("case", valid_cases(), ids=operator.attrgetter("name"))
8474
def test_compliance(case: Case) -> None:
8575
if case.name in SKIP:
@@ -89,4 +79,4 @@ def test_compliance(case: Case) -> None:
8979

9080
test_case = unittest.TestCase()
9181
rv = jsonpath.findall(case.selector, case.document)
92-
test_case.assertCountEqual(rv, case.result)
82+
test_case.assertCountEqual(rv, case.result) # noqa: PT009

‎consensus.py‎

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,18 @@
99
"""
1010
import operator
1111
import unittest
12-
1312
from dataclasses import dataclass
14-
15-
from typing import Any
16-
from typing import Dict
17-
from typing import List
18-
from typing import Mapping
19-
from typing import Optional
20-
from typing import Sequence
21-
from typing import Union
13+
from typing import Any, Dict, List, Mapping, Optional, Sequence, Union
2214

2315
import pytest
24-
25-
from yaml import load
26-
from yaml import CLoader as Loader
16+
from yaml import safe_load
2717

2818
import jsonpath
2919

30-
# pylint: disable=missing-function-docstring, missing-class-docstring
31-
3220

3321
@dataclass
34-
class Query: # pylint: disable=too-many-instance-attributes
35-
id: str
22+
class Query:
23+
id: str # noqa: A003
3624
selector: str
3725
document: Union[Mapping[str, Any], Sequence[Any]]
3826
consensus: Any = None
@@ -71,7 +59,7 @@ def clean_query(query: Dict[str, Any]) -> Dict[str, Any]:
7159

7260
def queries() -> List[Query]:
7361
with open("comparison_regression_suite.yaml", encoding="utf8") as fd:
74-
data = load(fd, Loader=Loader)
62+
data = safe_load(fd)
7563
return [Query(**clean_query(q)) for q in data["queries"]]
7664

7765

@@ -80,11 +68,10 @@ def queries() -> List[Query]:
8068
]
8169

8270

83-
# pylint: disable=redefined-outer-name
8471
@pytest.mark.parametrize("query", QUERIES_WITH_CONSENSUS, ids=operator.attrgetter("id"))
8572
def test_consensus(query: Query) -> None:
8673
if query.id in SKIP:
8774
pytest.skip(reason=SKIP[query.id])
8875
case = unittest.TestCase()
8976
rv = jsonpath.findall(query.selector, query.document)
90-
case.assertCountEqual(rv, query.consensus)
77+
case.assertCountEqual(rv, query.consensus) # noqa: PT009

‎jsonpath/__init__.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
#
33
# SPDX-License-Identifier: MIT
44

5-
from .path import CompoundJSONPath
6-
from .path import JSONPath
75
from .env import JSONPathEnvironment
8-
from .match import JSONPathMatch
96
from .lex import Lexer
7+
from .match import JSONPathMatch
108
from .parse import Parser
9+
from .path import CompoundJSONPath, JSONPath
1110

1211
__all__ = (
1312
"compile",
@@ -30,4 +29,4 @@
3029
finditer = DEFAULT_ENV.finditer
3130
findall_async = DEFAULT_ENV.findall_async
3231
finditer_async = DEFAULT_ENV.finditer_async
33-
compile = DEFAULT_ENV.compile # pylint: disable=redefined-builtin
32+
compile = DEFAULT_ENV.compile # noqa: A001

‎jsonpath/env.py‎

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,30 @@
22
from __future__ import annotations
33

44
import re
5-
65
from collections.abc import Collection
76
from operator import getitem
8-
9-
from typing import AsyncIterable
10-
from typing import Any
11-
from typing import Iterable
12-
from typing import List
13-
from typing import Mapping
14-
from typing import Optional
15-
from typing import Sequence
16-
from typing import Union
7+
from typing import (
8+
TYPE_CHECKING,
9+
Any,
10+
AsyncIterable,
11+
Iterable,
12+
List,
13+
Mapping,
14+
Optional,
15+
Sequence,
16+
Union,
17+
)
1718

1819
from .exceptions import JSONPathSyntaxError
1920
from .filter import UNDEFINED
2021
from .lex import Lexer
21-
from .match import FilterContextVars
22-
from .match import JSONPathMatch
2322
from .parse import Parser
24-
25-
from .path import CompoundJSONPath
26-
from .path import JSONPath
27-
23+
from .path import CompoundJSONPath, JSONPath
2824
from .stream import TokenStream
25+
from .token import TOKEN_EOF, TOKEN_INTERSECTION, TOKEN_UNION
2926

30-
from .token import TOKEN_EOF
31-
from .token import TOKEN_UNION
32-
from .token import TOKEN_INTERSECTION
27+
if TYPE_CHECKING:
28+
from .match import FilterContextVars, JSONPathMatch
3329

3430

3531
class JSONPathEnvironment:
@@ -50,7 +46,7 @@ def __init__(self) -> None:
5046
self.lexer = self.lexer_class(env=self)
5147
self.parser = self.parser_class(env=self)
5248

53-
def compile(self, path: str) -> Union[JSONPath, CompoundJSONPath]:
49+
def compile(self, path: str) -> Union[JSONPath, CompoundJSONPath]: # noqa: A003
5450
"""Prepare an internal representation of a JSONPath string."""
5551
tokens = self.lexer.tokenize(path)
5652
stream = TokenStream(tokens)
@@ -162,7 +158,7 @@ def is_truthy(self, obj: object) -> bool:
162158
return True
163159
return bool(obj)
164160

165-
# pylint: disable=too-many-return-statements, too-many-branches
161+
# ruff: noqa: PLR0912, PLR0911
166162
def compare(self, left: object, operator: str, right: object) -> bool:
167163
"""Object comparison within JSONPath filters."""
168164
if operator == "&&":

‎jsonpath/exceptions.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
"""JSONPath exceptions."""
22
from __future__ import annotations
33

4-
from typing import Optional
5-
from typing import TYPE_CHECKING
4+
from typing import TYPE_CHECKING, Optional
65

76
if TYPE_CHECKING:
87
from .token import Token
@@ -22,7 +21,6 @@ def __str__(self) -> str:
2221
return msg
2322

2423
line, column = self.token.position()
25-
# TODO: give context from source path string
2624
return f"{msg}, line {line}, column {column}"
2725

2826

‎jsonpath/filter.py‎

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,8 @@
11
from __future__ import annotations
22

33
import re
4-
5-
from abc import ABC
6-
from abc import abstractmethod
7-
8-
from typing import Generic
9-
from typing import List
10-
from typing import Mapping
11-
from typing import Pattern
12-
from typing import Sequence
13-
from typing import TypeVar
14-
from typing import TYPE_CHECKING
4+
from abc import ABC, abstractmethod
5+
from typing import TYPE_CHECKING, Generic, List, Mapping, Pattern, Sequence, TypeVar
156

167
from .exceptions import JSONPathTypeError
178

@@ -44,10 +35,10 @@ def __repr__(self) -> str: # pragma: no cover
4435
def __str__(self) -> str: # pragma: no cover
4536
return "nil"
4637

47-
def evaluate(self, context: FilterContext) -> None:
38+
def evaluate(self, _: FilterContext) -> None:
4839
return None
4940

50-
async def evaluate_async(self, context: FilterContext) -> None:
41+
async def evaluate_async(self, _: FilterContext) -> None:
5142
return None
5243

5344

@@ -74,10 +65,10 @@ def __eq__(self, other: object) -> bool:
7465
def __str__(self) -> str:
7566
return "undefined"
7667

77-
def evaluate(self, context: FilterContext) -> object:
68+
def evaluate(self, _: FilterContext) -> object:
7869
return UNDEFINED
7970

80-
async def evaluate_async(self, context: FilterContext) -> object:
71+
async def evaluate_async(self, _: FilterContext) -> object:
8172
return UNDEFINED
8273

8374

@@ -103,11 +94,11 @@ def __eq__(self, other: object) -> bool:
10394
def __hash__(self) -> int:
10495
return hash(self.value)
10596

106-
def evaluate(self, context: FilterContext) -> LITERAL_EXPRESSION_T:
97+
def evaluate(self, _: FilterContext) -> LITERAL_EXPRESSION_T:
10798
""""""
10899
return self.value
109100

110-
async def evaluate_async(self, context: FilterContext) -> LITERAL_EXPRESSION_T:
101+
async def evaluate_async(self, _: FilterContext) -> LITERAL_EXPRESSION_T:
111102
""""""
112103
return self.value
113104

0 commit comments

Comments
 (0)