Skip to content

Commit 82a4336

Browse files
authored
IStructure.to default to JSON when filename not specified (#4306)
* default to json * clarify docstring * minor test tweak
1 parent 6b94378 commit 82a4336

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

src/pymatgen/core/structure.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -2918,7 +2918,7 @@ def from_dict(
29182918
return cls.from_sites(sites, charge=charge, properties=dct.get("properties"))
29192919

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

2943+
# Default to JSON if filename not specified
2944+
if filename == "" and fmt == "":
2945+
fmt = "json"
2946+
29432947
if fmt == "cif" or fnmatch(filename.lower(), "*.cif*"):
29442948
from pymatgen.io.cif import CifWriter
29452949

tests/core/test_structure.py

+3
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,9 @@ def test_to_from_file_and_string(self):
930930
with pytest.raises(ValueError, match="Invalid fmt='badformat'"):
931931
self.struct.to(fmt="badformat")
932932

933+
# Default as JSON (no exception expected)
934+
assert self.struct.to() == self.struct.to(fmt="json")
935+
933936
self.struct.to(filename=(gz_json_path := "POSCAR.testing.gz"))
934937
struct = Structure.from_file(gz_json_path)
935938
assert struct == self.struct

0 commit comments

Comments
 (0)