The dynamic configurator for your Python Project
—
Fundamental configuration functionality including settings creation, value access, type casting, environment management, and multi-source data loading. This module provides the core classes and methods for managing application configuration in Python projects.
Create configuration instances with flexible initialization options.
class Dynaconf:
"""Main entry point for creating settings instances."""
def __init__(
self,
settings_files=None, # List of configuration file paths/globs
environments=False, # Enable environment layers
envvar_prefix=None, # Environment variable prefix
env_switcher=None, # Environment switching variable
load_dotenv=False, # Load .env files
**kwargs # Additional configuration options
): ...
class LazySettings:
"""Lazy-loading settings class that defers initialization."""
def __init__(self, wrapped=None, **kwargs): ...
def configure(self, settings_module=None, **kwargs):
"""Reconfigure the settings object."""
...
@property
def configured(self) -> bool:
"""Check if settings are configured."""
...Usage examples:
from dynaconf import Dynaconf
# Basic settings
settings = Dynaconf()
# Advanced configuration
settings = Dynaconf(
envvar_prefix="MYAPP",
settings_files=["config.toml", "local/*.yaml"],
environments=True,
load_dotenv=True,
env_switcher="MYAPP_ENV"
)Retrieve configuration values with optional defaults, type casting, and freshness control.
def get(
self,
key: str,
default=None, # Default value if key not found
cast=None, # Type casting function
fresh=False, # Force reload from source
dotted_lookup=True, # Enable dot notation lookup
parent=None, # Parent context for relative lookups
sysenv_fallback=None # System environment fallback
):
"""
Get setting value with optional casting and fallbacks.
Returns:
Any: The configuration value, cast to specified type
"""
...
def get_fresh(self, key: str, default=None, cast=None):
"""Always reload from source before getting value."""
...
def get_environ(self, key: str, default=None, cast=None):
"""Get value from environment variables only."""
...
def exists(self, key: str, fresh=False) -> bool:
"""Check if a configuration key exists."""
...
def exists_in_environ(self, key: str) -> bool:
"""Check if key exists in environment variables."""
...Built-in type conversion methods for common data types.
def as_bool(self, key: str) -> bool:
"""Cast configuration value to boolean."""
...
def as_int(self, key: str) -> int:
"""Cast configuration value to integer."""
...
def as_float(self, key: str) -> float:
"""Cast configuration value to float."""
...
def as_json(self, key: str) -> dict:
"""Parse configuration value as JSON."""
...Usage examples:
# Basic access
database_url = settings.get("DATABASE_URL")
port = settings.get("PORT", default=8000, cast=int)
# Type casting shortcuts
debug = settings.as_bool("DEBUG")
timeout = settings.as_float("TIMEOUT")
config = settings.as_json("COMPLEX_CONFIG")
# Check existence
if settings.exists("OPTIONAL_FEATURE"):
feature_config = settings.OPTIONAL_FEATURESet and update configuration values programmatically.
def set(
self,
key: str,
value,
loader_identifier=None, # Source identifier
tomlfy=False, # Convert to TOML format
dotted_lookup=True, # Enable dot notation
validate=True, # Run validation
merge=False # Merge with existing values
):
"""Set a configuration value."""
...
def update(self, data=None, **kwargs):
"""Update multiple configuration values."""
...
def setdefault(
self,
item: str,
default,
apply_default_on_none=False,
env="unknown"
):
"""Set default value if key doesn't exist."""
...
def unset(self, key: str, force=False):
"""Remove a configuration key."""
...Usage examples:
# Set individual values
settings.set("CACHE_TIMEOUT", 3600)
settings.set("NESTED.CONFIG", {"key": "value"}, merge=True)
# Bulk updates
settings.update({
"API_VERSION": "v2",
"TIMEOUT": 30,
"RETRIES": 3
})
# Set defaults
settings.setdefault("WORKERS", 4)Switch between different configuration environments.
def setenv(self, env=None, clean=True, silent=True, filename=None):
"""Switch to specified environment."""
...
def using_env(self, env: str, clean=True, silent=True, filename=None):
"""Context manager for temporary environment switching."""
...
def from_env(self, env: str = "", keep=False, **kwargs):
"""Create isolated settings instance for specific environment."""
...
@property
def current_env(self) -> str:
"""Get current active environment."""
...
@property
def loaded_envs(self) -> list:
"""List of loaded environments."""
...Usage examples:
# Switch environments
settings.setenv("production")
prod_db = settings.DATABASE_URL
# Temporary environment switching
with settings.using_env("testing"):
test_db = settings.DATABASE_URL # Different value for testing
# Create environment-specific instance
prod_settings = settings.from_env("production")Export configuration data and create copies of settings instances.
def as_dict(self, env=None, internal=False) -> dict:
"""Export settings as dictionary."""
...
def dynaconf_clone(self):
"""Create a deep copy of the settings instance."""
...
def populate_obj(
self,
obj,
keys=None, # Specific keys to populate
ignore=None, # Keys to ignore
internal=False, # Include internal settings
convert_to_dict=False # Convert nested objects to dicts
):
"""Populate another object with settings values."""
...Load configuration from files dynamically.
def load_file(
self,
path=None, # File path or list of paths
env=None, # Environment to load into
silent=True, # Suppress file not found errors
key=None, # Load under specific key
validate=True, # Run validation after loading
run_hooks=True # Execute post-load hooks
):
"""Load configuration from file(s)."""
...
def execute_loaders(
self,
env=None, # Environment to load
silent=None, # Suppress errors
key=None, # Load under specific key
filename=None, # Specific file to load
loaders=None # Specific loaders to execute
):
"""Execute configuration loaders."""
...
def reload(self, env=None, silent=None):
"""Clean and reload all configuration."""
...
def find_file(self, *args, **kwargs):
"""Find configuration files in the filesystem."""
...Simple feature flag functionality.
def flag(self, key: str, env=None) -> bool:
"""Get feature flag value."""
...Force reload from configuration sources.
def fresh(self):
"""Context manager for fresh loading from sources."""
...
def clean(self, *args, **kwargs):
"""Clean loaded values to force reload."""
...Usage examples:
# Force fresh load
with settings.fresh():
current_config = settings.DATABASE_URL # Reloaded from source
# Clean specific keys
settings.clean("CACHE_CONFIG")DEFAULT_SETTINGS_FILES: list
"""Default configuration file patterns to search for."""Install with Tessl CLI
npx tessl i tessl/pypi-dynaconf