Skip to content

Commit 7e0a404

Browse files
committed
add Traversable support and tests
1 parent f696f53 commit 7e0a404

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

pydantic_settings/sources/base.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,13 @@ def _read_files(self, files: PathType | None, deep_merge: bool = False) -> dict[
200200
files = [files]
201201
vars: dict[str, Any] = {}
202202
for file in files:
203-
file_path = Path(file).expanduser()
203+
if isinstance(file, str):
204+
file_path = Path(file)
205+
else:
206+
file_path = file
207+
if isinstance(file_path, Path):
208+
file_path = file_path.expanduser()
209+
204210
if not file_path.is_file():
205211
continue
206212

tests/test_source_json.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Test pydantic_settings.JsonConfigSettingsSource.
33
"""
44

5+
import importlib.resources
56
import json
67
from pathlib import Path
78

@@ -132,3 +133,33 @@ def settings_customise_sources(
132133

133134
s = Settings()
134135
assert s.model_dump() == {'hello': 'world', 'nested': {'foo': 3, 'bar': 2 if deep_merge else 0}}
136+
137+
138+
def test_traversable_support():
139+
# get Traversable object
140+
tests_package_dir = importlib.resources.files('tests')
141+
json_config_path = tests_package_dir / 'example_test_config.json'
142+
assert json_config_path.is_file()
143+
144+
class Settings(BaseSettings):
145+
foobar: str
146+
147+
model_config = SettingsConfigDict(
148+
# Traversable is not added in annotation, but is supported
149+
json_file=json_config_path,
150+
)
151+
152+
@classmethod
153+
def settings_customise_sources(
154+
cls,
155+
settings_cls: type[BaseSettings],
156+
init_settings: PydanticBaseSettingsSource,
157+
env_settings: PydanticBaseSettingsSource,
158+
dotenv_settings: PydanticBaseSettingsSource,
159+
file_secret_settings: PydanticBaseSettingsSource,
160+
) -> tuple[PydanticBaseSettingsSource, ...]:
161+
return (JsonConfigSettingsSource(settings_cls),)
162+
163+
s = Settings()
164+
# "test" value in file
165+
assert s.foobar == 'test'

0 commit comments

Comments
 (0)