Skip to content

Commit 1bdca30

Browse files
authored
Allow custom .pmgrc.yaml location via new PMG_CONFIG_FILE env var (#3949)
1 parent 5d925fe commit 1bdca30

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/pymatgen/core/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,12 @@
3737
def _load_pmg_settings() -> dict[str, Any]:
3838
settings: dict[str, Any] = {}
3939

40+
# PMG_CONFIG_FILE takes precedence over default settings location
41+
settings_file = os.getenv("PMG_CONFIG_FILE") or SETTINGS_FILE
42+
4043
# Load .pmgrc.yaml file
4144
yaml = YAML()
42-
for file_path in (SETTINGS_FILE, OLD_SETTINGS_FILE):
45+
for file_path in (settings_file, OLD_SETTINGS_FILE):
4346
try:
4447
with open(file_path, encoding="utf-8") as yml_file:
4548
settings = yaml.load(yml_file) or {}

tests/core/test_settings.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,34 @@ def test_load_settings(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
4848
# should return empty dict if file is invalid
4949
settings_file.write_text("---")
5050
assert _load_pmg_settings() == {}
51+
52+
53+
def test_env_var_pmg_config_file(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
54+
custom_config_file = tmp_path / "custom_config.yaml"
55+
custom_config_file.write_text("PMG_CUSTOM_SETTING: custom_value")
56+
57+
with monkeypatch.context() as ctx:
58+
ctx.setenv("PMG_CONFIG_FILE", str(custom_config_file))
59+
settings = _load_pmg_settings()
60+
assert "PMG_CUSTOM_SETTING" in settings
61+
assert settings["PMG_CUSTOM_SETTING"] == "custom_value"
62+
63+
# Test that PMG_CONFIG_FILE takes precedence over the default location
64+
settings_file = tmp_path / ".pmgrc.yaml"
65+
monkeypatch.setattr("pymatgen.core.SETTINGS_FILE", settings_file)
66+
settings_file.write_text("PMG_DEFAULT_SETTING: default_value")
67+
custom_config_file.write_text("PMG_CUSTOM_SETTING: custom_value")
68+
69+
with monkeypatch.context() as ctx:
70+
ctx.setenv("PMG_CONFIG_FILE", str(custom_config_file))
71+
settings = _load_pmg_settings()
72+
assert "PMG_CUSTOM_SETTING" in settings
73+
assert "PMG_DEFAULT_SETTING" not in settings
74+
assert settings["PMG_CUSTOM_SETTING"] == "custom_value"
75+
76+
# Test that env vars still take precedence over the values specified in PMG_CONFIG_FILE
77+
with monkeypatch.context() as ctx:
78+
ctx.setenv("PMG_CONFIG_FILE", str(custom_config_file))
79+
ctx.setenv("PMG_CUSTOM_SETTING", "env_value")
80+
settings = _load_pmg_settings()
81+
assert settings["PMG_CUSTOM_SETTING"] == "env_value"

0 commit comments

Comments
 (0)