Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernise strings #643

Merged
merged 2 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 18 additions & 19 deletions MDANSE/Src/MDANSE/Chemistry/Databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def __getitem__(self, item: str) -> dict:
return copy.deepcopy(self._data[item])
except KeyError:
raise AtomsDatabaseError(
"The element {} is not registered in the database.".format(item)
f"The element {item} is not registered in the database."
)

def _load(self, user_database: str = None, default_database: str = None) -> None:
Expand Down Expand Up @@ -253,7 +253,7 @@ def add_atom(self, atom: str) -> None:

if atom in self._data:
raise AtomsDatabaseError(
"The atom {} is already stored in the database".format(atom)
f"The atom {atom} is already stored in the database"
)

self._data[atom] = {}
Expand All @@ -272,11 +272,11 @@ def add_property(self, pname: str, ptype: str) -> None:

if pname in self._properties:
raise AtomsDatabaseError(
"The property {} is already registered in the database.".format(pname)
f"The property {pname} is already registered in the database."
)

if ptype not in AtomsDatabase._TYPES:
raise AtomsDatabaseError("The property type {} is unknown".format(ptype))
raise AtomsDatabaseError(f"The property type {ptype} is unknown")

self._properties[pname] = ptype
ptype = AtomsDatabase._TYPES[ptype]
Expand Down Expand Up @@ -307,7 +307,7 @@ def get_isotopes(self, atom: str) -> list[str]:
"""

if atom not in self._data:
raise AtomsDatabaseError("The atom {} is unknown".format(atom))
raise AtomsDatabaseError(f"The atom {atom} is unknown")

# The isotopes are searched according to |symbol| property
symbol = self._data[atom]["symbol"]
Expand Down Expand Up @@ -340,7 +340,7 @@ def get_property(self, pname: str) -> dict[str, Union[str, int, float, list]]:

if pname not in self._properties:
raise AtomsDatabaseError(
"The property {} is not registered in the database".format(pname)
f"The property {pname} is not registered in the database"
)

ptype = AtomsDatabase._TYPES[self._properties[pname]]
Expand All @@ -365,11 +365,11 @@ def get_value(self, atom: str, pname: str) -> Union[str, int, float, list]:
"""

if atom not in self._data:
raise AtomsDatabaseError("The atom {} is unknown".format(atom))
raise AtomsDatabaseError(f"The atom {atom} is unknown")

if pname not in self._properties:
raise AtomsDatabaseError(
"The property {} is not registered in the database".format(pname)
f"The property {pname} is not registered in the database"
)

