Skip to content

Commit 457a3f5

Browse files
committed
mass reformat & upgrade to Python 3.10+ syntax
1 parent 4aaf642 commit 457a3f5

File tree

143 files changed

+3429
-2876
lines changed

Some content is hidden

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

143 files changed

+3429
-2876
lines changed

contrib/mypy-stubs/pubsub/core/topictreetraverser.pyi

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
from .topicobj import Topic as Topic
21
from enum import IntEnum
32
from typing import Optional
43

4+
from .topicobj import Topic as Topic
5+
56
class ITopicTreeVisitor: ...
67

78
class TreeTraversal(IntEnum):
@@ -12,4 +13,6 @@ class TreeTraversal(IntEnum):
1213
class TopicTreeTraverser:
1314
def __init__(self, visitor: Optional[ITopicTreeVisitor] = None) -> None: ...
1415
def setVisitor(self, visitor: ITopicTreeVisitor) -> None: ...
15-
def traverse(self, topicObj: Topic, how: TreeTraversal = ..., onlyFiltered: bool = True) -> None: ...
16+
def traverse(
17+
self, topicObj: Topic, how: TreeTraversal = ..., onlyFiltered: bool = True
18+
) -> None: ...

src/toil/__init__.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,11 @@
1616
import re
1717
import socket
1818
import sys
19-
from datetime import datetime
20-
from typing import TYPE_CHECKING, Optional
21-
22-
from toil.lib.web import web_session
19+
from typing import TYPE_CHECKING
2320

2421
from docker.errors import ImageNotFound
2522
from toil.lib.memoize import memoize
26-
from toil.lib.retry import retry as retry
23+
from toil.lib.web import web_session
2724
from toil.version import currentCommit
2825

2926
if TYPE_CHECKING:
@@ -32,7 +29,7 @@
3229
log = logging.getLogger(__name__)
3330

3431

35-
def which(cmd, mode=os.F_OK | os.X_OK, path=None) -> Optional[str]:
32+
def which(cmd, mode=os.F_OK | os.X_OK, path=None) -> str | None:
3633
"""
3734
Return the path with conforms to the given mode on the Path.
3835
@@ -479,4 +476,3 @@ def logProcessContext(config: "Config") -> None:
479476

480477
log.info("Running Toil version %s on host %s.", version, socket.gethostname())
481478
log.debug("Configuration: %s", config.__dict__)
482-

src/toil/batchSystems/abstractBatchSystem.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14-
from dataclasses import dataclass
1514
import enum
1615
import logging
1716
import os
@@ -21,8 +20,9 @@
2120
from argparse import ArgumentParser, _ArgumentGroup
2221
from collections.abc import Iterator
2322
from contextlib import contextmanager
23+
from dataclasses import dataclass
2424
from threading import Condition
25-
from typing import Any, ContextManager, NamedTuple, Optional, Union, cast
25+
from typing import Any, ContextManager, NamedTuple, cast
2626

2727
from toil.batchSystems.options import OptionSetter
2828
from toil.bus import MessageBus, MessageOutbox
@@ -73,6 +73,7 @@ def to_string(cls, value: int) -> str:
7373
except ValueError:
7474
return str(value)
7575

76+
7677
@dataclass
7778
class UpdatedBatchJobInfo:
7879
jobID: int
@@ -87,20 +88,20 @@ class UpdatedBatchJobInfo:
8788
(e.g. job is lost, or otherwise died but actual exit code was not reported).
8889
"""
8990

90-
exitReason: Optional[BatchJobExitReason] = None
91-
wallTime: Union[float, int, None] = None
92-
backing_id: Optional[str] = None
91+
exitReason: BatchJobExitReason | None = None
92+
wallTime: float | int | None = None
93+
backing_id: str | None = None
9394
"""
9495
The identifier for the job in the backing scheduler, if available.
9596
"""
9697

9798

9899
# Information required for worker cleanup on shutdown of the batch system.
99100
class WorkerCleanupInfo(NamedTuple):
100-
work_dir: Optional[str]
101+
work_dir: str | None
101102
"""Work directory path (where the cache would go) if specified by user"""
102103

103-
coordination_dir: Optional[str]
104+
coordination_dir: str | None
104105
"""Coordination directory path (where lock files would go) if specified by user"""
105106

