-
-
Notifications
You must be signed in to change notification settings - Fork 117
Open
Labels
Description
The link below describes a way to define --food, but there is no way to read food from Settings instead of from parsed_args.
https://docs.pydantic.dev/latest/concepts/pydantic_settings/#cli-shortcuts-for-arguments
import sys
from argparse import ArgumentParser
from pydantic_settings import BaseSettings, CliApp, CliSettingsSource
parser = ArgumentParser()
parser.add_argument('--food', choices=['pear', 'kiwi', 'lime'])
class Settings(BaseSettings):
name: str = 'Bob'
food: str = ''
cli_settings = CliSettingsSource(Settings, root_parser=parser)
sys.argv = ['example.py', '--food', 'kiwi', '--name', 'waldo']
s = CliApp.run(Settings, cli_settings_source=cli_settings)
print(s.model_dump())
# argparse.ArgumentError: argument --food: conflicting option string: --food
# Load CLI settings from pre-parsed arguments. i.e., the parsing occurs elsewhere and we
# just need to load the pre-parsed args into the settings source.
parsed_args = parser.parse_args(['--food', 'kiwi', '--name', 'ralph'])
s = CliApp.run(Settings, cli_args=parsed_args, cli_settings_source=cli_settings)
print(s.model_dump())
# argparse.ArgumentError: argument --food: conflicting option string: --food