Skip to content

Commit 229319c

Browse files
Fix a bug when loading empty yaml file (#330)
Co-authored-by: Sydney Runkle <[email protected]>
1 parent d6db0f9 commit 229319c

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pydantic_settings/sources.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1692,7 +1692,7 @@ def __init__(
16921692
def _read_file(self, file_path: Path) -> dict[str, Any]:
16931693
import_yaml()
16941694
with open(file_path, encoding=self.yaml_file_encoding) as yaml_file:
1695-
return yaml.safe_load(yaml_file)
1695+
return yaml.safe_load(yaml_file) or {}
16961696

16971697

16981698
def _get_env_var_key(key: str, case_sensitive: bool = False) -> str:

tests/test_settings.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3485,6 +3485,29 @@ def settings_customise_sources(
34853485
assert s.model_dump() == {}
34863486

34873487

3488+
@pytest.mark.skipif(yaml is None, reason='pyYaml is not installed')
3489+
def test_yaml_empty_file(tmp_path):
3490+
p = tmp_path / '.env'
3491+
p.write_text('')
3492+
3493+
class Settings(BaseSettings):
3494+
model_config = SettingsConfigDict(yaml_file=p)
3495+
3496+
@classmethod
3497+
def settings_customise_sources(
3498+
cls,
3499+
settings_cls: Type[BaseSettings],
3500+
init_settings: PydanticBaseSettingsSource,
3501+
env_settings: PydanticBaseSettingsSource,
3502+
dotenv_settings: PydanticBaseSettingsSource,
3503+
file_secret_settings: PydanticBaseSettingsSource,
3504+
) -> Tuple[PydanticBaseSettingsSource, ...]:
3505+
return (YamlConfigSettingsSource(settings_cls),)
3506+
3507+
s = Settings()
3508+
assert s.model_dump() == {}
3509+
3510+
34883511
@pytest.mark.skipif(sys.version_info <= (3, 11) and tomli is None, reason='tomli/tomllib is not installed')
34893512
def test_toml_file(tmp_path):
34903513
p = tmp_path / '.env'

0 commit comments

Comments
 (0)