Skip to content

Commit

Permalink
Merge pull request #364 from incf-nidash/fstrs
Browse files Browse the repository at this point in the history
Improve string formatting syntax
  • Loading branch information
yarikoptic authored May 5, 2023
2 parents 078b7c9 + e3616fb commit 411fb22
Show file tree
Hide file tree
Showing 25 changed files with 549 additions and 559 deletions.
10 changes: 3 additions & 7 deletions docker/rest-server.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class NIDMRest(Resource):
def get(self, all): # noqa: A002
query_bits = []
for a in request.args.keys():
query_bits.append("{}={}".format(a, request.args.get(a)))
query_bits.append(f"{a}={request.args.get(a)}")
query = "&".join(query_bits)

files = getTTLFiles()
Expand All @@ -29,9 +29,7 @@ def get(self, all): # noqa: A002
output_format=RestParser.OBJECT_FORMAT, verbosity_level=5
)

json_str = json.dumps(
restParser.run(files, "{}?{}".format(all, query)), indent=2
)
json_str = json.dumps(restParser.run(files, f"{all}?{query}"), indent=2)
response = app.response_class(
response=json_str, status=200, mimetype="application/json"
)
Expand All @@ -42,9 +40,7 @@ def get(self, all): # noqa: A002
class Instructions(Resource):
def get(self):
return {
"message": "You probably want to start at {}projects See instructions at PyNIDM/docker/README.md for details on the API and loading data.".format(
request.url_root
)
"message": f"You probably want to start at {request.url_root}projects See instructions at PyNIDM/docker/README.md for details on the API and loading data."
}


Expand Down
46 changes: 19 additions & 27 deletions src/nidm/core/dot.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@
def htlm_link_if_uri(value):
try:
uri = value.uri
return '<a href="%s">%s</a>' % (uri, str(value))
return f'<a href="{uri}">{value}</a>'
except AttributeError:
return str(value)