106107
workflow_id: str
@@ -171,7 +172,7 @@ def issueBatchJob(
171172
self,
172173
command: str,
173174
job_desc: JobDescription,
174-
job_environment: Optional[dict[str, str]] = None,
175+
job_environment: dict[str, str] | None = None,
175176
) -> int:
176177
"""
177178
Issues a job with the specified command to the batch system and returns
@@ -224,7 +225,7 @@ def getRunningBatchJobIDs(self) -> dict[int, float]:
224225
raise NotImplementedError()
225226

226227
@abstractmethod
227-
def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]:
228+
def getUpdatedBatchJob(self, maxWait: int) -> UpdatedBatchJobInfo | None:
228229
"""
229230
Returns information about job that has updated its status (i.e. ceased
230231
running, either successfully or with an error). Each such job will be
@@ -242,7 +243,7 @@ def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]:
242243
"""
243244
raise NotImplementedError()
244245

245-
def getSchedulingStatusMessage(self) -> Optional[str]:
246+
def getSchedulingStatusMessage(self) -> str | None:
246247
"""
247248
Get a log message fragment for the user about anything that might be
248249
going wrong in the batch system, if available.
@@ -269,7 +270,7 @@ def shutdown(self) -> None:
269270
"""
270271
raise NotImplementedError()
271272

272-
def setEnv(self, name: str, value: Optional[str] = None) -> None:
273+
def setEnv(self, name: str, value: str | None = None) -> None:
273274
"""
274275
Set an environment variable for the worker process before it is launched.
275276
@@ -286,7 +287,7 @@ def setEnv(self, name: str, value: Optional[str] = None) -> None:
286287
raise NotImplementedError()
287288

288289
@classmethod
289-
def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) -> None:
290+
def add_options(cls, parser: ArgumentParser | _ArgumentGroup) -> None:
290291
"""
291292
If this batch system provides any command line options, add them to the given parser.
292293
"""
@@ -351,7 +352,7 @@ def __init__(
351352
workflow_id=config.workflowID,
352353
clean_work_dir=config.cleanWorkDir,
353354
)
354-
self._outbox: Optional[MessageOutbox] = None
355+
self._outbox: MessageOutbox | None = None
355356

356357
def check_resource_request(self, requirer: Requirer) -> None:
357358
"""
@@ -400,7 +401,7 @@ def _check_accelerator_request(self, requirer: Requirer) -> None:
400401
details=["The batch system does not support any accelerators."],
401402
)
402403

403-
def setEnv(self, name: str, value: Optional[str] = None) -> None:
404+
def setEnv(self, name: str, value: str | None = None) -> None:
404405
"""
405406
Set an environment variable for the worker process before it is launched. The worker
406407
process will typically inherit the environment of the machine it is running on but this
@@ -572,7 +573,7 @@ class AbstractScalableBatchSystem(AbstractBatchSystem):
572573

