### Install simple-toml-settings Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Commands to install the library using common Python package managers. ```bash # Using uv (recommended) uv add simple-toml-settings # Using poetry poetry add simple-toml-settings # Using pip pip install simple-toml-settings ``` -------------------------------- ### Install simple-toml-settings using uv, Poetry, or pip Source: https://github.com/seapagan/simple-toml-settings/blob/main/README.md Instructions for installing the simple-toml-settings Python package. It recommends using a virtual environment and provides commands for uv, Poetry, and pip. ```console $ uv add simple-toml-settings ``` ```console $ poetry add simple-toml-settings ``` ```console $ pip install simple-toml-settings ``` -------------------------------- ### Example TOML Configuration File Structure Source: https://github.com/seapagan/simple-toml-settings/blob/main/README.md Illustrates the expected structure and content of a TOML configuration file generated by the simple-toml-settings library based on the MySettings class example. ```toml [test_app] age = 42 favourite_colour = "blue" favourite_number = 42 name = "My Name" schema_version = "none" favourite_foods = ["pizza", "chocolate", "ice cream"] ``` -------------------------------- ### Python: Get Setting with Default Value Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Provides an example of using the `get` method with a default value parameter to retrieve a setting, returning the default if the key does not exist. ```python # Returns None if "missing_key" doesn't exist value = settings.get("missing_key") ``` -------------------------------- ### Retrieve Settings with get() Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Retrieve configuration values by key, with support for default values and strict mode for missing keys. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): username: str = "admin" port: int = 8080 settings = MySettings("my_app") # Get existing setting username = settings.get("username") # Get with default for missing key theme = settings.get("theme", default="dark") # With strict_get=True, missing keys raise KeyError strict_settings = MySettings("strict_app", strict_get=True) try: strict_settings.get("nonexistent") except KeyError as e: print(f"Error: {e}") ``` -------------------------------- ### Python: Get, Set, and Delete Settings Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Shows alternative methods for interacting with settings in Python using `get`, `set`, and `delete` functions. The `get` method supports a default value. ```python settings = MySettings("my_app_name") name = settings.get("name") settings.set("name", "My New Name") settings.delete("old_setting") ``` -------------------------------- ### Define and Initialize TOMLSettings Class in Python Source: https://github.com/seapagan/simple-toml-settings/blob/main/README.md Example of defining a custom settings class by inheriting from TOMLSettings. It shows how to declare settings with type hints and default values, and how to initialize the settings object, which automatically handles file creation and loading. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): """My settings class.""" # Define the settings you want to save name: str = "My Name" age: int = 42 favourite_colour: str = "blue" favourite_number: int = 42 favourite_foods: list = ["pizza", "chocolate", "ice cream"] settings = MySettings("test_app") ``` -------------------------------- ### GET /settings/get Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Retrieves a setting value by key, with support for default values and strict mode. ```APIDOC ## GET /settings/get ### Description Retrieves a value from the settings. If the key is missing, it returns the provided default value or raises a KeyError if strict_get is enabled. ### Method GET ### Endpoint settings.get(key, default=None) ### Parameters #### Query Parameters - **key** (string) - Required - The setting key to retrieve. - **default** (any) - Optional - The value to return if the key is missing. ### Request Example settings.get("missing_key", default="my_default") ### Response #### Success Response (200) - **value** (any) - The value associated with the key or the default value. ``` -------------------------------- ### Python: Customize Settings File Name Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Example of creating a settings object in Python, specifying a custom filename for the TOML configuration file using the `settings_file_name` parameter. ```python settings = MySettings("my_app_name", settings_file_name="my_settings.toml") ``` -------------------------------- ### Get Setting with Default Value Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Retrieves a setting value from the TOML configuration. If the specified key does not exist, it returns the provided default value. This is useful for handling optional configuration parameters. ```python value = settings.get("missing_key", default="my_default") ``` -------------------------------- ### Initialization and Configuration Source: https://context7.com/seapagan/simple-toml-settings/llms.txt How to initialize settings with default values and handle missing configuration files. ```APIDOC ## Initialization: TOMLSettings ### Description Initializes the settings manager. If allow_missing_file is set to True, the application will run using default values defined in the class if the configuration file is not found. ### Method Constructor (Class Instantiation) ### Parameters #### Path Parameters - **app_name** (str) - Required - The name of the application used to determine the configuration file path. #### Query Parameters - **allow_missing_file** (bool) - Optional - If True, allows the application to start without a config file. ### Request Example settings = MySettings("my_app", allow_missing_file=True) ### Response #### Success Response (200) - **settings** (object) - An instance of the settings class with loaded or default values. ``` -------------------------------- ### Initialize Settings with Defaults Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Demonstrates how to initialize settings for an application. If a configuration file does not exist, it uses default values defined in the class. The configuration directory is created if it doesn't exist, and the user can later create a config file to override defaults. ```Python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): theme: str = "system" language: str = "en" auto_update: bool = True # Allow running without config file settings = MySettings("my_app", allow_missing_file=True) # Uses defaults if no config exists print(settings.theme) # Output: system # User can later create config to override defaults # Settings folder is still created for future use settings.set("theme", "dark") # Creates config file on first save ``` -------------------------------- ### Define and Initialize Settings Class Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/index.md Demonstrates how to define a settings class by inheriting from TOMLSettings and initializing it with an application name. This automatically creates the configuration file and loads or saves default values. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): """My settings class.""" name: str = "My Name" age: int = 42 favourite_colour: str = "blue" favourite_number: int = 42 favourite_foods: list = ["pizza", "chocolate", "ice cream"] settings = MySettings("test_app") ``` -------------------------------- ### Instantiate Settings Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Initialize the settings class by providing an application name. This creates the necessary file structure for storing the TOML data. ```python settings = MySettings("my_app_name") ``` -------------------------------- ### Load Existing Config or Initialize New Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Shows the basic initialization of settings. On subsequent runs, it loads the existing configuration without prompting the user, ensuring persistence of settings. ```Python settings = MySettings("my_app") print(f"Welcome, {settings.username}!") ``` -------------------------------- ### Initialization and Configuration Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Methods for initializing the settings object, including custom file paths, section headers, and schema versioning. ```APIDOC ## Initialization ### Description Initializes the settings manager, which automatically creates a configuration directory and file in the user's home directory. ### Parameters - **app_name** (string) - Required - The name of the application, used to create the config directory. - **use_section_header** (boolean) - Optional - If False, the TOML file will be flat-rooted without a top-level section header. - **schema_version** (string) - Optional - Version string for schema validation. Defaults to 'none'. - **settings_file_name** (string) - Optional - Custom filename for the TOML config. Defaults to 'config.toml'. ### Request Example ```python settings = MySettings("my_app_name", use_section_header=False, schema_version="1.0.0") ``` ``` -------------------------------- ### Define and Instantiate Settings Class Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Create a configuration schema by subclassing TOMLSettings with typed attributes. The library automatically handles file creation and persistence. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): """Application settings with typed defaults.""" name: str = "Default User" age: int = 25 debug_mode: bool = False api_key: str = "" max_retries: int = 3 allowed_hosts: list = ["localhost", "127.0.0.1"] database: dict = { "host": "localhost", "port": 5432, "name": "myapp_db" } # Instantiate - automatically creates ~/.my_app/config.toml settings = MySettings("my_app") ``` -------------------------------- ### Python: Create Settings Object with Flat TOML Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Demonstrates how to instantiate a settings object in Python, opting for a flat TOML file structure without a top-level section header by setting `use_section_header=False`. ```python settings = MySettings("my_app_name", use_section_header=False) ``` -------------------------------- ### Use post-create initialization hooks Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Overrides the __post_create_hook__ method to execute custom logic, such as prompting for user input, immediately after a new configuration file is generated. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): username: str = "" api_key: str = "" initialized: bool = False def __post_create_hook__(self) -> None: """Called automatically when config file is first created.""" self.username = input("Enter your username: ") self.api_key = input("Enter your API key: ") self.initialized = True ``` -------------------------------- ### Implement schema versioning Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Demonstrates how to track schema versions to detect configuration file incompatibilities and trigger migration logic when versions mismatch. ```python from simple_toml_settings import TOMLSettings from simple_toml_settings.exceptions import SettingsSchemaError class MySettings(TOMLSettings): name: str = "default" email: str = "" # Create settings with schema version settings = MySettings("my_app", schema_version="2.0") # If config file has different schema_version, SettingsSchemaError is raised try: settings = MySettings("my_app", schema_version="2.0") except SettingsSchemaError as e: print(f"Migration needed: {e}") ``` -------------------------------- ### List all configuration settings Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Retrieves all current configuration key-value pairs as a dictionary. This is useful for inspection or iteration over the settings object. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): name: str = "MyApp" version: str = "1.0.0" debug: bool = False max_connections: int = 100 settings = MySettings("my_app") # Get all settings as dictionary all_settings = settings.list_settings() print(all_settings) # Iterate over settings for key, value in settings.list_settings().items(): print(f"{key}: {value}") ``` -------------------------------- ### Implement Singleton Pattern with get_instance Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Use the get_instance method to share a single settings instance across an application, ensuring consistent state. ```python from simple_toml_settings import TOMLSettings class AppSettings(TOMLSettings): api_endpoint: str = "https://api.example.com" timeout: int = 30 verbose: bool = False # First call creates the instance settings1 = AppSettings.get_instance("my_app") settings1.verbose = True # Subsequent calls return the same instance settings2 = AppSettings.get_instance("my_app") print(settings2.verbose) # Output: True # Best practice: create a getter function def get_settings() -> AppSettings: return AppSettings.get_instance("my_app") ``` -------------------------------- ### Handle Configuration Errors with Exceptions Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Illustrates how to handle potential configuration errors using specific exception types provided by the library. This includes handling missing configuration files, schema version mismatches, and invalid option combinations. ```Python from simple_toml_settings import TOMLSettings from simple_toml_settings.exceptions import ( SettingsNotFoundError, SettingsSchemaError, SettingsMutuallyExclusiveError, ) class MySettings(TOMLSettings): value: str = "default" # SettingsNotFoundError: Config file missing with auto_create=False try: settings = MySettings("my_app", auto_create=False) except SettingsNotFoundError as e: print(f"Config not found: {e}") # Create default config or prompt user # SettingsSchemaError: Schema version mismatch try: settings = MySettings("my_app", schema_version="2.0") except SettingsSchemaError as e: print(f"Schema mismatch - expected: {e.expected}, found: {e.found}") # Handle migration # SettingsMutuallyExclusiveError: Conflicting location options try: settings = MySettings("my_app", local_file=True, flat_config=True) except SettingsMutuallyExclusiveError as e: print(f"Invalid options: {e}") ``` -------------------------------- ### Enable XDG Config Directory - Python Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Shows how to enable the XDG configuration directory for storing settings files. When `xdg_config=True`, settings are placed in a sub-folder of the XDG config directory (e.g., `~/.config/my_app_name/config.toml`), adhering to the XDG specification. ```python settings = MySettings("my_app_name", xdg_config=True) ``` -------------------------------- ### Load, Set, and Save Settings Manually Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Demonstrates the manual loading and saving of settings. While `load()` is typically called automatically on initialization and `save()` on `set()`, this shows explicit control. Note that manual `load()` is generally not needed. ```python settings = MySettings("my_app_name") settings.load() settings.set("name", "My New Name") settings.save() ``` -------------------------------- ### Specify Custom Settings Path - Python Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Illustrates how to specify a custom directory and file name for storing settings using `settings_path` and `settings_file_name`. The directory is created automatically if it doesn't exist, and relative paths are supported. ```python settings = MySettings( "my_app_name", settings_path="~/custom-configs", settings_file_name="my_settings.toml", ) ``` -------------------------------- ### Python: Access and Modify Settings Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Demonstrates basic usage of the settings object in Python, showing how to access settings by attribute and modify them. ```python settings = MySettings("my_app_name") name = settings.name settings.name = "My New Name" ``` -------------------------------- ### Configure storage locations for settings Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Explains how to define where the TOML file is stored, including XDG compliance, local directories, or custom paths. It also demonstrates how to disable section headers. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): setting1: str = "value1" # Default: ~/.my_app/config.toml settings = MySettings("my_app") # Local file: ./config.toml local_settings = MySettings("my_app", local_file=True) # Flat config: ~/config.toml flat_settings = MySettings("my_app", flat_config=True) # XDG compliant: ~/.config/my_app/config.toml xdg_settings = MySettings("my_app", xdg_config=True) # Custom path custom_settings = MySettings( "my_app", settings_path="~/custom-configs", settings_file_name="my_settings.toml" ) # Flat TOML structure (no [app_name] section header) flat_toml = MySettings("my_app", use_section_header=False) ``` -------------------------------- ### Python: Set Custom Schema Version Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Illustrates how to initialize a settings object in Python with a specific schema version string, which is used for configuration file validation. ```python settings = MySettings("my_app_name", schema_version="1.0.0") ``` -------------------------------- ### Post-create Hook Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md The __post_create_hook__ method allows for custom logic execution immediately after a new configuration file is generated. ```APIDOC ## __post_create_hook__ ### Description An overrideable method called automatically after a new config file is created. It is not called when loading an existing file. ### Usage Override this method in your class inheriting from `TOMLSettings` to perform user input or data population. ### Example ```python class MySettings(TOMLSettings): def __post_create_hook__(self): self.name = input("Enter your name: ") ``` ``` -------------------------------- ### Access Singleton Settings Instance Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Use the get_instance method to retrieve a singleton instance of the settings class. This ensures consistent configuration access across multiple modules in an application. ```python settings = MySettings.get_instance("my_app_name") def get_settings(): return MySettings.get_instance("my_app_name") ``` -------------------------------- ### TOMLSettings Configuration Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Configuration options for initializing the TOMLSettings class, including path management and file structure control. ```APIDOC ## Configuration Parameters ### Description Configures how the settings file is stored and structured on disk. ### Parameters #### Constructor Parameters - **use_section_header** (bool) - Optional - If True, wraps settings in a [app_name] table. Defaults to True. - **xdg_config** (bool) - Optional - If True, stores settings in the XDG config directory (~/.config/app_name). Defaults to False. - **settings_path** (str) - Optional - Specifies a custom directory path for the settings file. ### Note - The options `local_file`, `flat_config`, `xdg_config`, and `settings_path` are mutually exclusive. Raising `SettingsMutuallyExclusiveError` if more than one is provided. ### Example ```python settings = MySettings("my_app_name", xdg_config=True) ``` ``` -------------------------------- ### Distinguish Missing Keys from None Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Explains how to differentiate between a configuration key that is missing entirely and a key that has been explicitly set to `None`. This can be achieved using a custom default sentinel value or by enabling strict mode during initialization. ```python # Using a custom default sentinel settings.get("key", default=_MY_SENTINEL) # Enabling strict mode TOMLSettings("app", strict_get=True) ``` -------------------------------- ### POST /settings/set Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Sets a new value for a specific key and automatically persists the change to the TOML file. ```APIDOC ## POST /settings/set ### Description Updates a setting value and triggers an automatic save to the underlying configuration file. ### Method POST ### Endpoint settings.set(key, value) ### Parameters #### Request Body - **key** (string) - Required - The setting key to update. - **value** (any) - Required - The new value to assign. ### Request Example settings.set("name", "My New Name") ### Response #### Success Response (200) - **status** (string) - Confirmation that the value was set and saved. ``` -------------------------------- ### Update and Save Settings Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/index.md Illustrates how to modify settings attributes on the class instance and persist the changes to the underlying TOML file using the save method. ```python settings = MySettings("test_app") settings.favourite_colour = "red" settings.save() ``` -------------------------------- ### Define Settings Class Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Create a custom settings class by inheriting from TOMLSettings. Use type-hinted class attributes to define the configuration schema, which allows for automatic type conversion during loading. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): """My settings class.""" name: str = "My Name" age: int = 53 favourite_colour: str = "blue" favourite_number: int = 42 favourite_foods: list = ["pizza", "chocolate", "ice cream"] sub_settings: dict = { "sub_setting_1": "sub setting 1 text", "sub_setting_2": "sub setting 2 text", } ``` -------------------------------- ### Manual file operations for settings Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Shows how to explicitly trigger file saving and reloading. This is essential when modifying settings via direct attribute access rather than library methods. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): counter: int = 0 last_run: str = "" settings = MySettings("my_app") # Modify settings via attribute access settings.counter = 42 settings.last_run = "2024-01-15" # Manually save changes settings.save() # Reload settings from file settings.load() print(settings.counter) ``` -------------------------------- ### Exception Handling Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Handling common configuration errors such as missing files, schema mismatches, and conflicting options. ```APIDOC ## Exception Handling ### Description Provides specific exception types to handle configuration lifecycle errors. ### Exceptions - **SettingsNotFoundError**: Raised when the config file is missing and auto_create is False. - **SettingsSchemaError**: Raised when there is a mismatch between the expected schema version and the file version. - **SettingsMutuallyExclusiveError**: Raised when conflicting configuration options (e.g., local_file and flat_config) are provided. ### Example try: settings = MySettings("my_app", auto_create=False) except SettingsNotFoundError as e: print(f"Config not found: {e}") ``` -------------------------------- ### Delete settings with simple-toml-settings Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Demonstrates how to remove specific keys from a TOML configuration. It covers both auto-saving and manual saving workflows, as well as error handling for missing keys or protected attributes. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): old_feature: str = "enabled" new_feature: str = "beta" temp_value: int = 100 settings = MySettings("my_app") # Delete a setting (auto-saves) settings.delete("old_feature") # Delete without auto-save settings.delete("temp_value", autosave=False) settings.save() # Attempting to delete non-existent key raises KeyError try: settings.delete("nonexistent_key") except KeyError as e: print(f"Error: {e}") # Protected attributes cannot be deleted try: settings.delete("app_name") except ValueError as e: print(f"Error: {e}") ``` -------------------------------- ### Update Settings with set() Source: https://context7.com/seapagan/simple-toml-settings/llms.txt Update configuration values programmatically. Supports automatic saving to disk or manual batch updates. ```python from simple_toml_settings import TOMLSettings class MySettings(TOMLSettings): theme: str = "light" font_size: int = 12 notifications: bool = True settings = MySettings("my_app") # Set a value (auto-saves to file) settings.set("theme", "dark") # Set without auto-save for batch updates settings.set("notifications", False, autosave=False) settings.save() # Manually save once after batch updates ``` -------------------------------- ### TOML Default Settings Structure Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Illustrates the default structure of a TOML configuration file generated by the library, including nested tables and arrays. ```toml [my_app_name] age = 53 favourite_colour = "blue" favourite_number = 42 name = "My Name" schema_version = "none" favourite_foods = ["pizza", "chocolate", "ice cream"] [my_app_name.sub_settings] sub_setting_1 = "sub setting 1 text" sub_setting_2 = "sub setting 2 text" ``` -------------------------------- ### Set and Save Setting Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Sets a new value for a configuration key and automatically saves the change to the TOML file. This method ensures that the updated configuration is persisted. ```python settings = MySettings("my_app_name") settings.name = "My New Name" settings.save() ``` -------------------------------- ### TOML Flat Settings Structure Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Shows the TOML file structure when `use_section_header=False` is used, resulting in a flat file without a main application section header. ```toml age = 53 favourite_colour = "blue" favourite_number = 42 name = "My Name" schema_version = "none" favourite_foods = ["pizza", "chocolate", "ice cream"] [sub_settings] sub_setting_1 = "sub setting 1 text" sub_setting_2 = "sub setting 2 text" ``` -------------------------------- ### Configure Flat TOML File Structure Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/index.md Shows how to disable the default section header in the TOML file by setting the use_section_header parameter to False during initialization. ```python settings = MySettings("test_app", use_section_header=False) ``` -------------------------------- ### Settings Data Access Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Methods for retrieving, updating, and deleting configuration settings. ```APIDOC ## Data Access Methods ### Description Methods to interact with the settings data stored in the TOML file. ### Methods - **get(key, default=None)**: Retrieves a setting value. Returns the default if the key is missing. - **set(key, value)**: Updates or adds a setting value. - **delete(key)**: Removes a setting from the configuration. ### Usage Example ```python # Retrieve a value name = settings.get("name", default="Guest") # Update a value settings.set("name", "New Name") # Delete a value settings.delete("old_setting") ``` ``` -------------------------------- ### DELETE /settings/delete Source: https://github.com/seapagan/simple-toml-settings/blob/main/docs/usage.md Removes a setting from the configuration. ```APIDOC ## DELETE /settings/delete ### Description Deletes a key from the settings object. Raises a KeyError if the key does not exist or a ValueError if the attribute is protected. ### Method DELETE ### Endpoint settings.delete(key) ### Parameters #### Path Parameters - **key** (string) - Required - The key to remove. ### Response #### Success Response (200) - **status** (string) - Confirmation of deletion. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.