From ee04d3e7489101053f5256b1b355b334ca7876fc Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Mon, 1 Jul 2024 17:36:51 +0330 Subject: [PATCH 1/2] Fix a bug when loading empty yaml file --- pydantic_settings/sources.py | 3 ++- tests/test_settings.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/pydantic_settings/sources.py b/pydantic_settings/sources.py index c7c019a4..5f5a6ef3 100644 --- a/pydantic_settings/sources.py +++ b/pydantic_settings/sources.py @@ -1676,7 +1676,8 @@ def __init__( def _read_file(self, file_path: Path) -> dict[str, Any]: import_yaml() with open(file_path, encoding=self.yaml_file_encoding) as yaml_file: - return yaml.safe_load(yaml_file) + yaml_doc = yaml.safe_load(yaml_file) + return yaml_doc if yaml_doc is not None else {} def _get_env_var_key(key: str, case_sensitive: bool = False) -> str: diff --git a/tests/test_settings.py b/tests/test_settings.py index c4809e28..efea04ad 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -3454,6 +3454,29 @@ def settings_customise_sources( assert s.model_dump() == {} +@pytest.mark.skipif(yaml is None, reason='pyYaml is not installed') +def test_yaml_empty_file(tmp_path): + p = tmp_path / '.env' + p.write_text('') + + class Settings(BaseSettings): + model_config = SettingsConfigDict(yaml_file=p) + + @classmethod + def settings_customise_sources( + cls, + settings_cls: Type[BaseSettings], + init_settings: PydanticBaseSettingsSource, + env_settings: PydanticBaseSettingsSource, + dotenv_settings: PydanticBaseSettingsSource, + file_secret_settings: PydanticBaseSettingsSource, + ) -> Tuple[PydanticBaseSettingsSource, ...]: + return (YamlConfigSettingsSource(settings_cls),) + + s = Settings() + assert s.model_dump() == {} + + @pytest.mark.skipif(sys.version_info <= (3, 11) and tomli is None, reason='tomli/tomllib is not installed') def test_toml_file(tmp_path): p = tmp_path / '.env' From b749abd210e4c7413c798f9b40d1e866bae8e02e Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Tue, 2 Jul 2024 16:52:03 +0330 Subject: [PATCH 2/2] Update pydantic_settings/sources.py Co-authored-by: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com> --- pydantic_settings/sources.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pydantic_settings/sources.py b/pydantic_settings/sources.py index 5f5a6ef3..729747d7 100644 --- a/pydantic_settings/sources.py +++ b/pydantic_settings/sources.py @@ -1676,8 +1676,7 @@ def __init__( def _read_file(self, file_path: Path) -> dict[str, Any]: import_yaml() with open(file_path, encoding=self.yaml_file_encoding) as yaml_file: - yaml_doc = yaml.safe_load(yaml_file) - return yaml_doc if yaml_doc is not None else {} + return yaml.safe_load(yaml_file) or {} def _get_env_var_key(key: str, case_sensitive: bool = False) -> str: