From 4f3e623d5915845b34811f4ccd5a7694886b3a55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Fri, 7 Aug 2026 19:17:48 +0200 Subject: [PATCH 1/2] STYLE: Prefer using f-strings Prefer using f-strings. Documentation: https://peps.python.org/pep-0498/ --- trx/fetcher.py | 2 +- trx/io.py | 10 +-- trx/tests/test_io.py | 2 +- trx/trx_file_memmap.py | 148 ++++++++++++++++------------------------- trx/utils.py | 14 ++-- trx/workflows.py | 57 ++++++---------- 6 files changed, 91 insertions(+), 142 deletions(-) diff --git a/trx/fetcher.py b/trx/fetcher.py index 488427d5..a947e707 100644 --- a/trx/fetcher.py +++ b/trx/fetcher.py @@ -149,7 +149,7 @@ def fetch_data(files_dict, keys=None): # noqa: C901 url, expected_md5, expected_sha = file_entry full_path = os.path.join(trx_home, f) - logging.info("Downloading {} to {}".format(f, trx_home)) + logging.info(f"Downloading {f} to {trx_home}") if not os.path.exists(full_path): urllib.request.urlretrieve(url, full_path) diff --git a/trx/io.py b/trx/io.py index 102d3f39..3d633bba 100644 --- a/trx/io.py +++ b/trx/io.py @@ -82,20 +82,16 @@ def load_sft_with_reference(filepath, reference=None, bbox_check=True): _, ext = os.path.splitext(filepath) if ext == ".trk": if reference is not None and reference != "same": - logging.warning( - "Reference is discarded for this file format {}.".format(filepath) - ) + logging.warning(f"Reference is discarded for this file format {filepath}.") sft = load_tractogram(filepath, "same", bbox_valid_check=bbox_check) elif ext in [".tck", ".fib", ".vtk", ".dpy"]: if reference is None or reference == "same": - raise IOError( - "--reference is required for this file format {}.".format(filepath) - ) + raise IOError(f"--reference is required for this file format {filepath}.") else: sft = load_tractogram(filepath, reference, bbox_valid_check=bbox_check) else: - raise IOError("{} is an unsupported file format".format(filepath)) + raise IOError(f"{filepath} is an unsupported file format") return sft diff --git a/trx/tests/test_io.py b/trx/tests/test_io.py index c5e823dd..3db89a83 100644 --- a/trx/tests/test_io.py +++ b/trx/tests/test_io.py @@ -99,7 +99,7 @@ def test_multi_load_save_rasmm(path): obj = load(path, os.path.join(gs_dir, "gs.nii")) for i in range(3): - out_path = os.path.join(tmp_gs_dir, "{}_tmp{}_{}".format(basename, i, ext)) + out_path = os.path.join(tmp_gs_dir, f"{basename}_tmp{i}_{ext}") save(obj, out_path) if isinstance(obj, TrxFile): diff --git a/trx/trx_file_memmap.py b/trx/trx_file_memmap.py index 1556f598..04a35b51 100644 --- a/trx/trx_file_memmap.py +++ b/trx/trx_file_memmap.py @@ -152,13 +152,13 @@ def _generate_filename_from_data(arr: np.ndarray, filename: str) -> str: dtype = "bit" if dtype is np.dtype(bool) else dtype.name if arr.ndim == 1: - new_filename = "{}.{}".format(base, dtype) + new_filename = f"{base}.{dtype}" elif arr.ndim == 2: dim = arr.shape[-1] if dim == 1: - new_filename = "{}.{}".format(base, dtype) + new_filename = f"{base}.{dtype}" else: - new_filename = "{}.{}.{}".format(base, arr.shape[-1], dtype) + new_filename = f"{base}.{arr.shape[-1]}.{dtype}" else: raise ValueError("Invalid dimensionality.") @@ -184,7 +184,7 @@ def _split_ext_with_dimensionality(filename: str) -> Tuple[str, int, str]: if len(split) != 2 and len(split) != 3: raise ValueError("Invalid filename.") basename = split[0] - ext = ".{}".format(split[-1]) + ext = f".{split[-1]}" dim = 1 if len(split) == 2 else split[1] _is_dtype_valid(ext) @@ -365,9 +365,7 @@ def load(input_obj: str, check_dpg: bool = True) -> Type["TrxFile"]: if check_dpg: for dpg in trx.data_per_group.keys(): if dpg not in trx.groups.keys(): - raise ValueError( - "An undeclared group ({}) has data_per_group.".format(dpg) - ) + raise ValueError(f"An undeclared group ({dpg}) has data_per_group.") return trx @@ -403,7 +401,7 @@ def load_from_zip(filename: str) -> Type["TrxFile"]: if not _is_dtype_valid(ext): continue - raise ValueError("The dtype {} is not supported".format(elem_filename)) + raise ValueError(f"The dtype {elem_filename} is not supported") if ext == ".bit": ext = ".bool" @@ -472,9 +470,7 @@ def load_from_directory(directory: str) -> Type["TrxFile"]: continue if not _is_dtype_valid(ext): - raise ValueError( - "The dtype of {} is not supported".format(elem_filename) - ) + raise ValueError(f"The dtype of {elem_filename} is not supported") if ext == ".bit": ext = ".bool" @@ -579,17 +575,14 @@ def _verify_dpv_coherence( or key not in curr_trx.data_per_vertex.keys() ): if not delete_dpv: - logging.debug( - "{} dpv key does not exist in all TrxFile.".format(key) - ) + logging.debug(f"{key} dpv key does not exist in all TrxFile.") raise ValueError("TrxFile must be sharing identical dpv keys.") elif ( ref_trx.data_per_vertex[key]._data.dtype != curr_trx.data_per_vertex[key]._data.dtype ): logging.debug( - "{} dpv key is not declared with the same dtype " - "in all TrxFile.".format(key) + f"{key} dpv key is not declared with the same dtype in all TrxFile." ) raise ValueError("Shared dpv key, has different dtype.") @@ -622,17 +615,14 @@ def _verify_dps_coherence( or key not in curr_trx.data_per_streamline.keys() ): if not delete_dps: - logging.debug( - "{} dps key does not exist in all TrxFile.".format(key) - ) + logging.debug(f"{key} dps key does not exist in all TrxFile.") raise ValueError("TrxFile must be sharing identical dps keys.") elif ( ref_trx.data_per_streamline[key].dtype != curr_trx.data_per_streamline[key].dtype ): logging.debug( - "{} dps key is not declared with the same dtype " - "in all TrxFile.".format(key) + f"{key} dps key is not declared with the same dtype in all TrxFile." ) raise ValueError("Shared dps key, has different dtype.") @@ -750,9 +740,7 @@ def _setup_groups_for_concatenation( os.mkdir(os.path.join(tmp_dir, "groups/")) dtype = all_groups_dtype[group_key] - group_filename = os.path.join( - tmp_dir, "groups/{}.{}".format(group_key, dtype.name) - ) + group_filename = os.path.join(tmp_dir, f"groups/{group_key}.{dtype.name}") group_len = all_groups_len[group_key] new_trx.groups[group_key] = _create_memmap( group_filename, mode="w+", shape=(group_len,), dtype=dtype @@ -985,9 +973,8 @@ def __init__( elif nb_vertices is not None and nb_streamlines is not None: logging.debug( - "Preallocating TrxFile with size {} streamlinesand {} vertices.".format( - nb_streamlines, nb_vertices - ) + f"Preallocating TrxFile with size {nb_streamlines} streamlines and " + f"{nb_vertices} vertices." ) trx = self._initialize_empty_trx( nb_streamlines, nb_vertices, init_as=init_as @@ -1009,50 +996,49 @@ def __str__(self) -> str: vox_sizes = np.array(voxel_sizes(affine), dtype=np.float32) vox_order = "".join(aff2axcodes(affine)) - text = "VOXEL_TO_RASMM: \n{}".format( - np.array2string(affine, formatter={"float_kind": lambda x: "%.6f" % x}) - ) - text += "\nDIMENSIONS: {}".format(np.array2string(dimensions)) - text += "\nVOX_SIZES: {}".format( - np.array2string(vox_sizes, formatter={"float_kind": lambda x: "%.2f" % x}) - ) - text += "\nVOX_ORDER: {}".format(vox_order) + formatter = {"float_kind": lambda x: "%.6f" % x} + text = f"VOXEL_TO_RASMM: \n{np.array2string(affine, formatter=formatter)}" + text += f"\nDIMENSIONS: {np.array2string(dimensions)}" + formatter = {"float_kind": lambda x: "%.2f" % x} + text += f"\nVOX_SIZES: {np.array2string(vox_sizes, formatter=formatter)}" + text += f"\nVOX_ORDER: {vox_order}" strs_size = self.header["NB_STREAMLINES"] pts_size = self.header["NB_VERTICES"] strs_len, pts_len = self._get_real_len() if strs_size != strs_len or pts_size != pts_len: - text += "\nstreamline_size: {}".format(strs_size) - text += "\nvertex_size: {}".format(pts_size) + text += f"\nstreamline_size: {strs_size}" + text += f"\nvertex_size: {pts_size}" - text += "\nstreamline_count: {}".format(strs_len) - text += "\nvertex_count: {}".format(pts_len) + text += f"\nstreamline_count: {strs_len}" + text += f"\nvertex_count: {pts_len}" dpv_keys = list(self.data_per_vertex.keys()) if dpv_keys: - text += "\ndata_per_vertex keys: {}".format(dpv_keys) + text += f"\ndata_per_vertex keys: {dpv_keys}" else: text += "\nNo data per vertex (dpv) keys" dps_keys = list(self.data_per_streamline.keys()) if dps_keys: - text += "\ndata_per_streamline keys: {}".format(dps_keys) + text += f"\ndata_per_streamline keys: {dps_keys}" else: text += "\nNo data per streamline (dps) keys" group_keys = list(self.groups.keys()) if group_keys: - text += "\ngroups keys: {}".format(group_keys) + text += f"\ngroups keys: {group_keys}" else: text += "\nNo group keys" for group_key in self.groups.keys(): if group_key in self.data_per_group: - text += "\ndata_per_groups ({}) keys: {}".format( - group_key, list(self.data_per_group[group_key].keys()) + text += ( + f"\ndata_per_groups ({group_key}) keys: " + f"{list(self.data_per_group[group_key].keys())}" ) - text += "\ncopy_safe: {}".format(self._copy_safe) + text += f"\ncopy_safe: {self._copy_safe}" return text @@ -1295,7 +1281,7 @@ def _initialize_empty_trx( # noqa: C901 """ trx = TrxFile() tmp_dir = get_trx_tmp_dir() - logging.info("Temporary folder for memmaps: {}".format(tmp_dir.name)) + logging.info(f"Temporary folder for memmaps: {tmp_dir.name}") trx.header["NB_VERTICES"] = nb_vertices trx.header["NB_STREAMLINES"] = nb_streamlines @@ -1311,23 +1297,19 @@ def _initialize_empty_trx( # noqa: C901 offsets_dtype = np.dtype(np.uint32) lengths_dtype = np.dtype(np.uint32) - logging.debug( - "Initializing positions with dtype: {}".format(positions_dtype.name) - ) - logging.debug("Initializing offsets with dtype: {}".format(offsets_dtype.name)) - logging.debug("Initializing lengths with dtype: {}".format(lengths_dtype.name)) + logging.debug(f"Initializing positions with dtype: {positions_dtype.name}") + logging.debug(f"Initializing offsets with dtype: {offsets_dtype.name}") + logging.debug(f"Initializing lengths with dtype: {lengths_dtype.name}") # A TrxFile without init_as only contain the essential arrays positions_filename = os.path.join( - tmp_dir.name, "positions.3.{}".format(positions_dtype.name) + tmp_dir.name, f"positions.3.{positions_dtype.name}" ) trx.streamlines._data = _create_memmap( positions_filename, mode="w+", shape=(nb_vertices, 3), dtype=positions_dtype ) - offsets_filename = os.path.join( - tmp_dir.name, "offsets.{}".format(offsets_dtype.name) - ) + offsets_filename = os.path.join(tmp_dir.name, f"offsets.{offsets_dtype.name}") trx.streamlines._offsets = _create_memmap( offsets_filename, mode="w+", shape=(nb_streamlines,), dtype=offsets_dtype ) @@ -1347,21 +1329,19 @@ def _initialize_empty_trx( # noqa: C901 tmp_as = init_as.data_per_vertex[dpv_key]._data if tmp_as.ndim == 1: dpv_filename = os.path.join( - tmp_dir.name, "dpv/{}.{}".format(dpv_key, dtype.name) + tmp_dir.name, f"dpv/{dpv_key}.{dtype.name}" ) shape = (nb_vertices, 1) elif tmp_as.ndim == 2: dim = tmp_as.shape[-1] shape = (nb_vertices, dim) dpv_filename = os.path.join( - tmp_dir.name, "dpv/{}.{}.{}".format(dpv_key, dim, dtype.name) + tmp_dir.name, f"dpv/{dpv_key}.{dim}.{dtype.name}" ) else: raise ValueError("Invalid dimensionality.") - logging.debug( - "Initializing {} (dpv) with dtype: {}".format(dpv_key, dtype.name) - ) + logging.debug(f"Initializing {dpv_key} (dpv) with dtype: {dtype.name}") trx.data_per_vertex[dpv_key] = ArraySequence() trx.data_per_vertex[dpv_key]._data = _create_memmap( dpv_filename, mode="w+", shape=shape, dtype=dtype @@ -1374,22 +1354,20 @@ def _initialize_empty_trx( # noqa: C901 tmp_as = init_as.data_per_streamline[dps_key] if tmp_as.ndim == 1: dps_filename = os.path.join( - tmp_dir.name, "dps/{}.{}".format(dps_key, dtype.name) + tmp_dir.name, f"dps/{dps_key}.{dtype.name}" ) shape = (nb_streamlines,) elif tmp_as.ndim == 2: dim = tmp_as.shape[-1] shape = (nb_streamlines, dim) dps_filename = os.path.join( - tmp_dir.name, "dps/{}.{}.{}".format(dps_key, dim, dtype.name) + tmp_dir.name, f"dps/{dps_key}.{dim}.{dtype.name}" ) else: raise ValueError("Invalid dimensionality.") logging.debug( - "Initializing {} (dps) with and dtype: {}".format( - dps_key, dtype.name - ) + f"Initializing {dps_key} (dps) with and dtype: {dtype.name}" ) trx.data_per_streamline[dps_key] = _create_memmap( dps_filename, mode="w+", shape=shape, dtype=dtype @@ -1530,9 +1508,7 @@ def _create_trx_from_pointer( # noqa: C901 filename, mode="r+", offset=mem_adress, shape=shape, dtype=ext[1:] ) else: - logging.error( - "{} is not part of a valid structure.".format(elem_filename) - ) + logging.error(f"{elem_filename} is not part of a valid structure.") # All essential array must be declared if positions is not None and offsets is not None: @@ -1599,14 +1575,12 @@ def resize( # noqa: C901 trx = self._initialize_empty_trx(nb_streamlines, nb_vertices, init_as=self) logging.info( - "Resizing streamlines from size {} to {}".format( - len(self.streamlines), nb_streamlines - ) + "Resizing streamlines from size " + f"{len(self.streamlines)} to {nb_streamlines}" ) logging.info( - "Resizing vertices from size {} to {}".format( - len(self.streamlines._data), nb_vertices - ) + "Resizing vertices from size " + f"{len(self.streamlines._data)} to {nb_vertices}" ) # Copy the fixed-sized info from the original TrxFile to the new @@ -1623,7 +1597,7 @@ def resize( # noqa: C901 for group_key in self.groups.keys(): group_dtype = self.groups[group_key].dtype group_name = os.path.join( - tmp_dir, "groups/", "{}.{}".format(group_key, group_dtype.name) + tmp_dir, "groups/", f"{group_key}.{group_dtype.name}" ) ori_len = len(self.groups[group_key]) @@ -1632,9 +1606,7 @@ def resize( # noqa: C901 trx.groups[group_key] = _create_memmap( group_name, mode="w+", shape=(len(tmp),), dtype=group_dtype ) - logging.debug( - "{} group went from {} items to {}".format(group_key, ori_len, len(tmp)) - ) + logging.debug(f"{group_key} group went from {ori_len} items to {len(tmp)}") trx.groups[group_key][:] = tmp if delete_dpg: @@ -1728,7 +1700,7 @@ def append(self, obj, extra_buffer: int = 0) -> None: dipy_available and not isinstance(obj, StatefulTractogram) ): raise TypeError( - "{} is not a supported object type for appending.".format(type(obj)) + f"{type(obj)} is not a supported object type for appending." ) elif isinstance(obj, Tractogram): obj = self.from_tractogram( @@ -1990,15 +1962,14 @@ def from_sft(sft, dtype_dict=None): if not np.issubdtype(positions_dtype, np.floating): logging.warning( - "Casting positions as {}, considering using a floating point " - "dtype.".format(positions_dtype) + f"Casting positions as {positions_dtype}, considering using a floating " + "point dtype." ) if not np.issubdtype(offsets_dtype, np.integer): logging.warning( - "Casting offsets as {}, considering using a integer dtype.".format( - offsets_dtype - ) + f"Casting offsets as {offsets_dtype}, considering using a integer " + "dtype." ) trx = TrxFile( @@ -2092,15 +2063,14 @@ def from_tractogram( if not np.issubdtype(positions_dtype, np.floating): logging.warning( - "Casting positions as {}, considering using a floating point " - "dtype.".format(positions_dtype) + f"Casting positions as {positions_dtype}, considering using a floating " + "point dtype." ) if not np.issubdtype(offsets_dtype, np.integer): logging.warning( - "Casting offsets as {}, considering using a integer dtype.".format( - offsets_dtype - ) + f"Casting offsets as {offsets_dtype}, considering using a integer " + "dtype." ) trx = TrxFile( diff --git a/trx/utils.py b/trx/utils.py index 885f988b..92c0f3c5 100644 --- a/trx/utils.py +++ b/trx/utils.py @@ -348,7 +348,7 @@ def load_matrix_in_any_format(filepath): elif ext == ".npy": data = np.load(filepath) else: - raise ValueError("Extension {} is not supported".format(ext)) + raise ValueError(f"Extension {ext} is not supported") return data @@ -489,15 +489,13 @@ def verify_trx_dtype(trx, dict_dtype): # noqa: C901 elif key == "dpv": for key_dpv in dict_dtype[key]: if trx.data_per_vertex[key_dpv]._data.dtype != dict_dtype[key][key_dpv]: - logging.warning( - "Data per vertex ({}) dtype is different".format(key_dpv) - ) + logging.warning(f"Data per vertex ({key_dpv}) dtype is different") identical = False elif key == "dps": for key_dps in dict_dtype[key]: if trx.data_per_streamline[key_dps].dtype != dict_dtype[key][key_dps]: logging.warning( - "Data per streamline ({}) dtype is different".format(key_dps) + f"Data per streamline ({key_dps}) dtype is different" ) identical = False elif key == "dpg": @@ -508,7 +506,7 @@ def verify_trx_dtype(trx, dict_dtype): # noqa: C901 != dict_dtype[key][key_group][key_dpg] ): logging.warning( - "Data per group ({}) dtype is different".format(key_dpg) + f"Data per group ({key_dpg}) dtype is different" ) identical = False elif key == "groups": @@ -517,9 +515,7 @@ def verify_trx_dtype(trx, dict_dtype): # noqa: C901 trx.data_per_point[key_group]._data.dtype != dict_dtype[key][key_group] ): - logging.warning( - "Data per group ({}) dtype is different".format(key_group) - ) + logging.warning(f"Data per group ({key_group}) dtype is different") identical = False return identical diff --git a/trx/workflows.py b/trx/workflows.py index bdea9c72..b30986a3 100644 --- a/trx/workflows.py +++ b/trx/workflows.py @@ -78,7 +78,7 @@ def convert_dsi_studio( elif in_ext == ".trk": sft = load_tractogram(in_dsi_tractogram, "same", bbox_valid_check=False) else: - raise IOError("{} is not currently supported.".format(in_ext)) + raise IOError(f"{in_ext} is not currently supported.") sft.to_vox() sft_fix = StatefulTractogram( @@ -210,9 +210,8 @@ def tractogram_simple_compare(in_tractograms, reference): print("Matching tractograms in rasmm!") else: print( - "Average difference in rasmm of {}".format( - np.average(sft_1.streamlines._data - sft_2.streamlines._data, axis=0) - ) + "Average difference in rasmm of " + f"{np.average(sft_1.streamlines._data - sft_2.streamlines._data, axis=0)}" ) sft_1.to_voxmm() @@ -221,9 +220,8 @@ def tractogram_simple_compare(in_tractograms, reference): print("Matching tractograms in voxmm!") else: print( - "Average difference in voxmm of {}".format( - np.average(sft_1.streamlines._data - sft_2.streamlines._data, axis=0) - ) + "Average difference in voxmm of " + f"{np.average(sft_1.streamlines._data - sft_2.streamlines._data, axis=0)}" ) sft_1.to_vox() @@ -232,9 +230,8 @@ def tractogram_simple_compare(in_tractograms, reference): print("Matching tractograms in vox!") else: print( - "Average difference in vox of {}".format( - np.average(sft_1.streamlines._data - sft_2.streamlines._data, axis=0) - ) + "Average difference in vox of " + f"{np.average(sft_1.streamlines._data - sft_2.streamlines._data, axis=0)}" ) @@ -258,14 +255,12 @@ def verify_header_compatibility(in_files): all_valid = True for filepath in in_files: if not os.path.isfile(filepath): - print("{} does not exist".format(filepath)) + print(f"{filepath} does not exist") _, in_extension = split_name_with_gz(filepath) if in_extension not in [".trk", ".nii", ".nii.gz", ".trx"]: - raise IOError("{} does not have a supported extension".format(filepath)) + raise IOError(f"{filepath} does not have a supported extension") if not is_header_compatible(in_files[0], filepath): - print( - "{} and {} do not have compatible header.".format(in_files[0], filepath) - ) + print(f"{in_files[0]} and {filepath} do not have compatible header.") all_valid = False if all_valid: print("All input files have compatible headers.") @@ -318,16 +313,12 @@ def validate_tractogram( invalid_coord_ind, _ = sft.remove_invalid_streamlines() tot_remove += len(invalid_coord_ind) logging.warning( - "Removed {} streamlines with invalid coordinates.".format( - len(invalid_coord_ind) - ) + f"Removed {len(invalid_coord_ind)} streamlines with invalid coordinates." ) indices = [i for i in range(len(sft)) if len(sft.streamlines[i]) <= 1] tot_remove = +len(indices) - logging.warning( - "Removed {} invalid streamlines (1 or 0 points).".format(len(indices)) - ) + logging.warning(f"Removed {len(indices)} invalid streamlines (1 or 0 points).") for i in np.setdiff1d(range(len(sft)), indices): norm = np.linalg.norm(np.diff(sft.streamlines[i], axis=0), axis=1) @@ -337,9 +328,8 @@ def validate_tractogram( indices_val = np.setdiff1d(range(len(sft)), indices).astype(np.uint32) logging.warning( - "Removed {} invalid streamlines (overlapping points).".format( - ori_len - len(indices_val) - ) + f"Removed {ori_len - len(indices_val)} invalid streamlines " + "(overlapping points)." ) tot_remove += ori_len - len(indices_val) @@ -349,9 +339,8 @@ def validate_tractogram( ) indices_final = np.intersect1d(indices_val, indices_uniq).astype(np.uint32) logging.warning( - "Removed {} overlapping streamlines.".format( - ori_len - len(indices_final) - tot_remove - ) + f"Removed {ori_len - len(indices_final) - tot_remove} " + "overlapping streamlines." ) indices_final = np.intersect1d(indices_val, indices_uniq) @@ -458,9 +447,7 @@ def _apply_spatial_transforms( sft = StatefulTractogram(streamlines, reference, space, origin) if verify_invalid: rem, _ = sft.remove_invalid_streamlines() - print( - "{} streamlines were removed becaused they were invalid.".format(len(rem)) - ) + print(f"{len(rem)} streamlines were removed because they were invalid.") sft.to_rasmm() sft.to_center() streamlines = sft.streamlines @@ -509,11 +496,11 @@ def _write_streamline_data(tmp_dir_name, streamlines, positions_dtype, offsets_d offsets_dtype : str Datatype for offsets array. """ - curr_filename = os.path.join(tmp_dir_name, "positions.3.{}".format(positions_dtype)) + curr_filename = os.path.join(tmp_dir_name, f"positions.3.{positions_dtype}") positions = streamlines._data.astype(positions_dtype) tmm._ensure_little_endian(positions).tofile(curr_filename) - curr_filename = os.path.join(tmp_dir_name, "offsets.{}".format(offsets_dtype)) + curr_filename = os.path.join(tmp_dir_name, f"offsets.{offsets_dtype}") offsets = streamlines._offsets.astype(offsets_dtype) tmm._ensure_little_endian(offsets).tofile(curr_filename) @@ -572,15 +559,15 @@ def _write_data_array(tmp_dir_name, subdir_name, args, is_dpg=False): if curr_arr.shape == (1, 1): curr_arr = curr_arr.reshape((1,)) - dim = "" if curr_arr.ndim == 1 else "{}.".format(curr_arr.shape[-1]) + dim = "" if curr_arr.ndim == 1 else f"{curr_arr.shape[-1]}." if is_dpg: curr_filename = os.path.join( - tmp_dir_name, "dpg", args[0], "{}.{}{}".format(basename, dim, dtype) + tmp_dir_name, "dpg", args[0], f"{basename}.{dim}{dtype}" ) else: curr_filename = os.path.join( - tmp_dir_name, subdir_name, "{}.{}{}".format(basename, dim, dtype) + tmp_dir_name, subdir_name, f"{basename}.{dim}{dtype}" ) tmm._ensure_little_endian(curr_arr).tofile(curr_filename) From a6ff4b9a8e819225b79062e85c5ad9a581b40f06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Mon, 10 Aug 2026 22:12:47 +0200 Subject: [PATCH 2/2] STY: Replace single-letter variable names with descriptive names Replace single-letter variable names with descriptive names. --- trx/fetcher.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/trx/fetcher.py b/trx/fetcher.py index a947e707..1323c852 100644 --- a/trx/fetcher.py +++ b/trx/fetcher.py @@ -84,8 +84,8 @@ def md5sum(filename): Hexadecimal MD5 digest. """ h = hashlib.md5() - with open(filename, "rb") as f: - for chunk in iter(lambda: f.read(128 * h.block_size), b""): + with open(filename, "rb") as file: + for chunk in iter(lambda: file.read(128 * h.block_size), b""): h.update(chunk) return h.hexdigest() @@ -104,8 +104,8 @@ def sha256sum(filename): Hexadecimal SHA256 digest. """ h = hashlib.sha256() - with open(filename, "rb") as f: - for chunk in iter(lambda: f.read(128 * h.block_size), b""): + with open(filename, "rb") as file: + for chunk in iter(lambda: file.read(128 * h.block_size), b""): h.update(chunk) return h.hexdigest() @@ -140,23 +140,23 @@ def fetch_data(files_dict, keys=None): # noqa: C901 elif isinstance(keys, str): keys = [keys] - for f in keys: - file_entry = files_dict[f] + for fname in keys: + file_entry = files_dict[fname] if len(file_entry) == 2: url, expected_md5 = file_entry expected_sha = None else: url, expected_md5, expected_sha = file_entry - full_path = os.path.join(trx_home, f) + full_path = os.path.join(trx_home, fname) - logging.info(f"Downloading {f} to {trx_home}") + logging.info(f"Downloading {fname} to {trx_home}") if not os.path.exists(full_path): urllib.request.urlretrieve(url, full_path) actual_md5 = md5sum(full_path) if expected_md5 != actual_md5: raise ValueError( - f"Md5sum for {f} does not match. " + f"Md5sum for {fname} does not match. " "Please remove the file to download it again: " + full_path ) @@ -164,10 +164,10 @@ def fetch_data(files_dict, keys=None): # noqa: C901 actual_sha = sha256sum(full_path) if expected_sha != actual_sha: raise ValueError( - f"SHA256 for {f} does not match. " + f"SHA256 for {fname} does not match. " "Please remove the file to download it again: " + full_path ) - if f.endswith(".zip"): - dst_dir = os.path.join(trx_home, f[:-4]) + if fname.endswith(".zip"): + dst_dir = os.path.join(trx_home, fname[:-4]) shutil.unpack_archive(full_path, extract_dir=dst_dir, format="zip")