Expand Down Expand Up @@ -279,7 +279,7 @@ def _attach_attribute_annotation(node, record):
% (
attr.uri,
escape(str(attr)),
' href="%s"' % value.uri if isinstance(value, Identifier) else "",
f' href="{value.uri}"' if isinstance(value, Identifier) else "",
escape(
str(value)
if not isinstance(value, datetime)
Expand All @@ -291,66 +291,58 @@ def _attach_attribute_annotation(node, record):
ann_rows.append(ANNOTATION_END_ROW)
count[3] += 1
annotations = pydot.Node(
"ann%d" % count[3], label="\n".join(ann_rows), **ANNOTATION_STYLE
f"ann{count[3]}", label="\n".join(ann_rows), **ANNOTATION_STYLE
)
dot.add_node(annotations)
dot.add_edge(pydot.Edge(annotations, node, **ANNOTATION_LINK_STYLE))

def _add_bundle(bundle):
count[2] += 1
subdot = pydot.Cluster(
graph_name="c%d" % count[2], URL='"%s"' % bundle.identifier.uri
graph_name=f"c{count[2]}", URL=f'"{bundle.identifier.uri}"'
)
if use_labels:
if bundle.label == bundle.identifier:
bundle_label = '"%s"' % str(bundle.label)
bundle_label = f'"{bundle.label}"'
else:
# Fancier label if both are different. The label will be
# the main node text, whereas the identifier will be a
# kind of subtitle.
bundle_label = (
"<%s<br />"
f"<{bundle.label}<br />"
'<font color="#333333" point-size="10">'
"%s</font>>"
f"{bundle.identifier}</font>>"
)
bundle_label = bundle_label % (
str(bundle.label),
str(bundle.identifier),
)
subdot.set_label('"%s"' % str(bundle_label))
subdot.set_label(f'"{bundle_label}"')
else:
subdot.set_label('"%s"' % str(bundle.identifier))
subdot.set_label(f'"{bundle.identifier}"')
_bundle_to_dot(subdot, bundle)
dot.add_subgraph(subdot)
return subdot

def _add_node(record):
count[0] += 1
node_id = "n%d" % count[0]
node_id = f"n{count[0]}"
if use_labels:
if record.label == record.identifier:
node_label = '"%s"' % str(record.label)
node_label = f'"{record.label}"'
else:
# Fancier label if both are different. The label will be
# the main node text, whereas the identifier will be a
# kind of subtitle.
node_label = (
"<%s<br />"
f"<{record.label}<br />"
'<font color="#333333" point-size="10">'
"%s</font>>"
)
node_label = node_label % (
str(record.label),
str(record.identifier),
f"{record.identifier}</font>>"
)
else:
node_label = '"%s"' % str(record.identifier)
node_label = f'"{record.identifier}"'

uri = record.identifier.uri
print("record type: ", record.get_type())
style = DOT_PROVONE_STYLE[record.get_type()]
print("style: ", style)
node = pydot.Node(node_id, label=node_label, URL='"%s"' % uri, **style)
node = pydot.Node(node_id, label=node_label, URL=f'"{uri}"', **style)
node_map[uri] = node
dot.add_node(node)

Expand All @@ -360,19 +352,19 @@ def _add_node(record):

def _add_generic_node(qname):
count[0] += 1
node_id = "n%d" % count[0]
node_label = '"%s"' % str(qname)
node_id = f"n{count[0]}"
node_label = f'"{qname}"'

uri = qname.uri
style = DOT_PROVONE_STYLE[0]
node = pydot.Node(node_id, label=node_label, URL='"%s"' % uri, **style)
node = pydot.Node(node_id, label=node_label, URL=f'"{uri}"', **style)
node_map[uri] = node
dot.add_node(node)
return node

def _get_bnode():
count[1] += 1
bnode_id = "b%d" % count[1]
bnode_id = f"b{count[1]}"
bnode = pydot.Node(bnode_id, label='""', shape="point", color="gray")
dot.add_node(bnode)
return bnode
Expand Down
2 changes: 1 addition & 1 deletion src/nidm/core/serializers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,4 @@ def get(format_name):
try:
return Registry.serializers[format_name]
except KeyError:
raise DoNotExist('No serializer available for the format "%s"' % format_name)
raise DoNotExist(f'No serializer available for the format "{format_name}"')
4 changes: 2 additions & 2 deletions src/nidm/core/serializers/provonerdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(self):
def get_anon_id(self, obj, local_prefix="id"):
if obj not in self._cache:
self._count += 1
self._cache[obj] = pm.Identifier("_:%s%d" % (local_prefix, self._count)).uri
self._cache[obj] = pm.Identifier(f"_:{local_prefix}{self._count}").uri
return self._cache[obj]


Expand Down Expand Up @@ -178,7 +178,7 @@ def decode_rdf_representation(self, literal, graph):
if datatype == XSD["gYearMonth"]:
parsed_info = dateutil.parser.parse(literal)
return pm.Literal(
"{0}-{1:02d}".format(parsed_info.year, parsed_info.month),
f"{parsed_info.year}-{parsed_info.month:02d}",
datatype=self.valid_identifier(datatype),
)
else:
Expand Down
6 changes: 3 additions & 3 deletions src/nidm/experiment/CDE.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def download_cde_files():
cde_dir = tempfile.gettempdir()

for url in Constants.CDE_FILE_LOCATIONS:
urlretrieve(url, "{}/{}".format(cde_dir, url.split("/")[-1]))
urlretrieve(url, f"{cde_dir}/{url.split('/')[-1]}")

return cde_dir

Expand All @@ -25,7 +25,7 @@ def getCDEs(file_list=None):
hasher.update(str(file_list).encode("utf-8"))
h = hasher.hexdigest()

cache_file_name = tempfile.gettempdir() + "/cde_graph.{}.pickle".format(h)
cache_file_name = tempfile.gettempdir() + f"/cde_graph.{h}.pickle"

if path.isfile(cache_file_name):
with open(cache_file_name, "rb") as fp:
Expand All @@ -50,7 +50,7 @@ def getCDEs(file_list=None):

file_list = []
for f in ["ants_cde.ttl", "fs_cde.ttl", "fsl_cde.ttl"]:
fname = "{}/{}".format(cde_dir, f)
fname = f"{cde_dir}/{f}"
if path.isfile(fname):
file_list.append(fname)

Expand Down
13 changes: 7 additions & 6 deletions src/nidm/experiment/Core.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,8 +250,9 @@ def addLiteralAttribute(
)
except KeyError as e:
print(
'\nPredicate namespace identifier " %s " not found! \n'
% (str(e).split("'")[1])
'\nPredicate namespace identifier "',
str(e).split("'")[1],
'" not found! \n',
)
print(
"Use addNamespace method to add namespace before adding literal attribute \n"
Expand Down Expand Up @@ -364,7 +365,7 @@ def get_metadata_dict(self, NIDM_TYPE):
uri = s

if uri is None:
print("Error finding %s in NIDM-Exp Graph" % NIDM_TYPE)
print(f"Error finding {NIDM_TYPE} in NIDM-Exp Graph")
return metadata

# Cycle through metadata and add to json
Expand Down Expand Up @@ -531,7 +532,7 @@ def save_DotGraph(self, filename, format=None): # noqa: A002
"""
qres = rdf_graph.query(query)
for row in qres:
print("project uuid = %s" % row)
print(f"project uuid = {row}")
# parse uuid from project URI
# project_uuid = str(row[0]).rsplit('/', 1)[-1]
project_uuid = str(row[0])
Expand All @@ -557,7 +558,7 @@ def save_DotGraph(self, filename, format=None): # noqa: A002
dot.obj_dict["nodes"][key][0]["attributes"]["URL"]
):
session_node = key
# print("session node = %s" %key)
# print(f"session node = {key}")

# add to DOT structure edge between project_node and session_node
dot.add_edge(Edge(session_node, project_node, **style))
Expand All @@ -574,7 +575,7 @@ def save_DotGraph(self, filename, format=None): # noqa: A002
]
):
acquisition_node = key
# print("acquisition node = %s" %key)
# print(f"acquisition node = {key}")

dot.add_edge(
Edge(
Expand Down
2 changes: 1 addition & 1 deletion src/nidm/experiment/Navigate.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ def GetDataelementDetails(nidm_files_tuple, dataelement):
if d in rdf_graph.subjects(
predicate=isa, object=Constants.NIDM["Project"]
):
result["inProjects"].add("{} ({})".format(str(d), file))
result["inProjects"].add(f"{d} ({file})")

return result # found it, we are done

Expand Down
Loading

0 comments on commit 411fb22

Please sign in to comment.