Skip to content

Commit bda4df0

Browse files
authored
Merge pull request #404 from ialarmedalien/ruff_format
Ruff format
2 parents fcf16db + 7615438 commit bda4df0

File tree

147 files changed

+11311
-5847
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

147 files changed

+11311
-5847
lines changed

.github/workflows/main.yaml

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,9 @@ jobs:
3434
- name: Run code format checks
3535
run: tox -e format_check
3636

37-
3837
test:
39-
# TODO: uncomment when ruff format has been run over the codebase
40-
# needs:
41-
# - quality-checks
38+
needs:
39+
- quality-checks
4240
strategy:
4341
fail-fast: false
4442
matrix:

linkml_runtime/__init__.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212
# the version in the code
1313
import importlib.metadata as importlib_metadata
1414

15-
LINKML = CurieNamespace('linkml', 'https://w3id.org/linkml/')
16-
TCCM = CurieNamespace('tccm', 'https://ontologies.r.us/tccm/')
17-
OWL = CurieNamespace('owl', OWL)
18-
RDF = CurieNamespace('rdf', RDF)
19-
RDFS = CurieNamespace('rdfs', RDFS)
20-
SKOS = CurieNamespace('skos', SKOS)
21-
XSD = CurieNamespace('xsd', XSD)
15+
LINKML = CurieNamespace("linkml", "https://w3id.org/linkml/")
16+
TCCM = CurieNamespace("tccm", "https://ontologies.r.us/tccm/")
17+
OWL = CurieNamespace("owl", OWL)
18+
RDF = CurieNamespace("rdf", RDF)
19+
RDFS = CurieNamespace("rdfs", RDFS)
20+
SKOS = CurieNamespace("skos", SKOS)
21+
XSD = CurieNamespace("xsd", XSD)
2222

2323
__version__ = importlib_metadata.version(__name__)
2424

@@ -39,24 +39,28 @@
3939

4040

4141
URI_TO_LOCAL = {
42-
'https://w3id.org/linkml/annotations.yaml': str(LINKML_ANNOTATIONS),
43-
'https://w3id.org/linkml/array.yaml': str(LINKML_ARRAY),
44-
'https://w3id.org/linkml/extensions.yaml': str(LINKML_EXTENSIONS),
45-
'https://w3id.org/linkml/mappings.yaml': str(LINKML_MAPPINGS),
46-
'https://w3id.org/linkml/meta.yaml': str(MAIN_SCHEMA_PATH),
47-
'https://w3id.org/linkml/types.yaml': str(LINKML_TYPES),
48-
'https://w3id.org/linkml/units.yaml': str(LINKML_UNITS),
49-
'https://w3id.org/linkml/validation.yaml': str(LINKML_VALIDATION),
42+
"https://w3id.org/linkml/annotations.yaml": str(LINKML_ANNOTATIONS),
43+
"https://w3id.org/linkml/array.yaml": str(LINKML_ARRAY),
44+
"https://w3id.org/linkml/extensions.yaml": str(LINKML_EXTENSIONS),
45+
"https://w3id.org/linkml/mappings.yaml": str(LINKML_MAPPINGS),
46+
"https://w3id.org/linkml/meta.yaml": str(MAIN_SCHEMA_PATH),
47+
"https://w3id.org/linkml/types.yaml": str(LINKML_TYPES),
48+
"https://w3id.org/linkml/units.yaml": str(LINKML_UNITS),
49+
"https://w3id.org/linkml/validation.yaml": str(LINKML_VALIDATION),
5050
}
5151

52+
5253
class MappingError(ValueError):
5354
"""
5455
An error when mapping elements of a LinkML model to runtime objects
5556
"""
57+
5658
pass
5759

60+
5861
class DataNotFoundError(ValueError):
5962
"""
6063
An error in which data cannot be found
6164
"""
65+
6266
pass

linkml_runtime/dumpers/csv_dumper.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33

44
class CSVDumper(DelimitedFileDumper):
5-
65
@property
76
def delimiter(self):
87
return ","

linkml_runtime/dumpers/delimited_file_dumper.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,20 @@
1616

1717

1818
class DelimitedFileDumper(Dumper, ABC):
19-
2019
@property
2120
@abstractmethod
2221
def delimiter(self):
2322
pass
2423

25-
def dumps(self, element: Union[BaseModel, YAMLRoot],
26-
index_slot: SlotDefinitionName = None,
27-
schema: SchemaDefinition = None,
28-
schemaview: SchemaView = None,
29-
**kwargs) -> str:
30-
""" Return element formatted as CSV lines """
24+
def dumps(
25+
self,
26+
element: Union[BaseModel, YAMLRoot],
27+
index_slot: SlotDefinitionName = None,
28+
schema: SchemaDefinition = None,
29+
schemaview: SchemaView = None,
30+
**kwargs,
31+
) -> str:
32+
"""Return element formatted as CSV lines"""
3133
json_dumper = JSONDumper()
3234
element_j = json.loads(json_dumper.dumps(element))
3335
objs = element_j[index_slot]

linkml_runtime/dumpers/dumper_root.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77

88
class Dumper(ABC):
9-
""" Abstract base class for all dumpers """
9+
"""Abstract base class for all dumpers"""
1010

1111
def dump(self, element: Union[BaseModel, YAMLRoot], to_file: str, **_) -> None:
1212
"""
@@ -15,7 +15,7 @@ def dump(self, element: Union[BaseModel, YAMLRoot], to_file: str, **_) -> None:
1515
:param to_file: file to dump to
1616
:@param _: method specific arguments
1717
"""
18-
with open(to_file, 'w', encoding='UTF-8') as output_file:
18+
with open(to_file, "w", encoding="UTF-8") as output_file:
1919
output_file.write(self.dumps(element, **_))
2020

2121
@abstractmethod

linkml_runtime/dumpers/json_dumper.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515

1616

1717
class JSONDumper(Dumper):
18-
19-
def dump(self, element: Union[BaseModel, YAMLRoot], to_file: str, contexts: CONTEXTS_PARAM_TYPE = None,
20-
**kwargs) -> None:
18+
def dump(
19+
self, element: Union[BaseModel, YAMLRoot], to_file: str, contexts: CONTEXTS_PARAM_TYPE = None, **kwargs
20+
) -> None:
2121
"""
2222
Write element as json to to_file
2323
:param element: LinkML object to be serialized as YAML
@@ -61,12 +61,12 @@ def default(o):
6161
return str(o)
6262
else:
6363
return json.JSONDecoder().decode(o)
64+
6465
if isinstance(element, BaseModel):
6566
element = element.model_dump()
66-
return json.dumps(as_json_object(element, contexts, inject_type=inject_type),
67-
default=default,
68-
ensure_ascii=False,
69-
indent=' ')
67+
return json.dumps(
68+
as_json_object(element, contexts, inject_type=inject_type), default=default, ensure_ascii=False, indent=" "
69+
)
7070

7171
@staticmethod
7272
@deprecated("Use `utils/formatutils/remove_empty_items` instead")
@@ -78,8 +78,9 @@ def remove_empty_items(obj: dict) -> dict:
7878
"""
7979
return formatutils.remove_empty_items(obj, hide_protected_keys=True)
8080

81-
def to_json_object(self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_PARAM_TYPE = None,
82-
inject_type=True) -> JsonObj:
81+
def to_json_object(
82+
self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_PARAM_TYPE = None, inject_type=True
83+
) -> JsonObj:
8384
"""
8485
As dumps(), except returns a JsonObj, not a string
8586

linkml_runtime/dumpers/rdf_dumper.py

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313

1414

1515
class RDFDumper(Dumper):
16-
def as_rdf_graph(self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_PARAM_TYPE, namespaces: CONTEXT_TYPE = None) -> Graph:
16+
def as_rdf_graph(
17+
self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_PARAM_TYPE, namespaces: CONTEXT_TYPE = None
18+
) -> Graph:
1719
"""
1820
Convert element into an RDF graph guided by the context(s) in contexts
1921
:param element: element to represent in RDF
@@ -29,42 +31,49 @@ def as_rdf_graph(self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_P
2931
:return: rdflib Graph containing element
3032
"""
3133
if contexts is None:
32-
raise Exception(f'Must pass in JSON-LD context via contexts parameter')
34+
raise Exception(f"Must pass in JSON-LD context via contexts parameter")
3335
if isinstance(contexts, list):
3436
inp_contexts = [json.loads(hbread(c)) for c in contexts]
3537
else:
3638
inp_contexts = json.loads(hbread(contexts))
3739

3840
from linkml_runtime.dumpers import json_dumper
41+
3942
jsonld_str = json_dumper.dumps(element)
40-
g = Graph().parse(data=jsonld_str, format='json-ld')
41-
#rdf_jsonld = expand()
42-
#g = rdflib_graph_from_pyld_jsonld(rdf_jsonld)
43+
g = Graph().parse(data=jsonld_str, format="json-ld")
44+
# rdf_jsonld = expand()
45+
# g = rdflib_graph_from_pyld_jsonld(rdf_jsonld)
4346

4447
if namespaces is not None:
4548
ns_source = json.loads(hbread(namespaces))
4649
else:
4750
ns_source = inp_contexts
4851

4952
# TODO: make a utility out of this or add it to prefixcommons
50-
if ns_source and '@context' in ns_source:
51-
ns_contexts = ns_source['@context']
53+
if ns_source and "@context" in ns_source:
54+
ns_contexts = ns_source["@context"]
5255
if isinstance(ns_contexts, dict):
5356
ns_contexts = [ns_contexts]
5457
for ns_context in ns_contexts:
5558
if isinstance(ns_context, dict):
5659
for pfx, ns in ns_context.items():
5760
if isinstance(ns, dict):
58-
if '@id' in ns and ns.get('@prefix', False):
59-
ns = ns['@id']
61+
if "@id" in ns and ns.get("@prefix", False):
62+
ns = ns["@id"]
6063
else:
6164
continue
62-
if not pfx.startswith('@'):
65+
if not pfx.startswith("@"):
6366
g.bind(pfx, ns)
6467

6568
return g
6669

67-
def dump(self, element: Union[BaseModel, YAMLRoot], to_file: str, contexts: CONTEXTS_PARAM_TYPE = None, fmt: str = 'turtle') -> None:
70+
def dump(
71+
self,
72+
element: Union[BaseModel, YAMLRoot],
73+
to_file: str,
74+
contexts: CONTEXTS_PARAM_TYPE = None,
75+
fmt: str = "turtle",
76+
) -> None:
6877
"""
6978
Write element as rdf to to_file
7079
:param element: LinkML object to be emitted
@@ -82,7 +91,9 @@ def dump(self, element: Union[BaseModel, YAMLRoot], to_file: str, contexts: CONT
8291
element = element.model_dump()
8392
super().dump(element, to_file, contexts=contexts, fmt=fmt)
8493

85-
def dumps(self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_PARAM_TYPE = None, fmt: Optional[str] = 'turtle') -> str:
94+
def dumps(
95+
self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_PARAM_TYPE = None, fmt: Optional[str] = "turtle"
96+
) -> str:
8697
"""
8798
Convert element into an RDF graph guided by the context(s) in contexts
8899
:param element: element to represent in RDF
@@ -92,5 +103,4 @@ def dumps(self, element: Union[BaseModel, YAMLRoot], contexts: CONTEXTS_PARAM_TY
92103
"""
93104
if isinstance(element, BaseModel):
94105
element = element.model_dump()
95-
return self.as_rdf_graph(remove_empty_items(element, hide_protected_keys=True), contexts).\
96-
serialize(format=fmt)
106+
return self.as_rdf_graph(remove_empty_items(element, hide_protected_keys=True), contexts).serialize(format=fmt)

linkml_runtime/dumpers/rdflib_dumper.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class RDFLibDumper(Dumper):
2626
This requires a SchemaView object
2727
2828
"""
29+
2930
def as_rdf_graph(
3031
self,
3132
element: Union[BaseModel, YAMLRoot],
@@ -45,7 +46,7 @@ def as_rdf_graph(
4546
if isinstance(prefix_map, Converter):
4647
# TODO replace with `prefix_map = prefix_map.bimap` after making minimum requirement on python 3.8
4748
prefix_map = {record.prefix: record.uri_prefix for record in prefix_map.records}
48-
logger.debug(f'PREFIXMAP={prefix_map}')
49+
logger.debug(f"PREFIXMAP={prefix_map}")
4950
namespaces = schemaview.namespaces()
5051
if prefix_map:
5152
for k, v in prefix_map.items():
@@ -69,7 +70,9 @@ def as_rdf_graph(
6970
self.inject_triples(element, schemaview, g)
7071
return g
7172

72-
def inject_triples(self, element: Any, schemaview: SchemaView, graph: Graph, target_type: ElementName = None) -> Node:
73+
def inject_triples(
74+
self, element: Any, schemaview: SchemaView, graph: Graph, target_type: ElementName = None
75+
) -> Node:
7376
"""
7477
Inject triples from conversion of element into a Graph
7578
@@ -81,7 +84,7 @@ def inject_triples(self, element: Any, schemaview: SchemaView, graph: Graph, tar
8184
"""
8285
namespaces = schemaview.namespaces()
8386
slot_name_map = schemaview.slot_name_mappings()
84-
logger.debug(f'CONVERT: {element} // {type(element)} // {target_type}')
87+
logger.debug(f"CONVERT: {element} // {type(element)} // {target_type}")
8588
if target_type in schemaview.all_enums():
8689
if isinstance(element, PermissibleValueText):
8790
e = schemaview.get_enum(target_type)
@@ -97,22 +100,22 @@ def inject_triples(self, element: Any, schemaview: SchemaView, graph: Graph, tar
97100
t = schemaview.get_type(target_type)
98101
dt_uri = t.uri
99102
if dt_uri:
100-
if dt_uri == 'rdfs:Resource':
103+
if dt_uri == "rdfs:Resource":
101104
return URIRef(schemaview.expand_curie(element))
102-
elif dt_uri == 'xsd:string':
105+
elif dt_uri == "xsd:string":
103106
return Literal(element)
104107
else:
105108
if "xsd" not in namespaces:
106109
namespaces["xsd"] = XSD
107110
return Literal(element, datatype=namespaces.uri_for(dt_uri))
108111
else:
109-
logger.warning(f'No datatype specified for : {t.name}, using plain Literal')
112+
logger.warning(f"No datatype specified for : {t.name}, using plain Literal")
110113
return Literal(element)
111-
element_vars = {k: v for k, v in vars(element).items() if not k.startswith('_')}
114+
element_vars = {k: v for k, v in vars(element).items() if not k.startswith("_")}
112115
if len(element_vars) == 0:
113116
id_slot = schemaview.get_identifier_slot(target_type)
114117
return self._as_uri(element, id_slot, schemaview)
115-
#return URIRef(schemaview.expand_curie(str(element)))
118+
# return URIRef(schemaview.expand_curie(str(element)))
116119
element_type = type(element)
117120
cn = element_type.class_name
118121
id_slot = schemaview.get_identifier_slot(cn)
@@ -135,7 +138,7 @@ def inject_triples(self, element: Any, schemaview: SchemaView, graph: Graph, tar
135138
if k in slot_name_map:
136139
k = slot_name_map[k].name
137140
else:
138-
logger.error(f'Slot {k} not in name map')
141+
logger.error(f"Slot {k} not in name map")
139142
slot = schemaview.induced_slot(k, cn)
140143
if not slot.identifier:
141144
slot_uri = URIRef(schemaview.get_uri(slot, expand=True))
@@ -152,7 +155,7 @@ def dump(
152155
element: Union[BaseModel, YAMLRoot],
153156
to_file: str,
154157
schemaview: SchemaView = None,
155-
fmt: str = 'turtle',
158+
fmt: str = "turtle",
156159
prefix_map: Union[dict[str, str], Converter, None] = None,
157160
**args,
158161
) -> None:
@@ -172,7 +175,7 @@ def dumps(
172175
self,
173176
element: Union[BaseModel, YAMLRoot],
174177
schemaview: SchemaView = None,
175-
fmt: Optional[str] = 'turtle',
178+
fmt: Optional[str] = "turtle",
176179
prefix_map: Union[dict[str, str], Converter, None] = None,
177180
) -> str:
178181
"""
@@ -184,12 +187,10 @@ def dumps(
184187
:param prefix_map:
185188
:return: serialization of rdflib Graph containing element
186189
"""
187-
return self.as_rdf_graph(element, schemaview, prefix_map=prefix_map).\
188-
serialize(format=fmt)
190+
return self.as_rdf_graph(element, schemaview, prefix_map=prefix_map).serialize(format=fmt)
189191

190192
def _as_uri(self, element_id: str, id_slot: Optional[SlotDefinition], schemaview: SchemaView) -> URIRef:
191193
if id_slot and schemaview.is_slot_percent_encoded(id_slot):
192194
return URIRef(urllib.parse.quote(element_id))
193195
else:
194196
return schemaview.namespaces().uri_for(element_id)
195-

linkml_runtime/dumpers/tsv_dumper.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33

44
class TSVDumper(DelimitedFileDumper):
5-
65
@property
76
def delimiter(self):
87
return "\t"

linkml_runtime/dumpers/yaml_dumper.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,18 @@
66
from linkml_runtime.utils.formatutils import remove_empty_items
77
from linkml_runtime.utils.yamlutils import YAMLRoot
88

9-
class YAMLDumper(Dumper):
109

10+
class YAMLDumper(Dumper):
1111
def dumps(self, element: Union[BaseModel, YAMLRoot], **kwargs) -> str:
12-
""" Return element formatted as a YAML string """
12+
"""Return element formatted as a YAML string"""
1313
# Internal note: remove_empty_items will also convert Decimals to int/float;
1414
# this is necessary until https://github.com/yaml/pyyaml/pull/372 is merged
1515

1616
dumper_safe_element = element.model_dump() if isinstance(element, BaseModel) else element
17-
return yaml.dump(remove_empty_items(dumper_safe_element, hide_protected_keys=True),
18-
Dumper=yaml.SafeDumper, sort_keys=False,
19-
allow_unicode=True,
20-
**kwargs)
17+
return yaml.dump(
18+
remove_empty_items(dumper_safe_element, hide_protected_keys=True),
19+
Dumper=yaml.SafeDumper,
20+
sort_keys=False,
21+
allow_unicode=True,
22+
**kwargs,
23+
)

0 commit comments

Comments
 (0)