diff --git a/Makefile b/Makefile
index 15e90641d751..7b413259b3c7 100644
--- a/Makefile
+++ b/Makefile
@@ -53,9 +53,9 @@ remove-unused-imports: ## Remove unused imports in Python code base
$(IN_VENV) autoflake --in-place --remove-all-unused-imports --recursive --verbose lib/ test/
pyupgrade: ## Convert older code patterns to Python3.7/3.8 idiomatic ones
- ack --type=python -f | grep -v '^lib/galaxy/schema/bco/\|^lib/galaxy/schema/drs/\|^lib/tool_shed_client/schema/trs\|^tools/\|^.venv/\|^.tox/\|^lib/galaxy/files/sources/\|^lib/galaxy/job_metrics/\|^lib/galaxy/objectstore/\|^lib/galaxy/tool_util/\|^lib/galaxy/util/\|^test/functional/tools/cwl_tools/' | xargs pyupgrade --py38-plus
- ack --type=python -f | grep -v '^lib/galaxy/schema/bco/\|^lib/galaxy/schema/drs/\|^lib/tool_shed_client/schema/trs\|^tools/\|^.venv/\|^.tox/\|^lib/galaxy/files/sources/\|^lib/galaxy/job_metrics/\|^lib/galaxy/objectstore/\|^lib/galaxy/tool_util/\|^lib/galaxy/util/\|^test/functional/tools/cwl_tools/' | xargs auto-walrus
- ack --type=python -f lib/galaxy/files/sources/ lib/galaxy/job_metrics/ lib/galaxy/objectstore/ lib/galaxy/tool_util/ lib/galaxy/util/ | xargs pyupgrade --py37-plus
+ ack --type=python -f | grep -v '^lib/galaxy/schema/bco/\|^lib/galaxy/schema/drs/\|^lib/tool_shed_client/schema/trs\|^tools/\|^.venv/\|^.tox/\|^lib/galaxy/exceptions/\|^lib/galaxy/job_metrics/\|^lib/galaxy/objectstore/\|^lib/galaxy/tool_util/\|^lib/galaxy/util/\|^test/functional/tools/cwl_tools/' | xargs pyupgrade --py38-plus
+ ack --type=python -f | grep -v '^lib/galaxy/schema/bco/\|^lib/galaxy/schema/drs/\|^lib/tool_shed_client/schema/trs\|^tools/\|^.venv/\|^.tox/\|^lib/galaxy/exceptions/\|^lib/galaxy/job_metrics/\|^lib/galaxy/objectstore/\|^lib/galaxy/tool_util/\|^lib/galaxy/util/\|^test/functional/tools/cwl_tools/' | xargs auto-walrus
+ ack --type=python -f lib/galaxy/exceptions/ lib/galaxy/job_metrics/ lib/galaxy/objectstore/ lib/galaxy/tool_util/ lib/galaxy/util/ | xargs pyupgrade --py37-plus
docs-slides-ready:
test -f plantuml.jar || wget http://jaist.dl.sourceforge.net/project/plantuml/plantuml.jar
diff --git a/lib/galaxy/authnz/managers.py b/lib/galaxy/authnz/managers.py
index 6b526643162e..3fca049269fc 100644
--- a/lib/galaxy/authnz/managers.py
+++ b/lib/galaxy/authnz/managers.py
@@ -193,7 +193,7 @@ def _parse_custos_config(self, config_xml):
if config_xml.find("well_known_oidc_config_uri") is not None:
rtv["well_known_oidc_config_uri"] = config_xml.find("well_known_oidc_config_uri").text
if config_xml.findall("allowed_idp") is not None:
- self.allowed_idps = list(map(lambda idp: idp.text, config_xml.findall("allowed_idp")))
+ self.allowed_idps = [idp.text for idp in config_xml.findall("allowed_idp")]
if config_xml.find("ca_bundle") is not None:
rtv["ca_bundle"] = config_xml.find("ca_bundle").text
if config_xml.find("icon") is not None:
diff --git a/lib/galaxy/datatypes/anvio.py b/lib/galaxy/datatypes/anvio.py
index a6feff14af5c..e89e3db59edd 100644
--- a/lib/galaxy/datatypes/anvio.py
+++ b/lib/galaxy/datatypes/anvio.py
@@ -45,7 +45,7 @@ def generate_primary_file(self, dataset: HasExtraFilesAndMetadata) -> str:
missing_text = " (missing)"
rval.append(f'
{composite_name}{opt_text}{missing_text}')
rval.append("")
- defined_files = map(lambda x: x[0], defined_files)
+ defined_files = (x[0] for x in defined_files)
extra_files = []
for dirpath, _dirnames, filenames in os.walk(dataset.extra_files_path, followlinks=True):
for filename in filenames:
diff --git a/lib/galaxy/datatypes/binary.py b/lib/galaxy/datatypes/binary.py
index de92e2a165dc..de47ca2548ae 100644
--- a/lib/galaxy/datatypes/binary.py
+++ b/lib/galaxy/datatypes/binary.py
@@ -2210,8 +2210,8 @@ def set_meta(self, dataset: DatasetProtocol, overwrite: bool = True, **kwd) -> N
try:
with h5py.File(dataset.get_file_name(), "r") as mat_file:
dataset.metadata.materials = list(mat_file.keys())
- sgn = dict()
- lp = dict()
+ sgn = {}
+ lp = {}
for m in mat_file.keys():
if "SpaceGroupNumber" in mat_file[m] and len(mat_file[m]["SpaceGroupNumber"]) > 0:
sgn[m] = mat_file[m]["SpaceGroupNumber"][0].item()
@@ -2401,8 +2401,8 @@ def init_meta(self, dataset: HasMetadata, copy_from: Optional[HasMetadata] = Non
def set_meta(self, dataset: DatasetProtocol, overwrite: bool = True, **kwd) -> None:
try:
tables = []
- columns = dict()
- rowcounts = dict()
+ columns = {}
+ rowcounts = {}
conn = sqlite.connect(dataset.get_file_name())
c = conn.cursor()
tables_query = "SELECT name,sql FROM sqlite_master WHERE type='table' ORDER BY name"
diff --git a/lib/galaxy/datatypes/dataproviders/base.py b/lib/galaxy/datatypes/dataproviders/base.py
index 30f02eea525c..c1239f86b9ff 100644
--- a/lib/galaxy/datatypes/dataproviders/base.py
+++ b/lib/galaxy/datatypes/dataproviders/base.py
@@ -128,7 +128,7 @@ def writelines(self, sequence):
# def readline( self ):
# return self.next()
def readlines(self):
- return [line for line in self]
+ return list(self)
# iterator interface
def __iter__(self):
diff --git a/lib/galaxy/datatypes/dataproviders/dataset.py b/lib/galaxy/datatypes/dataproviders/dataset.py
index dfce2edef527..6c8075835393 100644
--- a/lib/galaxy/datatypes/dataproviders/dataset.py
+++ b/lib/galaxy/datatypes/dataproviders/dataset.py
@@ -749,7 +749,7 @@ def __iter__(self):
for i, row in enumerate(results):
if i >= self.limit:
break
- yield [val for val in row]
+ yield list(row)
else:
yield
diff --git a/lib/galaxy/datatypes/dataproviders/line.py b/lib/galaxy/datatypes/dataproviders/line.py
index d47215b58382..ac2dc3a51f3a 100644
--- a/lib/galaxy/datatypes/dataproviders/line.py
+++ b/lib/galaxy/datatypes/dataproviders/line.py
@@ -249,7 +249,7 @@ def assemble_current_block(self):
Called per block (just before providing).
"""
# empty block_lines and assemble block
- return list(self.block_lines.popleft() for i in range(len(self.block_lines)))
+ return [self.block_lines.popleft() for i in range(len(self.block_lines))]
def filter_block(self, block):
"""
diff --git a/lib/galaxy/datatypes/goldenpath.py b/lib/galaxy/datatypes/goldenpath.py
index 94ce38b547bd..9ce878714a69 100644
--- a/lib/galaxy/datatypes/goldenpath.py
+++ b/lib/galaxy/datatypes/goldenpath.py
@@ -84,7 +84,7 @@ def sniff_prefix(self, file_prefix: FilePrefix) -> bool:
assert line[8] in ["+", "-", "?", "0", "na"]
if line[4] == "U":
assert int(line[5]) == 100
- assert all(map(lambda x: str(x).isnumeric() and int(x) > 0, ostensible_numbers))
+ assert all(str(x).isnumeric() and int(x) > 0 for x in ostensible_numbers)
found_non_comment_lines = True
except Exception:
return False
diff --git a/lib/galaxy/datatypes/text.py b/lib/galaxy/datatypes/text.py
index 54a8f28aa4b9..95fa625aa789 100644
--- a/lib/galaxy/datatypes/text.py
+++ b/lib/galaxy/datatypes/text.py
@@ -471,7 +471,7 @@ def _transform_dict_list_ids(dict_list):
for k, v in column["metadata"].items():
if v is not None:
keep_columns.add(k)
- final_list = sorted(list(keep_columns))
+ final_list = sorted(keep_columns)
dataset.metadata.table_column_metadata_headers = final_list
if b_name in b_transform:
metadata_value = b_transform[b_name](metadata_value)
diff --git a/lib/galaxy/datatypes/util/maf_utilities.py b/lib/galaxy/datatypes/util/maf_utilities.py
index 52c18931c3c9..8ed6f1670c5b 100644
--- a/lib/galaxy/datatypes/util/maf_utilities.py
+++ b/lib/galaxy/datatypes/util/maf_utilities.py
@@ -183,7 +183,7 @@ def get_sequence(self, species):
# returns the reverse complement of the sequence for a species
def get_sequence_reverse_complement(self, species):
- complement = [base for base in self.get_sequence(species).translate(self.DNA_COMPLEMENT)]
+ complement = list(self.get_sequence(species).translate(self.DNA_COMPLEMENT))
complement.reverse()
return "".join(complement)
@@ -274,7 +274,7 @@ def get_sequence(self, species):
# returns the reverse complement of the sequence for a species
def get_sequence_reverse_complement(self, species):
- complement = [base for base in self.get_sequence(species).translate(self.DNA_COMPLEMENT)]
+ complement = list(self.get_sequence(species).translate(self.DNA_COMPLEMENT))
complement.reverse()
return "".join(complement)
@@ -683,7 +683,7 @@ def iter_components_by_src(block, src):
def get_components_by_src(block, src):
- return [value for value in iter_components_by_src(block, src)]
+ return list(iter_components_by_src(block, src))
def iter_components_by_src_start(block, src):
@@ -693,7 +693,7 @@ def iter_components_by_src_start(block, src):
def get_components_by_src_start(block, src):
- return [value for value in iter_components_by_src_start(block, src)]
+ return list(iter_components_by_src_start(block, src))
def sort_block_components_by_block(block1, block2):
diff --git a/lib/galaxy/files/sources/__init__.py b/lib/galaxy/files/sources/__init__.py
index 0339e3aaed48..61d6a328108e 100644
--- a/lib/galaxy/files/sources/__init__.py
+++ b/lib/galaxy/files/sources/__init__.py
@@ -468,8 +468,7 @@ def _get_error_msg_for(rule_name: str) -> str:
def uri_join(*args):
# url_join doesn't work with non-standard scheme
- arg0 = args[0]
- if "://" in arg0:
+ if "://" in (arg0 := args[0]):
scheme, path = arg0.split("://", 1)
rval = f"{scheme}://{slash_join(path, *args[1:]) if path else slash_join(*args[1:])}"
else:
diff --git a/lib/galaxy/files/sources/drs.py b/lib/galaxy/files/sources/drs.py
index 3e05ca4bd56e..590bfd4666b3 100644
--- a/lib/galaxy/files/sources/drs.py
+++ b/lib/galaxy/files/sources/drs.py
@@ -8,13 +8,13 @@
from typing_extensions import Unpack
-from galaxy.util.drs import fetch_drs_to_file
from . import (
BaseFilesSource,
FilesSourceOptions,
FilesSourceProperties,
PluginKind,
)
+from .util import fetch_drs_to_file
log = logging.getLogger(__name__)
diff --git a/lib/galaxy/files/sources/http.py b/lib/galaxy/files/sources/http.py
index d2a5b331ccea..0e538baec1dc 100644
--- a/lib/galaxy/files/sources/http.py
+++ b/lib/galaxy/files/sources/http.py
@@ -85,8 +85,7 @@ def _serialization_props(self, user_context=None) -> HTTPFilesSourceProperties:
return cast(HTTPFilesSourceProperties, effective_props)
def score_url_match(self, url: str):
- match = self._url_regex.match(url)
- if match:
+ if match := self._url_regex.match(url):
return match.span()[1]
else:
return 0
diff --git a/lib/galaxy/util/drs.py b/lib/galaxy/files/sources/util.py
similarity index 100%
rename from lib/galaxy/util/drs.py
rename to lib/galaxy/files/sources/util.py
diff --git a/lib/galaxy/jobs/__init__.py b/lib/galaxy/jobs/__init__.py
index 86c43b45ed7c..b015cdd38198 100644
--- a/lib/galaxy/jobs/__init__.py
+++ b/lib/galaxy/jobs/__init__.py
@@ -122,7 +122,7 @@ def __init__(self, **kwds):
self["env"] = []
self["resubmit"] = []
# dict is appropriate (rather than a bunch) since keys may not be valid as attributes
- self["params"] = dict()
+ self["params"] = {}
# Use the values persisted in an existing job
if "from_job" in kwds and kwds["from_job"].destination_id is not None:
@@ -143,7 +143,7 @@ class JobToolConfiguration(Bunch):
def __init__(self, **kwds):
self["handler"] = None
self["destination"] = None
- self["params"] = dict()
+ self["params"] = {}
super().__init__(**kwds)
def get_resource_group(self):
@@ -448,7 +448,7 @@ def _configure_from_dict(self, job_config_dict):
execution_dict = job_config_dict.get("execution", {})
environments = execution_dict.get("environments", [])
enviroment_iter = (
- map(lambda e: (e["id"], e), environments) if isinstance(environments, list) else environments.items()
+ ((e["id"], e) for e in environments) if isinstance(environments, list) else environments.items()
)
for environment_id, environment_dict in enviroment_iter:
metrics = environment_dict.get("metrics")
@@ -520,11 +520,11 @@ def _configure_from_dict(self, job_config_dict):
assert tool_class is None
tool_id = raw_tool_id.lower().rstrip("/")
if tool_id not in self.tools:
- self.tools[tool_id] = list()
+ self.tools[tool_id] = []
else:
assert tool_class in VALID_TOOL_CLASSES, tool_class
if tool_class not in self.tool_classes:
- self.tool_classes[tool_class] = list()
+ self.tool_classes[tool_class] = []
params = tool.get("params")
if params is None:
@@ -663,7 +663,7 @@ def get_params(config, parent):
key = param.get("id")
if key in ["container", "container_override"]:
containers = map(requirements.container_from_element, param.findall("container"))
- param_value = list(map(lambda c: c.to_dict(), containers))
+ param_value = [c.to_dict() for c in containers]
else:
param_value = param.text
@@ -2273,7 +2273,7 @@ def setup_external_metadata(
if set_extension:
for output_dataset_assoc in job.output_datasets:
if output_dataset_assoc.dataset.ext == "auto":
- context = self.get_dataset_finish_context(dict(), output_dataset_assoc)
+ context = self.get_dataset_finish_context({}, output_dataset_assoc)
output_dataset_assoc.dataset.extension = context.get("ext", "data")
with transaction(self.sa_session):
self.sa_session.commit()
diff --git a/lib/galaxy/jobs/runners/condor.py b/lib/galaxy/jobs/runners/condor.py
index 629d165f5625..04b4d2f2e3c6 100644
--- a/lib/galaxy/jobs/runners/condor.py
+++ b/lib/galaxy/jobs/runners/condor.py
@@ -227,7 +227,7 @@ def stop_job(self, job_wrapper):
try:
log.info(f"stop_job(): {job.id}: trying to stop container .... ({external_id})")
# self.watched = [cjs for cjs in self.watched if cjs.job_id != external_id]
- new_watch_list = list()
+ new_watch_list = []
cjs = None
for tcjs in self.watched:
if tcjs.job_id != external_id:
diff --git a/lib/galaxy/jobs/runners/drmaa.py b/lib/galaxy/jobs/runners/drmaa.py
index 6abb6fbef02e..05c2398da190 100644
--- a/lib/galaxy/jobs/runners/drmaa.py
+++ b/lib/galaxy/jobs/runners/drmaa.py
@@ -51,7 +51,7 @@ def __init__(self, app, nworkers, **kwargs):
runner_param_specs[f"{retry_exception}_retries"] = dict(map=int, valid=lambda x: int(x) >= 0, default=0)
if "runner_param_specs" not in kwargs:
- kwargs["runner_param_specs"] = dict()
+ kwargs["runner_param_specs"] = {}
kwargs["runner_param_specs"].update(runner_param_specs)
super().__init__(app, nworkers, **kwargs)
diff --git a/lib/galaxy/jobs/runners/godocker.py b/lib/galaxy/jobs/runners/godocker.py
index bcacb84fb700..4ba4b6c67ab5 100644
--- a/lib/galaxy/jobs/runners/godocker.py
+++ b/lib/galaxy/jobs/runners/godocker.py
@@ -133,7 +133,7 @@ def __init__(self, app, nworkers, **kwargs):
godocker_master=dict(map=str), user=dict(map=str), key=dict(map=str), godocker_project=dict(map=str)
)
if "runner_param_specs" not in kwargs:
- kwargs["runner_param_specs"] = dict()
+ kwargs["runner_param_specs"] = {}
kwargs["runner_param_specs"].update(runner_param_specs)
# Start the job runner parent object
@@ -379,7 +379,7 @@ def post_task(self, job_wrapper):
volume = job_destination.params["godocker_volumes"]
volume = volume.split(",")
for i in volume:
- temp = dict({"name": i})
+ temp = {"name": i}
volumes.append(temp)
except Exception:
log.debug("godocker_volume not set, using default.")
diff --git a/lib/galaxy/jobs/runners/kubernetes.py b/lib/galaxy/jobs/runners/kubernetes.py
index ffac91490a2f..a360f0c87aab 100644
--- a/lib/galaxy/jobs/runners/kubernetes.py
+++ b/lib/galaxy/jobs/runners/kubernetes.py
@@ -112,7 +112,7 @@ def __init__(self, app, nworkers, **kwargs):
)
if "runner_param_specs" not in kwargs:
- kwargs["runner_param_specs"] = dict()
+ kwargs["runner_param_specs"] = {}
kwargs["runner_param_specs"].update(runner_param_specs)
# Start the job runner parent object
@@ -972,8 +972,7 @@ def __cleanup_k8s_guest_ports(self, job_wrapper, k8s_job):
else:
log.debug(f"No service found for job with k8s_job_name {k8s_job_name}")
# remove the interactive environment entrypoints
- eps = job_wrapper.get_job().interactivetool_entry_points
- if eps:
+ if eps := job_wrapper.get_job().interactivetool_entry_points:
log.debug(f"Removing entry points for job with ID {job_wrapper.get_id_tag()}")
self.app.interactivetool_manager.remove_entry_points(eps)
diff --git a/lib/galaxy/jobs/runners/univa.py b/lib/galaxy/jobs/runners/univa.py
index 12cf317db4f5..edcfdce07fca 100644
--- a/lib/galaxy/jobs/runners/univa.py
+++ b/lib/galaxy/jobs/runners/univa.py
@@ -72,7 +72,7 @@ def check_watched_item(self, ajs, new_watched):
return state
def _complete_terminal_job(self, ajs, drmaa_state, **kwargs):
- extinfo = dict()
+ extinfo = {}
# get state with job_info/qstat + wait/qacct
state = self._get_drmaa_state(ajs.job_id, self.ds, True, extinfo)
# log.debug("UnivaJobRunner:_complete_terminal_job ({jobid}) -> state {state} info {info}".format(jobid=ajs.job_id, state=self.drmaa_job_state_strings[state], info=extinfo))
@@ -214,7 +214,7 @@ def _get_drmaa_state_qacct(self, job_id, extinfo):
# log.debug("UnivaJobRunner._get_drmaa_state_qacct ({jobid})".format(jobid=job_id))
signals = {
k: v
- for v, k in reversed(sorted(signal.__dict__.items()))
+ for v, k in sorted(signal.__dict__.items(), reverse=True)
if v.startswith("SIG") and not v.startswith("SIG_")
}
cmd = ["qacct", "-j", job_id]
@@ -235,7 +235,7 @@ def _get_drmaa_state_qacct(self, job_id, extinfo):
return self.drmaa.JobState.UNDETERMINED
else:
break
- qacct = dict()
+ qacct = {}
for line in stdout.split("\n"):
# remove header
if line.startswith("=") or line == "":
diff --git a/lib/galaxy/managers/collections.py b/lib/galaxy/managers/collections.py
index 8db9037b55a5..9798445bcc6f 100644
--- a/lib/galaxy/managers/collections.py
+++ b/lib/galaxy/managers/collections.py
@@ -350,7 +350,7 @@ def get_converters_for_collection(
suitable_converters = suitable_converters.intersection(set_of_new_converters)
if suitable_converters:
most_recent_datatype = datatype
- suitable_tool_ids = list()
+ suitable_tool_ids = []
for tool in suitable_converters:
tool_info = {
"tool_id": tool[1].id,
diff --git a/lib/galaxy/managers/datasets.py b/lib/galaxy/managers/datasets.py
index 612a69989deb..207d92ca407c 100644
--- a/lib/galaxy/managers/datasets.py
+++ b/lib/galaxy/managers/datasets.py
@@ -164,8 +164,7 @@ def update_object_store_id(self, trans, dataset, object_store_id: str):
# has been shared.
raise exceptions.InsufficientPermissionsException("Cannot change dataset permissions...")
- quota_source_map = self.app.object_store.get_quota_source_map()
- if quota_source_map:
+ if quota_source_map := self.app.object_store.get_quota_source_map():
old_label = quota_source_map.get_quota_source_label(old_object_store_id)
new_label = quota_source_map.get_quota_source_label(new_object_store_id)
if old_label != new_label:
diff --git a/lib/galaxy/managers/datatypes.py b/lib/galaxy/managers/datatypes.py
index 72dbbdb8f5a5..9899cf8b98a2 100644
--- a/lib/galaxy/managers/datatypes.py
+++ b/lib/galaxy/managers/datatypes.py
@@ -25,7 +25,7 @@ def view_index(
if upload_only:
return datatypes_registry.upload_file_formats
else:
- return [ext for ext in datatypes_registry.datatypes_by_extension]
+ return list(datatypes_registry.datatypes_by_extension)
else:
rval = []
for datatype_info_dict in datatypes_registry.datatype_info_dicts:
diff --git a/lib/galaxy/managers/history_contents.py b/lib/galaxy/managers/history_contents.py
index 0a4a09f08f00..c73e82b12ce1 100644
--- a/lib/galaxy/managers/history_contents.py
+++ b/lib/galaxy/managers/history_contents.py
@@ -236,9 +236,7 @@ def _union_of_contents(self, container, expand_models=True, **kwargs):
return contents_results
# partition ids into a map of { component_class names -> list of ids } from the above union query
- id_map: Dict[str, List[int]] = dict(
- [(self.contained_class_type_name, []), (self.subcontainer_class_type_name, [])]
- )
+ id_map: Dict[str, List[int]] = {self.contained_class_type_name: [], self.subcontainer_class_type_name: []}
for result in contents_results:
result_type = self._get_union_type(result)
contents_id = self._get_union_id(result)
diff --git a/lib/galaxy/managers/libraries.py b/lib/galaxy/managers/libraries.py
index 45c1c582a074..2ed55907fe79 100644
--- a/lib/galaxy/managers/libraries.py
+++ b/lib/galaxy/managers/libraries.py
@@ -155,7 +155,7 @@ def list(self, trans, deleted: Optional[bool] = False) -> Tuple[Query, Dict[str,
"""
is_admin = trans.user_is_admin
library_access_action = trans.app.security_agent.permitted_actions.LIBRARY_ACCESS.action
- restricted_library_ids = {id for id in get_library_ids(trans.sa_session, library_access_action)}
+ restricted_library_ids = set(get_library_ids(trans.sa_session, library_access_action))
prefetched_ids = {"restricted_library_ids": restricted_library_ids}
if is_admin:
diff --git a/lib/galaxy/managers/users.py b/lib/galaxy/managers/users.py
index 8f4b9c428e82..c1795da3b395 100644
--- a/lib/galaxy/managers/users.py
+++ b/lib/galaxy/managers/users.py
@@ -406,7 +406,7 @@ def user_can_do_run_as(self, user) -> bool:
# ---- preferences
def preferences(self, user):
- return {key: value for key, value in user.preferences.items()}
+ return dict(user.preferences.items())
# ---- roles and permissions
def private_role(self, user):
diff --git a/lib/galaxy/model/__init__.py b/lib/galaxy/model/__init__.py
index 1e7353c93060..0291c08fbced 100644
--- a/lib/galaxy/model/__init__.py
+++ b/lib/galaxy/model/__init__.py
@@ -2562,7 +2562,7 @@ class FakeDatasetAssociation:
def __init__(self, dataset=None):
self.dataset = dataset
- self.metadata = dict()
+ self.metadata = {}
def get_file_name(self, sync_cache=True):
return self.dataset.get_file_name(sync_cache)
@@ -4241,8 +4241,8 @@ def to_int(n) -> Optional[int]:
total_size=to_int(self.total_size),
created_from_basename=self.created_from_basename,
uuid=str(self.uuid or "") or None,
- hashes=list(map(lambda h: h.serialize(id_encoder, serialization_options), self.hashes)),
- sources=list(map(lambda s: s.serialize(id_encoder, serialization_options), self.sources)),
+ hashes=[h.serialize(id_encoder, serialization_options) for h in self.hashes],
+ sources=[s.serialize(id_encoder, serialization_options) for s in self.sources],
)
serialization_options.attach_identifier(id_encoder, self, rval)
return rval
@@ -4404,7 +4404,7 @@ def __init__(
self.designation = designation
# set private variable to None here, since the attribute may be needed in by MetadataCollection.__init__
self._metadata = None
- self.metadata = metadata or dict()
+ self.metadata = metadata or {}
self.metadata_deferred = metadata_deferred
self.extended_metadata = extended_metadata
if (
@@ -6571,7 +6571,7 @@ def _serialize(self, id_encoder, serialization_options):
type=self.collection_type,
populated_state=self.populated_state,
populated_state_message=self.populated_state_message,
- elements=list(map(lambda e: e.serialize(id_encoder, serialization_options), self.elements)),
+ elements=[e.serialize(id_encoder, serialization_options) for e in self.elements],
)
serialization_options.attach_identifier(id_encoder, self, rval)
return rval
@@ -8493,7 +8493,7 @@ def poll_unhandled_workflow_ids(sa_session):
.where(WorkflowInvocation.handler.is_(None))
.order_by(WorkflowInvocation.id.asc())
)
- return [wid for wid in sa_session.scalars(stmt)]
+ return list(sa_session.scalars(stmt))
@staticmethod
def poll_active_workflow_ids(engine, scheduler=None, handler=None):
diff --git a/lib/galaxy/model/dataset_collections/structure.py b/lib/galaxy/model/dataset_collections/structure.py
index af6395054b27..673585a8c87f 100644
--- a/lib/galaxy/model/dataset_collections/structure.py
+++ b/lib/galaxy/model/dataset_collections/structure.py
@@ -149,7 +149,7 @@ def clone(self):
return Tree(cloned_children, self.collection_type_description)
def __str__(self):
- return f"Tree[collection_type={self.collection_type_description},children={','.join(map(lambda identifier_and_element: f'{identifier_and_element[0]}={identifier_and_element[1]}', self.children))}]"
+ return f"Tree[collection_type={self.collection_type_description},children={','.join(f'{identifier_and_element[0]}={identifier_and_element[1]}' for identifier_and_element in self.children)}]"
def tool_output_to_structure(get_sliced_input_collection_structure, tool_output, collections_manager):
diff --git a/lib/galaxy/model/security.py b/lib/galaxy/model/security.py
index 378f446c5155..8769c132c3db 100644
--- a/lib/galaxy/model/security.py
+++ b/lib/galaxy/model/security.py
@@ -110,7 +110,7 @@ def get_all_roles(self, trans, cntrller):
# Add all remaining non-private, non-sharing roles
for role in self._get_npns_roles(trans):
roles.add(role)
- return self.sort_by_attr([role for role in roles], "name")
+ return self.sort_by_attr(list(roles), "name")
def get_roles_for_action(self, item, action):
"""
@@ -218,7 +218,7 @@ def get_valid_roles(self, trans, item, query=None, page=None, page_limit=None, i
return_roles = set(roles)
if total_count is None:
total_count = len(return_roles)
- return self.sort_by_attr([role for role in return_roles], "name"), total_count
+ return self.sort_by_attr(list(return_roles), "name"), total_count
def get_legitimate_roles(self, trans, item, cntrller):
"""
@@ -269,7 +269,7 @@ def get_legitimate_roles(self, trans, item, cntrller):
for ura in user.roles:
if admin_controller or self.ok_to_display(trans.user, ura.role):
roles.add(ura.role)
- return self.sort_by_attr([role for role in roles], "name")
+ return self.sort_by_attr(list(roles), "name")
def ok_to_display(self, user, role):
"""
diff --git a/lib/galaxy/model/tags.py b/lib/galaxy/model/tags.py
index a62051b79eef..8d31bc32ba1d 100644
--- a/lib/galaxy/model/tags.py
+++ b/lib/galaxy/model/tags.py
@@ -369,7 +369,7 @@ def parse_tags(self, tag_str):
"""
# Gracefully handle None.
if not tag_str:
- return dict()
+ return {}
# Strip unicode control characters
tag_str = strip_control_characters(tag_str)
# Split tags based on separators.
@@ -423,7 +423,7 @@ def _scrub_tag_name(self, name):
def _scrub_tag_name_list(self, tag_name_list):
"""Scrub a tag name list."""
- scrubbed_tag_list = list()
+ scrubbed_tag_list = []
for tag in tag_name_list:
scrubbed_tag_list.append(self._scrub_tag_name(tag))
return scrubbed_tag_list
diff --git a/lib/galaxy/objectstore/pithos.py b/lib/galaxy/objectstore/pithos.py
index cd20cbbe8771..fdfb78bf6d90 100644
--- a/lib/galaxy/objectstore/pithos.py
+++ b/lib/galaxy/objectstore/pithos.py
@@ -43,7 +43,7 @@ def parse_config_xml(config_xml):
:returns: (dict) according to syntax
:raises: various XML parse errors
"""
- r = dict()
+ r = {}
try:
for tag, required_attrs, optional_attrs in (
(
diff --git a/lib/galaxy/security/object_wrapper.py b/lib/galaxy/security/object_wrapper.py
index 1c7176a29b16..df4ead07d6ea 100644
--- a/lib/galaxy/security/object_wrapper.py
+++ b/lib/galaxy/security/object_wrapper.py
@@ -217,7 +217,7 @@ def pickle_safe_object(safe_object):
no_wrap_classes = list(no_wrap_classes) + list(__DONT_SANITIZE_TYPES__) + [SafeStringWrapper]
else:
no_wrap_classes = list(__DONT_SANITIZE_TYPES__) + [SafeStringWrapper]
- no_wrap_classes = tuple(set(sorted(no_wrap_classes, key=str)))
+ no_wrap_classes = tuple(set(no_wrap_classes))
return __do_wrap(value)
diff --git a/lib/galaxy/tool_shed/galaxy_install/repository_dependencies/repository_dependency_manager.py b/lib/galaxy/tool_shed/galaxy_install/repository_dependencies/repository_dependency_manager.py
index b367a3322fba..17facc7a0b39 100644
--- a/lib/galaxy/tool_shed/galaxy_install/repository_dependencies/repository_dependency_manager.py
+++ b/lib/galaxy/tool_shed/galaxy_install/repository_dependencies/repository_dependency_manager.py
@@ -193,7 +193,7 @@ def create_repository_dependency_objects(
all_repo_info_dicts = all_required_repo_info_dict.get("all_repo_info_dicts", [])
if not all_repo_info_dicts:
# No repository dependencies were discovered so process the received repositories.
- all_repo_info_dicts = [rid for rid in repo_info_dicts]
+ all_repo_info_dicts = list(repo_info_dicts)
for repo_info_dict in all_repo_info_dicts:
# If the user elected to install repository dependencies, all items in the
# all_repo_info_dicts list will be processed. However, if repository dependencies
diff --git a/lib/galaxy/tool_shed/galaxy_install/tools/data_manager.py b/lib/galaxy/tool_shed/galaxy_install/tools/data_manager.py
index 95af11b21f53..d4f2157f82d5 100644
--- a/lib/galaxy/tool_shed/galaxy_install/tools/data_manager.py
+++ b/lib/galaxy/tool_shed/galaxy_install/tools/data_manager.py
@@ -92,7 +92,9 @@ def install_data_managers(
raise
if tree is None:
return rval
- config_elems = [elem for elem in tree.getroot()]
+ config_elems = list(
+ tree.getroot().__iter__()
+ ) # `.__iter__()` is a workaround for lxml-stubs declaring _Element a subclass of Iterable["_Element"]
repo_data_manager_conf_filename = metadata_dict["data_manager"].get("config_filename", None)
if repo_data_manager_conf_filename is None:
log.debug("No data_manager_conf.xml file has been defined.")
diff --git a/lib/galaxy/tool_shed/util/utility_container_manager.py b/lib/galaxy/tool_shed/util/utility_container_manager.py
index 07582e5e8362..e67d552aa2ee 100644
--- a/lib/galaxy/tool_shed/util/utility_container_manager.py
+++ b/lib/galaxy/tool_shed/util/utility_container_manager.py
@@ -863,7 +863,7 @@ def prune_repository_dependencies(self, folder):
dependency has its own repository dependency). This method will remove all repository
dependencies from folder that are also sub-folders of folder.
"""
- repository_dependencies = [rd for rd in folder.repository_dependencies]
+ repository_dependencies = list(folder.repository_dependencies)
for repository_dependency in repository_dependencies:
self.prune_folder(folder, repository_dependency)
for sub_folder in folder.folders:
diff --git a/lib/galaxy/tool_util/data/__init__.py b/lib/galaxy/tool_util/data/__init__.py
index 921dc100fd38..04786715be8e 100644
--- a/lib/galaxy/tool_util/data/__init__.py
+++ b/lib/galaxy/tool_util/data/__init__.py
@@ -1113,7 +1113,7 @@ def to_xml_file(
else:
raise
root = tree.getroot()
- out_elems = [elem for elem in root]
+ out_elems = list(root)
except Exception as e:
out_elems = []
log.debug("Could not parse existing tool data table config, assume no existing elements: %s", e)
diff --git a/lib/galaxy/tool_util/deps/__init__.py b/lib/galaxy/tool_util/deps/__init__.py
index 2dc75c3dfac3..6a1eff2f1aa6 100644
--- a/lib/galaxy/tool_util/deps/__init__.py
+++ b/lib/galaxy/tool_util/deps/__init__.py
@@ -149,7 +149,7 @@ def __init__(
def set_enabled_container_types(self, container_types_to_destinations):
"""Set the union of all enabled container types."""
- self._enabled_container_types = [container_type for container_type in container_types_to_destinations.keys()]
+ self._enabled_container_types = list(container_types_to_destinations.keys())
# Just pick first enabled destination for a container type, probably covers the most common deployment scenarios
self._destination_for_container_type = container_types_to_destinations
@@ -323,7 +323,7 @@ def _requirements_to_dependencies_dict(self, requirements, search=False, **kwds)
return requirement_to_dependency
def uses_tool_shed_dependencies(self):
- return any(map(lambda r: isinstance(r, ToolShedPackageDependencyResolver), self.dependency_resolvers))
+ return any(isinstance(r, ToolShedPackageDependencyResolver) for r in self.dependency_resolvers)
def find_dep(self, name: str, version: Optional[str] = None, type: str = "package", **kwds):
log.debug(f"Find dependency {name} version {version}")
diff --git a/lib/galaxy/tool_util/deps/brew_exts.py b/lib/galaxy/tool_util/deps/brew_exts.py
index 852d7425a908..0f56b279251a 100755
--- a/lib/galaxy/tool_util/deps/brew_exts.py
+++ b/lib/galaxy/tool_util/deps/brew_exts.py
@@ -380,7 +380,7 @@ def __init__(self, keg_root, action_description):
@staticmethod
def build_env(env_actions):
new_env = os.environ.copy()
- map(lambda env_action: env_action.modify_environ(new_env), env_actions)
+ (env_action.modify_environ(new_env) for env_action in env_actions)
return new_env
def modify_environ(self, environ):
@@ -523,7 +523,7 @@ def recipe_cellar_path(cellar_path, recipe, version):
recipe_base_path = os.path.join(cellar_path, recipe_base, version)
revision_paths = glob.glob(f"{recipe_base_path}_*")
if revision_paths:
- revisions = map(lambda x: int(x.rsplit("_", 1)[-1]), revision_paths)
+ revisions = (int(x.rsplit("_", 1)[-1]) for x in revision_paths)
max_revision = max(revisions)
recipe_path = "%s_%d" % (recipe_base_path, max_revision)
else:
diff --git a/lib/galaxy/tool_util/deps/conda_util.py b/lib/galaxy/tool_util/deps/conda_util.py
index d5190383a1f9..4905b6091e3e 100644
--- a/lib/galaxy/tool_util/deps/conda_util.py
+++ b/lib/galaxy/tool_util/deps/conda_util.py
@@ -254,7 +254,7 @@ def exec_command(self, operation: str, args: List[str], stdout_path: Optional[st
if self.condarc_override:
env["CONDARC"] = self.condarc_override
cmd_string = shlex_join(cmd)
- kwds: Dict[str, Any] = dict()
+ kwds: Dict[str, Any] = {}
try:
if stdout_path:
kwds["stdout"] = open(stdout_path, "w")
diff --git a/lib/galaxy/tool_util/deps/container_classes.py b/lib/galaxy/tool_util/deps/container_classes.py
index 6fade14c37b4..880a3a5d4b59 100644
--- a/lib/galaxy/tool_util/deps/container_classes.py
+++ b/lib/galaxy/tool_util/deps/container_classes.py
@@ -320,7 +320,7 @@ def _expand_volume_str(self: ContainerProtocol, value: str) -> str:
return value
template = string.Template(value)
- variables = dict()
+ variables = {}
def add_var(name, value):
if value:
diff --git a/lib/galaxy/tool_util/deps/container_resolvers/mulled.py b/lib/galaxy/tool_util/deps/container_resolvers/mulled.py
index 1e51bcf97a17..b976662ccf6b 100644
--- a/lib/galaxy/tool_util/deps/container_resolvers/mulled.py
+++ b/lib/galaxy/tool_util/deps/container_resolvers/mulled.py
@@ -111,8 +111,8 @@ def __init__(self, path: str, hash_func: Literal["v1", "v2"] = "v2") -> None:
def _list_cached_mulled_images_from_path(self) -> List[CachedTarget]:
contents = os.listdir(self.path)
sorted_images = version_sorted(contents)
- raw_images = map(lambda name: identifier_to_cached_target(name, self.hash_func), sorted_images)
- return list(i for i in raw_images if i is not None)
+ raw_images = (identifier_to_cached_target(name, self.hash_func) for name in sorted_images)
+ return [i for i in raw_images if i is not None]
@abstractmethod
def list_cached_mulled_images_from_path(self) -> List[CachedTarget]:
@@ -202,7 +202,7 @@ def output_line_to_image(line: str) -> Optional[CachedTarget]:
return image
name_filter = get_filter(namespace)
- sorted_images = version_sorted([_ for _ in filter(name_filter, images_and_versions)])
+ sorted_images = version_sorted(list(filter(name_filter, images_and_versions)))
raw_images = (output_line_to_image(_) for _ in sorted_images)
return [i for i in raw_images if i is not None]
diff --git a/lib/galaxy/tool_util/deps/mulled/mulled_build.py b/lib/galaxy/tool_util/deps/mulled/mulled_build.py
index d2f6e0dc0090..173f4a9fc2f6 100644
--- a/lib/galaxy/tool_util/deps/mulled/mulled_build.py
+++ b/lib/galaxy/tool_util/deps/mulled/mulled_build.py
@@ -150,7 +150,7 @@ def get_affected_packages(args):
def conda_versions(pkg_name, file_name):
"""Return all conda version strings for a specified package name."""
j = json.load(open(file_name))
- ret = list()
+ ret = []
for pkg in j["packages"].values():
if pkg["name"] == pkg_name:
ret.append(f"{pkg['version']}--{pkg['build']}")
diff --git a/lib/galaxy/tool_util/deps/mulled/mulled_search.py b/lib/galaxy/tool_util/deps/mulled/mulled_search.py
index adb9cb91fc1b..a2553ddf770c 100755
--- a/lib/galaxy/tool_util/deps/mulled/mulled_search.py
+++ b/lib/galaxy/tool_util/deps/mulled/mulled_search.py
@@ -88,7 +88,7 @@ def search_repository(self, search_string, non_strict):
results_tmp = searcher.search(query)
results.extend(results_tmp)
- out = list()
+ out = []
for result in results:
title = result["title"]
diff --git a/lib/galaxy/tool_util/deps/mulled/util.py b/lib/galaxy/tool_util/deps/mulled/util.py
index 507a6bb5fe89..17aa33ba8fa2 100644
--- a/lib/galaxy/tool_util/deps/mulled/util.py
+++ b/lib/galaxy/tool_util/deps/mulled/util.py
@@ -347,14 +347,14 @@ def v2_image_name(
return _simple_image_name(targets, image_build=image_build)
else:
targets_order = sorted(targets, key=lambda t: t.package)
- package_name_buffer = "\n".join(map(lambda t: t.package, targets_order))
+ package_name_buffer = "\n".join(t.package for t in targets_order)
package_hash = hashlib.sha1()
package_hash.update(package_name_buffer.encode())
- versions = map(lambda t: t.version, targets_order)
+ versions = (t.version for t in targets_order)
if any(versions):
# Only hash versions if at least one package has versions...
- version_name_buffer = "\n".join(map(lambda t: t.version or "null", targets_order))
+ version_name_buffer = "\n".join(t.version or "null" for t in targets_order)
version_hash = hashlib.sha1()
version_hash.update(version_name_buffer.encode())
version_hash_str = version_hash.hexdigest()
diff --git a/lib/galaxy/tool_util/linters/inputs.py b/lib/galaxy/tool_util/linters/inputs.py
index 7f0e8889543f..d24644a1f37b 100644
--- a/lib/galaxy/tool_util/linters/inputs.py
+++ b/lib/galaxy/tool_util/linters/inputs.py
@@ -622,7 +622,7 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
if param_type != "select":
continue
select_options = param.findall("./option")
- select_options_values = list()
+ select_options_values = []
for option in select_options:
value = option.attrib.get("value", "")
select_options_values.append((value, option.attrib.get("selected", "false")))
@@ -648,7 +648,7 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
if param_type != "select":
continue
select_options = param.findall("./option")
- select_options_texts = list()
+ select_options_texts = []
for option in select_options:
if option.text is None:
text = option.attrib.get("value", "").capitalize()
@@ -702,7 +702,7 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
if options is None:
continue
filter_adds_options = any(
- [f.get("type", None) in ["add_value", "data_meta"] for f in param.findall("./options/filter")]
+ f.get("type", None) in ["add_value", "data_meta"] for f in param.findall("./options/filter")
)
from_file = options.get("from_file", None)
from_parameter = options.get("from_parameter", None)
@@ -1314,11 +1314,11 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
continue
if first_param_type == "select":
options = first_param.findall("./option[@value]")
- option_ids = set([option.get("value") for option in options])
+ option_ids = {option.get("value") for option in options}
else: # boolean
- option_ids = set([first_param.get("truevalue", "true"), first_param.get("falsevalue", "false")])
+ option_ids = {first_param.get("truevalue", "true"), first_param.get("falsevalue", "false")}
whens = conditional.findall("./when[@value]")
- when_ids = set([w.get("value") for w in whens if w.get("value") is not None])
+ when_ids = {w.get("value") for w in whens if w.get("value") is not None}
for option_id in option_ids - when_ids:
lint_ctx.warn(
f"Conditional [{conditional_name}] no block found for {first_param_type} option '{option_id}'",
@@ -1337,9 +1337,9 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
if first_param_type != "select":
continue
options = first_param.findall("./option[@value]")
- option_ids = set([option.get("value") for option in options])
+ option_ids = {option.get("value") for option in options}
whens = conditional.findall("./when[@value]")
- when_ids = set([w.get("value") for w in whens if w.get("value") is not None])
+ when_ids = {w.get("value") for w in whens if w.get("value") is not None}
for when_id in when_ids - option_ids:
lint_ctx.warn(
f"Conditional [{conditional_name}] no found for when block '{when_id}'",
@@ -1357,9 +1357,9 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
for conditional, conditional_name, first_param, first_param_type in _iter_conditional(tool_xml):
if first_param_type != "boolean":
continue
- option_ids = set([first_param.get("truevalue", "true"), first_param.get("falsevalue", "false")])
+ option_ids = {first_param.get("truevalue", "true"), first_param.get("falsevalue", "false")}
whens = conditional.findall("./when[@value]")
- when_ids = set([w.get("value") for w in whens if w.get("value")])
+ when_ids = {w.get("value") for w in whens if w.get("value")}
for when_id in when_ids - option_ids:
lint_ctx.warn(
f"Conditional [{conditional_name}] no truevalue/falsevalue found for when block '{when_id}'",
diff --git a/lib/galaxy/tool_util/linters/tests.py b/lib/galaxy/tool_util/linters/tests.py
index cb0cb7f29da7..8eba1a16259e 100644
--- a/lib/galaxy/tool_util/linters/tests.py
+++ b/lib/galaxy/tool_util/linters/tests.py
@@ -78,7 +78,7 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
):
if a.tag not in ["has_n_lines", "has_n_columns"]:
continue
- if not (set(a.attrib) & set(["n", "min", "max"])):
+ if not (set(a.attrib) & {"n", "min", "max"}):
lint_ctx.error(
f"Test {test_idx}: '{a.tag}' needs to specify 'n', 'min', or 'max'", linter=cls.name(), node=a
)
@@ -101,7 +101,7 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
):
if a.tag != "has_size":
continue
- if len(set(a.attrib) & set(["value", "size", "min", "max"])) == 0:
+ if len(set(a.attrib) & {"value", "size", "min", "max"}) == 0:
lint_ctx.error(
f"Test {test_idx}: '{a.tag}' needs to specify 'size', 'min', or 'max'",
linter=cls.name(),
@@ -522,7 +522,7 @@ def lint(cls, tool_source: "ToolSource", lint_ctx: "LintContext"):
def _iter_tests(tests: List["Element"], valid: bool) -> Iterator[Tuple[int, "Element"]]:
for test_idx, test in enumerate(tests, start=1):
is_valid = False
- is_valid |= bool(set(test.attrib) & set(("expect_failure", "expect_exit_code", "expect_num_outputs")))
+ is_valid |= bool(set(test.attrib) & {"expect_failure", "expect_exit_code", "expect_num_outputs"})
for ta in ("assert_stdout", "assert_stderr", "assert_command"):
if test.find(ta) is not None:
is_valid = True
diff --git a/lib/galaxy/tool_util/parser/output_collection_def.py b/lib/galaxy/tool_util/parser/output_collection_def.py
index 4d16cb5d3539..1e80ba1ea950 100644
--- a/lib/galaxy/tool_util/parser/output_collection_def.py
+++ b/lib/galaxy/tool_util/parser/output_collection_def.py
@@ -60,7 +60,7 @@ def _validate_collectors(collectors):
def dataset_collector_descriptions_from_list(discover_datasets_dicts):
- return list(map(lambda kwds: dataset_collection_description(**kwds), discover_datasets_dicts))
+ return [dataset_collection_description(**kwds) for kwds in discover_datasets_dicts]
def dataset_collection_description(**kwargs):
diff --git a/lib/galaxy/tool_util/parser/output_objects.py b/lib/galaxy/tool_util/parser/output_objects.py
index da819cab5172..27d06ca29c2b 100644
--- a/lib/galaxy/tool_util/parser/output_objects.py
+++ b/lib/galaxy/tool_util/parser/output_objects.py
@@ -128,7 +128,7 @@ def to_dict(self, view="collection", value_mapper=None, app=None):
as_dict["edam_format"] = edam_format
edam_data = app.datatypes_registry.edam_data.get(self.format)
as_dict["edam_data"] = edam_data
- as_dict["discover_datasets"] = list(map(lambda d: d.to_dict(), self.dataset_collector_descriptions))
+ as_dict["discover_datasets"] = [d.to_dict() for d in self.dataset_collector_descriptions]
return as_dict
@staticmethod
diff --git a/lib/galaxy/tool_util/parser/xml.py b/lib/galaxy/tool_util/parser/xml.py
index 7da01570ff81..749b3beb0fb8 100644
--- a/lib/galaxy/tool_util/parser/xml.py
+++ b/lib/galaxy/tool_util/parser/xml.py
@@ -990,8 +990,8 @@ def __parse_param_elem(param_elem, i=0):
class StdioParser:
def __init__(self, root):
try:
- self.stdio_exit_codes = list()
- self.stdio_regexes = list()
+ self.stdio_exit_codes = []
+ self.stdio_regexes = []
# We should have a single element, but handle the case for
# multiples.
diff --git a/lib/galaxy/tool_util/parser/yaml.py b/lib/galaxy/tool_util/parser/yaml.py
index 3270b49dead3..020f0019e99e 100644
--- a/lib/galaxy/tool_util/parser/yaml.py
+++ b/lib/galaxy/tool_util/parser/yaml.py
@@ -361,7 +361,7 @@ def parse_when_input_sources(self):
return sources
def parse_static_options(self):
- static_options = list()
+ static_options = []
input_dict = self.input_dict
for option in input_dict.get("options", {}):
value = option.get("value")
diff --git a/lib/galaxy/tool_util/toolbox/panel.py b/lib/galaxy/tool_util/toolbox/panel.py
index fb3e3127512e..0dd2fbbb3525 100644
--- a/lib/galaxy/tool_util/toolbox/panel.py
+++ b/lib/galaxy/tool_util/toolbox/panel.py
@@ -55,7 +55,7 @@ class ToolSection(Dictifiable, HasPanelItems):
def __init__(self, item=None):
"""Build a ToolSection from an ElementTree element or a dictionary."""
if item is None:
- item = dict()
+ item = {}
self.name = item.get("name") or ""
self.id = item.get("id") or ""
self.version = item.get("version") or ""
diff --git a/lib/galaxy/tool_util/verify/asserts/archive.py b/lib/galaxy/tool_util/verify/asserts/archive.py
index 5ddf786a1053..336b3ccfaee6 100644
--- a/lib/galaxy/tool_util/verify/asserts/archive.py
+++ b/lib/galaxy/tool_util/verify/asserts/archive.py
@@ -27,7 +27,7 @@ def _extract_from_tar(output_bytes, fn):
def _list_from_tar(output_bytes, path):
- lst = list()
+ lst = []
with io.BytesIO(output_bytes) as temp:
with tarfile.open(fileobj=temp, mode="r") as tar_temp:
for fn in tar_temp.getnames():
@@ -45,7 +45,7 @@ def _extract_from_zip(output_bytes, fn):
def _list_from_zip(output_bytes, path):
- lst = list()
+ lst = []
with io.BytesIO(output_bytes) as temp:
with zipfile.ZipFile(temp, mode="r") as zip_temp:
for fn in zip_temp.namelist():
diff --git a/lib/galaxy/tools/__init__.py b/lib/galaxy/tools/__init__.py
index f1640fd437d4..0935e4f6976e 100644
--- a/lib/galaxy/tools/__init__.py
+++ b/lib/galaxy/tools/__init__.py
@@ -765,10 +765,10 @@ def __init__(
self.repository_id = repository_id
self._allow_code_files = allow_code_files
# setup initial attribute values
- self.stdio_exit_codes: List = list()
- self.stdio_regexes: List = list()
- self.inputs_by_page: List[Dict] = list()
- self.display_by_page: List = list()
+ self.stdio_exit_codes: List = []
+ self.stdio_regexes: List = []
+ self.inputs_by_page: List[Dict] = []
+ self.display_by_page: List = []
self.action: Union[str, Tuple[str, str]] = "/tool_runner/index"
self.target = "galaxy_main"
self.method = "post"
@@ -1078,7 +1078,7 @@ def parse(self, tool_source: ToolSource, guid=None, dynamic=False):
if self.environment_variables:
if not self.docker_env_pass_through:
self.docker_env_pass_through = []
- self.docker_env_pass_through.extend(map(lambda x: x["name"], self.environment_variables))
+ self.docker_env_pass_through.extend(x["name"] for x in self.environment_variables)
# Parameters used to build URL for redirection to external app
redirect_url_params = tool_source.parse_redirect_url_params_elem()
@@ -2040,7 +2040,7 @@ def get_static_param_values(self, trans):
require any user input. Will raise an exception if any parameter
does require input.
"""
- args = dict()
+ args = {}
for key, param in self.inputs.items():
# BaseURLToolParameter is now a subclass of HiddenToolParameter, so
# we must check if param is a BaseURLToolParameter first
@@ -3707,7 +3707,7 @@ def add_copied_value_to_new_elements(new_label, dce_object):
# We have a tabular file, where the first column is an existing element identifier,
# and the second column is the new element identifier.
source_new_label = (line.strip().split("\t") for line in new_labels)
- new_labels_dict = {source: new_label for source, new_label in source_new_label}
+ new_labels_dict = dict(source_new_label)
for dce in hdca.collection.elements:
dce_object = dce.element_object
element_identifier = dce.element_identifier
diff --git a/lib/galaxy/tools/error_reports/plugins/sentry.py b/lib/galaxy/tools/error_reports/plugins/sentry.py
index 052f4c19dba3..127621e8803a 100644
--- a/lib/galaxy/tools/error_reports/plugins/sentry.py
+++ b/lib/galaxy/tools/error_reports/plugins/sentry.py
@@ -38,7 +38,7 @@ def submit_report(self, dataset, job, tool, **kwargs):
) # strip the tool's version from its long id
# Add contexts to the report.
- contexts: Dict[str, dict] = dict()
+ contexts: Dict[str, dict] = {}
# - "job" context
contexts["job"] = {
diff --git a/lib/galaxy/tools/parameters/__init__.py b/lib/galaxy/tools/parameters/__init__.py
index ef1f5d1a9d8a..e42b5f025938 100644
--- a/lib/galaxy/tools/parameters/__init__.py
+++ b/lib/galaxy/tools/parameters/__init__.py
@@ -260,7 +260,7 @@ def params_to_strings(
is then json encoded (this allowing complex nested parameters and
such).
"""
- rval = dict()
+ rval = {}
for key, value in param_values.items():
if key in params:
value = params[key].value_to_basic(value, app, use_security=use_security)
@@ -275,7 +275,7 @@ def params_from_strings(params: Dict[str, Union[Group, ToolParameter]], param_va
allow each parameter to convert the basic types into the parameters
preferred form).
"""
- rval = dict()
+ rval = {}
param_values = param_values or {}
for key, value in param_values.items():
param = params.get(key)
@@ -633,7 +633,7 @@ def _get_incoming_value(incoming, key, default):
"""
if f"__{key}__is_composite" in incoming:
composite_keys = incoming[f"__{key}__keys"].split()
- value = dict()
+ value = {}
for composite_key in composite_keys:
value[composite_key] = incoming[f"{key}_{composite_key}"]
return value
diff --git a/lib/galaxy/tools/parameters/dynamic_options.py b/lib/galaxy/tools/parameters/dynamic_options.py
index c93665945d26..4423a9a1bfd6 100644
--- a/lib/galaxy/tools/parameters/dynamic_options.py
+++ b/lib/galaxy/tools/parameters/dynamic_options.py
@@ -912,8 +912,7 @@ def strip_or_none(maybe_string: Optional[Element]) -> Optional[str]:
def parse_from_url_options(elem: Element) -> Optional[FromUrlOptions]:
- from_url = elem.get("from_url")
- if from_url:
+ if from_url := elem.get("from_url"):
request_method = cast(Literal["GET", "POST"], elem.get("request_method", "GET"))
assert request_method in get_args(REQUEST_METHODS)
request_headers = strip_or_none(elem.find("request_headers"))
diff --git a/lib/galaxy/tools/parameters/grouping.py b/lib/galaxy/tools/parameters/grouping.py
index 4ee100cbce7d..c53023cf410e 100644
--- a/lib/galaxy/tools/parameters/grouping.py
+++ b/lib/galaxy/tools/parameters/grouping.py
@@ -272,7 +272,7 @@ def get_composite_dataset_name(self, context):
if dataset_name is None:
dataset_name = context.get("files_metadata", {}).get("base_name", None)
if dataset_name is None:
- filenames = list()
+ filenames = []
for composite_file in context.get("files", []):
if not composite_file.get("ftp_files", ""):
filenames.append((composite_file.get("file_data") or {}).get("filename", ""))
@@ -748,7 +748,7 @@ def get_current_case(self, value):
def value_to_basic(self, value, app, use_security=False):
if self.test_param is None:
raise Exception("Must set 'test_param' attribute to use.")
- rval = dict()
+ rval = {}
rval[self.test_param.name] = self.test_param.value_to_basic(value[self.test_param.name], app)
current_case = rval["__current_case__"] = self.get_current_case(value[self.test_param.name])
for input in self.cases[current_case].inputs.values():
@@ -759,7 +759,7 @@ def value_to_basic(self, value, app, use_security=False):
def value_from_basic(self, value, app, ignore_errors=False):
if self.test_param is None:
raise Exception("Must set 'test_param' attribute to use.")
- rval = dict()
+ rval = {}
try:
rval[self.test_param.name] = self.test_param.value_from_basic(
value.get(self.test_param.name), app, ignore_errors
diff --git a/lib/galaxy/tools/parameters/sanitize.py b/lib/galaxy/tools/parameters/sanitize.py
index 5ea49dcd7342..f880f13205c5 100644
--- a/lib/galaxy/tools/parameters/sanitize.py
+++ b/lib/galaxy/tools/parameters/sanitize.py
@@ -59,7 +59,7 @@ def from_element(cls, elem):
rval._valid_chars = rval.get_valid_by_name(valid_elem.get("initial", "default"))
for action_elem in valid_elem:
preset = rval.get_valid_by_name(action_elem.get("preset", "none"))
- valid_value = [val for val in action_elem.get("value", [])]
+ valid_value = list(action_elem.get("value", []))
if action_elem.tag.lower() == "add":
for val in preset + valid_value:
if val not in rval._valid_chars:
diff --git a/lib/galaxy/tools/recommendations.py b/lib/galaxy/tools/recommendations.py
index f4041988afd2..6ff5f16c5701 100644
--- a/lib/galaxy/tools/recommendations.py
+++ b/lib/galaxy/tools/recommendations.py
@@ -27,12 +27,12 @@ class ToolRecommendations:
def __init__(self):
self.tool_recommendation_model_path = None
self.admin_tool_recommendations_path = None
- self.deprecated_tools = dict()
- self.admin_recommendations = dict()
- self.model_data_dictionary = dict()
- self.reverse_dictionary = dict()
- self.all_tools = dict()
- self.tool_weights_sorted = dict()
+ self.deprecated_tools = {}
+ self.admin_recommendations = {}
+ self.model_data_dictionary = {}
+ self.reverse_dictionary = {}
+ self.all_tools = {}
+ self.tool_weights_sorted = {}
self.loaded_model = None
self.compatible_tools = None
self.standard_connections = None
@@ -117,7 +117,7 @@ def get_predictions(self, trans, tool_sequence, remote_model_url):
"""
Compute tool predictions
"""
- recommended_tools = dict()
+ recommended_tools = {}
self.__collect_admin_preferences(trans.app.config.admin_tool_recommendations_path)
if self.model_ok is None:
self.__set_model(trans, remote_model_url)
@@ -197,8 +197,8 @@ def __get_tool_extensions(self, trans, tool_id):
module.recover_state(module_state)
inputs = module.get_all_inputs(connectable_only=True)
outputs = module.get_all_outputs()
- input_extensions = list()
- output_extensions = list()
+ input_extensions = []
+ output_extensions = []
for i_ext in inputs:
input_extensions.extend(i_ext["extensions"])
for o_ext in outputs:
@@ -210,7 +210,7 @@ def __filter_tool_predictions(self, trans, prediction_data, tool_ids, tool_score
Filter tool predictions based on datatype compatibility and tool connections.
Add admin preferences to recommendations.
"""
- last_compatible_tools = list()
+ last_compatible_tools = []
if last_tool_name in self.model_data_dictionary:
last_tool_name_id = self.model_data_dictionary[last_tool_name]
if last_tool_name_id in self.compatible_tools:
@@ -225,7 +225,7 @@ def __filter_tool_predictions(self, trans, prediction_data, tool_ids, tool_score
t_ids_scores = zip(tool_ids, tool_scores)
# form the payload of the predicted tools to be shown
for child, score in t_ids_scores:
- c_dict = dict()
+ c_dict = {}
for t_id in self.all_tools:
# select the name and tool id if it is installed in Galaxy
if (
@@ -285,7 +285,7 @@ def __sort_by_usage(self, t_list, class_weights, d_dict):
"""
Sort predictions by usage/class weights
"""
- tool_dict = dict()
+ tool_dict = {}
for tool in t_list:
t_id = d_dict[tool]
tool_dict[tool] = class_weights[int(t_id)]
@@ -296,7 +296,7 @@ def __separate_predictions(self, base_tools, predictions, last_tool_name, weight
"""
Get predictions from published and normal workflows
"""
- last_base_tools = list()
+ last_base_tools = []
prediction_pos = np.argsort(predictions, axis=-1)
topk_prediction_pos = prediction_pos[-topk:]
# get tool ids
@@ -317,10 +317,10 @@ def __compute_tool_prediction(self, trans, tool_sequence):
Return an empty payload with just the tool sequence if anything goes wrong within the try block
"""
topk = trans.app.config.topk_recommendations
- prediction_data = dict()
+ prediction_data = {}
tool_sequence = tool_sequence.split(",")[::-1]
prediction_data["name"] = ",".join(tool_sequence)
- prediction_data["children"] = list()
+ prediction_data["children"] = []
last_tool_name = tool_sequence[-1]
# do prediction only if the last is present in the collections of tools
if last_tool_name in self.model_data_dictionary:
diff --git a/lib/galaxy/util/__init__.py b/lib/galaxy/util/__init__.py
index 4769a6842ba3..f4b9050db271 100644
--- a/lib/galaxy/util/__init__.py
+++ b/lib/galaxy/util/__init__.py
@@ -433,7 +433,7 @@ def xml_element_to_dict(elem):
sub_elems = list(elem)
if sub_elems:
- sub_elem_dict = dict()
+ sub_elem_dict = {}
for sub_sub_elem_dict in map(xml_element_to_dict, sub_elems):
for key, value in sub_sub_elem_dict.items():
if key not in sub_elem_dict:
@@ -1280,8 +1280,8 @@ class ParamsWithSpecs(collections.defaultdict):
""" """
def __init__(self, specs=None, params=None):
- self.specs = specs or dict()
- self.params = params or dict()
+ self.specs = specs or {}
+ self.params = params or {}
for name, value in self.params.items():
if name not in self.specs:
self._param_unknown_error(name)
@@ -1817,7 +1817,7 @@ def parse_non_hex_float(s):
def build_url(base_url, port=80, scheme="http", pathspec=None, params=None, doseq=False):
if params is None:
- params = dict()
+ params = {}
if pathspec is None:
pathspec = []
parsed_url = urlparse(base_url)
diff --git a/lib/galaxy/util/commands.py b/lib/galaxy/util/commands.py
index 206bbb25b3c1..5f71a5455b48 100644
--- a/lib/galaxy/util/commands.py
+++ b/lib/galaxy/util/commands.py
@@ -76,7 +76,7 @@ def shell_process(cmds: Union[List[str], str], env: Optional[Dict[str, str]] = N
redirection.
"""
sys = kwds.get("sys", _sys)
- popen_kwds: Dict[str, Any] = dict()
+ popen_kwds: Dict[str, Any] = {}
if isinstance(cmds, str):
log.warning("Passing program arguments as a string may be a security hazard if combined with untrusted input")
popen_kwds["shell"] = True
diff --git a/lib/galaxy/util/form_builder.py b/lib/galaxy/util/form_builder.py
index 6bb84b4ecb1f..a75167d7def5 100644
--- a/lib/galaxy/util/form_builder.py
+++ b/lib/galaxy/util/form_builder.py
@@ -104,7 +104,7 @@ def __init__(
self.multiple = multiple or False
self.refresh_on_change = refresh_on_change
self.selectlist = selectlist or []
- self.options = list()
+ self.options = []
if display == "checkboxes":
assert multiple, "Checkbox display only supported for multiple select"
elif display == "radio":
diff --git a/lib/galaxy/util/heartbeat.py b/lib/galaxy/util/heartbeat.py
index 48bf6d5ea726..901f87291e8b 100644
--- a/lib/galaxy/util/heartbeat.py
+++ b/lib/galaxy/util/heartbeat.py
@@ -17,7 +17,7 @@ def get_current_thread_object_dict():
module does not expose any way to match 'Thread' objects with
intepreter thread identifiers (though it should).
"""
- rval = dict()
+ rval = {}
# Acquire the lock and then union the contents of 'active' and 'limbo'
# threads into the return value.
threading._active_limbo_lock.acquire()
diff --git a/lib/galaxy/util/rules_dsl.py b/lib/galaxy/util/rules_dsl.py
index 3d34c1df5536..3ce75495e7a3 100644
--- a/lib/galaxy/util/rules_dsl.py
+++ b/lib/galaxy/util/rules_dsl.py
@@ -578,7 +578,7 @@ def identifier_columns(self):
def collection_type(self):
mapping_as_dict = self.mapping_as_dict
list_columns = mapping_as_dict.get("list_identifiers", {"columns": []})["columns"]
- collection_type = ":".join(map(lambda c: "list", list_columns))
+ collection_type = ":".join("list" for c in list_columns)
if "paired_identifier" in mapping_as_dict:
if collection_type:
collection_type += ":paired"
diff --git a/lib/galaxy/util/watcher.py b/lib/galaxy/util/watcher.py
index dd4f0110299a..60fb6887aec5 100644
--- a/lib/galaxy/util/watcher.py
+++ b/lib/galaxy/util/watcher.py
@@ -162,7 +162,7 @@ def _handle(self, event):
ext_ok = self._extension_check(path, path)
else:
# reversed sort for getting the most specific dir first
- for key in reversed(sorted(self.watcher.dir_callbacks.keys())):
+ for key in sorted(self.watcher.dir_callbacks.keys(), reverse=True):
if os.path.commonprefix([path, key]) == key:
callback = self.watcher.dir_callbacks[key]
ext_ok = self._extension_check(key, path)
diff --git a/lib/galaxy/util/xml_macros.py b/lib/galaxy/util/xml_macros.py
index 6ffeb12dfb3c..a00f4e23f8b5 100644
--- a/lib/galaxy/util/xml_macros.py
+++ b/lib/galaxy/util/xml_macros.py
@@ -210,14 +210,14 @@ def _expand_yield_statements(macro_def, expand_el):
for token_el in expand_el.findall("./token"):
name = token_el.attrib.get("name", None)
assert name is not None, "Found unnamed token" + str(token_el.attrib)
- yield_els = [yield_el for yield_el in macro_def.findall(f".//yield[@name='{name}']")]
+ yield_els = list(macro_def.findall(f".//yield[@name='{name}']"))
assert len(yield_els) > 0, f"No named yield found for named token {name}"
token_el_children = list(token_el)
for yield_el in yield_els:
_xml_replace(yield_el, token_el_children)
# replace unnamed yields
- yield_els = [yield_el for yield_el in macro_def.findall(".//yield")]
+ yield_els = list(macro_def.findall(".//yield"))
expand_el_children = [c for c in expand_el if c.tag != "token"]
for yield_el in yield_els:
_xml_replace(yield_el, expand_el_children)
diff --git a/lib/galaxy/web/framework/base.py b/lib/galaxy/web/framework/base.py
index 364e6d4c72e2..1d4c510ef7d6 100644
--- a/lib/galaxy/web/framework/base.py
+++ b/lib/galaxy/web/framework/base.py
@@ -94,8 +94,8 @@ def __init__(self):
`finalize_config` when all controllers and routes have been added
and `__call__` to handle a request (WSGI style).
"""
- self.controllers = dict()
- self.api_controllers = dict()
+ self.controllers = {}
+ self.api_controllers = {}
self.mapper = routes.Mapper()
self.clientside_routes = routes.Mapper(controller_scan=None, register=False)
# FIXME: The following two options are deprecated and should be
diff --git a/lib/galaxy/web/framework/helpers/__init__.py b/lib/galaxy/web/framework/helpers/__init__.py
index a0e7e75b5b0e..7fde6906cf19 100644
--- a/lib/galaxy/web/framework/helpers/__init__.py
+++ b/lib/galaxy/web/framework/helpers/__init__.py
@@ -32,7 +32,7 @@ def time_ago(x):
return x.strftime("%b %d, %Y")
else:
# Workaround https://github.com/python-babel/babel/issues/137
- kwargs = dict()
+ kwargs = {}
if not default_locale("LC_TIME"):
kwargs["locale"] = "en_US_POSIX"
return format_timedelta(x - datetime.utcnow(), threshold=1, add_direction=True, **kwargs) # type: ignore[arg-type] # https://github.com/python/mypy/issues/9676
diff --git a/lib/galaxy/web/legacy_framework/grids.py b/lib/galaxy/web/legacy_framework/grids.py
index 3b62e8665012..f8a923661201 100644
--- a/lib/galaxy/web/legacy_framework/grids.py
+++ b/lib/galaxy/web/legacy_framework/grids.py
@@ -848,7 +848,7 @@ def url(*args, **kwargs):
# Only include sort/filter arguments if not linking to another
# page. This is a bit of a hack.
if "action" in kwargs:
- new_kwargs = dict()
+ new_kwargs = {}
else:
new_kwargs = dict(extra_url_args)
# Extend new_kwargs with first argument if found
diff --git a/lib/galaxy/webapps/base/webapp.py b/lib/galaxy/webapps/base/webapp.py
index 3b5247697f70..8c51b9f14db8 100644
--- a/lib/galaxy/webapps/base/webapp.py
+++ b/lib/galaxy/webapps/base/webapp.py
@@ -1005,7 +1005,7 @@ def new_history(self, name=None):
@base.lazy_property
def template_context(self):
- return dict()
+ return {}
def set_message(self, message, type=None):
"""
diff --git a/lib/galaxy/webapps/galaxy/api/__init__.py b/lib/galaxy/webapps/galaxy/api/__init__.py
index 66e12cc4fd9b..3f19076a2367 100644
--- a/lib/galaxy/webapps/galaxy/api/__init__.py
+++ b/lib/galaxy/webapps/galaxy/api/__init__.py
@@ -157,8 +157,7 @@ def get_api_user(
),
),
) -> Optional[User]:
- api_key = key or x_api_key
- if api_key:
+ if api_key := key or x_api_key:
user = user_manager.by_api_key(api_key=api_key)
elif bearer_token:
user = user_manager.by_oidc_access_token(access_token=bearer_token.credentials)
diff --git a/lib/galaxy/webapps/galaxy/api/dynamic_tools.py b/lib/galaxy/webapps/galaxy/api/dynamic_tools.py
index 6731bf511310..541b19901041 100644
--- a/lib/galaxy/webapps/galaxy/api/dynamic_tools.py
+++ b/lib/galaxy/webapps/galaxy/api/dynamic_tools.py
@@ -33,7 +33,7 @@ def index(self, trans, **kwds):
ID (and optionally version) returned from this endpoint.
"""
manager = self.app.dynamic_tools_manager
- return list(map(lambda t: t.to_dict(), manager.list_tools()))
+ return [t.to_dict() for t in manager.list_tools()]
@expose_api_anonymous_and_sessionless
def show(self, trans, id, **kwd):
diff --git a/lib/galaxy/webapps/galaxy/api/history_contents.py b/lib/galaxy/webapps/galaxy/api/history_contents.py
index 4f1933514014..189ab6d6d001 100644
--- a/lib/galaxy/webapps/galaxy/api/history_contents.py
+++ b/lib/galaxy/webapps/galaxy/api/history_contents.py
@@ -298,7 +298,7 @@ def parse_legacy_index_query_params(
if types:
content_types = parse_content_types(types)
else:
- content_types = [e for e in HistoryContentType]
+ content_types = list(HistoryContentType)
id_list = None
if ids:
diff --git a/lib/galaxy/webapps/galaxy/api/users.py b/lib/galaxy/webapps/galaxy/api/users.py
index 070175627e34..5dee3cdb63e2 100644
--- a/lib/galaxy/webapps/galaxy/api/users.py
+++ b/lib/galaxy/webapps/galaxy/api/users.py
@@ -738,7 +738,7 @@ def _build_extra_user_pref_inputs(self, trans, preferences, user):
"""
if not preferences:
return []
- extra_pref_inputs = list()
+ extra_pref_inputs = []
# Build sections for different categories of inputs
user_vault = UserVaultWrapper(trans.app.vault, user)
for item, value in preferences.items():
@@ -787,7 +787,7 @@ def get_information(self, trans, id, **kwd):
user = self._get_user(trans, id)
email = user.email
username = user.username
- inputs = list()
+ inputs = []
user_info = {
"email": email,
"username": username,
@@ -956,7 +956,7 @@ def set_information(self, trans, id, payload=None, **kwd):
user.values = form_values
# Update values for extra user preference items
- extra_user_pref_data = dict()
+ extra_user_pref_data = {}
extra_pref_keys = self._get_extra_user_preferences(trans)
user_vault = UserVaultWrapper(trans.app.vault, user)
if extra_pref_keys is not None:
@@ -1134,7 +1134,7 @@ def set_toolbox_filters(self, trans, id, payload=None, **kwd):
return {"message": "Toolbox filters have been saved."}
def _add_filter_inputs(self, factory, filter_types, inputs, errors, filter_type, saved_values):
- filter_inputs = list()
+ filter_inputs = []
filter_values = saved_values.get(filter_type, [])
filter_config = filter_types[filter_type]["config"]
filter_title = filter_types[filter_type]["title"]
diff --git a/lib/galaxy/webapps/galaxy/controllers/admin.py b/lib/galaxy/webapps/galaxy/controllers/admin.py
index 08bef7a9bb24..0070c9be7c56 100644
--- a/lib/galaxy/webapps/galaxy/controllers/admin.py
+++ b/lib/galaxy/webapps/galaxy/controllers/admin.py
@@ -125,8 +125,7 @@ def apply_query_filter(self, query, **kwargs):
}
deleted = False
purged = False
- search_query = kwargs.get("search")
- if search_query:
+ if search_query := kwargs.get("search"):
parsed_search = parse_filters_structured(search_query, INDEX_SEARCH_FILTERS)
for term in parsed_search.terms:
if isinstance(term, FilteredTerm):
@@ -195,8 +194,7 @@ def apply_query_filter(self, query, **kwargs):
}
deleted = False
query = query.filter(self.model_class.type != self.model_class.types.PRIVATE)
- search_query = kwargs.get("search")
- if search_query:
+ if search_query := kwargs.get("search"):
parsed_search = parse_filters_structured(search_query, INDEX_SEARCH_FILTERS)
for term in parsed_search.terms:
if isinstance(term, FilteredTerm):
@@ -255,8 +253,7 @@ def apply_query_filter(self, query, **kwargs):
"is": "is",
}
deleted = False
- search_query = kwargs.get("search")
- if search_query:
+ if search_query := kwargs.get("search"):
parsed_search = parse_filters_structured(search_query, INDEX_SEARCH_FILTERS)
for term in parsed_search.terms:
if isinstance(term, FilteredTerm):
@@ -326,8 +323,7 @@ def apply_query_filter(self, query, **kwargs):
"is": "is",
}
deleted = False
- search_query = kwargs.get("search")
- if search_query:
+ if search_query := kwargs.get("search"):
parsed_search = parse_filters_structured(search_query, INDEX_SEARCH_FILTERS)
for term in parsed_search.terms:
if isinstance(term, FilteredTerm):
@@ -389,7 +385,7 @@ def data_tables_list(self, trans, **kwd):
"name": data_table.name,
"filename": filename,
"tool_data_path": file_dict.get("tool_data_path"),
- "errors": ", ".join(file_missing + [error for error in file_dict.get("errors", [])]),
+ "errors": ", ".join(file_missing + list(file_dict.get("errors", []))),
}
)
diff --git a/lib/galaxy/webapps/galaxy/controllers/dataset.py b/lib/galaxy/webapps/galaxy/controllers/dataset.py
index c95d9df7882a..69f25c42866a 100644
--- a/lib/galaxy/webapps/galaxy/controllers/dataset.py
+++ b/lib/galaxy/webapps/galaxy/controllers/dataset.py
@@ -183,7 +183,7 @@ def get_edit(self, trans, dataset_id=None, **kwd):
(r.name, trans.security.encode_id(r.id))
for r in trans.app.security_agent.get_legitimate_roles(trans, data.dataset, "root")
]
- data_metadata = [(name, spec) for name, spec in data.metadata.spec.items()]
+ data_metadata = list(data.metadata.spec.items())
converters_collection = [(key, value.name) for key, value in data.get_converter_types().items()]
can_manage_dataset = trans.app.security_agent.can_manage_dataset(
trans.get_current_user_roles(), data.dataset
@@ -268,7 +268,7 @@ def get_edit(self, trans, dataset_id=None, **kwd):
]
# permissions
permission_disable = True
- permission_inputs = list()
+ permission_inputs = []
if trans.user:
if not data.dataset.shareable:
permission_message = "The dataset is stored on private storage to you and cannot be shared."
diff --git a/lib/galaxy/webapps/galaxy/controllers/forms.py b/lib/galaxy/webapps/galaxy/controllers/forms.py
index f62ef7c272cb..112f8fa998cc 100644
--- a/lib/galaxy/webapps/galaxy/controllers/forms.py
+++ b/lib/galaxy/webapps/galaxy/controllers/forms.py
@@ -69,8 +69,7 @@ def apply_query_filter(self, query, **kwargs):
}
deleted = False
query = query.join(model.FormDefinition, self.model_class.latest_form_id == model.FormDefinition.id)
- search_query = kwargs.get("search")
- if search_query:
+ if search_query := kwargs.get("search"):
parsed_search = parse_filters_structured(search_query, INDEX_SEARCH_FILTERS)
for term in parsed_search.terms:
if isinstance(term, FilteredTerm):
diff --git a/lib/galaxy/webapps/galaxy/controllers/tag.py b/lib/galaxy/webapps/galaxy/controllers/tag.py
index 04f315202da9..56176d57ee11 100644
--- a/lib/galaxy/webapps/galaxy/controllers/tag.py
+++ b/lib/galaxy/webapps/galaxy/controllers/tag.py
@@ -171,7 +171,7 @@ def _get_usernames_for_tag(self, trans, user, tag, item_class, item_tag_assoc_cl
.order_by(func.count().desc())
)
result_set = trans.sa_session.execute(query)
- user_tag_names = list()
+ user_tag_names = []
for row in result_set:
user_tag_names.append(row[0])
return user_tag_names
diff --git a/lib/galaxy/webapps/galaxy/services/history_contents.py b/lib/galaxy/webapps/galaxy/services/history_contents.py
index 781ad34965fd..d2d385fc787e 100644
--- a/lib/galaxy/webapps/galaxy/services/history_contents.py
+++ b/lib/galaxy/webapps/galaxy/services/history_contents.py
@@ -1365,7 +1365,7 @@ def _get_contents_by_item_list(
contents: List["HistoryItem"] = []
dataset_items = filter(lambda item: item.history_content_type == HistoryContentType.dataset, items)
- datasets_ids = map(lambda dataset: dataset.id, dataset_items)
+ datasets_ids = (dataset.id for dataset in dataset_items)
contents.extend(self.hda_manager.get_owned_ids(datasets_ids, history))
collection_items = filter(
diff --git a/lib/galaxy/webapps/galaxy/services/invocations.py b/lib/galaxy/webapps/galaxy/services/invocations.py
index 3e9f3385464f..f6d7b1c1a60d 100644
--- a/lib/galaxy/webapps/galaxy/services/invocations.py
+++ b/lib/galaxy/webapps/galaxy/services/invocations.py
@@ -227,9 +227,7 @@ def serialize_workflow_invocations(
params: InvocationSerializationParams,
default_view: InvocationSerializationView = InvocationSerializationView.collection,
):
- return list(
- map(lambda i: self.serialize_workflow_invocation(i, params, default_view=default_view), invocations)
- )
+ return [self.serialize_workflow_invocation(i, params, default_view=default_view) for i in invocations]
def serialize_workflow_invocation_step(
self,
diff --git a/lib/galaxy/webapps/galaxy/services/workflows.py b/lib/galaxy/webapps/galaxy/services/workflows.py
index 52e35d96c8fe..21f7062dc76f 100644
--- a/lib/galaxy/webapps/galaxy/services/workflows.py
+++ b/lib/galaxy/webapps/galaxy/services/workflows.py
@@ -85,7 +85,7 @@ def index(
if missing_tools:
workflows_missing_tools = []
workflows = []
- workflows_by_toolshed = dict()
+ workflows_by_toolshed = {}
for value in rval:
stored_workflow = self._workflows_manager.get_stored_workflow(trans, value["id"], by_stored_id=True)
tools = self._workflow_contents_manager.get_all_tools(stored_workflow.latest_workflow)
diff --git a/lib/galaxy/webapps/reports/controllers/jobs.py b/lib/galaxy/webapps/reports/controllers/jobs.py
index 7e034c0d5ba4..759380d78da4 100644
--- a/lib/galaxy/webapps/reports/controllers/jobs.py
+++ b/lib/galaxy/webapps/reports/controllers/jobs.py
@@ -324,7 +324,7 @@ def specified_date_handler(self, trans, **kwd):
return self.specified_date_list_grid(trans, **kwd)
def _calculate_trends_for_jobs(self, sa_session, jobs_query):
- trends = dict()
+ trends = {}
for job in sa_session.execute(jobs_query):
job_day = int(job.date.strftime("%-d")) - 1
job_month = int(job.date.strftime("%-m"))
@@ -446,7 +446,7 @@ def specified_month_all(self, trans, **kwd):
)
)
- trends = dict()
+ trends = {}
for job in trans.sa_session.execute(all_jobs):
job_hour = int(job.date.strftime("%-H"))
job_day = job.date.strftime("%d")
@@ -558,7 +558,7 @@ def specified_month_in_error(self, trans, **kwd):
)
)
- trends = dict()
+ trends = {}
for job in trans.sa_session.execute(all_jobs_in_error):
job_hour = int(job.date.strftime("%-H"))
job_day = job.date.strftime("%d")
@@ -871,7 +871,7 @@ def per_user(self, trans, **kwd):
)
currday = datetime.today()
- trends = dict()
+ trends = {}
q_time.start()
for job in trans.sa_session.execute(all_jobs_per_user):
if job.user_email is None:
@@ -970,7 +970,7 @@ def user_per_month(self, trans, **kwd):
.select_from(sa.join(model.Job.table, model.User.table))
)
- trends = dict()
+ trends = {}
for job in trans.sa_session.execute(all_jobs_per_user):
job_day = int(job.date.strftime("%-d")) - 1
job_month = int(job.date.strftime("%-m"))
@@ -1084,7 +1084,7 @@ def per_tool(self, trans, **kwd):
).where(model.Job.table.c.user_id != monitor_user_id)
currday = date.today()
- trends = dict()
+ trends = {}
for job in trans.sa_session.execute(all_jobs_per_tool):
curr_tool = re.sub(r"\W+", "", str(job.tool_id))
try:
@@ -1182,7 +1182,7 @@ def errors_per_tool(self, trans, **kwd):
).where(sa.and_(model.Job.table.c.state == "error", model.Job.table.c.user_id != monitor_user_id))
currday = date.today()
- trends = dict()
+ trends = {}
for job in trans.sa_session.execute(all_jobs_per_tool_errors):
curr_tool = re.sub(r"\W+", "", str(job.tool_id))
try:
@@ -1254,7 +1254,7 @@ def tool_per_month(self, trans, **kwd):
self.select_day(model.Job.table.c.create_time).label("day"),
model.Job.table.c.id.label("id"),
).where(sa.and_(model.Job.table.c.tool_id == tool_id, model.Job.table.c.user_id != monitor_user_id))
- trends = dict()
+ trends = {}
for job in trans.sa_session.execute(all_jobs_for_tool):
job_day = int(job.day.strftime("%-d")) - 1
job_month = int(job.month.strftime("%-m"))
diff --git a/lib/galaxy/webapps/reports/controllers/workflows.py b/lib/galaxy/webapps/reports/controllers/workflows.py
index 2291b7a499f2..4272c3d9184f 100644
--- a/lib/galaxy/webapps/reports/controllers/workflows.py
+++ b/lib/galaxy/webapps/reports/controllers/workflows.py
@@ -204,7 +204,7 @@ def per_month_all(self, trans, **kwd):
self.select_day(model.StoredWorkflow.table.c.create_time).label("date"), model.StoredWorkflow.table.c.id
)
- trends = dict()
+ trends = {}
for workflow in trans.sa_session.execute(all_workflows):
workflow_day = int(workflow.date.strftime("%-d")) - 1
workflow_month = int(workflow.date.strftime("%-m"))
@@ -292,7 +292,7 @@ def per_user(self, trans, **kwd):
model.StoredWorkflow.table.c.id,
).select_from(sa.outerjoin(model.StoredWorkflow.table, model.User.table))
currday = datetime.today()
- trends = dict()
+ trends = {}
for workflow in trans.sa_session.execute(all_workflows_per_user):
curr_user = re.sub(r"\W+", "", workflow.user_email)
try:
@@ -356,7 +356,7 @@ def user_per_month(self, trans, **kwd):
self.select_day(model.StoredWorkflow.table.c.create_time).label("date"), model.StoredWorkflow.table.c.id
).where(model.StoredWorkflow.table.c.user_id == user_id)
- trends = dict()
+ trends = {}
for workflow in trans.sa_session.execute(all_workflows_user_month):
workflow_day = int(workflow.date.strftime("%-d")) - 1
workflow_month = int(workflow.date.strftime("%-m"))
@@ -447,7 +447,7 @@ def per_workflow(self, trans, **kwd):
)
currday = date.today()
- trends = dict()
+ trends = {}
for run in trans.sa_session.execute(all_runs_per_workflow):
curr_tool = re.sub(r"\W+", "", str(run.workflow_id))
try:
diff --git a/lib/galaxy/workflow/modules.py b/lib/galaxy/workflow/modules.py
index 7783cfb40f05..2a7a60b9050b 100644
--- a/lib/galaxy/workflow/modules.py
+++ b/lib/galaxy/workflow/modules.py
@@ -826,7 +826,7 @@ def execute(
def get_runtime_state(self):
state = DefaultToolState()
- state.inputs = dict()
+ state.inputs = {}
return state
def get_runtime_inputs(self, step, connections: Optional[Iterable[WorkflowStepConnection]] = None):
@@ -1673,7 +1673,7 @@ def get_all_outputs(self, data_only=False):
def get_runtime_state(self):
state = DefaultToolState()
- state.inputs = dict()
+ state.inputs = {}
return state
def execute(
diff --git a/lib/galaxy_test/api/test_drs.py b/lib/galaxy_test/api/test_drs.py
index d37e641545da..b1c77c00e1e1 100644
--- a/lib/galaxy_test/api/test_drs.py
+++ b/lib/galaxy_test/api/test_drs.py
@@ -16,11 +16,11 @@
ConfiguredFileSourcesConfig,
DictFileSourcesUserContext,
)
-from galaxy.util.config_parsers import parse_allowlist_ips
-from galaxy.util.drs import (
+from galaxy.files.sources.util import (
fetch_drs_to_file,
RetryOptions,
)
+from galaxy.util.config_parsers import parse_allowlist_ips
from galaxy_test.base.populators import DatasetPopulator
from ._framework import ApiTestCase
diff --git a/lib/galaxy_test/api/test_history_contents.py b/lib/galaxy_test/api/test_history_contents.py
index 344ba4664156..3d00ac70e359 100644
--- a/lib/galaxy_test/api/test_history_contents.py
+++ b/lib/galaxy_test/api/test_history_contents.py
@@ -881,7 +881,7 @@ def test_explicit_items_selection(self):
},
],
}
- expected_hidden_item_ids = list(map(lambda item: item["id"], payload["items"]))
+ expected_hidden_item_ids = [item["id"] for item in payload["items"]]
expected_hidden_item_count = len(expected_hidden_item_ids)
bulk_operation_result = self._apply_bulk_operation(history_id, payload)
history_contents = self._get_history_contents(history_id)
@@ -1422,7 +1422,7 @@ def _create_test_history_contents(self, history_id) -> Tuple[List[str], List[str
collection_ids = self._create_collection_in_history(history_id, num_expected_collections)
history_contents = self._get_history_contents(history_id)
datasets = filter(lambda item: item["history_content_type"] == "dataset", history_contents)
- datasets_ids = list(map(lambda dataset: dataset["id"], datasets))
+ datasets_ids = [dataset["id"] for dataset in datasets]
assert len(history_contents) == num_expected_datasets + num_expected_collections
assert len(datasets_ids) == num_expected_datasets
for dataset_id in datasets_ids:
diff --git a/lib/galaxy_test/api/test_tools.py b/lib/galaxy_test/api/test_tools.py
index 7befe7f221b1..5cc548b00c42 100644
--- a/lib/galaxy_test/api/test_tools.py
+++ b/lib/galaxy_test/api/test_tools.py
@@ -2639,7 +2639,7 @@ def _cat1_outputs(self, history_id, inputs):
def _run_and_get_outputs(self, tool_id, history_id, inputs=None, tool_version=None):
if inputs is None:
- inputs = dict()
+ inputs = {}
return self._run_outputs(self._run(tool_id, history_id, inputs, tool_version=tool_version))
def _run_outputs(self, create_response):
diff --git a/lib/galaxy_test/api/test_tours.py b/lib/galaxy_test/api/test_tours.py
index 0f8ae8181980..403e10004fa4 100644
--- a/lib/galaxy_test/api/test_tours.py
+++ b/lib/galaxy_test/api/test_tours.py
@@ -6,7 +6,7 @@ def test_index(self):
response = self._get("tours")
self._assert_status_code_is(response, 200)
tours = response.json()
- tour_keys = map(lambda t: t["id"], tours)
+ tour_keys = (t["id"] for t in tours)
assert "core.history" in tour_keys
for tour in tours:
self._assert_has_keys(tour, "id", "name", "description", "tags")
diff --git a/lib/galaxy_test/base/api_asserts.py b/lib/galaxy_test/base/api_asserts.py
index 9b3e8c1f3daf..8e5796791e98 100644
--- a/lib/galaxy_test/base/api_asserts.py
+++ b/lib/galaxy_test/base/api_asserts.py
@@ -13,9 +13,6 @@
from galaxy.exceptions.error_codes import ErrorCode
-ASSERT_FAIL_ERROR_CODE = "Expected Galaxy error code %d, obtained %d"
-ASSERT_FAIL_STATUS_CODE = "Request status code (%d) was not expected value %s. Body was %s"
-
def assert_status_code_is(response: Response, expected_status_code: int, failure_message: Optional[str] = None):
"""Assert that the supplied response has the expect status code."""
@@ -45,7 +42,9 @@ def _report_status_code_error(
body = response.json()
except Exception:
body = f"INVALID JSON RESPONSE <{response.text}>"
- assertion_message = ASSERT_FAIL_STATUS_CODE % (response.status_code, expected_status_code, body)
+ assertion_message = (
+ f"Request status code ({response.status_code}) was not expected value {expected_status_code}. Body was {body}"
+ )
if failure_message:
assertion_message = f"{failure_message}. {assertion_message}"
raise AssertionError(assertion_message)
@@ -72,7 +71,7 @@ def assert_error_code_is(response: Union[Response, dict], error_code: Union[int,
as_dict = _as_dict(response)
assert_has_keys(as_dict, "err_code")
err_code = as_dict["err_code"]
- assert err_code == int(error_code), ASSERT_FAIL_ERROR_CODE % (error_code, err_code)
+ assert err_code == int(error_code), f"Expected Galaxy error code {error_code}, obtained {err_code}"
def assert_object_id_error(response: Response):
diff --git a/lib/galaxy_test/base/populators.py b/lib/galaxy_test/base/populators.py
index c4f7887e14ac..4f585ab24db3 100644
--- a/lib/galaxy_test/base/populators.py
+++ b/lib/galaxy_test/base/populators.py
@@ -667,7 +667,7 @@ def compute_hash(
extra_files_path: Optional[str] = None,
wait: bool = True,
) -> Response:
- data: Dict[str, Any] = dict()
+ data: Dict[str, Any] = {}
if hash_function:
data["hash_function"] = hash_function
if extra_files_path:
diff --git a/lib/galaxy_test/driver/driver_util.py b/lib/galaxy_test/driver/driver_util.py
index 88e956da5cfc..a95e19e376a5 100644
--- a/lib/galaxy_test/driver/driver_util.py
+++ b/lib/galaxy_test/driver/driver_util.py
@@ -451,7 +451,7 @@ def _get_static_settings():
def get_webapp_global_conf():
"""Get the global_conf dictionary sent to ``app_factory``."""
# (was originally sent 'dict()') - nothing here for now except static settings
- global_conf = dict()
+ global_conf = {}
global_conf.update(_get_static_settings())
return global_conf
diff --git a/lib/galaxy_test/selenium/framework.py b/lib/galaxy_test/selenium/framework.py
index 5b919286dbc3..310c88c88053 100644
--- a/lib/galaxy_test/selenium/framework.py
+++ b/lib/galaxy_test/selenium/framework.py
@@ -587,8 +587,7 @@ def assert_item_hid_text(self, hid):
class UsesWorkflowAssertions(NavigatesGalaxyMixin):
@retry_assertion_during_transitions
def _assert_showing_n_workflows(self, n):
- actual_count = len(self.workflow_card_elements())
- if actual_count != n:
+ if (actual_count := len(self.workflow_card_elements())) != n:
message = f"Expected {n} workflows to be displayed, based on DOM found {actual_count} workflow rows."
raise AssertionError(message)
diff --git a/lib/galaxy_test/selenium/test_history_panel.py b/lib/galaxy_test/selenium/test_history_panel.py
index 49a78b14ed9e..89cef7532a2c 100644
--- a/lib/galaxy_test/selenium/test_history_panel.py
+++ b/lib/galaxy_test/selenium/test_history_panel.py
@@ -83,7 +83,7 @@ def set_random_annotation(clear_text=True):
@selenium_test
def test_history_panel_tags_change(self):
def create_tags(size):
- history_panel_tags = list()
+ history_panel_tags = []
for i in range(size):
history_panel_tags.append(self._get_random_name(prefix="arbitrary_tag_%s_") % i)
return history_panel_tags
diff --git a/lib/galaxy_test/selenium/test_tool_form.py b/lib/galaxy_test/selenium/test_tool_form.py
index d303dc7f2c0c..42740dd72044 100644
--- a/lib/galaxy_test/selenium/test_tool_form.py
+++ b/lib/galaxy_test/selenium/test_tool_form.py
@@ -145,7 +145,7 @@ def assert_input_order(inputs: List[str]):
self.tool_form_execute()
self.history_panel_wait_for_hid_ok(1)
- details = list(map(lambda d: d.text, self._get_dataset_tool_parameters(1)))
+ details = [d.text for d in self._get_dataset_tool_parameters(1)]
assert details == ["texttest", "Text C", "texttest", "Text B", "texttest", "Text A"]
diff --git a/lib/tool_shed/dependencies/attribute_handlers.py b/lib/tool_shed/dependencies/attribute_handlers.py
index e581137bdb4f..87cba9e1a6fd 100644
--- a/lib/tool_shed/dependencies/attribute_handlers.py
+++ b/lib/tool_shed/dependencies/attribute_handlers.py
@@ -88,7 +88,7 @@ def handle_elem(self, elem):
prior_installation_required = elem.get("prior_installation_required")
if prior_installation_required is not None and not asbool(prior_installation_required):
del elem.attrib["prior_installation_required"]
- sub_elems = [child_elem for child_elem in list(elem)]
+ sub_elems = list(elem)
if len(sub_elems) > 0:
# At this point, a tag will point only to a package.
#
diff --git a/lib/tool_shed/grids/admin_grids.py b/lib/tool_shed/grids/admin_grids.py
index 45a4dcd1ff1f..52f68837b501 100644
--- a/lib/tool_shed/grids/admin_grids.py
+++ b/lib/tool_shed/grids/admin_grids.py
@@ -306,7 +306,7 @@ def get_value(self, trans, grid, group):
class ManageCategoryGrid(CategoryGrid):
- columns = [col for col in CategoryGrid.columns]
+ columns = list(CategoryGrid.columns)
# Override the NameColumn to include an Edit link
columns[0] = CategoryGrid.NameColumn(
"Name",
@@ -355,7 +355,7 @@ def get_value(self, trans, grid, repository):
filterable="standard",
)
)
- operations = [operation for operation in RepositoryGrid.operations]
+ operations = list(RepositoryGrid.operations)
operations.append(
grids.GridOperation(
"Delete", allow_multiple=False, condition=(lambda item: not item.deleted), async_compatible=False
diff --git a/lib/tool_shed/grids/repository_grids.py b/lib/tool_shed/grids/repository_grids.py
index 5c80c185ff38..9eb430f0c8e2 100644
--- a/lib/tool_shed/grids/repository_grids.py
+++ b/lib/tool_shed/grids/repository_grids.py
@@ -377,7 +377,7 @@ def build_initial_query(self, trans, **kwd):
class InstallMatchedRepositoryGrid(MatchedRepositoryGrid):
- columns = [col for col in MatchedRepositoryGrid.columns]
+ columns = list(MatchedRepositoryGrid.columns)
# Override the NameColumn
columns[0] = MatchedRepositoryGrid.NameColumn(
"Name", link=(lambda item: dict(operation="view_or_manage_repository", id=item.id)), attach_popup=False
@@ -748,7 +748,7 @@ def build_initial_query(self, trans, **kwd):
class MyWritableRepositoriesMissingToolTestComponentsGrid(RepositoriesMissingToolTestComponentsGrid):
# This grid displays only the latest installable revision of each repository.
title = "Repositories I can change with missing tool test components"
- columns = [col for col in RepositoriesMissingToolTestComponentsGrid.columns]
+ columns = list(RepositoriesMissingToolTestComponentsGrid.columns)
def build_initial_query(self, trans, **kwd):
# First get all repositories that the current user is authorized to update.
@@ -915,7 +915,7 @@ def build_initial_query(self, trans, **kwd):
class MyWritableRepositoriesWithInvalidToolsGrid(RepositoriesWithInvalidToolsGrid):
# This grid displays only the latest installable revision of each repository.
title = "Repositories I can change with invalid tools"
- columns = [col for col in RepositoriesWithInvalidToolsGrid.columns]
+ columns = list(RepositoriesWithInvalidToolsGrid.columns)
def build_initial_query(self, trans, **kwd):
# First get all repositories that the current user is authorized to update.
diff --git a/lib/tool_shed/managers/repositories.py b/lib/tool_shed/managers/repositories.py
index 79fbb68cc0d5..cd7980c3e0e3 100644
--- a/lib/tool_shed/managers/repositories.py
+++ b/lib/tool_shed/managers/repositories.py
@@ -205,7 +205,7 @@ def guid_to_repository(app: ToolShedApp, tool_id: str) -> "Repository":
def index_tool_ids(app: ToolShedApp, tool_ids: List[str]) -> Dict[str, Any]:
repository_found = []
- all_metadata = dict()
+ all_metadata = {}
for tool_id in tool_ids:
repository = guid_to_repository(app, tool_id)
owner = repository.user.username
diff --git a/lib/tool_shed/metadata/repository_metadata_manager.py b/lib/tool_shed/metadata/repository_metadata_manager.py
index a5df2eddcf91..cc8a771c61e7 100644
--- a/lib/tool_shed/metadata/repository_metadata_manager.py
+++ b/lib/tool_shed/metadata/repository_metadata_manager.py
@@ -365,19 +365,17 @@ def compare_data_manager(self, ancestor_metadata, current_metadata):
def __data_manager_dict_to_tuple_list(metadata_dict):
# we do not check tool_guid or tool conf file name
- return set(
- sorted(
- (
- name,
- tuple(sorted(value.get("data_tables", []))),
- value.get("guid"),
- value.get("version"),
- value.get("name"),
- value.get("id"),
- )
- for name, value in metadata_dict.items()
+ return {
+ (
+ name,
+ tuple(sorted(value.get("data_tables", []))),
+ value.get("guid"),
+ value.get("version"),
+ value.get("name"),
+ value.get("id"),
)
- )
+ for name, value in metadata_dict.items()
+ }
# only compare valid entries, any invalid entries are ignored
ancestor_metadata = __data_manager_dict_to_tuple_list(ancestor_metadata.get("data_managers", {}))
diff --git a/lib/tool_shed/test/base/twilltestcase.py b/lib/tool_shed/test/base/twilltestcase.py
index 968109ac0235..ae678a55f4f2 100644
--- a/lib/tool_shed/test/base/twilltestcase.py
+++ b/lib/tool_shed/test/base/twilltestcase.py
@@ -824,7 +824,7 @@ def submit_form(self, form_no=-1, button="runtool_btn", form=None, **kwd):
def join_url_and_params(self, url: str, params, query=None) -> str:
if params is None:
- params = dict()
+ params = {}
if query is None:
query = urlparse(url).query
if query:
@@ -1510,7 +1510,7 @@ def get_repository_metadata(self, repository: Repository):
return self.get_repository_metadata_for_db_object(self._db_repository(repository))
def get_repository_metadata_for_db_object(self, repository: DbRepository):
- return [metadata_revision for metadata_revision in repository.metadata_revisions]
+ return list(repository.metadata_revisions)
def get_repository_metadata_by_changeset_revision(self, repository_id: int, changeset_revision):
return test_db_util.get_repository_metadata_by_repository_id_changeset_revision(
@@ -2069,8 +2069,8 @@ def _assert_repo_has_invalid_tool_in_file(
assert found_it, f"Did not find invalid tool file {name} in {invalid_tools}"
def verify_unchanged_repository_metadata(self, repository: Repository):
- old_metadata = dict()
- new_metadata = dict()
+ old_metadata = {}
+ new_metadata = {}
for metadata in self.get_repository_metadata(repository):
old_metadata[metadata.changeset_revision] = metadata.metadata
self.reset_repository_metadata(repository)
diff --git a/lib/tool_shed/test/functional/test_0300_reset_all_metadata.py b/lib/tool_shed/test/functional/test_0300_reset_all_metadata.py
index 3032ccd26639..f9397ef6024b 100644
--- a/lib/tool_shed/test/functional/test_0300_reset_all_metadata.py
+++ b/lib/tool_shed/test/functional/test_0300_reset_all_metadata.py
@@ -562,16 +562,16 @@ def test_0100_create_and_upload_dependency_definitions(self):
def test_0110_reset_metadata_on_all_repositories(self):
"""Reset metadata on all repositories, then verify that it has not changed."""
self.login(email=common.admin_email, username=common.admin_username)
- old_metadata: Dict[str, Dict] = dict()
- new_metadata: Dict[str, Dict] = dict()
+ old_metadata: Dict[str, Dict] = {}
+ new_metadata: Dict[str, Dict] = {}
repositories = self.test_db_util.get_all_repositories()
for repository in repositories:
- old_metadata[self.security.encode_id(repository.id)] = dict()
+ old_metadata[self.security.encode_id(repository.id)] = {}
for metadata in self.get_repository_metadata_for_db_object(repository):
old_metadata[self.security.encode_id(repository.id)][metadata.changeset_revision] = metadata.metadata
self.reset_metadata_on_selected_repositories(list(old_metadata.keys()))
for repository in repositories:
- new_metadata[self.security.encode_id(repository.id)] = dict()
+ new_metadata[self.security.encode_id(repository.id)] = {}
for metadata in self.get_repository_metadata_for_db_object(repository):
new_metadata[self.security.encode_id(repository.id)][metadata.changeset_revision] = metadata.metadata
if (
diff --git a/lib/tool_shed/webapp/model/__init__.py b/lib/tool_shed/webapp/model/__init__.py
index 2f2be9dccfbe..fff29c906672 100644
--- a/lib/tool_shed/webapp/model/__init__.py
+++ b/lib/tool_shed/webapp/model/__init__.py
@@ -733,10 +733,7 @@ def includes_tools_for_display_in_tool_panel(self):
@property
def repository_dependencies(self):
if self.has_repository_dependencies:
- return [
- repository_dependency
- for repository_dependency in self.metadata["repository_dependencies"]["repository_dependencies"]
- ]
+ return list(self.metadata["repository_dependencies"]["repository_dependencies"])
return []
diff --git a/lib/tool_shed_client/schema/__init__.py b/lib/tool_shed_client/schema/__init__.py
index 24b40d468f86..42c890ad4afd 100644
--- a/lib/tool_shed_client/schema/__init__.py
+++ b/lib/tool_shed_client/schema/__init__.py
@@ -410,7 +410,7 @@ def from_legacy_dict(as_dict: ValidToolDict) -> "ValidTool":
@staticmethod
def from_legacy_list(as_dicts: List[ValidToolDict]) -> List["ValidTool"]:
- return list(ValidTool.from_legacy_dict(d) for d in as_dicts)
+ return [ValidTool.from_legacy_dict(d) for d in as_dicts]
class RepositoryMetadataInstallInfo(BaseModel):
diff --git a/pyproject.toml b/pyproject.toml
index ad564163ad68..7d4ebc52df5c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -191,8 +191,8 @@ exclude = [
[tool.ruff.lint]
# Enable: pycodestyle errors (E), Pyflakes (F), flake8-bugbear (B),
-# flake8-logging-format (G) and pyupgrade (UP)
-select = ["E", "F", "B", "G", "UP"]
+# flake8-comprehensions (C4), flake8-logging-format (G) and pyupgrade (UP)
+select = ["E", "F", "B", "C4", "G", "UP"]
# Exceptions:
# B008 Do not perform function calls in argument defaults (for FastAPI Depends and Body)
# B9 flake8-bugbear opinionated warnings
@@ -201,6 +201,9 @@ select = ["E", "F", "B", "G", "UP"]
# G* are TODOs
ignore = ["B008", "B9", "E402", "E501", "G001", "G002", "G004"]
+[tool.ruff.lint.flake8-comprehensions]
+allow-dict-calls-with-keyword-arguments = true
+
[tool.ruff.lint.isort]
# We are not selecting "I" rules in ruff yet because support for all the isort
# options we need is not complete, but these are the one currently implemented.
diff --git a/scripts/apply_tags.py b/scripts/apply_tags.py
index fabf9470eebf..fa4ebb258bb3 100644
--- a/scripts/apply_tags.py
+++ b/scripts/apply_tags.py
@@ -42,9 +42,9 @@ def find_dataset_parents_update_tags(self, history, job, history_id):
Operate on datasets for a particular history and recursively find parents
for a dataset
"""
- datasets_inheritance_chain = dict()
- own_tags = dict()
- parent_tags = dict()
+ datasets_inheritance_chain = {}
+ own_tags = {}
+ parent_tags = {}
count_datasets_updated = 0
# get all datasets belonging to a history
all_datasets = history.show_history(history_id, contents=True)
@@ -107,7 +107,7 @@ def find_parent_recursive(dataset_id, recursive_parents):
for parent in dataset_parents:
find_parent_recursive(parent, recursive_parents)
- recursive_parent_ids = dict()
+ recursive_parent_ids = {}
for item in datasets_inheritance_chain:
recursive_parents: List = []
diff --git a/scripts/cleanup_datasets/pgcleanup.py b/scripts/cleanup_datasets/pgcleanup.py
index 735f2d0a47cd..7ff09d7c4a5a 100755
--- a/scripts/cleanup_datasets/pgcleanup.py
+++ b/scripts/cleanup_datasets/pgcleanup.py
@@ -450,7 +450,7 @@ def remove_object(self, dataset):
extra_dir = f"dataset_{dataset.uuid}_files"
else:
extra_dir = f"dataset_{dataset.id}_files"
- self.remove_from_object_store(dataset, dict())
+ self.remove_from_object_store(dataset, {})
self.remove_from_object_store(
dataset, dict(dir_only=True, extra_dir=extra_dir), entire_dir=True, check_exists=True
)
diff --git a/scripts/fix_dm_versions.py b/scripts/fix_dm_versions.py
index 4578cabf8b84..bdd2d539182b 100755
--- a/scripts/fix_dm_versions.py
+++ b/scripts/fix_dm_versions.py
@@ -44,7 +44,7 @@
tree = etree.parse(args.shed_data_manager_conf)
root = tree.getroot()
-guid_mapping = dict()
+guid_mapping = {}
for dm in root.iter("data_manager"):
guid = dm.attrib["guid"]
if guid not in guid_mapping:
diff --git a/scripts/tests_markdown.py b/scripts/tests_markdown.py
index 41cd1afe9aa0..1b6fb8edd2c4 100644
--- a/scripts/tests_markdown.py
+++ b/scripts/tests_markdown.py
@@ -224,7 +224,7 @@ def __inject_api_timing_summary_test(test):
internal_timings = {}
def summarize_times(timings):
- times = list(map(lambda t: t["time"], timings))
+ times = [t["time"] for t in timings]
return __inject_statistics(
{
"raw": times,
@@ -232,7 +232,7 @@ def summarize_times(timings):
)
def summarize_counter(c):
- counters = list(map(lambda t: t["n"], c))
+ counters = [t["n"] for t in c]
return __inject_statistics(
{
"raw": counters,
diff --git a/test/functional/test_toolbox.py b/test/functional/test_toolbox.py
index 571c452cb490..e8a357637d5e 100644
--- a/test/functional/test_toolbox.py
+++ b/test/functional/test_toolbox.py
@@ -98,7 +98,7 @@ def test_tool(self):
continue
name = name_prefix + tool_id.replace(" ", "_")
baseclasses = (baseclass,)
- namespace = dict()
+ namespace = {}
all_versions_test_count = 0
diff --git a/test/integration/test_celery_user_rate_limit.py b/test/integration/test_celery_user_rate_limit.py
index ac69062dfda1..3267a2dd5f53 100644
--- a/test/integration/test_celery_user_rate_limit.py
+++ b/test/integration/test_celery_user_rate_limit.py
@@ -39,7 +39,7 @@ def setup_users(dburl: str, num_users: int = 2):
This is because the new celery_user_rate_limit table has
a user_id with a foreign key pointing to galaxy_user table.
"""
- expected_user_ids = [i for i in range(2, num_users + 2)]
+ expected_user_ids = list(range(2, num_users + 2))
with sqlalchemy_engine(dburl) as engine:
with engine.begin() as conn:
found_user_ids = conn.scalars(
@@ -73,7 +73,7 @@ def setUp(self):
super().setUp()
def _test_mock_pass_user_id_task(self, num_users: int, num_calls: int, tasks_per_user_per_sec: float):
- users = [i for i in range(2, num_users + 2)]
+ users = list(range(2, num_users + 2))
expected_duration: float
if tasks_per_user_per_sec == 0.0:
expected_duration = 0.0
diff --git a/test/integration/test_job_resubmission.py b/test/integration/test_job_resubmission.py
index 9ef520a37f06..dd6da5d423a3 100644
--- a/test/integration/test_job_resubmission.py
+++ b/test/integration/test_job_resubmission.py
@@ -56,7 +56,7 @@ def handle_galaxy_config_kwds(cls, config):
def test_retry_tools_have_resource_params(self):
tool_show = self._get("tools/simple_constructs", data=dict(io_details=True)).json()
tool_inputs = tool_show["inputs"]
- input_names = map(lambda x: x["name"], tool_inputs)
+ input_names = (x["name"] for x in tool_inputs)
assert "__job_resource" in input_names
def test_job_resources(self):
diff --git a/test/unit/app/jobs/dynamic_tool_destination/mockGalaxy.py b/test/unit/app/jobs/dynamic_tool_destination/mockGalaxy.py
index 17f4ce9cf726..56758f79176f 100644
--- a/test/unit/app/jobs/dynamic_tool_destination/mockGalaxy.py
+++ b/test/unit/app/jobs/dynamic_tool_destination/mockGalaxy.py
@@ -6,7 +6,7 @@ class Job:
def __init__(self):
self.input_datasets = []
self.input_library_datasets = []
- self.param_values = dict()
+ self.param_values = {}
self.parameters = []
def get_param_values(self, app, ignore_errors=False):
@@ -37,7 +37,7 @@ def __init__(self, file_name, file_ext, value):
self.file_name_ = file_name
self.datatype = Datatype(file_ext)
self.ext = file_ext
- self.metadata = dict()
+ self.metadata = {}
self.metadata["sequences"] = value
def get_metadata(self):
diff --git a/test/unit/app/jobs/test_mapper.py b/test/unit/app/jobs/test_mapper.py
index bf49b262c98b..f2ec4cd1b87b 100644
--- a/test/unit/app/jobs/test_mapper.py
+++ b/test/unit/app/jobs/test_mapper.py
@@ -83,7 +83,7 @@ def test_dynamic_mapping_workflow_invocation_parameter():
def test_dynamic_mapping_no_function():
- dest = __dynamic_destination(dict())
+ dest = __dynamic_destination({})
mapper = __mapper(dest)
mapper.job_wrapper.tool.all_ids = ["no_such_function"]
error_message = ERROR_MESSAGE_NO_RULE_FUNCTION % dest
diff --git a/test/unit/app/test_dbscript.py b/test/unit/app/test_dbscript.py
index a5abf8951c07..ee0decf538c1 100644
--- a/test/unit/app/test_dbscript.py
+++ b/test/unit/app/test_dbscript.py
@@ -102,7 +102,7 @@ def test_revision_cmd(self, config):
run_command(f"{DEV_CMD} revision --rev-id 3 --message foo3")
script_dir = ScriptDirectory.from_config(config)
- revisions = [rev for rev in script_dir.walk_revisions()]
+ revisions = list(script_dir.walk_revisions())
assert len(revisions) == 5 # verify total revisions: 2 base + 3 new
rev = script_dir.get_revision("3")
diff --git a/test/unit/app/tools/test_evaluation.py b/test/unit/app/tools/test_evaluation.py
index 06e0e2380e19..52d25566b638 100644
--- a/test/unit/app/tools/test_evaluation.py
+++ b/test/unit/app/tools/test_evaluation.py
@@ -219,7 +219,7 @@ def _set_compute_environment(self, **kwds):
def _setup_test_bwa_job(self):
def hda(id, name, path):
- hda = HistoryDatasetAssociation(name=name, metadata=dict())
+ hda = HistoryDatasetAssociation(name=name, metadata={})
hda.dataset = Dataset(id=id, external_filename=path)
return hda
@@ -232,7 +232,7 @@ def hda(id, name, path):
class MockHistoryDatasetAssociation(HistoryDatasetAssociation):
def __init__(self, **kwds):
- self._metadata = dict()
+ self._metadata = {}
super().__init__(**kwds)
diff --git a/test/unit/app/visualizations/plugins/test_VisualizationPlugin.py b/test/unit/app/visualizations/plugins/test_VisualizationPlugin.py
index bada3b4b4e62..baf72fe065c8 100644
--- a/test/unit/app/visualizations/plugins/test_VisualizationPlugin.py
+++ b/test/unit/app/visualizations/plugins/test_VisualizationPlugin.py
@@ -59,7 +59,7 @@ def test_init_without_static_or_templates(self):
A plugin that has neither template or static directory should serve neither.
"""
vis_dir = galaxy_mock.MockDir({"config": {"vis1.xml": ""}})
- plugin = self.plugin_class(galaxy_mock.MockApp(), vis_dir.root_path, "myvis", dict())
+ plugin = self.plugin_class(galaxy_mock.MockApp(), vis_dir.root_path, "myvis", {})
assert not plugin.serves_templates
# not sure what this would do, but...
@@ -83,21 +83,21 @@ def test_build_render_vars_default(self):
def test_build_config(self):
""" """
- plugin_config: dict = dict()
+ plugin_config: dict = {}
plugin = self.plugin_class(galaxy_mock.MockApp(), "", "myvis", plugin_config)
config = plugin._build_config({})
assert isinstance(config, vis_utils.OpenObject)
assert config.__dict__ == {}
# existing should flow through
- plugin_config = dict()
+ plugin_config = {}
plugin = self.plugin_class(galaxy_mock.MockApp(), "", "myvis", plugin_config)
existing_config = dict(wat=1)
config = plugin._build_config(existing_config)
assert config.wat == 1
# unlisted/non-param kwargs should NOT overwrite existing
- plugin_config = dict()
+ plugin_config = {}
plugin = self.plugin_class(galaxy_mock.MockApp(), "", "myvis", plugin_config)
existing_config = dict(wat=1)
config = plugin._build_config(existing_config, wat=2)
diff --git a/test/unit/auth/test_auth.py b/test/unit/auth/test_auth.py
index f633b5364eac..679ccb266455 100644
--- a/test/unit/auth/test_auth.py
+++ b/test/unit/auth/test_auth.py
@@ -5,7 +5,7 @@
def test_alwaysreject():
t = AlwaysReject()
- assert t.authenticate("testmail", "testuser", "secret", dict(), None) == (None, "", "")
+ assert t.authenticate("testmail", "testuser", "secret", {}, None) == (None, "", "")
def test_localdb():
diff --git a/test/unit/data/test_galaxy_mapping.py b/test/unit/data/test_galaxy_mapping.py
index 7e6c35d757f1..5cb87936b71a 100644
--- a/test/unit/data/test_galaxy_mapping.py
+++ b/test/unit/data/test_galaxy_mapping.py
@@ -651,7 +651,7 @@ def contents_iter_names(**kwds):
history = self.model.session.scalars(
select(model.History).filter(model.History.name == "HistoryContentsHistory1").limit(1)
).first()
- return list(map(lambda hda: hda.name, history.contents_iter(**kwds)))
+ return [hda.name for hda in history.contents_iter(**kwds)]
assert contents_iter_names() == ["1", "2", "3", "4"]
assert contents_iter_names(deleted=False) == ["1", "2"]
diff --git a/test/unit/tool_util/test_tool_linters.py b/test/unit/tool_util/test_tool_linters.py
index e553d2c16884..a97c0cf24514 100644
--- a/test/unit/tool_util/test_tool_linters.py
+++ b/test/unit/tool_util/test_tool_linters.py
@@ -934,7 +934,7 @@ def get_tool_xml_exact(xml_string: str):
def run_lint_module(lint_ctx, lint_module, lint_target):
- lint_tool_source_with_modules(lint_ctx, lint_target, list(set([lint_module, xsd])))
+ lint_tool_source_with_modules(lint_ctx, lint_target, list({lint_module, xsd}))
def run_lint(lint_ctx, lint_func, lint_target):
diff --git a/test/unit/webapps/api/test_cbv.py b/test/unit/webapps/api/test_cbv.py
index df3e9db3a5d0..3cfea81b1265 100644
--- a/test/unit/webapps/api/test_cbv.py
+++ b/test/unit/webapps/api/test_cbv.py
@@ -3,8 +3,6 @@
https://github.com/dmontagu/fastapi-utils
"""
-from __future__ import annotations
-
from typing import (
Any,
ClassVar,
@@ -85,7 +83,7 @@ class RootHandler:
@router.get("/items/?")
@router.get("/items/{item_path:path}")
@router.get("/database/{item_path:path}")
- def root(self, item_path: Optional[str] = None, item_query: Optional[str] = None) -> Any: # noqa: UP007
+ def root(self, item_path: Optional[str] = None, item_query: Optional[str] = None) -> Any:
if item_path:
return {"item_path": item_path}
if item_query:
diff --git a/tools/filters/axt_to_concat_fasta.py b/tools/filters/axt_to_concat_fasta.py
index 759913abed4d..c1e9eb9a022f 100644
--- a/tools/filters/axt_to_concat_fasta.py
+++ b/tools/filters/axt_to_concat_fasta.py
@@ -27,8 +27,8 @@ def main():
# convert the alignment blocks
reader = bx.align.axt.Reader(sys.stdin, support_ids=True, species1=species1, species2=species2)
- sp1text = list()
- sp2text = list()
+ sp1text = []
+ sp2text = []
for a in reader:
sp1text.append(a.components[0].text)
sp2text.append(a.components[1].text)
diff --git a/tools/phenotype_association/senatag.py b/tools/phenotype_association/senatag.py
index 79a4847c96ba..577225d8d583 100755
--- a/tools/phenotype_association/senatag.py
+++ b/tools/phenotype_association/senatag.py
@@ -94,7 +94,7 @@ def add_edges(self, n1, n2):
def check_graph(self):
for n in self.nodes.values():
- ms = [x for x in n.edges]
+ ms = list(n.edges)
for m in ms:
if n not in m.edges:
print("check : %s - %s" % (n, m), file=stderr)
diff --git a/tools/stats/aggregate_scores_in_intervals.py b/tools/stats/aggregate_scores_in_intervals.py
index f30de9208e3a..1efd06919fbc 100755
--- a/tools/stats/aggregate_scores_in_intervals.py
+++ b/tools/stats/aggregate_scores_in_intervals.py
@@ -85,7 +85,7 @@ class FileBinnedArrayDir(Mapping):
def __init__(self, dir):
self.dir = dir
- self.cache = dict()
+ self.cache = {}
def __getitem__(self, key):
value = None
@@ -117,7 +117,7 @@ def load_scores_wiggle(fname, chrom_buffer_size=3):
Read a wiggle file and return a dict of BinnedArray objects keyed
by chromosome.
"""
- scores_by_chrom = dict()
+ scores_by_chrom = {}
try:
for chrom, pos, val in bx.wiggle.Reader(UCSCOutWrapper(open(fname))):
if chrom not in scores_by_chrom: