diff --git a/dev_scripts/chemenv/get_plane_permutations_optimized.py b/dev_scripts/chemenv/get_plane_permutations_optimized.py index 00ed4e0f1b6..15064fae49d 100644 --- a/dev_scripts/chemenv/get_plane_permutations_optimized.py +++ b/dev_scripts/chemenv/get_plane_permutations_optimized.py @@ -48,8 +48,15 @@ def prt2(string, printing_volume): # Iterator function for the random permutations -def random_permutations_iterator(initial_permutation, npermutations): - for _ in range(npermutations): +def random_permutations_iterator(initial_permutation, n_permutations): + """ + It takes a list and returns an iterator that yields random permutations of that list + + Args: + initial_permutation: the initial permutation of the data + n_permutations: the number of permutations to generate + """ + for _ in range(n_permutations): shuffle(initial_permutation) yield initial_permutation @@ -157,7 +164,7 @@ def random_permutations_iterator(initial_permutation, npermutations): cg = all_cg[cg_symbol] - print(f'Getting explicit permutations for geometry "{cg.name}" (symbol : "{cg_symbol}")\n') + print(f"Getting explicit permutations for geometry {cg.name!r} (symbol : {cg_symbol!r})\n") # Setup of the local geometry finder lgf = LocalGeometryFinder() @@ -274,8 +281,8 @@ def random_permutations_iterator(initial_permutation, npermutations): while True: test = input( - f'Get the explicit optimized permutations for geometry "{cg.name}" (symbol : ' - f'"{cg_symbol}") ? ("y" to confirm, "q" to quit)\n' + f"Get the explicit optimized permutations for geometry {cg.name!r} (symbol : " + f'{cg_symbol!r}) ? ("y" to confirm, "q" to quit)\n' ) if test not in ["y", "q"]: print("Wrong key, try again") @@ -285,7 +292,7 @@ def random_permutations_iterator(initial_permutation, npermutations): elif test == "q": exit() # 2. Optimization of the permutations - print(f'Getting explicit optimized permutations for geometry "{cg.name}" (symbol : "{cg_symbol}")\n') + print(f"Getting explicit optimized permutations for geometry {cg.name!r} (symbol : {cg_symbol!r})\n") perms_used_algos = [dict() for algo in cg.algorithms] # Loop on algorithms @@ -424,7 +431,7 @@ def random_permutations_iterator(initial_permutation, npermutations): algo.explicit_optimized_permutations = np.array(explicit_optimized_permutations) test = input( - f'Save coordination geometry "{cg.name}" (symbol "{cg_symbol}") and new explicit and optimized ' + f"Save coordination geometry {cg.name!r} (symbol {cg_symbol!r}) and new explicit and optimized " 'permutations ? ("y" to confirm)' ) if test == "y": diff --git a/dev_scripts/chemenv/test_algos.py b/dev_scripts/chemenv/test_algos.py index 8ca7407f2d0..b30b543dcec 100644 --- a/dev_scripts/chemenv/test_algos.py +++ b/dev_scripts/chemenv/test_algos.py @@ -97,4 +97,4 @@ print(" => ", algos_results) iperm += 1 t2 = time.clock() - print(f'Time to test {nperms} permutations for geometry "{cg.name}" (symbol "{cg_symbol}") : {t2 - t1:.2f} seconds') + print(f"Time to test {nperms} permutations for geometry {cg.name!r} (symbol {cg_symbol!r}) : {t2 - t1:.2f} seconds") diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index 439f5ed5553..ea88d14581e 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -210,7 +210,7 @@ def __init__( environments_data=None, links_data=None, graph=None, - ): + ) -> None: """ Constructor for the ConnectedComponent object. @@ -354,7 +354,7 @@ def coordination_sequence(self, source_node, path_size=5, coordination="number", elif coordination == "env:number": cseq[0] = {source_node.coordination_environment: 1} else: - raise ValueError(f'Coordination type "{coordination}" is not valid for coordination_sequence.') + raise ValueError(f"Coordination type {coordination!r} is not valid for coordination_sequence.") while path_len < path_size: new_ends = [] for current_node_end, current_delta_end in current_ends: @@ -377,7 +377,7 @@ def coordination_sequence(self, source_node, path_size=5, coordination="number", myenvs = [myend.coordination_environment for myend, _ in current_ends] cseq[path_len] = {myenv: myenvs.count(myenv) for myenv in set(myenvs)} else: - raise ValueError(f'Coordination type "{coordination}" is not valid for coordination_sequence.') + raise ValueError(f"Coordination type {coordination!r} is not valid for coordination_sequence.") return cseq def __len__(self): @@ -395,7 +395,7 @@ def compute_periodicity(self, algorithm="all_simple_paths"): elif algorithm == "cycle_basis": self.compute_periodicity_cycle_basis() else: - raise ValueError(f'Algorithm "{algorithm}" is not allowed to compute periodicity') + raise ValueError(f"Algorithm {algorithm!r} is not allowed to compute periodicity") self._order_periodicity_vectors() def compute_periodicity_all_simple_paths_algorithm(self): diff --git a/pymatgen/analysis/chemenv/connectivity/connectivity_finder.py b/pymatgen/analysis/chemenv/connectivity/connectivity_finder.py index d0685bf6b1a..7d2054bcb08 100644 --- a/pymatgen/analysis/chemenv/connectivity/connectivity_finder.py +++ b/pymatgen/analysis/chemenv/connectivity/connectivity_finder.py @@ -76,6 +76,6 @@ def setup_parameters(self, multiple_environments_choice): if multiple_environments_choice is not None: if multiple_environments_choice not in ["TAKE_HIGHEST_FRACTION"]: raise ValueError( - f'Option "{multiple_environments_choice}" for multiple_environments_choice is not allowed' + f"Option {multiple_environments_choice!r} for multiple_environments_choice is not allowed" ) self.multiple_environments_choice = multiple_environments_choice diff --git a/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py b/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py index dc5673a1ca2..cb42041a31b 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py +++ b/pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py @@ -162,7 +162,7 @@ class AdditionalConditionInt(int, StrategyOption): allowed_values = "Integer amongst :\n" for integer, description in AdditionalConditions.CONDITION_DESCRIPTION.items(): - allowed_values += f' - {integer:d} for "{description}"\n' + allowed_values += f" - {integer:d} for {description!r}\n" def __new__(cls, integer): """Special int representing additional conditions.""" @@ -442,7 +442,7 @@ def __eq__(self, other: object) -> bool: raise NotImplementedError() def __str__(self): - out = f' Chemenv Strategy "{type(self).__name__}"\n' + out = f" Chemenv Strategy {type(self).__name__!r}\n" out += f" {'=' * (19 + len(type(self).__name__))}\n\n" out += f" Description :\n {'-' * 13}\n" out += self.STRATEGY_DESCRIPTION @@ -1335,7 +1335,7 @@ def __init__(self, average_type, aa, bb): elif self.average_type == "arithmetic": self.eval = self.aweight else: - raise ValueError(f'Average type is "{average_type}" while it should be "geometric" or "arithmetic"') + raise ValueError(f"Average type is {average_type!r} while it should be 'geometric' or 'arithmetic'") self.aa = aa self.bb = bb if self.aa == 0: @@ -2046,7 +2046,7 @@ def __init__( raise NotImplementedError() # self.area_weight = self.w_area_has_intersection_smoothstep else: - raise ValueError(f'Weight type is "{weight_type}" while it should be "has_intersection"') + raise ValueError(f'Weight type is {weight_type!r} while it should be "has_intersection"') self.surface_definition = surface_definition self.nb_sets_from_hints = nb_sets_from_hints self.other_nb_sets = other_nb_sets diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py index 01a12e1b6e4..5a9599b9d46 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py @@ -392,7 +392,7 @@ def __init__(self, hints_type, options): neighbors set could be found from a "cap hint". """ if hints_type not in self.ALLOWED_HINTS_TYPES: - raise ValueError(f'Type "{type}" for NeighborsSetsHints is not allowed') + raise ValueError(f"Type {type!r} for NeighborsSetsHints is not allowed") self.hints_type = hints_type self.options = options @@ -1171,7 +1171,7 @@ def get_geometry_from_name(self, name): for gg in self.cg_list: if gg.name == name or name in gg.alternative_names: return gg - raise LookupError(f'No coordination geometry found with name "{name}"') + raise LookupError(f"No coordination geometry found with name {name!r}") def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol): """ @@ -1183,7 +1183,7 @@ def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol): for gg in self.cg_list: if gg.IUPAC_symbol == IUPAC_symbol: return gg - raise LookupError(f'No coordination geometry found with IUPAC symbol "{IUPAC_symbol}"') + raise LookupError(f"No coordination geometry found with IUPAC symbol {IUPAC_symbol!r}") def get_geometry_from_IUCr_symbol(self, IUCr_symbol): """ @@ -1195,7 +1195,7 @@ def get_geometry_from_IUCr_symbol(self, IUCr_symbol): for gg in self.cg_list: if gg.IUCr_symbol == IUCr_symbol: return gg - raise LookupError(f'No coordination geometry found with IUCr symbol "{IUCr_symbol}"') + raise LookupError(f"No coordination geometry found with IUCr symbol {IUCr_symbol!r}") def get_geometry_from_mp_symbol(self, mp_symbol): """ @@ -1207,7 +1207,7 @@ def get_geometry_from_mp_symbol(self, mp_symbol): for gg in self.cg_list: if gg.mp_symbol == mp_symbol: return gg - raise LookupError(f'No coordination geometry found with mp_symbol "{mp_symbol}"') + raise LookupError(f"No coordination geometry found with mp_symbol {mp_symbol!r}") def is_a_valid_coordination_geometry( self, mp_symbol=None, IUPAC_symbol=None, IUCr_symbol=None, name=None, cn=None diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py index 9bbb2b0ea91..a9dda6f94cd 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py @@ -785,7 +785,7 @@ def compute_structure_environments( # Get possibly missing neighbors sets if cg.neighbors_sets_hints is None: continue - logging.debug(f' ... getting hints from cg with mp_symbol "{cg_symbol}" ...') + logging.debug(f" ... getting hints from cg with mp_symbol {cg_symbol!r} ...") hints_info = { "csm": cg_dict["symmetry_measure"], "nb_set": nb_set, diff --git a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py index 9fc54a4eaab..056343b291e 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py +++ b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py @@ -651,7 +651,7 @@ def get_csm(self, isite, mp_symbol): raise ChemenvError( "StructureEnvironments", "get_csm", - f'Number of csms for site #{str(isite)} with mp_symbol "{mp_symbol}" = {str(len(csms))}', + f"Number of csms for site #{str(isite)} with mp_symbol {mp_symbol!r} = {str(len(csms))}", ) return csms[0] @@ -1968,7 +1968,7 @@ def site_has_clear_environment(self, isite, conditions=None): if ce[target] > condition["maxnumber"]: return False else: - raise ValueError(f'Target "{target}" for condition of clear environment is not allowed') + raise ValueError(f"Target {target!r} for condition of clear environment is not allowed") return True def structure_has_clear_environments(self, conditions=None, skip_none=True, skip_empty=False): @@ -2294,7 +2294,7 @@ def add_coord_geom( raise ChemenvError( self.__class__, "add_coord_geom", - f'Coordination geometry with mp_symbol "{mp_symbol}" is not valid', + f"Coordination geometry with mp_symbol {mp_symbol!r} is not valid", ) if mp_symbol in list(self.coord_geoms) and not override: raise ChemenvError( diff --git a/pymatgen/analysis/chemenv/coordination_environments/tests/test_coordination_geometries.py b/pymatgen/analysis/chemenv/coordination_environments/tests/test_coordination_geometries.py index d690bd1307f..e4d3d0fbb60 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/tests/test_coordination_geometries.py +++ b/pymatgen/analysis/chemenv/coordination_environments/tests/test_coordination_geometries.py @@ -296,21 +296,21 @@ def test_coordination_geometry(self): assert allcg.get_geometry_from_name("Octahedron").mp_symbol == cg_oct.mp_symbol with pytest.raises(LookupError) as exc_info: allcg.get_geometry_from_name("Octahedran") - assert str(exc_info.value) == 'No coordination geometry found with name "Octahedran"' + assert str(exc_info.value) == "No coordination geometry found with name 'Octahedran'" assert allcg.get_geometry_from_IUPAC_symbol("OC-6").mp_symbol == cg_oct.mp_symbol with pytest.raises(LookupError) as exc_info: allcg.get_geometry_from_IUPAC_symbol("OC-7") - assert str(exc_info.value) == 'No coordination geometry found with IUPAC symbol "OC-7"' + assert str(exc_info.value) == "No coordination geometry found with IUPAC symbol 'OC-7'" assert allcg.get_geometry_from_IUCr_symbol("[6o]").mp_symbol == cg_oct.mp_symbol with pytest.raises(LookupError) as exc_info: allcg.get_geometry_from_IUCr_symbol("[6oct]") - assert str(exc_info.value) == 'No coordination geometry found with IUCr symbol "[6oct]"' + assert str(exc_info.value) == "No coordination geometry found with IUCr symbol '[6oct]'" with pytest.raises(LookupError) as exc_info: allcg.get_geometry_from_mp_symbol("O:7") - assert str(exc_info.value) == 'No coordination geometry found with mp_symbol "O:7"' + assert str(exc_info.value) == "No coordination geometry found with mp_symbol 'O:7'" assert ( allcg.pretty_print(maxcn=4) diff --git a/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py b/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py index e149c022e75..9c369b58970 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py +++ b/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py @@ -131,7 +131,7 @@ def test_normalized_angle_distance_weight(self): with pytest.raises(ValueError, match="Both exponents are 0."): NormalizedAngleDistanceNbSetWeight(average_type="arithmetic", aa=0, bb=0) with pytest.raises( - ValueError, match='Average type is "arithmetix" ' 'while it should be "geometric" or "arithmetic"' + ValueError, match="Average type is 'arithmetix' while it should be 'geometric' or 'arithmetic'" ): NormalizedAngleDistanceNbSetWeight(average_type="arithmetix", aa=1, bb=1) diff --git a/pymatgen/analysis/chemenv/coordination_environments/voronoi.py b/pymatgen/analysis/chemenv/coordination_environments/voronoi.py index d0f65689652..fc8d050498e 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/voronoi.py +++ b/pymatgen/analysis/chemenv/coordination_environments/voronoi.py @@ -475,7 +475,7 @@ def neighbors_surfaces_bounded(self, isite, surface_calculation_options=None): } else: raise ValueError( - f'Type "{surface_calculation_options["type"]}" for the surface calculation in DetailedVoronoiContainer ' + f'Type {surface_calculation_options["type"]!r} for the surface calculation in DetailedVoronoiContainer ' "is invalid" ) max_dist = surface_calculation_options["distance_bounds"]["upper"] + 0.1 @@ -705,7 +705,7 @@ def voronoi_parameters_bounds_and_limits(self, isite, plot_type, max_dist): dist_limits = [0.0, 1.0] else: raise NotImplementedError( - f"Plotting type \"{plot_type['distance_parameter']}\" for the distance is not implemented" + f"Plotting type {plot_type['distance_parameter']!r} for the distance is not implemented" ) if plot_type["angle_parameter"][0] == "initial_normalized": aa = [0.0] @@ -718,7 +718,7 @@ def voronoi_parameters_bounds_and_limits(self, isite, plot_type, max_dist): angle_bounds = np.array(aa) else: raise NotImplementedError( - f"Plotting type \"{plot_type['angle_parameter']}\" for the angle is not implemented" + f"Plotting type {plot_type['angle_parameter']!r} for the angle is not implemented" ) ang_limits = [0.0, 1.0] return { @@ -854,7 +854,7 @@ def dp_func(dp): for idist, dist in enumerate(mydists): yy += mydcns[idist] * normal_cdf_step(xx, mean=dist, scale=scale) else: - raise ValueError(f"Step function of type \"{step_function['type']}\" is not allowed") + raise ValueError(f"Step function of type {step_function['type']!r} is not allowed") subplot.plot(xx, yy) return fig @@ -913,7 +913,7 @@ def ap_func(ap): for iang, ang in enumerate(myangs): yy += mydcns[iang] * normal_cdf_step(xx, mean=ang, scale=scale) else: - raise ValueError(f"Step function of type \"{step_function['type']}\" is not allowed") + raise ValueError(f"Step function of type {step_function['type']!r} is not allowed") subplot.plot(xx, yy) return fig diff --git a/pymatgen/analysis/chemenv/utils/chemenv_config.py b/pymatgen/analysis/chemenv/utils/chemenv_config.py index 13f56ec6303..9fa05c1f3c9 100644 --- a/pymatgen/analysis/chemenv/utils/chemenv_config.py +++ b/pymatgen/analysis/chemenv/utils/chemenv_config.py @@ -89,7 +89,7 @@ def setup(self): print(" ... wrong key, try again ...") print() if test == "S": - print(f'Configuration has been saved to file "{config_file}"') + print(f"Configuration has been saved to file {config_file!r}") @property def has_materials_project_access(self): @@ -117,7 +117,7 @@ def setup_package_options(self): if len(strategy_class.STRATEGY_OPTIONS) > 0: for option, option_dict in strategy_class.STRATEGY_OPTIONS.items(): while True: - print(f" => Enter value for option '{option}' ( for default = {option_dict['default']})\n") + print(f" => Enter value for option {option!r} ( for default = {option_dict['default']})\n") print(" Valid options are :\n") print(f" {option_dict['type'].allowed_values}") test = input(" Your choice : ") @@ -184,6 +184,6 @@ def auto_load(cls, root_dir=None): return ChemEnvConfig(package_options=config_dict["package_options"]) except OSError: - print(f'Unable to load configuration from file "{config_file}" ...') + print(f"Unable to load configuration from file {config_file!r} ...") print(" ... loading default configuration") return ChemEnvConfig() diff --git a/pymatgen/analysis/chemenv/utils/func_utils.py b/pymatgen/analysis/chemenv/utils/func_utils.py index 2b40fb29fe6..6dcea9c2966 100644 --- a/pymatgen/analysis/chemenv/utils/func_utils.py +++ b/pymatgen/analysis/chemenv/utils/func_utils.py @@ -40,7 +40,7 @@ def __init__(self, function, options_dict=None): :param options_dict: Dictionary containing the parameters for the ratio function. """ if function not in self.ALLOWED_FUNCTIONS: - raise ValueError(f'Function "{function}" is not allowed in RatioFunction of type "{type(self).__name__}"') + raise ValueError(f'Function {function!r} is not allowed in RatioFunction of type "{type(self).__name__}"') self.eval = object.__getattribute__(self, function) self.function = function self.setup_parameters(options_dict=options_dict) @@ -67,26 +67,26 @@ def setup_parameters(self, options_dict): if len(function_options) == 1: opts = f'Option "{function_options[0]}"' else: - opts1 = ", ".join(f'"{op}"' for op in function_options[:-1]) + opts1 = ", ".join(f"{op!r}" for op in function_options[:-1]) opts = f'Options {opts1} and "{function_options[-1]}"' if options_dict is None or len(options_dict) == 0: missing = "no option was provided." else: optgiven = list(options_dict) if len(options_dict) == 1: - missing = f'only "{optgiven[0]}" was provided.' + missing = f"only {optgiven[0]!r} was provided." else: - missing1 = ", ".join(f'"{miss}"' for miss in optgiven[:-1]) - missing = f'only {missing1} and "{optgiven[-1]}" were provided.' + missing1 = ", ".join(f"{miss!r}" for miss in optgiven[:-1]) + missing = f"only {missing1} and {optgiven[-1]!r} were provided." raise ValueError( - f'{opts} should be provided for function "{self.function}" in RatioFunction of ' - f'type "{type(self).__name__}" while {missing}' + f"{opts} should be provided for function {self.function!r} in RatioFunction of " + f"type {type(self).__name__!r} while {missing}" ) # Setup the options and raise an error if a wrong option is provided for key, val in options_dict.items(): if key not in function_options: raise ValueError( - f'Option "{key}" not allowed for function "{self.function}" in RatioFunction of ' + f"Option {key!r} not allowed for function {self.function!r} in RatioFunction of " f'type "{type(self).__name__}"' ) setattr(self, key, val) diff --git a/pymatgen/analysis/eos.py b/pymatgen/analysis/eos.py index bc79b43fd63..0685331dbda 100644 --- a/pymatgen/analysis/eos.py +++ b/pymatgen/analysis/eos.py @@ -598,7 +598,7 @@ def __init__(self, eos_name="murnaghan"): """ if eos_name not in self.MODELS: raise EOSError( - f"The equation of state '{eos_name}' is not supported. " + f"The equation of state {eos_name!r} is not supported. " f"Please choose one from the following list: {list(self.MODELS)}" ) self._eos_name = eos_name diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index c7a22c4a94f..be37ae95e94 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -2008,7 +2008,7 @@ def get_okeeffe_params(el_symbol): if el not in list(BV_PARAMS): raise RuntimeError( "Could not find O'Keeffe parameters for element" - f' "{el_symbol}" in "BV_PARAMS"dictionary' + f' {el_symbol!r} in "BV_PARAMS"dictionary' " provided by pymatgen" ) diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index 085c2a3b281..73c7502a093 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -3369,7 +3369,7 @@ def order_phase_diagram(lines, stable_entries, unstable_entries, ordering): if (nameup not in ordering) or (nameright not in ordering) or (nameleft not in ordering): raise ValueError( "Error in ordering_phase_diagram :\n" - f"'{nameup}', '{nameleft}' and '{nameright}' should be in ordering : {ordering}" + f"{nameup!r}, {nameleft!r} and {nameright!r} should be in ordering : {ordering}" ) cc = np.array([0.5, np.sqrt(3.0) / 6.0], np.float_) diff --git a/pymatgen/electronic_structure/boltztrap.py b/pymatgen/electronic_structure/boltztrap.py index 71df890ce15..5728ae40718 100644 --- a/pymatgen/electronic_structure/boltztrap.py +++ b/pymatgen/electronic_structure/boltztrap.py @@ -429,7 +429,7 @@ def write_proj(self, output_file_proj, output_file_def): for oi, o in enumerate(Orbital): for site_nb in range(0, len(self._bs.structure.sites)): if oi < len(self._bs.projections[Spin.up][0][0]): - f.write(f"{i},'boltztrap.proj_{site_nb}_{o.name}' 'old', 'formatted',0\n") + f.write(f"{i},'boltztrap.proj_{site_nb}_{o.name}old', 'formatted',0\n") i += 1 def write_intrans(self, output_file): diff --git a/pymatgen/electronic_structure/plotter.py b/pymatgen/electronic_structure/plotter.py index dd110cc4bd0..e3f2f60b978 100644 --- a/pymatgen/electronic_structure/plotter.py +++ b/pymatgen/electronic_structure/plotter.py @@ -1800,7 +1800,7 @@ def _Orbitals_SumOrbitals(cls, dictio, sum_morbs): ) if elt not in dictio: raise ValueError( - f"You cannot sum projection over orbitals of atoms '{elt}' because they are not " + f"You cannot sum projection over orbitals of atoms {elt!r} because they are not " "mentioned in 'dictio'." ) else: @@ -1811,7 +1811,7 @@ def _Orbitals_SumOrbitals(cls, dictio, sum_morbs): if len(dictio[elt][0]) > 1: if elt in sum_morbs: raise ValueError( - f"You cannot sum projection over one individual orbital '{dictio[elt][0]}' of '{elt}'." + f"You cannot sum projection over one individual orbital {dictio[elt][0]!r} of {elt!r}." ) else: if sum_morbs is None: @@ -1824,10 +1824,10 @@ def _Orbitals_SumOrbitals(cls, dictio, sum_morbs): if len(sum_morbs[elt]) > 1: for orb in sum_morbs[elt]: if dictio[elt][0] not in orb: - raise ValueError(f"The invalid orbital '{orb}' was put into 'sum_morbs[{elt}]'.") + raise ValueError(f"The invalid orbital {orb!r} was put into 'sum_morbs[{elt}]'.") else: if orb == "s" or len(orb) > 1: - raise ValueError(f"The invalid orbital '{orb}' was put into sum_orbs['{elt}'].") + raise ValueError(f"The invalid orbital {orb!r} was put into sum_orbs[{elt!r}].") sum_morbs[elt] = individual_orbs[dictio[elt][0]] dictio[elt] = individual_orbs[dictio[elt][0]] else: @@ -1896,7 +1896,7 @@ def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs): if isinstance(number, str): if number.lower() == "all": dictpa[elt] = indices - print(f"You want to consider all '{elt}' atoms.") + print(f"You want to consider all {elt!r} atoms.") break raise ValueError(f"You put wrong site numbers in 'dictpa[{elt}]': {number}.") @@ -1917,10 +1917,10 @@ def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs): raise KeyError("The number of keys in 'dictio' and 'dictpa' are not the same.") for elt in dictio: if elt not in dictpa: - raise KeyError(f"The element '{elt}' is not in both dictpa and dictio.") + raise KeyError(f"The element {elt!r} is not in both dictpa and dictio.") for elt in dictpa: if elt not in dictio: - raise KeyError(f"The element '{elt}' in not in both dictpa and dictio.") + raise KeyError(f"The element {elt!r} in not in both dictpa and dictio.") if sum_atoms is None: print("You do not want to sum projection over atoms.") @@ -1943,7 +1943,7 @@ def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs): if isinstance(number, str): if number.lower() == "all": sum_atoms[elt] = indices - print(f"You want to sum projection over all '{elt}' atoms.") + print(f"You want to sum projection over all {elt!r} atoms.") break raise ValueError(f"You put wrong site numbers in 'sum_atoms[{elt}]'.") if isinstance(number, int): @@ -1951,7 +1951,7 @@ def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs): raise ValueError(f"You put wrong site numbers in 'sum_atoms[{elt}]'.") if number not in dictpa[elt]: raise ValueError( - f"You cannot sum projection with atom number '{number}' because it is not " + f"You cannot sum projection with atom number {number!r} because it is not " f"mentioned in dicpta[{elt}]" ) else: @@ -1965,7 +1965,7 @@ def _number_of_subfigures(self, dictio, dictpa, sum_atoms, sum_morbs): ) if elt not in dictpa: raise ValueError( - f"You cannot sum projection over atoms '{elt}' because it is not mentioned in 'dictio'." + f"You cannot sum projection over atoms {elt!r} because it is not mentioned in 'dictio'." ) else: raise KeyError(f"The invalid element was put into 'sum_atoms' as a key: {elt}") diff --git a/pymatgen/ext/optimade.py b/pymatgen/ext/optimade.py index d8af651661f..d08b603f83e 100644 --- a/pymatgen/ext/optimade.py +++ b/pymatgen/ext/optimade.py @@ -174,7 +174,7 @@ def _build_filter( if elements: if isinstance(elements, str): elements = [elements] - elements_str = ", ".join(f'"{el}"' for el in elements) + elements_str = ", ".join(f"{el!r}" for el in elements) filters.append(f"(elements HAS ALL {elements_str})") if nsites: @@ -190,10 +190,10 @@ def _build_filter( filters.append(f"({nelements=})") if chemical_formula_anonymous: - filters.append(f'(chemical_formula_anonymous="{chemical_formula_anonymous}")') + filters.append(f"(chemical_formula_anonymous={chemical_formula_anonymous!r})") if chemical_formula_hill: - filters.append(f'(chemical_formula_hill="{chemical_formula_anonymous}")') + filters.append(f"(chemical_formula_hill={chemical_formula_anonymous!r})") return " AND ".join(filters) diff --git a/pymatgen/io/core.py b/pymatgen/io/core.py index 90b5b06f1b6..33c3875e39c 100644 --- a/pymatgen/io/core.py +++ b/pymatgen/io/core.py @@ -139,7 +139,7 @@ def __getattr__(self, k): # allow accessing keys as attributes if k in self._kwargs: return self.get(k) - raise AttributeError(f"'{type(self).__name__}' object has no attribute '{k}'") + raise AttributeError(f"'{type(self).__name__}' object has no attribute {k!r}") def __len__(self): return len(self.inputs) diff --git a/pymatgen/io/cp2k/utils.py b/pymatgen/io/cp2k/utils.py index 39c8e9d1e90..26fd29548c6 100644 --- a/pymatgen/io/cp2k/utils.py +++ b/pymatgen/io/cp2k/utils.py @@ -39,12 +39,12 @@ def postprocessor(data: str) -> str | int | float | bool | None: try: return int(data) except ValueError as exc: - raise ValueError(f"Error parsing '{data}' as int in CP2K file.") from exc + raise ValueError(f"Error parsing {data!r} as int in CP2K file.") from exc if re.match(r"^[+\-]?(?=.)(?:0|[1-9]\d*)?(?:\.\d*)?(?:\d[eE][+\-]?\d+)?$", data): try: return float(data) except ValueError as exc: - raise ValueError(f"Error parsing '{data}' as float in CP2K file.") from exc + raise ValueError(f"Error parsing {data!r} as float in CP2K file.") from exc if re.match(r"\*+", data): return np.NaN return data diff --git a/pymatgen/io/packmol.py b/pymatgen/io/packmol.py index 1c3a4105c73..c36818c2872 100644 --- a/pymatgen/io/packmol.py +++ b/pymatgen/io/packmol.py @@ -63,7 +63,7 @@ def run(self, path: str | Path, timeout=30): try: os.chdir(path) p = subprocess.run( - f"packmol < '{self.inputfile}'", + f"packmol < {self.inputfile!r}", check=True, shell=True, timeout=timeout, @@ -172,7 +172,7 @@ def get_input_set( # type: ignore if " " in str(self.outputfile): # NOTE - double quotes are deliberately used inside the f-string here, do not change # fmt: off - file_contents += f'output "{self.outputfile}"\n\n' + file_contents += f'output {self.outputfile!r}\n\n' # fmt: on else: file_contents += f"output {self.outputfile}\n\n" @@ -210,7 +210,7 @@ def get_input_set( # type: ignore if " " in str(fname): # NOTE - double quotes are deliberately used inside the f-string here, do not change # fmt: off - file_contents += f'structure "{fname}"\n' + file_contents += f'structure {fname!r}\n' # fmt: on else: file_contents += f"structure {fname}\n" diff --git a/pymatgen/io/pwscf.py b/pymatgen/io/pwscf.py index b1d6f651396..45148553671 100644 --- a/pymatgen/io/pwscf.py +++ b/pymatgen/io/pwscf.py @@ -107,7 +107,7 @@ def __str__(self): def to_str(v): if isinstance(v, str): - return f"'{v}'" + return f"{v!r}" if isinstance(v, float): return f"{str(v).replace('e', 'd')}" if isinstance(v, bool): diff --git a/pymatgen/io/shengbte.py b/pymatgen/io/shengbte.py index 8d1cf384127..4f5ff6b4949 100644 --- a/pymatgen/io/shengbte.py +++ b/pymatgen/io/shengbte.py @@ -181,7 +181,7 @@ def to_file(self, filename: str = "CONTROL"): """ for param in self.required_params: if param not in self.as_dict(): - warnings.warn(f"Required parameter '{param}' not specified!") + warnings.warn(f"Required parameter {param!r} not specified!") alloc_dict = _get_subdict(self, self.allocations_keys) alloc_nml = f90nml.Namelist({"allocations": alloc_dict}) diff --git a/pymatgen/transformations/advanced_transformations.py b/pymatgen/transformations/advanced_transformations.py index 3cb982a80e2..34cfeb1e551 100644 --- a/pymatgen/transformations/advanced_transformations.py +++ b/pymatgen/transformations/advanced_transformations.py @@ -149,12 +149,7 @@ def apply_transformation(self, structure: Structure, return_ranked_list=False): d["transformation"] = t structures.append(d) else: - structures.append( - { - "transformation": t, - "structure": t.apply_transformation(structure), - } - ) + structures.append({"transformation": t, "structure": t.apply_transformation(structure)}) return structures def __str__(self): diff --git a/setup.cfg b/setup.cfg index 02519efb822..bd09b6c1cd5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -14,8 +14,6 @@ exclude = docs_rst/*.py [flake8] exclude = .git,__pycache__,docs_rst/conf.py,tests -# B019: Use of `functools.lru_cache` on methods can lead to memory leaks -# B023: Function definition does not bind loop variable extend-ignore = E741,W291,W293,E501,E231,E203,B019,B023,B028 max-line-length = 120 per-file-ignores = diff --git a/tasks.py b/tasks.py index 75da70a9da8..c7ad676d90a 100644 --- a/tasks.py +++ b/tasks.py @@ -183,14 +183,14 @@ def publish(ctx): def set_ver(ctx, version): with open("pymatgen/core/__init__.py") as f: contents = f.read() - contents = re.sub(r"__version__ = .*\n", f'__version__ = "{version}"\n', contents) + contents = re.sub(r"__version__ = .*\n", f"__version__ = {version!r}\n", contents) with open("pymatgen/core/__init__.py", "wt") as f: f.write(contents) with open("setup.py") as f: contents = f.read() - contents = re.sub(r"version=([^,]+),", f'version="{version}",', contents) + contents = re.sub(r"version=([^,]+),", f"version={version!r},", contents) with open("setup.py", "wt") as f: f.write(contents)