Skip to content

Commit f01009c

Browse files
authored
Fix ruff PERF401: manual-list-comprehension (#4449)
* unignore PERF401 rule * fix core * fix dev_scripts * fix ext * fix entries * fix symmetry * fix transformations * fix alchemy * fix apps * fix command line * fix phonon * fix lobster * fix vasp * fix io * fix electronic structure * fix analysis * fix typo * fix some mypy error * add test
1 parent 0d708d6 commit f01009c

Some content is hidden

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

70 files changed

+392
-559
lines changed

dev_scripts/chemenv/get_plane_permutations_optimized.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,7 @@ def random_permutations_iterator(initial_permutation, n_permutations):
131131
continue
132132
n_cols = 5
133133
n_lines = int(np.ceil(float(len(sep_plane_cgs)) / n_cols))
134-
sep_plane_cgs_grid = []
135-
for _ in range(n_lines):
136-
sep_plane_cgs_grid.append([""] * n_cols)
134+
sep_plane_cgs_grid = [[""] * n_cols for _ in range(n_lines)]
137135
for line_idx in range(n_lines):
138136
for col_idx in range(n_cols):
139137
ii = line_idx * n_cols + col_idx

dev_scripts/update_spacegroup_data.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,7 @@ def remove_identity_from_full_hermann_mauguin(symbol: str) -> str:
5858
blickrichtungen = symbol.split(" ")
5959
if blickrichtungen[1].startswith("3"):
6060
return symbol
61-
blickrichtungen_new = []
62-
for br in blickrichtungen:
63-
if br != "1":
64-
blickrichtungen_new.append(br + " ")
61+
blickrichtungen_new = [br + " " for br in blickrichtungen if br != "1"]
6562
return "".join(blickrichtungen_new)
6663

6764

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,6 @@ ignore = [
213213
"FBT002", # Boolean default positional argument in function
214214
"PD011", # (A lot of false positive on non-Pandas objects)
215215
"PERF203", # Use of try-except in for/while loop
216-
"PERF401", # Replace "for" loops with list comprehension
217216
"PLR0911", # Too many return statements
218217
"PLR0912", # Too many branches
219218
"PLR0913", # Too many arguments

src/pymatgen/alchemy/transmuters.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,7 @@ def __len__(self):
8080

8181
def __str__(self):
8282
output = ["Current structures", "------------"]
83-
for ts in self.transformed_structures:
84-
output.append(str(ts.final_structure))
83+
output.extend(str(ts.final_structure) for ts in self.transformed_structures)
8584
return "\n".join(output)
8685

8786
def undo_last_change(self) -> None:

src/pymatgen/analysis/adsorption.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -454,20 +454,17 @@ def generate_adsorption_structures(
454454
xrep = np.ceil(min_lw / np.linalg.norm(self.slab.lattice.matrix[0]))
455455
yrep = np.ceil(min_lw / np.linalg.norm(self.slab.lattice.matrix[1]))
456456
repeat = [xrep, yrep, 1]
457-
structs = []
458457

459-
find_args = find_args or {}
460-
for coords in self.find_adsorption_sites(**find_args)["all"]:
461-
structs.append(
462-
self.add_adsorbate(
463-
molecule,
464-
coords,
465-
repeat=repeat,
466-
translate=translate,
467-
reorient=reorient,
468-
)
458+
return [
459+
self.add_adsorbate(
460+
molecule,
461+
coords,
462+
repeat=repeat,
463+
translate=translate,
464+
reorient=reorient,
469465
)
470-
return structs
466+
for coords in self.find_adsorption_sites(**(find_args or {}))["all"]
467+
]
471468

472469
def adsorb_both_surfaces(
473470
self,

src/pymatgen/analysis/bond_dissociation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,12 +150,12 @@ def fragment_and_process(self, bonds):
150150
# Since a ring opening still yields a single molecule, it should have the same charge as the
151151
# principle:
152152
if frag["initial_molecule"]["charge"] == self.molecule_entry["final_molecule"]["charge"]:
153-
good_entries.append(frag)
153+
good_entries.append(frag) # noqa: PERF401
154154
# If we didn't find any good entries, let's also look at those that exhibit structural changes:
155155
if len(good_entries) == 0:
156156
for frag in opened_entries[1]: # 1 -> YES structural change
157157
if frag["initial_molecule"]["charge"] == self.molecule_entry["final_molecule"]["charge"]:
158-
good_entries.append(frag)
158+
good_entries.append(frag) # noqa: PERF401
159159
# If we still have no good entries, something must have gone wrong with the calculations:
160160
if len(good_entries) == 0:
161161
bb = BabelMolAdaptor.from_molecule_graph(RO_frag)

src/pymatgen/analysis/bond_valence.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -414,9 +414,7 @@ def _recurse(assigned=None):
414414

415415
return [int(assigned[site]) for site in structure]
416416
assigned = {}
417-
new_best_vset = []
418-
for _ in equi_sites:
419-
new_best_vset.append([])
417+
new_best_vset = [[] for _ in equi_sites]
420418
for ival, val in enumerate(self._best_vset):
421419
new_best_vset[attrib[ival]].append(val)
422420
for val, sites in zip(new_best_vset, equi_sites, strict=True):

src/pymatgen/analysis/chemenv/connectivity/connected_components.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -451,8 +451,7 @@ def compute_periodicity_all_simple_paths_algorithm(self):
451451
this_path_deltas_new = []
452452
for edge_data in self._connected_subgraph[node1][node2].values():
453453
delta = get_delta(node1, node2, edge_data)
454-
for current_delta in this_path_deltas:
455-
this_path_deltas_new.append(current_delta + delta)
454+
this_path_deltas_new.extend(current_delta + delta for current_delta in this_path_deltas)
456455
this_path_deltas = this_path_deltas_new
457456
this_node_cell_img_vectors.extend(this_path_deltas)
458457
this_node_cell_img_vectors = get_linearly_independent_vectors(this_node_cell_img_vectors)
@@ -487,8 +486,7 @@ def compute_periodicity_cycle_basis(self) -> None:
487486
this_cycle_deltas_new = []
488487
for edge_data in self._connected_subgraph[node1][node2].values():
489488
delta = get_delta(node1, node2, edge_data)
490-
for current_delta in this_cycle_deltas:
491-
this_cycle_deltas_new.append(current_delta + delta)
489+
this_cycle_deltas_new.extend(current_delta + delta for current_delta in this_cycle_deltas)
492490
this_cycle_deltas = this_cycle_deltas_new
493491
all_deltas.extend(this_cycle_deltas)
494492
all_deltas = get_linearly_independent_vectors(all_deltas)

src/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2729,11 +2729,10 @@ def get_site_coordination_environments_fractions(
27292729
site_nb_sets = self.structure_environments.neighbors_sets[isite]
27302730
if site_nb_sets is None:
27312731
return None
2732-
cn_maps = []
2733-
for cn, nb_sets in site_nb_sets.items():
2734-
for inb_set in range(len(nb_sets)):
2735-
# CHECK THE ADDITIONAL CONDITION HERE ?
2736-
cn_maps.append((cn, inb_set))
2732+
2733+
# CHECK THE ADDITIONAL CONDITION HERE ?
2734+
cn_maps = [(cn, inb_set) for cn, nb_sets in site_nb_sets.items() for inb_set in range(len(nb_sets))]
2735+
27372736
weights_additional_info = {"weights": {isite: {}}}
27382737
for wdict in self.ordered_weights:
27392738
cn_maps_new = []

src/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -632,8 +632,7 @@ def __str__(self):
632632
outs.append("... not yet implemented")
633633
else:
634634
outs.append(" - list of points :")
635-
for pp in self.points:
636-
outs.append(f" - {pp}")
635+
outs.extend(f" - {pp}" for pp in self.points)
637636
outs.extend(("------------------------------------------------------------", ""))
638637

639638
return "\n".join(outs)
@@ -754,9 +753,7 @@ def ref_permutation(self, permutation):
754753
Returns:
755754
Permutation: Reference permutation of the perfect CoordinationGeometry.
756755
"""
757-
perms = []
758-
for eqv_indices in self.equivalent_indices:
759-
perms.append(tuple(permutation[ii] for ii in eqv_indices))
756+
perms = [tuple(permutation[ii] for ii in eqv_indices) for eqv_indices in self.equivalent_indices]
760757
perms.sort()
761758
return perms[0]
762759

@@ -925,8 +922,8 @@ def __repr__(self):
925922
"#=================================#",
926923
"",
927924
]
928-
for cg in self.cg_list:
929-
outs.append(repr(cg))
925+
926+
outs.extend(repr(cg) for cg in self.cg_list)
930927

931928
return "\n".join(outs)
932929

@@ -939,9 +936,8 @@ def __str__(self):
939936
"#=======================================================#",
940937
"",
941938
]
942-
for cg in self.cg_list:
943-
if cg.is_implemented():
944-
outs.append(str(cg))
939+
940+
outs.extend(str(cg) for cg in self.cg_list if cg.is_implemented())
945941

946942
return "\n".join(outs)
947943

0 commit comments

Comments
 (0)