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

Remove redundant total_ordering decorator usage #4203

Merged
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
20 changes: 14 additions & 6 deletions src/pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

if TYPE_CHECKING:
from collections.abc import Generator, Iterator
from typing import Any, ClassVar
from typing import Any, ClassVar, Literal

from typing_extensions import Self

Expand Down Expand Up @@ -774,17 +774,25 @@ def to_reduced_dict(self) -> dict[str, float]:
def to_weight_dict(self) -> dict[str, float]:
"""
Returns:
dict[str, float] with weight fraction of each component {"Ti": 0.90, "V": 0.06, "Al": 0.04}.
dict[str, float]: weight fractions of each component, e.g. {"Ti": 0.90, "V": 0.06, "Al": 0.04}.
"""
return {str(el): self.get_wt_fraction(el) for el in self.elements}

@property
def to_data_dict(self) -> dict[str, Any]:
def to_data_dict(
self,
) -> dict[
Literal["reduced_cell_composition", "unit_cell_composition", "reduced_cell_formula", "elements", "nelements"],
Any,
]:
"""
Returns:
A dict with many keys and values relating to Composition/Formula,
including reduced_cell_composition, unit_cell_composition,
reduced_cell_formula, elements and nelements.
dict with the following keys:
- reduced_cell_composition
- unit_cell_composition
- reduced_cell_formula
- elements
- nelements.
"""
return {
"reduced_cell_composition": self.reduced_composition,
Expand Down
3 changes: 0 additions & 3 deletions src/pymatgen/core/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,6 @@ def print_periodic_table(filter_function: Callable | None = None) -> None:
print(" ".join(row_str))


@functools.total_ordering
class Element(ElementBase):
"""Enum representing an element in the periodic table."""

Expand Down Expand Up @@ -1597,14 +1596,12 @@ def from_dict(cls, dct: dict) -> Self:
return cls(dct["element"], dct["oxidation_state"], spin=dct.get("spin"))


@functools.total_ordering
class Specie(Species):
"""This maps the historical grammatically inaccurate Specie to Species
to maintain backwards compatibility.
"""


@functools.total_ordering
class DummySpecie(DummySpecies):
"""This maps the historical grammatically inaccurate DummySpecie to DummySpecies
to maintain backwards compatibility.
Expand Down
13 changes: 6 additions & 7 deletions src/pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import MutableSequence
from fnmatch import fnmatch
from io import StringIO
from typing import TYPE_CHECKING, Literal, cast, get_args

import numpy as np
Expand Down Expand Up @@ -245,7 +243,7 @@ def sites(self) -> list[PeriodicSite] | tuple[PeriodicSite, ...]:
def sites(self, sites: Sequence[PeriodicSite]) -> None:
"""Set the sites in the Structure."""
# If self is mutable Structure or Molecule, set _sites as list
is_mutable = isinstance(self._sites, MutableSequence)
is_mutable = isinstance(self._sites, collections.abc.MutableSequence)
self._sites: list[PeriodicSite] | tuple[PeriodicSite, ...] = list(sites) if is_mutable else tuple(sites)

@abstractmethod
Expand Down Expand Up @@ -1098,9 +1096,8 @@ def __init__(
self._properties = properties or {}

def __eq__(self, other: object) -> bool:
"""Define equality by comparing all three attributes: lattice, sites, properties."""
needed_attrs = ("lattice", "sites", "properties")

# Return NotImplemented as in https://docs.python.org/3/library/functools.html#functools.total_ordering
Copy link
Contributor Author

@DanielYang59 DanielYang59 Nov 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess total_ordering was applied on IStructure at some point but I believe this comment should be removed now (currently it more servers as an equality definition):

class IStructure(SiteCollection, MSONable):

Also current implementation of IStructure doesn't fulfill the prerequisite of applying total_ordering (only __eq__ is defined):

The class must define one of lt(), le(), gt(), or ge(). In addition, the class should supply an eq() method.

if not all(hasattr(other, attr) for attr in needed_attrs):
return NotImplemented

Expand All @@ -1109,8 +1106,10 @@ def __eq__(self, other: object) -> bool:

if other is self:
return True

if len(self) != len(other):
return False

if self.lattice != other.lattice:
return False
if self.properties != other.properties:
Expand Down Expand Up @@ -2982,7 +2981,7 @@ def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str:
return Prismatic(self).to_str()
elif fmt in ("yaml", "yml") or fnmatch(filename, "*.yaml*") or fnmatch(filename, "*.yml*"):
yaml = YAML()
str_io = StringIO()
str_io = io.StringIO()
yaml.dump(self.as_dict(), str_io)
yaml_str = str_io.getvalue()
if filename:
Expand Down Expand Up @@ -3923,7 +3922,7 @@ def to(self, filename: str = "", fmt: str = "") -> str | None:
return json_str
elif fmt in {"yaml", "yml"} or fnmatch(filename, "*.yaml*") or fnmatch(filename, "*.yml*"):
yaml = YAML()
str_io = StringIO()
str_io = io.StringIO()
yaml.dump(self.as_dict(), str_io)
yaml_str = str_io.getvalue()
if filename:
Expand Down
Loading