Skip to content

Commit

Permalink
Add strict parameter to _parse_formula method and raise ValueError if…
Browse files Browse the repository at this point in the history
… formula str is only numbers and spaces
  • Loading branch information
janosh committed Dec 15, 2023
1 parent 4a94f9c commit d194bf7
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,10 +522,12 @@ def contains_element_type(self, category: str) -> bool:
return any(category[0] in el.block for el in self.elements)
return any(getattr(el, f"is_{category}") for el in self.elements)

def _parse_formula(self, formula: str) -> dict[str, float]:
def _parse_formula(self, formula: str, strict: bool = True) -> dict[str, float]:
"""
Args:
formula (str): A string formula, e.g. Fe2O3, Li3Fe2(PO4)3.
strict (bool): Whether to throw an error if formula string is invalid (e.g. empty).
Defaults to True.
Returns:
Composition with that formula.
Expand All @@ -534,6 +536,9 @@ def _parse_formula(self, formula: str) -> dict[str, float]:
In the case of Metallofullerene formula (e.g. Y3N@C80),
the @ mark will be dropped and passed to parser.
"""
# throw if formula contains special characters or only spaces and/or numbers
if strict and re.match(r"[\s\d]*$", formula):
raise ValueError(f"Invalid {formula=}")
# for Metallofullerene like "Y3N@C80"
formula = formula.replace("@", "")

Expand Down

0 comments on commit d194bf7

Please sign in to comment.