573574
@abstractmethod
574575
def getNodes(
575-
self, preemptible: Optional[bool] = None, timeout: int = 600
576+
self, preemptible: bool | None = None, timeout: int = 600
576577
) -> dict[str, NodeInfo]:
577578
"""
578579
Returns a dictionary mapping node identifiers of preemptible or non-preemptible nodes to
@@ -622,9 +623,9 @@ def __init__(
622623
self,
623624
requirer: Requirer,
624625
resource: str,
625-
available: Optional[ParsedRequirement] = None,
626-
batch_system: Optional[str] = None,
627-
source: Optional[str] = None,
626+
available: ParsedRequirement | None = None,
627+
batch_system: str | None = None,
628+
source: str | None = None,
628629
details: list[str] = [],
629630
) -> None:
630631
"""
@@ -639,7 +640,7 @@ def __init__(
639640
:param details: Any extra details about the problem that can be attached to the error.
640641
"""
641642

642-
self.job_name: Optional[str] = str(requirer)
643+
self.job_name: str | None = str(requirer)
643644
self.resource = resource
644645
self.requested = cast(ParsedRequirement, getattr(requirer, resource))
645646
self.available = available
@@ -695,8 +696,8 @@ class AcquisitionTimeoutException(Exception):
695696
def __init__(
696697
self,
697698
resource: str,
698-
requested: Union[int, float, set[int]],
699-
available: Union[int, float, set[int]],
699+
requested: int | float | set[int],
700+
available: int | float | set[int],
700701
) -> None:
701702
"""
702703
Creates an instance of this exception that indicates which resource is insufficient for

src/toil/batchSystems/abstractGridEngineBatchSystem.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
from datetime import datetime
1818
from queue import Empty, Queue
1919
from threading import Lock, Thread
20-
from typing import Optional, Union
2120

2221
from toil.batchSystems.abstractBatchSystem import (
2322
BatchJobExitReason,
@@ -27,9 +26,9 @@
2726
from toil.bus import ExternalBatchIdMessage, get_job_kind
2827
from toil.common import Config
2928
from toil.job import AcceleratorRequirement, JobDescription
30-
from toil.statsAndLogging import TRACE
3129
from toil.lib.misc import CalledProcessErrorStderr
3230
from toil.lib.retry import DEFAULT_DELAYS, old_retry
31+
from toil.statsAndLogging import TRACE
3332

3433
logger = logging.getLogger(__name__)
3534

@@ -172,7 +171,7 @@ def createJobs(self, newJob: JobTuple) -> bool:
172171
"Job %s with batch system ID %s queued as job %s",
173172
jobName,
174173
jobID,
175-
str(batchJobID)
174+
str(batchJobID),
176175
)
177176

178177
# Store dict for mapping Toil job ID to batch job ID
@@ -258,8 +257,12 @@ def checkOnJobs(self):
258257
self.coalesce_job_exit_codes, batch_job_id_list
259258
)
260259
# We got the statuses as a batch
261-
for running_job_id, status, backing_id in zip(running_job_list, statuses, batch_job_id_list):
262-
activity = self._handle_job_status(running_job_id, status, activity, backing_id)
260+
for running_job_id, status, backing_id in zip(
261+
running_job_list, statuses, batch_job_id_list
262+
):
263+
activity = self._handle_job_status(
264+
running_job_id, status, activity, backing_id
265+
)
263266

264267
self._checkOnJobsCache = activity
265268
self._checkOnJobsTimestamp = datetime.now()
@@ -268,7 +271,7 @@ def checkOnJobs(self):
268271
def _handle_job_status(
269272
self,
270273
job_id: int,
271-
status: Union[int, tuple[int, Optional[BatchJobExitReason]], None],
274+
status: int | tuple[int, BatchJobExitReason | None] | None,
272275
activity: bool,
273276
backing_id: str,
274277
) -> bool:
@@ -313,7 +316,9 @@ def _runStep(self):
313316
if self.checkOnJobs():
314317
activity = True
315318
if not activity:
316-
logger.log(TRACE, "No activity, sleeping for %is", self.boss.sleepSeconds())
319+
logger.log(
320+
TRACE, "No activity, sleeping for %is", self.boss.sleepSeconds()
321+
)
317322
return True
318323

319324
def run(self):
@@ -332,7 +337,7 @@ def run(self):
332337

333338
def coalesce_job_exit_codes(
334339
self, batch_job_id_list: list
335-
) -> list[Union[int, tuple[int, Optional[BatchJobExitReason]], None]]:
340+
) -> list[int | tuple[int, BatchJobExitReason | None] | None]:
336341
"""
337342
Returns exit codes and possibly exit reasons for a list of jobs, or None if they are running.
338343
@@ -362,8 +367,8 @@ def prepareSubmission(
362367
jobID: int,
363368
command: str,
364369
jobName: str,
365-
job_environment: Optional[dict[str, str]] = None,
366-
gpus: Optional[int] = None,
370+
job_environment: dict[str, str] | None = None,
371+
gpus: int | None = None,
367372
) -> list[str]:
368373
"""
369374
Preparation in putting together a command-line string
@@ -416,7 +421,7 @@ def killJob(self, jobID):
416421
@abstractmethod
417422
def getJobExitCode(
418423
self, batchJobID
419-
) -> Union[int, tuple[int, Optional[BatchJobExitReason]], None]:
424+
) -> int | tuple[int, BatchJobExitReason | None] | None:
420425
"""
421426
Returns job exit code and possibly an instance of abstractBatchSystem.BatchJobExitReason.
422427
@@ -478,11 +483,10 @@ def issueBatchJob(
478483
self,
479484
command: str,
480485
job_desc: JobDescription,
481-
job_environment: Optional[dict[str, str]] = None,
486+
job_environment: dict[str, str] | None = None,
482487
):
483488
# Avoid submitting internal jobs to the batch queue, handle locally
484-
local_id = self.handleLocalJob(command, job_desc)
485-
if local_id is not None:
489+
if (local_id := self.handleLocalJob(command, job_desc)) is not None:
486490
return local_id
487491
else:
488492
self.check_resource_request(job_desc)

src/toil/batchSystems/awsBatch.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import uuid
3636
from argparse import ArgumentParser, _ArgumentGroup
3737
from collections.abc import Iterator
38-
from typing import Any, Optional, Union
38+
from typing import Any
3939

4040
from botocore.exceptions import ClientError
4141

@@ -137,15 +137,15 @@ def __init__(
137137
# is managed by the BatchSystemLocalSupport.
138138

139139
# Here is where we will store the user script resource object if we get one.
140-
self.user_script: Optional[Resource] = None
140+
self.user_script: Resource | None = None
141141

142142
# Get the image to deploy from Toil's configuration
143143
self.docker_image = applianceSelf()
144144

145145
# We can't use AWS Batch without a job definition. But we can use one
146146
# of them for all the jobs. We want to lazily initialize it. This will
147147
# be an ARN.
148-
self.job_definition: Optional[str] = None
148+
self.job_definition: str | None = None
149149

150150
# We need a way to map between our batch system ID numbers, and AWS Batch job IDs from the server.
151151
self.bs_id_to_aws_id: dict[int, str] = {}
@@ -179,11 +179,10 @@ def issueBatchJob(
179179
self,
180180
command: str,
181181
job_desc: JobDescription,
182-
job_environment: Optional[dict[str, str]] = None,
182+
job_environment: dict[str, str] | None = None,
183183
) -> int:
184184
# Try the job as local
185-
local_id = self.handleLocalJob(command, job_desc)
186-
if local_id is not None:
185+
if (local_id := self.handleLocalJob(command, job_desc)) is not None:
187186
# It is a local job
188187
return local_id
189188
else:
@@ -298,7 +297,7 @@ def _ensafen_name(input_name: str) -> str:
298297
# And re-compose them into a string
299298
return "".join(kept_chars)
300299

301-
def _get_runtime(self, job_detail: dict[str, Any]) -> Optional[float]:
300+
def _get_runtime(self, job_detail: dict[str, Any]) -> float | None:
302301
"""
303302
Internal function. Should not be called outside this class.
304303
@@ -349,7 +348,7 @@ def _get_exit_code(self, job_detail: dict[str, Any]) -> int:
349348
)
350349
)
351350

352-
def getUpdatedBatchJob(self, maxWait: int) -> Optional[UpdatedBatchJobInfo]:
351+
def getUpdatedBatchJob(self, maxWait: int) -> UpdatedBatchJobInfo | None:
353352
# Remember when we started, for respecting the timeout
354353
entry = datetime.datetime.now()
355354
while (
@@ -494,7 +493,7 @@ def _get_or_create_job_definition(self) -> str:
494493
if self.job_definition is None:
495494
# First work out what volume mounts to make, because the type
496495
# system is happiest this way
497-
volumes: list[dict[str, Union[str, dict[str, str]]]] = []
496+
volumes: list[dict[str, str | dict[str, str]]] = []
498497
mount_points: list[dict[str, str]] = []
499498
for i, shared_path in enumerate(
500499
{
@@ -650,7 +649,7 @@ def killBatchJobs(self, job_ids: list[int]) -> None:
650649
self._wait_until_stopped(self.bs_id_to_aws_id[bs_id])
651650

652651
@classmethod
653-
def add_options(cls, parser: Union[ArgumentParser, _ArgumentGroup]) -> None:
652+
def add_options(cls, parser: ArgumentParser | _ArgumentGroup) -> None:
654653
parser.add_argument(
655654
"--awsBatchRegion",
656655
dest="aws_batch_region",

0 commit comments

Comments
 (0)