### Install Project Dependencies with Poetry Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Installs all project dependencies using poetry, the specified dependency management tool for this repository. Ensure poetry is installed before running this command. ```shell poetry install ``` -------------------------------- ### Build and Publish Package with Poetry Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Builds the project package and publishes it to PyPI. This command is typically handled by a GitHub action but can be run manually. Requires poetry to be installed. ```shell poetry publish --build ``` -------------------------------- ### Install ConfZ using pip Source: https://github.com/zuehlke/confz/blob/main/docs/source/index.rst This command installs the ConfZ library and its dependencies using pip, the Python package installer. It requires Python version 3.8 or higher. ```console pip install confz ``` -------------------------------- ### Instantiate Configuration with Keyword Arguments Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst This example shows how to instantiate the APIConfig class defined previously by passing configuration values as keyword arguments. The nested DBConfig is provided as a dictionary, which Pydantic automatically parses into the correct type. ```python api_config = APIConfig( host="http://my-host.com", port=1234, db={"user": "my-user", "password": "my-password"} ) ``` -------------------------------- ### Use Custom ConfZ Source in a Configuration Class Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/extensions.rst This example shows how to instantiate a `BaseConfig` subclass and provide the custom `CustomSource` during initialization. The `platform` and `version` attributes of `CustomSource` are mapped to configuration attributes (`attr1` and `attr2` respectively), demonstrating how the custom loader injects the system information into the config object. ```python from confz import BaseConfig class MyConfig(BaseConfig): attr1: str attr2: str # Assuming CustomSource and CustomLoader are already defined and registered # MyConfig(config_sources=CustomSource( # platform="attr1", # version="attr2" # )) # Example instantiation (output will vary based on system): # >>> MyConfig(config_sources=CustomSource( # ... platform="attr1", # ... version="attr2" # ... )) # MyConfig(attr1='win32' attr2='3.9') ``` -------------------------------- ### Build Documentation Locally with Sphinx Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Builds the project's documentation locally using Sphinx. This command should be run from the 'docs' directory. ```shell make html ``` -------------------------------- ### Running Asynchronous Configuration Validation Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/listeners.rst Demonstrates how to execute an asynchronous application entry point that includes loading configurations and listeners. This is necessary when asynchronous listeners are defined. ```python import asyncio from confz import validate_all_configs async def main(): await validate_all_configs(include_listeners=True) # your application code if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Check Test Coverage with Coverage.py Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Runs tests and generates a coverage report, failing if coverage is below 100%. This helps ensure all code paths are tested. ```shell coverage run -m pytest coverage report --fail-under=100 ``` -------------------------------- ### Forcing Early Loading of All Configurations and Listeners Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/listeners.rst Shows how to use the `confz.validate_all_configs` function to explicitly load all configuration sources. Setting `include_listeners=True` also forces decorated functions (listeners) to execute. ```python from confz import validate_all_configs if __name__ == '__main__': validate_all_configs(include_listeners=True) # your application code ``` -------------------------------- ### SQLAlchemy Engine Creation with Module-Level Config Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/listeners.rst Demonstrates how to define an SQLAlchemy engine at the module level by wrapping its creation in a function decorated with `confz.depends_on`. This ensures the engine is a singleton and updates when its dependent configuration changes. ```python from confz import depends_on from sqlalchemy import create_engine # Assuming DBConfig is a ConfZ configuration class # class DBConfig(ConfZBase): # path: str = "my_db.db" @depends_on(DBConfig) def get_engine(): return create_engine(f"sqlite:///{DBConfig().path}", echo=True, future=True) ``` -------------------------------- ### ConfZ Singleton and Immutability Source: https://github.com/zuehlke/confz/blob/main/README.md Illustrates the singleton pattern and immutability features of ConfZ. It verifies that accessing the same configuration class multiple times returns the same instance and that attempts to modify it raise an error. ```python assert APIConfig() is APIConfig() # true because of singleton mechanism APIConfig().port = 1234 # raises an error because of immutability APIConfig().model_dump() # call pydantic's method to get a dict representation ``` -------------------------------- ### Define Custom ConfZ Source and Loader in Python Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/extensions.rst This snippet demonstrates how to create a custom `ConfigSource` to hold platform and version information and a `Loader` to populate these into the configuration dictionary. The loader uses `sys.platform` and `sys.version_info` to gather the data. The custom loader is then registered using `confz.loaders.register_loader`. ```python import sys from dataclasses import dataclass from confz import ConfigSource from confz.loaders import Loader, register_loader @dataclass class CustomSource(ConfigSource): platform: str = None # Write the current platform into a config variable with this name version: str = None # Write the current python version into a config variable with this name class CustomLoader(Loader): @classmethod def populate_config(cls, config: dict, config_source: CustomSource): config_update = { config_source.platform: sys.platform, config_source.version: f"{sys.version_info[0]}.{sys.version_info[1]}" } cls.update_dict_recursively(config, config_update) register_loader(CustomSource, CustomLoader) ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Executes all tests in the project using pytest. The '-W error' flag treats warnings as errors, ensuring high code quality. Aims for 100% test coverage. ```shell pytest -W error ``` -------------------------------- ### ConfZ with Multiple Sources (Env, File, CLI) Source: https://github.com/zuehlke/confz/blob/main/README.md Shows how to configure ConfZ to load configuration from multiple sources, including environment variables (with optional .env file support) and command-line arguments. It demonstrates how ConfZ handles precedence and recursive model structures. ```python from confz import BaseConfig, EnvSource, CLArgSource class MyConfig(BaseConfig): ... CONFIG_SOURCES = [ EnvSource(allow_all=True, file=".env.local"), CLArgSource(prefix='conf_') ] ``` -------------------------------- ### Load Configuration from YAML File Source Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst This snippet illustrates how to load configuration from an external YAML file. It uses ConfZ's FileSource to specify the file path and passes it as the `config_sources` argument during instantiation. ```python from confz import FileSource # Assuming a config.yaml file exists with host, port, and db details APIConfig(config_sources=FileSource(file="/path/to/config.yaml")) ``` -------------------------------- ### ConfZ with Multiple Environments via FileSource Source: https://github.com/zuehlke/confz/blob/main/README.md Demonstrates configuring ConfZ to load configuration from a folder, using an environment variable to specify the active configuration file. This is useful for managing configurations across different deployment environments. ```python from confz import BaseConfig, FileSource class MyConfig(BaseConfig): ... CONFIG_SOURCES = FileSource( folder='/path/to/config/folder', file_from_env='ENVIRONMENT' ) ``` -------------------------------- ### Explicit Configuration Loading in Python Source: https://github.com/zuehlke/confz/blob/main/README.md Demonstrates how to load configuration explicitly by passing config sources directly to the constructor of a BaseConfig subclass. This method avoids the global singleton pattern and allows for localized configuration management. Additional keyword arguments can be provided for direct value setting. ```python from confz import BaseConfig, FileSource, EnvSource class MyConfig(BaseConfig): number: int text: str config1 = MyConfig(config_sources=FileSource(file='/path/to/config.yml')) config2 = MyConfig(config_sources=EnvSource(prefix='CONF_', allow=['text']), number=1) config3 = MyConfig(number=1, text='hello world') ``` -------------------------------- ### Declare Config Classes and Sources with ConfZ Source: https://github.com/zuehlke/confz/blob/main/README.md Demonstrates how to declare configuration classes using ConfZ's BaseConfig and pydantic's types. It shows how to define configuration sources, such as YAML files, and access the configuration as pydantic models. ```python from confz import BaseConfig, FileSource from pydantic import SecretStr, AnyUrl class DBConfig(BaseConfig): user: str password: SecretStr class APIConfig(BaseConfig): host: AnyUrl port: int db: DBConfig CONFIG_SOURCES = FileSource(file='/path/to/config.yml') ``` -------------------------------- ### Lint Code with Pylint Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Analyzes Python code for errors and style issues using pylint. This ensures code consistency and adherence to best practices. ```shell pylint confz ``` -------------------------------- ### Manually Validate All Configurations Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst This function, `validate_all_configs`, allows for early loading and validation of all configuration classes that have `CONFIG_SOURCES` defined. It's recommended to call this at the application's entry point to catch configuration errors proactively. ```python from confz import validate_all_configs if __name__ == '__main__': validate_all_configs() # your application code ``` -------------------------------- ### Format Code with Black Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Automatically formats all Python files in the current directory using the black code formatter. This enforces a consistent coding style across the project. ```shell black . ``` -------------------------------- ### Verify Singleton Behavior Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst When `CONFIG_SOURCES` is defined as a class variable, ConfZ ensures that only one instance of the configuration class is created and reused. This snippet verifies this singleton pattern by comparing two instances obtained through separate calls. ```python APIConfig() is APIConfig() ``` -------------------------------- ### Define Database and API Configuration with Pydantic Types Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst This snippet demonstrates how to define configuration classes using ConfZ's BaseConfig, which inherits from Pydantic's BaseModel. It shows the use of standard Python types, Pydantic's SecretStr for sensitive data, and AnyUrl for URLs. Validators are also supported but not explicitly shown here. ```python from confz import BaseConfig from pydantic import SecretStr, AnyUrl class DBConfig(BaseConfig): user: str password: SecretStr class APIConfig(BaseConfig): host: AnyUrl port: int db: DBConfig ``` -------------------------------- ### Using Confz Context Manager for Temporary Configuration Changes Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/context_manager.rst Demonstrates how to use the `change_config_sources` context manager to temporarily override configuration values. This is useful for scenarios like unit testing where specific configurations are needed for a short duration. The original configuration is restored upon exiting the context. ```python from pathlib import Path from confz import BaseConfig, FileSource, DataSource class MyConfig(BaseConfig): number: int CONFIG_SOURCES = FileSource(file="/path/to/config.yml") print(MyConfig().number) new_source = DataSource(data={"number": 42}) with MyConfig.change_config_sources(new_source): print(MyConfig().number) print(MyConfig().number) ``` -------------------------------- ### Dump Configuration to JSON Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst Demonstrates how to serialize the ConfZ configuration object into a JSON string using the `model_dump_json` method inherited from Pydantic's BaseModel. This is useful for logging or sending configuration data. ```python api_config.model_dump_json() ``` -------------------------------- ### Define Configuration Sources as a Class Variable Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst This method defines configuration sources directly within the class using the `CONFIG_SOURCES` class variable. This approach centralizes the source definition and enables automatic singleton behavior for the configuration class. ```python from confz import BaseConfig, FileSource from pydantic import SecretStr, AnyUrl class DBConfig(BaseConfig): user: str password: SecretStr class APIConfig(BaseConfig): host: AnyUrl port: int db: DBConfig CONFIG_SOURCES = FileSource(file="/path/to/config.yaml") ``` -------------------------------- ### Access ConfZ Configuration Source: https://github.com/zuehlke/confz/blob/main/README.md Shows how to access the declared configuration from anywhere in your Python project after defining it with ConfZ. The configuration is automatically loaded and cached as a singleton instance upon first access. ```python from config import APIConfig print(f"Serving API at {APIConfig().host}, port {APIConfig().port}.") ``` -------------------------------- ### Asynchronous Engine Creation with `depends_on` Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/listeners.rst Illustrates the use of the `depends_on` decorator with asynchronous functions for creating an asynchronous SQLAlchemy engine. This pattern is useful when configuration-dependent asynchronous operations are needed. ```python from confz import depends_on from sqlalchemy.ext.asyncio import create_async_engine # Assuming DBConfig and meta are defined elsewhere # class DBConfig(ConfZBase): # path: str = "my_db.db" # meta = MetaData() @depends_on(DBConfig) async def get_engine(): engine = create_async_engine(f"sqlite:///{DBConfig().path}", echo=True) async with engine.begin() as conn: await conn.run_sync(meta.drop_all) await conn.run_sync(meta.create_all) return engine ``` -------------------------------- ### Access Configuration Values with Class Variable Sources Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/confz_class.rst Once `CONFIG_SOURCES` is defined as a class variable, configuration values can be accessed directly by importing and instantiating the config class. This provides a convenient way to access configurations throughout the application. ```python # Assuming APIConfig is defined with CONFIG_SOURCES APIConfig().port APIConfig().db.user ``` -------------------------------- ### Temporarily Changing Configuration Sources in Python Source: https://github.com/zuehlke/confz/blob/main/README.md Shows how to use a context manager (`change_config_sources`) to temporarily override the configuration sources of a `BaseConfig` subclass. This is particularly useful for unit testing, allowing specific configuration values to be injected without affecting the global configuration state. ```python from confz import BaseConfig, FileSource, DataSource class MyConfig(BaseConfig): number: int CONFIG_SOURCES = FileSource(file="/path/to/config.yml") print(MyConfig().number) new_source = DataSource(data={'number': 42}) with MyConfig.change_config_sources(new_source): print(MyConfig().number) print(MyConfig().number) ``` -------------------------------- ### Perform Type Checking with Mypy Source: https://github.com/zuehlke/confz/blob/main/CONTRIBUTING.md Checks the Python code for type errors using mypy. This helps catch potential bugs early in the development process. ```shell mypy confz ``` -------------------------------- ### Ignoring MyPy Metaclass Errors in ConfZ Source: https://github.com/zuehlke/confz/blob/main/docs/source/usage/mypy.rst This snippet demonstrates how to ignore MyPy metaclass conflicts when using ConfZ by adding '# type: ignore' to the class definition. This is a workaround for MyPy's current limitations with metaclasses. ```python class MyConfig(BaseConfig): # type: ignore my_variable: bool ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.