Skip to content

Commit 9c702a9

Browse files
committed
upgrade to py3.6+ syntax
1 parent 83a489e commit 9c702a9

Some content is hidden

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

42 files changed

+226
-226
lines changed

Makefile

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,12 @@ MODULE=cwltool
2525
# `SHELL=bash` doesn't work for some, so don't use BASH-isms like
2626
# `[[` conditional expressions.
2727
PYSOURCES=$(wildcard ${MODULE}/**.py tests/*.py) setup.py
28-
DEVPKGS=diff_cover black pylint coverage pep257 pydocstyle flake8\
29-
isort wheel autoflake flake8-bugbear pyupgrade bandit -rtest-requirements.txt -rmypy_requirements.txt
28+
DEVPKGS=diff_cover black pylint coverage pep257 pydocstyle flake8 tox\
29+
isort wheel autoflake flake8-bugbear pyupgrade bandit \
30+
-rtest-requirements.txt -rmypy_requirements.txt
3031
DEBDEVPKGS=pep8 python-autopep8 pylint python-coverage pydocstyle sloccount \
3132
python-flake8 python-mock shellcheck
33+
3234
VERSION=3.0.$(shell TZ=UTC git log --first-parent --max-count=1 \
3335
--format=format:%cd --date=format-local:%Y%m%d%H%M%S)
3436
mkfile_dir := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
@@ -190,7 +192,7 @@ release: release-test
190192
twine upload testenv2/src/${MODULE}/dist/* && \
191193
git tag ${VERSION} && git push --tags
192194

193-
flake8: $(filter-out setup.py,${PYSOURCES})
195+
flake8: ${PYSOURCES}
194196
flake8 $^
195197

196198
FORCE:

cwltool/argparser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ def __init__(
694694
"""Fail if nargs is used."""
695695
if nargs is not None:
696696
raise ValueError("nargs not allowed")
697-
super(FSAction, self).__init__(option_strings, dest, **kwargs)
697+
super().__init__(option_strings, dest, **kwargs)
698698

699699
def __call__(
700700
self,
@@ -722,7 +722,7 @@ def __init__(
722722
"""Initialize."""
723723
if nargs is not None:
724724
raise ValueError("nargs not allowed")
725-
super(FSAppendAction, self).__init__(option_strings, dest, **kwargs)
725+
super().__init__(option_strings, dest, **kwargs)
726726

727727
def __call__(
728728
self,

cwltool/builder.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,9 @@ def check_format(
130130
)
131131

132132

133-
class HasReqsHints(object):
133+
class HasReqsHints:
134+
"""Base class for get_requirement()."""
135+
134136
def __init__(self) -> None:
135137
"""Initialize this reqs decorator."""
136138
self.requirements = [] # type: List[CWLObjectType]
@@ -294,7 +296,7 @@ def bind_input(
294296
bound_input = True
295297
if not bound_input:
296298
raise ValidationException(
297-
"'%s' is not a valid union %s" % (datum, schema["type"])
299+
"'{}' is not a valid union {}".format(datum, schema["type"])
298300
)
299301
elif isinstance(schema["type"], MutableMapping):
300302
st = copy.deepcopy(schema["type"])
@@ -398,7 +400,9 @@ def _capture_files(f: CWLObjectType) -> CWLObjectType:
398400
) as f2:
399401
datum["contents"] = content_limit_respected_read(f2)
400402
except Exception as e:
401-
raise Exception("Reading %s\n%s" % (datum["location"], e))
403+
raise Exception(
404+
"Reading {}\n{}".format(datum["location"], e)
405+
)
402406

403407
if "secondaryFiles" in schema:
404408
if "secondaryFiles" not in datum:
@@ -545,7 +549,7 @@ def tostr(self, value: Union[MutableMapping[str, str], Any]) -> str:
545549
):
546550
if "path" not in value:
547551
raise WorkflowException(
548-
u'%s object missing "path": %s' % (value["class"], value)
552+
'{} object missing "path": {}'.format(value["class"], value)
549553
)
550554

551555
# Path adjust for windows file path when passing to docker, docker accepts unix like path only

cwltool/checker.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def check_types(
6060
return check_types(
6161
merge_flatten_type(_get_type(srctype)), _get_type(sinktype), None, None
6262
)
63-
raise WorkflowException("Unrecognized linkMerge enum '{}'".format(linkMerge))
63+
raise WorkflowException(f"Unrecognized linkMerge enum '{linkMerge}'")
6464

6565

6666
def merge_flatten_type(src: SinkType) -> CWLOutputType:
@@ -222,7 +222,7 @@ def static_checker(
222222
# by the source
223223
missing = missing_subset(srcsf, sinksf)
224224
if missing:
225-
msg1 = "Parameter '%s' requires secondaryFiles %s but" % (
225+
msg1 = "Parameter '{}' requires secondaryFiles {} but".format(
226226
shortname(sink["id"]),
227227
missing,
228228
)
@@ -241,7 +241,7 @@ def static_checker(
241241
% shortname(sink["id"])
242242
)
243243
msg = SourceLine(sink).makeError(
244-
"%s\n%s" % (msg1, bullets([msg3, msg4, msg5], " "))
244+
"{}\n{}".format(msg1, bullets([msg3, msg4, msg5], " "))
245245
)
246246
elif sink.get("not_connected"):
247247
if not sink.get("used_by_step"):

cwltool/command_line_tool.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@
104104
"""
105105

106106

107-
class ExpressionJob(object):
107+
class ExpressionJob:
108108
"""Job for ExpressionTools."""
109109

110110
def __init__(
@@ -267,7 +267,9 @@ def revmap_file(
267267
)
268268

269269

270-
class CallbackJob(object):
270+
class CallbackJob:
271+
"""Callback Job class, used by CommandLine.job()."""
272+
271273
def __init__(
272274
self,
273275
job: "CommandLineTool",
@@ -352,7 +354,7 @@ def check_valid_locations(fs_access: StdFsAccess, ob: CWLObjectType) -> None:
352354
class ParameterOutputWorkflowException(WorkflowException):
353355
def __init__(self, msg: str, port: CWLObjectType, **kwargs: Any) -> None:
354356
"""Exception for when there was an error collecting output for a parameter."""
355-
super(ParameterOutputWorkflowException, self).__init__(
357+
super().__init__(
356358
"Error collecting output for parameter '%s':\n%s"
357359
% (shortname(cast(str, port["id"])), msg),
358360
kwargs,
@@ -364,7 +366,7 @@ def __init__(
364366
self, toolpath_object: CommentedMap, loadingContext: LoadingContext
365367
) -> None:
366368
"""Initialize this CommandLineTool."""
367-
super(CommandLineTool, self).__init__(toolpath_object, loadingContext)
369+
super().__init__(toolpath_object, loadingContext)
368370
self.prov_obj = loadingContext.prov_obj
369371

370372
def make_job_runner(self, runtimeContext: RuntimeContext) -> Type[JobBase]:
@@ -792,7 +794,7 @@ def calc_checksum(location: str) -> Optional[str]:
792794
jobcache = os.path.join(runtimeContext.cachedir, cachekey)
793795

794796
# Create a lockfile to manage cache status.
795-
jobcachepending = "{}.status".format(jobcache)
797+
jobcachepending = f"{jobcache}.status"
796798
jobcachelock = None
797799
jobstatus = None
798800

cwltool/context.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@
2727
from .provenance_profile import ProvenanceProfile
2828

2929

30-
class ContextBase(object):
30+
class ContextBase:
31+
"""Shared kwargs based initilizer for {Runtime,Loading}Context."""
32+
3133
def __init__(self, kwargs: Optional[Dict[str, Any]] = None) -> None:
3234
"""Initialize."""
3335
if kwargs:
@@ -73,7 +75,7 @@ def __init__(self, kwargs: Optional[Dict[str, Any]] = None) -> None:
7375
self.jobdefaults = None # type: Optional[CommentedMap]
7476
self.doc_cache = True # type: bool
7577

76-
super(LoadingContext, self).__init__(kwargs)
78+
super().__init__(kwargs)
7779

7880
def copy(self):
7981
# type: () -> LoadingContext
@@ -149,7 +151,7 @@ def __init__(self, kwargs: Optional[Dict[str, Any]] = None) -> None:
149151
self.mpi_config = MpiConfig() # type: MpiConfig
150152
self.default_stdout = None # type: Optional[Union[IO[bytes], TextIO]]
151153
self.default_stderr = None # type: Optional[Union[IO[bytes], TextIO]]
152-
super(RuntimeContext, self).__init__(kwargs)
154+
super().__init__(kwargs)
153155
if self.tmp_outdir_prefix == "":
154156
self.tmp_outdir_prefix = self.tmpdir_prefix
155157

cwltool/cwlrdf.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ def dot_with_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> None:
4747

4848
for step, run, _ in qres:
4949
stdout.write(
50-
u'"%s" [label="%s"]\n'
51-
% (lastpart(step), "%s (%s)" % (lastpart(step), lastpart(run)))
50+
'"%s" [label="%s"]\n'
51+
% (lastpart(step), "{} ({})".format(lastpart(step), lastpart(run)))
5252
)
5353

5454
qres = g.query(
@@ -61,12 +61,12 @@ def dot_with_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> None:
6161
)
6262

6363
for step, inp, source in qres:
64-
stdout.write(u'"%s" [shape=box]\n' % (lastpart(inp)))
64+
stdout.write('"%s" [shape=box]\n' % (lastpart(inp)))
6565
stdout.write(
66-
u'"%s" -> "%s" [label="%s"]\n' % (lastpart(source), lastpart(inp), "")
66+
'"{}" -> "{}" [label="{}"]\n'.format(lastpart(source), lastpart(inp), "")
6767
)
6868
stdout.write(
69-
u'"%s" -> "%s" [label="%s"]\n' % (lastpart(inp), lastpart(step), "")
69+
'"{}" -> "{}" [label="{}"]\n'.format(lastpart(inp), lastpart(step), "")
7070
)
7171

7272
qres = g.query(
@@ -78,9 +78,9 @@ def dot_with_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> None:
7878
)
7979

8080
for step, out in qres:
81-
stdout.write(u'"%s" [shape=box]\n' % (lastpart(out)))
81+
stdout.write('"%s" [shape=box]\n' % (lastpart(out)))
8282
stdout.write(
83-
u'"%s" -> "%s" [label="%s"]\n' % (lastpart(step), lastpart(out), "")
83+
'"{}" -> "{}" [label="{}"]\n'.format(lastpart(step), lastpart(out), "")
8484
)
8585

8686
qres = g.query(
@@ -92,9 +92,9 @@ def dot_with_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> None:
9292
)
9393

9494
for out, source in qres:
95-
stdout.write(u'"%s" [shape=octagon]\n' % (lastpart(out)))
95+
stdout.write('"%s" [shape=octagon]\n' % (lastpart(out)))
9696
stdout.write(
97-
u'"%s" -> "%s" [label="%s"]\n' % (lastpart(source), lastpart(out), "")
97+
'"{}" -> "{}" [label="{}"]\n'.format(lastpart(source), lastpart(out), "")
9898
)
9999

100100
qres = g.query(
@@ -106,7 +106,7 @@ def dot_with_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> None:
106106
)
107107

108108
for (inp,) in qres:
109-
stdout.write(u'"%s" [shape=octagon]\n' % (lastpart(inp)))
109+
stdout.write('"%s" [shape=octagon]\n' % (lastpart(inp)))
110110

111111

112112
def dot_without_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> None:
@@ -150,7 +150,7 @@ def dot_without_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> Non
150150
if wf not in dotname:
151151
dotname[wf] = "cluster_" + lastpart(wf)
152152
stdout.write(
153-
u'subgraph "%s" { label="%s"\n' % (dotname[wf], lastpart(wf))
153+
'subgraph "{}" {{ label="{}"\n'.format(dotname[wf], lastpart(wf))
154154
)
155155
currentwf = wf
156156
clusternode[wf] = step
@@ -159,7 +159,7 @@ def dot_without_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> Non
159159

160160
if str(runtype) != "https://w3id.org/cwl/cwl#Workflow":
161161
stdout.write(
162-
u'"%s" [label="%s"]\n'
162+
'"%s" [label="%s"]\n'
163163
% (dotname[step], urllib.parse.urldefrag(str(step))[1])
164164
)
165165

@@ -182,12 +182,12 @@ def dot_without_parameters(g: Graph, stdout: Union[TextIO, StreamWriter]) -> Non
182182
for src, sink, srcrun, sinkrun in qres:
183183
attr = ""
184184
if srcrun in clusternode:
185-
attr += u'ltail="%s"' % dotname[srcrun]
185+
attr += 'ltail="%s"' % dotname[srcrun]
186186
src = clusternode[srcrun]
187187
if sinkrun in clusternode:
188-
attr += u' lhead="%s"' % dotname[sinkrun]
188+
attr += ' lhead="%s"' % dotname[sinkrun]
189189
sink = clusternode[sinkrun]
190-
stdout.write(u'"%s" -> "%s" [%s]\n' % (dotname[src], dotname[sink], attr))
190+
stdout.write('"{}" -> "{}" [{}]\n'.format(dotname[src], dotname[sink], attr))
191191

192192

193193
def printdot(

cwltool/docker.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import sys
1010
import threading
1111
from distutils import spawn
12-
from io import StringIO, open # pylint: disable=redefined-builtin
12+
from io import StringIO # pylint: disable=redefined-builtin
1313
from typing import Callable, Dict, List, MutableMapping, Optional, Set, Tuple, cast
1414

1515
import requests
@@ -99,9 +99,7 @@ def __init__(
9999
name: str,
100100
) -> None:
101101
"""Initialize a command line builder using the Docker software container engine."""
102-
super(DockerCommandLineJob, self).__init__(
103-
builder, joborder, make_path_mapper, requirements, hints, name
104-
)
102+
super().__init__(builder, joborder, make_path_mapper, requirements, hints, name)
105103

106104
@staticmethod
107105
def get_image(
@@ -261,7 +259,7 @@ def append_volume(
261259
output = StringIO()
262260
csv.writer(output).writerow(options)
263261
mount_arg = output.getvalue().strip()
264-
runtime.append("--mount={}".format(mount_arg))
262+
runtime.append(f"--mount={mount_arg}")
265263
# Unlike "--volume", "--mount" will fail if the volume doesn't already exist.
266264
if not os.path.exists(source):
267265
os.makedirs(source)
@@ -382,7 +380,7 @@ def create_runtime(
382380

383381
if self.networkaccess:
384382
if runtimeContext.custom_net:
385-
runtime.append("--net={0}".format(runtimeContext.custom_net))
383+
runtime.append(f"--net={runtimeContext.custom_net}")
386384
else:
387385
runtime.append("--net=none")
388386

@@ -437,7 +435,7 @@ def create_runtime(
437435
cidfile_path = os.path.join(cidfile_dir, cidfile_name)
438436
runtime.append("--cidfile=%s" % cidfile_path)
439437
for key, value in self.environment.items():
440-
runtime.append("--env=%s=%s" % (key, value))
438+
runtime.append(f"--env={key}={value}")
441439

442440
if runtimeContext.strict_memory_limit and not user_space_docker_cmd:
443441
ram = self.builder.resources["ram"]

cwltool/executors.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""Single and multi-threaded executors."""
32
import datetime
43
import functools
@@ -40,7 +39,7 @@
4039
TMPDIR_LOCK = Lock()
4140

4241

43-
class JobExecutor(object, metaclass=ABCMeta):
42+
class JobExecutor(metaclass=ABCMeta):
4443
"""Abstract base job executor."""
4544

4645
def __init__(self) -> None:
@@ -278,7 +277,7 @@ class MultithreadedJobExecutor(JobExecutor):
278277

279278
def __init__(self) -> None:
280279
"""Initialize."""
281-
super(MultithreadedJobExecutor, self).__init__()
280+
super().__init__()
282281
self.exceptions = [] # type: List[WorkflowException]
283282
self.pending_jobs = [] # type: List[JobsType]
284283
self.pending_jobs_lock = threading.Lock()
@@ -332,10 +331,10 @@ def _runner(self, job, runtime_context, TMPDIR_LOCK):
332331
)
333332
job.run(runtime_context, TMPDIR_LOCK)
334333
except WorkflowException as err:
335-
_logger.exception("Got workflow error: {}".format(err))
334+
_logger.exception(f"Got workflow error: {err}")
336335
self.exceptions.append(err)
337336
except Exception as err: # pylint: disable=broad-except
338-
_logger.exception("Got workflow error: {}".format(err))
337+
_logger.exception(f"Got workflow error: {err}")
339338
self.exceptions.append(WorkflowException(str(err)))
340339
finally:
341340
if runtime_context.workflow_eval_lock:

0 commit comments

Comments
 (0)