Skip to content

Commit 46ce03e

Browse files
committed
pylint inspired cleanups
Use single quotes instead of backticks in error messages for consistency
1 parent f48e623 commit 46ce03e

16 files changed

+268
-330
lines changed

schema_salad/avro/schema.py

Lines changed: 18 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def __init__(self, atype: str, other_props: Optional[PropsType] = None) -> None:
100100
raise SchemaParseException(
101101
f"Schema type {atype!r} must be a string, was {type(atype)!r}."
102102
)
103-
elif atype not in VALID_TYPES:
103+
if atype not in VALID_TYPES:
104104
fail_msg = f"{atype} is not a valid type."
105105
raise SchemaParseException(fail_msg)
106106

@@ -177,8 +177,7 @@ def get_space(self) -> Optional[str]:
177177

178178
if self._full.find(".") > 0:
179179
return self._full.rsplit(".", 1)[0]
180-
else:
181-
return None
180+
return None
182181

183182

184183
class Names:
@@ -215,10 +214,10 @@ def add_name(
215214
if to_add.fullname in VALID_TYPES:
216215
fail_msg = f"{to_add.fullname} is a reserved type name."
217216
raise SchemaParseException(fail_msg)
218-
elif to_add.fullname in self.names:
217+
if to_add.fullname in self.names:
219218
fail_msg = f"The name {to_add.fullname!r} is already in use."
220219
raise SchemaParseException(fail_msg)
221-
elif to_add.fullname is None:
220+
if to_add.fullname is None:
222221
fail_msg = f"{to_add.fullname} is missing, but this is impossible."
223222
raise SchemaParseException(fail_msg)
224223

@@ -240,9 +239,9 @@ def __init__(
240239
# Ensure valid ctor args
241240
if not name:
242241
raise SchemaParseException("Named Schemas must have a non-empty name.")
243-
elif not isinstance(name, str):
242+
if not isinstance(name, str):
244243
raise SchemaParseException("The name property must be a string.")
245-
elif namespace is not None and not isinstance(namespace, str):
244+
if namespace is not None and not isinstance(namespace, str):
246245
raise SchemaParseException("The namespace property must be a string.")
247246
if names is None:
248247
raise SchemaParseException("Must provide Names.")
@@ -284,10 +283,10 @@ def __init__(
284283
if not name:
285284
fail_msg = "Fields must have a non-empty name."
286285
raise SchemaParseException(fail_msg)
287-
elif not isinstance(name, str):
286+
if not isinstance(name, str):
288287
fail_msg = "The name property must be a string." # type: ignore[unreachable]
289288
raise SchemaParseException(fail_msg)
290-
elif order is not None and order not in VALID_FIELD_SORT_ORDERS:
289+
if order is not None and order not in VALID_FIELD_SORT_ORDERS:
291290
fail_msg = f"The order property {order} is not valid."
292291
raise SchemaParseException(fail_msg)
293292

@@ -365,9 +364,9 @@ def __init__(
365364
# Ensure valid ctor args
366365
if not isinstance(symbols, list):
367366
raise AvroException("Enum Schema requires a JSON array for the symbols property.")
368-
elif False in [isinstance(s, str) for s in symbols]:
367+
if False in [isinstance(s, str) for s in symbols]:
369368
raise AvroException("Enum Schema requires all symbols to be JSON strings.")
370-
elif len(set(symbols)) < len(symbols):
369+
if len(set(symbols)) < len(symbols):
371370
raise AvroException(f"Duplicate symbol: {symbols}")
372371

373372
# Call parent ctor
@@ -457,10 +456,9 @@ def __init__(
457456
and new_schema.type in [schema.type for schema in schema_objects]
458457
):
459458
raise SchemaParseException(f"{new_schema.type} type already in Union")
460-
elif new_schema.type == "union":
459+
if new_schema.type == "union":
461460
raise SchemaParseException("Unions cannot contain other unions.")
462-
else:
463-
schema_objects.append(new_schema)
461+
schema_objects.append(new_schema)
464462
self._schemas = schema_objects
465463

466464
# read-only properties
@@ -490,10 +488,9 @@ def make_field_objects(field_data: List[PropsType], names: Names) -> List[Field]
490488
if not (order is None or isinstance(order, str)):
491489
raise SchemaParseException('"order" must be a string or None')
492490
doc = field.get("doc")
493-
if not (doc is None or isinstance(doc, str) or isinstance(doc, list)):
491+
if not (doc is None or isinstance(doc, (list, str))):
494492
raise SchemaParseException('"doc" must be a string, list of strings, or None')
495-
else:
496-
doc = cast(Union[str, List[str], None], doc)
493+
doc = cast(Union[str, List[str], None], doc)
497494
other_props = get_other_props(field, FIELD_RESERVED_PROPS)
498495
new_field = Field(atype, name, has_default, default, order, names, doc, other_props)
499496
parsed_fields[new_field.name] = field
@@ -583,7 +580,7 @@ def make_avsc_object(json_data: JsonDataType, names: Optional[Names] = None) ->
583580
raise SchemaParseException(
584581
f'"namespace" for type {atype} must be a string or None: {json_data}'
585582
)
586-
if not (doc is None or isinstance(doc, str) or isinstance(doc, list)):
583+
if not (doc is None or isinstance(doc, (str, list))):
587584
raise SchemaParseException(
588585
f'"doc" for type {atype} must be a string, '
589586
f"a list of strings, or None: {json_data}"
@@ -594,19 +591,15 @@ def make_avsc_object(json_data: JsonDataType, names: Optional[Names] = None) ->
594591
raise SchemaParseException(
595592
f'"symbols" for type enum must be a list of strings: {json_data}'
596593
)
597-
else:
598-
symbols = cast(List[str], symbols)
594+
symbols = cast(List[str], symbols)
599595
return EnumSchema(name, namespace, symbols, names, doc, other_props)
600596
if atype in ["record", "error"]:
601597
fields = json_data.get("fields", [])
602598
if not isinstance(fields, list):
603599
raise SchemaParseException(
604-
'"fields" for type {} must be a list of mappings: {}'.format(
605-
atype, json_data
606-
)
600+
f'"fields" for type {atype} must be a list of mappings: {json_data}'
607601
)
608-
else:
609-
fields = cast(List[PropsType], fields)
602+
fields = cast(List[PropsType], fields)
610603
return RecordSchema(name, namespace, fields, names, atype, doc, other_props)
611604
raise SchemaParseException(f"Unknown Named Type: {atype}")
612605
if atype in VALID_TYPES:

schema_salad/codegen.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def codegen(
5757
else ".".join(list(reversed(sp.netloc.split("."))) + sp.path.strip("/").split("/"))
5858
)
5959
info = parser_info or pkg
60-
if lang == "python" or lang == "cpp" or lang == "dlang":
60+
if lang in set(["python", "cpp", "dlang"]):
6161
if target:
6262
dest: Union[TextIOWrapper, TextIO] = open(target, mode="w", encoding="utf-8")
6363
else:
@@ -72,7 +72,7 @@ def codegen(
7272
)
7373
gen.parse(j)
7474
return
75-
elif lang == "dlang":
75+
if lang == "dlang":
7676
gen = DlangCodeGen(
7777
base,
7878
dest,
@@ -83,8 +83,7 @@ def codegen(
8383
)
8484
gen.parse(j)
8585
return
86-
else:
87-
gen = PythonCodeGen(dest, copyright=copyright, parser_info=info)
86+
gen = PythonCodeGen(dest, copyright=copyright, parser_info=info)
8887

8988
elif lang == "java":
9089
gen = JavaCodeGen(

schema_salad/exceptions.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def with_sourceline(self, sl: Optional[SourceLine]) -> "SchemaSaladException":
7373
return self
7474

7575
def leaves(self) -> List["SchemaSaladException"]:
76-
if len(self.children):
76+
if len(self.children) > 0:
7777
return sum((c.leaves() for c in self.children), [])
7878
if len(self.message):
7979
return [self]
@@ -93,7 +93,7 @@ def prefix(self) -> str:
9393
def summary(self, level: int = 0, with_bullet: bool = False) -> str:
9494
indent_per_level = 2
9595
spaces = (level * indent_per_level) * " "
96-
bullet = self.bullet + " " if len(self.bullet) and with_bullet else ""
96+
bullet = self.bullet + " " if len(self.bullet) > 0 and with_bullet else ""
9797
return f"{self.prefix()}{spaces}{bullet}{self.message}"
9898

9999
def __str__(self) -> str:
@@ -108,8 +108,7 @@ def pretty_str(self, level: int = 0) -> str:
108108
ret = "\n".join(e for e in my_summary + [c.pretty_str(next_level) for c in self.children])
109109
if level == 0:
110110
return strip_duplicated_lineno(reflow_all(ret))
111-
else:
112-
return ret
111+
return ret
113112

114113

115114
class SchemaException(SchemaSaladException):

schema_salad/fetcher.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,10 @@ class Fetcher(ABC):
2323
@abstractmethod
2424
def fetch_text(self, url: str, content_types: Optional[List[str]] = None) -> str:
2525
"""Retrieve the given resource as a string."""
26-
...
2726

2827
@abstractmethod
2928
def check_exists(self, url: str) -> bool:
3029
"""Check if the given resource exists."""
31-
...
3230

3331
@abstractmethod
3432
def urljoin(self, base_url: str, url: str) -> str:
@@ -82,8 +80,10 @@ def fetch_text(self, url: str, content_types: Optional[List[str]] = None) -> str
8280
content_type = resp.headers["content-type"].split(";")[:1][0]
8381
if content_type not in content_types:
8482
_logger.warning(
85-
f"While fetching {url}, got content-type of "
86-
f"{content_type!r}. Expected one of {content_types}."
83+
"While fetching %s, got content-type of %r. Expected one of %s.",
84+
url,
85+
content_type,
86+
content_types,
8787
)
8888
return resp.text
8989
if scheme == "file":
@@ -101,8 +101,7 @@ def fetch_text(self, url: str, content_types: Optional[List[str]] = None) -> str
101101
except OSError as err:
102102
if err.filename == path:
103103
raise ValidationException(str(err)) from err
104-
else:
105-
raise ValidationException(f"Error reading {url}: {err}") from err
104+
raise ValidationException(f"Error reading {url}: {err}") from err
106105
raise ValidationException(f"Unsupported scheme in url: {url}")
107106

108107
def check_exists(self, url: str) -> bool:

schema_salad/jsonld_context.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,8 @@ def process_type(
116116

117117
if context.get(recordname, predicate) != predicate:
118118
raise SchemaException(
119-
"Predicate collision on '{}', '{}' != '{}'".format(
120-
recordname, context[recordname], predicate
121-
)
119+
f"Predicate collision on {recordname!r}, "
120+
f"{context[recordname]!r} != {predicate!r}"
122121
)
123122

124123
if not recordname:

schema_salad/main.py

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from .ref_resolver import Loader, file_uri
2121
from .utils import json_dump, stdout
2222

23-
if int(rdflib_version.split(".")[0]) < 6:
23+
if int(rdflib_version.split(".", maxsplit=1)[0]) < 6:
2424
register("json-ld", Parser, "rdflib_jsonld.parser", "JsonLDParser")
2525
_logger = logging.getLogger("salad")
2626

@@ -226,8 +226,7 @@ def main(argsl: Optional[List[str]] = None) -> int:
226226
if args.version:
227227
print(f"{sys.argv[0]} Current version: {pkg[0].version}")
228228
return 0
229-
else:
230-
_logger.info("%s Current version: %s", sys.argv[0], pkg[0].version)
229+
_logger.info("%s Current version: %s", sys.argv[0], pkg[0].version)
231230

232231
# Get the metaschema to validate the schema
233232
metaschema_names, metaschema_doc, metaschema_loader = schema.get_metaschema()
@@ -243,20 +242,20 @@ def main(argsl: Optional[List[str]] = None) -> int:
243242
schema_doc, schema_metadata = metaschema_loader.resolve_all(schema_raw_doc, schema_uri)
244243
except ValidationException as e:
245244
_logger.error(
246-
"Schema `%s` failed link checking:\n%s",
245+
"Schema %r failed link checking:\n%s",
247246
args.schema,
248247
str(e),
249-
exc_info=(True if args.debug else False),
248+
exc_info=bool(args.debug),
250249
)
251250
_logger.debug("Index is %s", list(metaschema_loader.idx.keys()))
252251
_logger.debug("Vocabulary is %s", list(metaschema_loader.vocab.keys()))
253252
return 1
254253
except RuntimeError as e:
255254
_logger.error(
256-
"Schema `%s` read error:\n%s",
255+
"Schema %r read error:\n%s",
257256
args.schema,
258257
str(e),
259-
exc_info=(True if args.debug else False),
258+
exc_info=bool(args.debug),
260259
)
261260
return 1
262261

@@ -287,7 +286,7 @@ def main(argsl: Optional[List[str]] = None) -> int:
287286
try:
288287
schema.validate_doc(metaschema_names, schema_doc, metaschema_loader, args.strict)
289288
except ValidationException as e:
290-
_logger.error("While validating schema `%s`:\n%s", args.schema, str(e))
289+
_logger.error("While validating schema %r:\n%s", args.schema, str(e))
291290
return 1
292291

293292
# Get the json-ld context and RDFS representation from the schema
@@ -324,7 +323,7 @@ def main(argsl: Optional[List[str]] = None) -> int:
324323
avsc_names = schema.make_avro_schema_from_avro(avsc_obj)
325324
except SchemaParseException as err:
326325
_logger.error(
327-
"Schema `%s` error:\n%s",
326+
"Schema %r error:\n%s",
328327
args.schema,
329328
str(err),
330329
exc_info=((type(err), err, None) if args.debug else None),
@@ -333,7 +332,7 @@ def main(argsl: Optional[List[str]] = None) -> int:
333332
json_dump(avsc_obj, fp=sys.stdout, indent=4, default=str)
334333
return 1
335334
else:
336-
_logger.error("Schema `%s` must be a list.", args.schema) # type: ignore[unreachable]
335+
_logger.error("Schema %r must be a list.", args.schema) # type: ignore[unreachable]
337336
return 1
338337

339338
# Optionally print Avro-compatible schema from schema
@@ -366,7 +365,7 @@ def main(argsl: Optional[List[str]] = None) -> int:
366365

367366
# If no document specified, all done.
368367
if not args.document:
369-
print(f"Schema `{args.schema}` is valid")
368+
print(f"Schema {args.schema!r} is valid")
370369
return 0
371370

372371
# Load target document and resolve refs
@@ -378,7 +377,7 @@ def main(argsl: Optional[List[str]] = None) -> int:
378377
except ValidationException as e:
379378
msg = to_one_line_messages(e) if args.print_oneline else str(e)
380379
_logger.error(
381-
"Document `%s` failed validation:\n%s",
380+
"Document %r failed validation:\n%s",
382381
args.document,
383382
msg,
384383
exc_info=args.debug,
@@ -405,23 +404,22 @@ def main(argsl: Optional[List[str]] = None) -> int:
405404
)
406405
except ValidationException as e:
407406
msg2 = to_one_line_messages(e) if args.print_oneline else str(e)
408-
_logger.error(f"While validating document {uri!r}:\n{msg2}")
407+
_logger.error("While validating document %r:\n%s", uri, msg2)
409408
return 1
410409

411410
# Optionally convert the document to RDF
412411
if args.print_rdf:
413412
if isinstance(document, (Mapping, MutableSequence)):
414413
printrdf(uri, document, schema_ctx, args.rdf_serializer)
415414
return 0
416-
else:
417-
print("Document must be a dictionary or list.")
418-
return 1
415+
print("Document must be a dictionary or list.")
416+
return 1
419417

420418
if args.print_metadata:
421419
json_dump(doc_metadata, fp=sys.stdout, indent=4, default=str)
422420
return 0
423421

424-
_logger.info(f"Document {uri!r} is valid")
422+
_logger.info("Document %r is valid", uri)
425423

426424
return 0
427425

0 commit comments

Comments
 (0)