3
3
import asyncio
4
4
import inspect
5
5
import threading
6
+ import warnings
6
7
from argparse import Namespace
7
8
from collections .abc import Mapping
8
9
from types import SimpleNamespace
24
25
DotenvType ,
25
26
EnvSettingsSource ,
26
27
InitSettingsSource ,
28
+ JsonConfigSettingsSource ,
27
29
PathType ,
28
30
PydanticBaseSettingsSource ,
29
31
PydanticModel ,
32
+ PyprojectTomlConfigSettingsSource ,
30
33
SecretsSettingsSource ,
34
+ TomlConfigSettingsSource ,
35
+ YamlConfigSettingsSource ,
31
36
get_subcommand ,
32
37
)
33
38
@@ -417,6 +422,8 @@ def _settings_build_values(
417
422
elif cli_parse_args not in (None , False ) and not custom_cli_sources [0 ].env_vars :
418
423
custom_cli_sources [0 ](args = cli_parse_args ) # type: ignore
419
424
425
+ self ._settings_warn_unused_config_keys (sources , self .model_config )
426
+
420
427
if sources :
421
428
state : dict [str , Any ] = {}
422
429
states : dict [str , dict [str , Any ]] = {}
@@ -436,6 +443,37 @@ def _settings_build_values(
436
443
# to an informative error and much better than a confusing error
437
444
return {}
438
445
446
+ @staticmethod
447
+ def _settings_warn_unused_config_keys (sources : tuple [object , ...], model_config : SettingsConfigDict ) -> None :
448
+ """
449
+ Warns if any values in model_config were set but the corresponding settings source has not been initialised.
450
+
451
+ The list alternative sources and their config keys can be found here:
452
+ https://docs.pydantic.dev/latest/concepts/pydantic_settings/#other-settings-source
453
+
454
+ Args:
455
+ sources: The tuple of configured sources
456
+ model_config: The model config to check for unused config keys
457
+ """
458
+
459
+ def warn_if_not_used (source_type : type [PydanticBaseSettingsSource ], keys : tuple [str , ...]) -> None :
460
+ if not any (isinstance (source , source_type ) for source in sources ):
461
+ for key in keys :
462
+ if model_config .get (key ) is not None :
463
+ warnings .warn (
464
+ f'Config key `{ key } ` is set in model_config but will be ignored because no '
465
+ f'{ source_type .__name__ } source is configured. To use this config key, add a '
466
+ f'{ source_type .__name__ } source to the settings sources via the '
467
+ 'settings_customise_sources hook.' ,
468
+ UserWarning ,
469
+ stacklevel = 3 ,
470
+ )
471
+
472
+ warn_if_not_used (JsonConfigSettingsSource , ('json_file' , 'json_file_encoding' ))
473
+ warn_if_not_used (PyprojectTomlConfigSettingsSource , ('pyproject_toml_depth' , 'pyproject_toml_table_header' ))
474
+ warn_if_not_used (TomlConfigSettingsSource , ('toml_file' ,))
475
+ warn_if_not_used (YamlConfigSettingsSource , ('yaml_file' , 'yaml_file_encoding' , 'yaml_config_section' ))
476
+
439
477
model_config : ClassVar [SettingsConfigDict ] = SettingsConfigDict (
440
478
extra = 'forbid' ,
441
479
arbitrary_types_allowed = True ,
0 commit comments