ptype = self._properties[pname]
Expand Down Expand Up @@ -397,12 +397,12 @@ def get_values_for_multiple_atoms(

if not all(atom in self._data for atom in atoms):
raise AtomsDatabaseError(
"One or more of the provided atoms {} are unknown".format(atoms)
f"One or more of the provided atoms {atoms} are unknown"
)

if prop not in self._properties:
raise AtomsDatabaseError(
"The property {} is not registered in the database".format(prop)
f"The property {prop} is not registered in the database"
)

values = {name: self._data[name][prop] for name in unique_atoms}
Expand All @@ -425,11 +425,11 @@ def set_value(
"""

if atom not in self._data:
raise AtomsDatabaseError("The element {} is unknown".format(atom))
raise AtomsDatabaseError(f"The element {atom} is unknown")

if pname not in self._properties:
raise AtomsDatabaseError(
"The property {} is not registered in the database".format(pname)
f"The property {pname} is not registered in the database"
)

try:
Expand All @@ -438,7 +438,7 @@ def set_value(
)
except ValueError:
raise AtomsDatabaseError(
"Can not coerce {} to {} type".format(value, self._properties[pname])
f"Can not coerce {value} to {self._properties[pname]} type"
)

def has_atom(self, atom: str) -> bool:
Expand Down Expand Up @@ -480,19 +480,18 @@ def info(self, atom: str) -> str:

# A delimiter line.
delimiter = "-" * 70
tab_fmt = " {:<20}{!s:>50}"

info = [
delimiter,
"%s" % atom.center(70),
"%s" % " {0:<20}{1:>50}".format("property", "value"),
f"{atom:^70}",
tab_fmt.format("property", "value"),
delimiter,
]

# The values for all element's properties
for pname in sorted(self._properties):
info.append(
" {0:<20}{1:>50}".format(pname, str(self._data[atom].get(pname, None)))
)
info.append(tab_fmt.format(pname, self._data[atom].get(pname, None)))

info.append(delimiter)
info = "\n".join(info)
Expand Down Expand Up @@ -525,7 +524,7 @@ def match_numeric_property(
)
except KeyError:
raise AtomsDatabaseError(
"The property {} is not registered in the database".format(pname)
f"The property {pname} is not registered in the database"
)

tolerance = abs(tolerance)
Expand Down
66 changes: 19 additions & 47 deletions MDANSE/Src/MDANSE/Framework/Configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ class ConfigurationError(Error):
class Configurable(object):
"""
This class allows any object that derives from it to be configurable within the MDANSE framework.

Within that framework, to be configurable, a class must:
#. derive from this class
#. implement the "configurators" class attribute as a list of 3-tuple whose:
#.. 0-value is the type of the configurator that will be used to fetch the corresponding \
MDANSE.Framework.Configurators.IConfigurator.IConfigurator derived class from the configurators registry
#.. 1-value is the name of the configurator that will be used as the key of the _configuration attribute.
#.. 2-value is the dictionary of the keywords used when initializing the configurator.
#.. 2-value is the dictionary of the keywords used when initializing the configurator.
"""

enabled = True
Expand Down Expand Up @@ -94,7 +94,7 @@ def build_configuration(self):
)
# Any kind of error has to be caught
except:
raise ConfigurationError("Could not set %r configuration item" % name)
raise ConfigurationError(f"Could not set {name!r} configuration item")

def set_settings(self, settings):
self.settings = settings
Expand Down Expand Up @@ -228,10 +228,10 @@ def build_doc_example(cls):
docstring += ">>> \n"
docstring += ">>> \n"
docstring += ">>> parameters = {}\n"
for k, v in list(cls.get_default_parameters().items()):
docstring += ">>> parameters[%r]=%r\n" % (k, v)
for k, v in cls.get_default_parameters().items():
docstring += f">>> parameters[{k!r}]={v!r}\n"
docstring += ">>> \n"
docstring += ">>> job = IJob.create(%r)\n" % cls.__name__
docstring += f">>> job = IJob.create({cls.__name__!r})\n"
docstring += ">>> job.setup(parameters)\n"
docstring += ">>> job.run()\n"
return docstring
Expand All @@ -249,53 +249,25 @@ def build_doc_texttable(cls, doclist):
sizes[1] = max(sizes[1], len(v["Default value"]))
# Case of Description field: has to be splitted and parsed for inserting sphinx "|" keyword for multiline
v["Description"] = v["Description"].strip()
v["Description"] = v["Description"].split("\n")
v["Description"] = v["Description"].splitlines()
v["Description"] = ["| " + vv.strip() for vv in v["Description"]]
sizes[2] = max(sizes[2], max([len(d) for d in v["Description"]]))

docstring += "+%s+%s+%s+\n" % (
"-" * (sizes[0] + 1),
"-" * (sizes[1] + 1),
"-" * (sizes[2] + 1),
)
docstring += "| %-*s| %-*s| %-*s|\n" % (
sizes[0],
columns[0],
sizes[1],
columns[1],
sizes[2],
columns[2],
)
docstring += "+%s+%s+%s+\n" % (
"=" * (sizes[0] + 1),
"=" * (sizes[1] + 1),
"=" * (sizes[2] + 1),
)
sizes[2] = max(sizes[2], max(map(len, v["Description"])))

data_line = "| " + "| ".join(f"{{}}:<{size}" for size in sizes) + "|\n"
sep_line = "+" + "+".join("-" * (size + 1) for size in sizes) + "+\n"

docstring += sep_line
docstring += data_line.format(*columns)
docstring += sep_line.replace("-", "=")

for v in doclist:
docstring += "| %-*s| %-*s| %-*s|\n" % (
sizes[0],
v["Configurator"],
sizes[1],
v["Default value"],
sizes[2],
v["Description"][0],
docstring += data_line.format(
v["Configurator"], v["Default value"], v["Description"][0]
)
if len(v["Description"]) > 1:
for descr in v["Description"][1:]:
docstring += "| %-*s| %-*s| %-*s|\n" % (
sizes[0],
"",
sizes[1],
"",
sizes[2],
descr,
)
docstring += "+%s+%s+%s+\n" % (
"-" * (sizes[0] + 1),
"-" * (sizes[1] + 1),
"-" * (sizes[2] + 1),
)
data_line.format("", "", descr)
docstring += sep_line

docstring += "\n"
return docstring
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,4 @@ def get_information(self):
LOG.error(result)
return result
else:
return "Input file: %r\n" % self["value"]
return f"Input file: {self['value']!r}\n"
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ def get_information(self) -> str:
return "Not configured yet\n"

info = []
info.append("Number of selected atoms:%d" % self["selection_length"])
info.append("Selected elements:%s" % self["unique_names"])
info.append(f"Number of selected atoms:{self['selection_length']:d}")
info.append(f"Selected elements:{self['unique_names']}")

return "\n".join(info) + "\n"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def get_information(self) -> str:
if self["value"] is None:
return "No atoms selected for transmutation\n"

return "Number of transmuted atoms:%d\n" % self._nTransmutedAtoms
return f"Number of transmuted atoms:{self._nTransmutedAtoms:d}\n"

def get_transmuter(self) -> AtomTransmuter:
"""
Expand Down
16 changes: 5 additions & 11 deletions MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ def configure(self, value):
traj_configurator = self._configurable[self._dependencies["trajectory"]]

if UD_STORE.has_definition(
traj_configurator["basename"], "%d_atoms_list" % self._nAtoms, value
traj_configurator["basename"], f"{self._nAtoms:d}_atoms_list", value
):
molecule, atoms = UD_STORE.get_definition(
traj_configurator["basename"], "%d_atoms_list" % self._nAtoms, value
traj_configurator["basename"], f"{self._nAtoms:d}_atoms_list", value
)
elif UD_STORE.has_definition(
traj_configurator["basename"], "AtomsListConfigurator", value
Expand All @@ -78,11 +78,8 @@ def configure(self, value):
natoms = tempdict["natoms"]
if not natoms == self._nAtoms:
raise ValueError(
"The atom list must have "
+ str(self._nAtoms)
+ " atoms per molecule, but "
+ str(natoms)
+ " were found."
f"The atom list must have {self._nAtoms} "
f"atoms per molecule, but {natoms} were found."
)
atoms = tempdict["indices"]
self["value"] = value
Expand Down Expand Up @@ -111,9 +108,6 @@ def get_information(self):
if "atoms" not in self:
return "No configured yet"

info = []
info.append(
"Number of selected %d-tuplets:%d" % (self._nAtoms, self["n_values"])
)
info = [f"Number of selected {self._nAtoms:d}-tuplets:{self['n_values']:d}"]

return "\n".join(info) + "\n"
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ class AxisSelectionConfigurator(IConfigurator):

def configure(self, value):
"""
Configure an input value.
Configure an input value.

The value can be:

#. a dict with *'molecule'*, *'endpoint1'* and *'endpoint2'* keys. *'molecule'* key \
is the name of the molecule for which the axis selection will be performed and *'endpoint1'* \
and *'endpoint2'* keys are the names of two atoms of the molecule along which the axis will be defined
and *'endpoint2'* keys are the names of two atoms of the molecule along which the axis will be defined
#. str: the axis selection will be performed by reading the corresponding user definition.

:param configuration: the current configuration
:type configuration: MDANSE.Framework.Configurable.Configurable
:param value: the input value
:type value: tuple or str
:type value: tuple or str
"""
self._original_input = value

Expand Down Expand Up @@ -88,4 +88,4 @@ def get_information(self):
if "value" not in self:
return "Not configured yet\n"

return "Axis vector:%s\n" % self["value"]
return f"Axis vector:{self['value']}\n"
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ class BasisSelectionConfigurator(IConfigurator):

def configure(self, value):
"""
Configure an input value.
Configure an input value.

The value can be:

#. a dict with *'molecule'*, *'origin'*, *'x_axis'* and *'y_axis'* keys. *'molecule'* key is \
the name of the molecule for which the axis selection will be performed and *'origin'*, *'x_axis'* and *'y_axis'* \
keys are the names of three atoms of the molecule that will be used to define respectively the origin, the X and Y axis of the basis
keys are the names of three atoms of the molecule that will be used to define respectively the origin, the X and Y axis of the basis
#. str: the axis selection will be performed by reading the corresponding user definition.

:param value: the input value
:type value: tuple or str
:type value: tuple or str

:note: this configurator depends on 'trajectory' configurator to be configured
"""
Expand Down Expand Up @@ -85,4 +85,4 @@ def get_information(self):
if "value" not in self:
return "Not configured yet\n"

return "Basis vector:%s\n" % self["value"]
return f"Basis vector:{self['value']}\n"
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@ def get_information(self):
if "value" not in self:
return "Not configured yet\n"

return "Value: %r\n" % self["value"]
return f"Value: {self['value']!r}\n"
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,4 @@ def get_information(self):
if "value" not in self:
return "Not configured yet\n"

return "Value: %r\n" % self["value"]
return f"Value: {self['value']!r}\n"
Loading