Skip to content

Commit

Permalink
IStructure.to default to JSON when filename not specified (#4306)
Browse files Browse the repository at this point in the history
* default to json

* clarify docstring

* minor test tweak
  • Loading branch information
DanielYang59 authored Mar 3, 2025
1 parent 6b94378 commit 82a4336
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2918,7 +2918,7 @@ def from_dict(
return cls.from_sites(sites, charge=charge, properties=dct.get("properties"))

def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str:
"""Output the structure to a file or string.
"""Output the structure to a string (and to a file when filename is given).
Args:
filename (PathLike): If provided, output will be written to a file. If
Expand All @@ -2940,6 +2940,10 @@ def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str:
"""
filename, fmt = str(filename), cast(FileFormats, fmt.lower())

# Default to JSON if filename not specified
if filename == "" and fmt == "":
fmt = "json"

if fmt == "cif" or fnmatch(filename.lower(), "*.cif*"):
from pymatgen.io.cif import CifWriter

Expand Down
3 changes: 3 additions & 0 deletions tests/core/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,9 @@ def test_to_from_file_and_string(self):
with pytest.raises(ValueError, match="Invalid fmt='badformat'"):
self.struct.to(fmt="badformat")

# Default as JSON (no exception expected)
assert self.struct.to() == self.struct.to(fmt="json")

self.struct.to(filename=(gz_json_path := "POSCAR.testing.gz"))
struct = Structure.from_file(gz_json_path)
assert struct == self.struct
Expand Down

0 comments on commit 82a4336

Please sign in to comment.