From db1e18591333fa72c30fac3b7dfc7ef175612578 Mon Sep 17 00:00:00 2001 From: Julian Berman Date: Wed, 15 Mar 2023 14:42:11 -0400 Subject: flake8 -> ruff, a mostly painless affair. --- jsonschema/__init__.py | 18 +++++++++++++++++- jsonschema/__main__.py | 3 +++ jsonschema/_format.py | 8 +++----- jsonschema/_legacy_validators.py | 2 +- jsonschema/_types.py | 13 ++++++------- jsonschema/exceptions.py | 8 ++------ jsonschema/protocols.py | 2 +- jsonschema/tests/test_jsonschema_test_suite.py | 2 +- jsonschema/tests/test_validators.py | 6 +++--- jsonschema/validators.py | 13 ++++--------- 10 files changed, 41 insertions(+), 34 deletions(-) (limited to 'jsonschema') diff --git a/jsonschema/__init__.py b/jsonschema/__init__.py index ad7affc..efa59f4 100644 --- a/jsonschema/__init__.py +++ b/jsonschema/__init__.py @@ -1,5 +1,5 @@ """ -An implementation of JSON Schema for Python +An implementation of JSON Schema for Python. The main functionality is provided by the validator classes for each of the supported JSON Schema versions. @@ -98,3 +98,19 @@ def __getattr__(name): return ValidatorForFormat.FORMAT_CHECKER raise AttributeError(f"module {__name__} has no attribute {name}") + + +__all__ = [ + "Draft201909Validator", + "Draft202012Validator", + "Draft3Validator", + "Draft4Validator", + "Draft6Validator", + "Draft7Validator", + "FormatChecker", + "SchemaError", + "TypeChecker", + "ValidationError", + "Validator", + "validate", +] diff --git a/jsonschema/__main__.py b/jsonschema/__main__.py index fdc21e2..fb260ae 100644 --- a/jsonschema/__main__.py +++ b/jsonschema/__main__.py @@ -1,3 +1,6 @@ +""" +The jsonschema CLI is now deprecated in favor of check-jsonschema. +""" from jsonschema.cli import main main() diff --git a/jsonschema/_format.py b/jsonschema/_format.py index 6a7f4a8..d274c5f 100644 --- a/jsonschema/_format.py +++ b/jsonschema/_format.py @@ -51,9 +51,9 @@ class FormatChecker: self.checkers = {k: self.checkers[k] for k in formats} def __repr__(self): - return "".format(sorted(self.checkers)) + return f"" - def checks( + def checks( # noqa: D417,D214,D405 (charliermarsh/ruff#3547) self, format: str, raises: _RaisesType = (), ) -> typing.Callable[[_F], _F]: """ @@ -73,7 +73,7 @@ class FormatChecker: The exception object will be accessible as the `jsonschema.exceptions.ValidationError.cause` attribute of the resulting validation error. - """ + """ # noqa: D417,D214,D405 (charliermarsh/ruff#3547) def _checks(func: _F) -> _F: self.checkers[format] = (func, raises) @@ -126,7 +126,6 @@ class FormatChecker: if the instance does not conform to ``format`` """ - if format not in self.checkers: return @@ -157,7 +156,6 @@ class FormatChecker: bool: whether it conformed """ - try: self.check(instance, format) except FormatError: diff --git a/jsonschema/_legacy_validators.py b/jsonschema/_legacy_validators.py index 9a211f3..a338624 100644 --- a/jsonschema/_legacy_validators.py +++ b/jsonschema/_legacy_validators.py @@ -222,7 +222,7 @@ def recursiveRef(validator, recursiveRef, instance, schema): def find_evaluated_item_indexes_by_schema(validator, instance, schema): """ - Get all indexes of items that get evaluated under the current schema + Get all indexes of items that get evaluated under the current schema. Covers all keywords related to unevaluatedItems: items, prefixItems, if, then, else, contains, unevaluatedItems, allOf, oneOf, anyOf diff --git a/jsonschema/_types.py b/jsonschema/_types.py index 9f8dfa0..d142810 100644 --- a/jsonschema/_types.py +++ b/jsonschema/_types.py @@ -14,8 +14,8 @@ from jsonschema.exceptions import UndefinedTypeCheck # the concrete type of a type checker mapping # this "do nothing" wrapper presents the correct information to mypy def _typed_map_converter( - init_val: Mapping[str, Callable[["TypeChecker", Any], bool]], -) -> HashTrieMap[str, Callable[["TypeChecker", Any], bool]]: + init_val: Mapping[str, Callable[[TypeChecker, Any], bool]], +) -> HashTrieMap[str, Callable[[TypeChecker, Any], bool]]: return HashTrieMap.convert(init_val) @@ -79,7 +79,7 @@ class TypeChecker: """ _type_checkers: HashTrieMap[ - str, Callable[["TypeChecker", Any], bool], + str, Callable[[TypeChecker, Any], bool], ] = attr.ib( default=HashTrieMap(), converter=_typed_map_converter, @@ -116,7 +116,7 @@ class TypeChecker: return fn(self, instance) - def redefine(self, type: str, fn) -> "TypeChecker": + def redefine(self, type: str, fn) -> TypeChecker: """ Produce a new checker with the given type redefined. @@ -135,7 +135,7 @@ class TypeChecker: """ return self.redefine_many({type: fn}) - def redefine_many(self, definitions=()) -> "TypeChecker": + def redefine_many(self, definitions=()) -> TypeChecker: """ Produce a new checker with the given types redefined. @@ -148,7 +148,7 @@ class TypeChecker: type_checkers = self._type_checkers.update(definitions) return attr.evolve(self, type_checkers=type_checkers) - def remove(self, *types) -> "TypeChecker": + def remove(self, *types) -> TypeChecker: """ Produce a new checker with the given types forgotten. @@ -164,7 +164,6 @@ class TypeChecker: if any given type is unknown to this object """ - type_checkers = self._type_checkers for each in types: try: diff --git a/jsonschema/exceptions.py b/jsonschema/exceptions.py index 5e88d74..d1ee50a 100644 --- a/jsonschema/exceptions.py +++ b/jsonschema/exceptions.py @@ -51,7 +51,7 @@ class _Error(Exception): parent=None, type_checker=_unset, ): - super(_Error, self).__init__( + super().__init__( message, validator, path, @@ -252,7 +252,7 @@ class FormatError(Exception): """ def __init__(self, message, cause=None): - super(FormatError, self).__init__(message, cause) + super().__init__(message, cause) self.message = message self.cause = self.__cause__ = cause @@ -283,7 +283,6 @@ class ErrorTree: """ Check whether ``instance[index]`` has any errors. """ - return index in self._contents def __getitem__(self, index): @@ -295,7 +294,6 @@ class ErrorTree: by ``instance.__getitem__`` will be propagated (usually this is some subclass of `LookupError`. """ - if self._instance is not _unset and index not in self: self._instance[index] return self._contents[index] @@ -310,7 +308,6 @@ class ErrorTree: """ Iterate (non-recursively) over the indices in the instance with errors. """ - return iter(self._contents) def __len__(self): @@ -329,7 +326,6 @@ class ErrorTree: """ The total number of errors in the entire tree, including children. """ - child_errors = sum(len(tree) for _, tree in self._contents.items()) return len(self.errors) + child_errors diff --git a/jsonschema/protocols.py b/jsonschema/protocols.py index f324ea1..4ad43e7 100644 --- a/jsonschema/protocols.py +++ b/jsonschema/protocols.py @@ -206,7 +206,7 @@ class Validator(Protocol): ValidationError: [2, 3, 4] is too long """ - def evolve(self, **kwargs) -> "Validator": + def evolve(self, **kwargs) -> Validator: """ Create a new validator like this one, but with given changes. diff --git a/jsonschema/tests/test_jsonschema_test_suite.py b/jsonschema/tests/test_jsonschema_test_suite.py index fd2c499..9c63714 100644 --- a/jsonschema/tests/test_jsonschema_test_suite.py +++ b/jsonschema/tests/test_jsonschema_test_suite.py @@ -39,7 +39,7 @@ def missing_format(Validator): ): return - return "Format checker {0!r} not found.".format(schema["format"]) + return f"Format checker {schema['format']!r} not found." return missing_format diff --git a/jsonschema/tests/test_validators.py b/jsonschema/tests/test_validators.py index 6a5756b..8afdbe4 100644 --- a/jsonschema/tests/test_validators.py +++ b/jsonschema/tests/test_validators.py @@ -1522,7 +1522,7 @@ class MetaSchemaTestsMixin: ) -class ValidatorTestMixin(MetaSchemaTestsMixin, object): +class ValidatorTestMixin(MetaSchemaTestsMixin): def test_it_implements_the_validator_protocol(self): self.assertIsInstance(self.Validator({}), protocols.Validator) @@ -1632,7 +1632,7 @@ class ValidatorTestMixin(MetaSchemaTestsMixin, object): elif value == "bad": raise bad else: # pragma: no cover - self.fail("What is {}? [Baby Don't Hurt Me]".format(value)) + self.fail(f"What is {value}? [Baby Don't Hurt Me]") validator = self.Validator( {"format": "foo"}, format_checker=checker, @@ -2201,7 +2201,7 @@ class TestRefResolver(TestCase): self.addCleanup(os.remove, tempf.name) json.dump({"foo": "bar"}, tempf) - ref = "file://{}#foo".format(pathname2url(tempf.name)) + ref = f"file://{pathname2url(tempf.name)}#foo" with self.resolver.resolving(ref) as resolved: self.assertEqual(resolved, "bar") diff --git a/jsonschema/validators.py b/jsonschema/validators.py index ae4e921..5487b84 100644 --- a/jsonschema/validators.py +++ b/jsonschema/validators.py @@ -518,7 +518,6 @@ def extend( likely be made before modifying it, in order to not affect the old validator. """ - all_validators = dict(validator.VALIDATORS) all_validators.update(validators) @@ -892,7 +891,7 @@ class _RefResolver: self._remote_cache = remote_cache @classmethod - def from_schema( + def from_schema( # noqa: D417 cls, schema, id_of=referencing.jsonschema.DRAFT202012.id_of, @@ -912,7 +911,6 @@ class _RefResolver: `_RefResolver` """ - return cls(base_uri=id_of(schema) or "", referrer=schema, *args, **kwargs) # noqa: B026, E501 def push_scope(self, scope): @@ -992,7 +990,6 @@ class _RefResolver: The reference to resolve """ - url, resolved = self.resolve(ref) self.push_scope(url) try: @@ -1003,7 +1000,7 @@ class _RefResolver: def _find_in_referrer(self, key): return self._get_subschemas_cache()[key] - @lru_cache() # noqa: B019 + @lru_cache # noqa: B019 def _get_subschemas_cache(self): cache = {key: [] for key in _SUBSCHEMAS_KEYWORDS} for keyword, subschema in _search_schema( @@ -1012,7 +1009,7 @@ class _RefResolver: cache[keyword].append(subschema) return cache - @lru_cache() # noqa: B019 + @lru_cache # noqa: B019 def _find_in_subschemas(self, url): subschemas = self._get_subschemas_cache()["$id"] if not subschemas: @@ -1073,7 +1070,6 @@ class _RefResolver: a URI fragment to resolve within it """ - fragment = fragment.lstrip("/") if not fragment: @@ -1196,7 +1192,7 @@ def _search_schema(schema, matcher): values.extendleft(value.values()) -def validate(instance, schema, cls=None, *args, **kwargs): +def validate(instance, schema, cls=None, *args, **kwargs): # noqa: D417 """ Validate an instance under the given schema. @@ -1323,7 +1319,6 @@ def validator_for(schema, default=_UNSET): recommended. """ - DefaultValidator = _LATEST_VERSION if default is _UNSET else default if schema is True or schema is False or "$schema" not in schema: -- cgit v1.2.1