Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python configuration libraries load application settings from environment variables, files, and command-line arguments. A settings loader reads each source in a fixed order of precedence and converts the raw strings into typed values. These libraries let apps and services run the same code in development, test, and production.
Popularity
python-dotenv has the most monthly downloads in this comparison, at 757.3M.
def _ambient_client_token_source() -> str | None:
"""
Return where a token picked up by the standard `ClientConfig` constructor
would come from (the environment, or one of the `.env` files it reads), or
`None` if there is none. The `.env` files are probed with `ClientConfig`'s
own pydantic-settings dotenv source, one file at a time so the warning can
name the file, which keeps the answer identical to what the constructor
would actually load.
"""
if os.environ.get("HATCHET_CLIENT_TOKEN"):
return "the environment"
env_prefix = str(ClientConfig.model_config.get("env_prefix", ""))
env_file_setting = ClientConfig.model_config.get("env_file")
env_files: tuple[Path | str, ...]
if env_file_setting is None:
env_files = ()
elif isinstance(env_file_setting, (str, Path)):
env_files = (env_file_setting,)
else:
env_files = tuple(env_file_setting)
for name in env_files:
source = DotEnvSettingsSource(
ClientConfig, env_file=name, env_prefix=env_prefix
)
if source().get("token"):
return str(name)
return None
Traitlets
Provides a configuration system for Python applications.
def load_config_file(self, suppress_errors: bool = True) -> None: # type:ignore[override]
"""Load the config file.
By default, errors in loading config are handled, and a warning
printed on screen. For testing, the suppress_errors option is set
to False, so errors will make tests fail.
"""
self.log.debug("Searching %s for config files", self.config_file_paths)
base_config = "jupyter_config"
try:
super().load_config_file(
base_config,
path=self.config_file_paths,
)
except ConfigFileNotFound:
# ignore errors loading parent self.log.debug("Config file %s not found", base_config)
if self.config_file:
path, config_file_name = os.path.split(self.config_file)
else:
path = self.config_file_paths # type:ignore[assignment]
config_file_name = self.config_file_name
if not config_file_name or (config_file_name == base_config):
return
try:
super().load_config_file(config_file_name, path=path)
except ConfigFileNotFound:
self.log.debug("Config file not found, skipping: %s", config_file_name)
except Exception:
# Reraise errors for testing purposes, or if set in # self.raise_config_file_errors if (not suppress_errors) or self.raise_config_file_errors:
raise
self.log.warning("Error loading config file: %s", config_file_name, exc_info=True)
OmegaConf
Builds hierarchical configuration objects with interpolation, structured schemas, and configuration composition.
Downloads / mo
38.8M
Stars
2.4K
Last release
2.4.0
License
BSD-3-Clause
Strengths
Interpolates related settings lazily.Reference other configuration values and resolve them when accessed.
Validates structured configuration.Use dataclass or attrs schemas to validate assignments at runtime.
Limitations
Implicit conversions emit warnings.Use matching types or OmegaConf.update to request conversion explicitly.
Resolution in place removes expressions.Copy configuration before resolve when lazy references must be preserved.
def generate_secret_key_if_missing(data_dir: str) -> str:
env_key = 'SECRET_KEY'
env = environ.Env()
env_filepath = os.path.join(data_dir, '.env')
restrict_env_file_permissions(env_filepath)
environ.Env.read_env(env_filepath)
if existing_secret := env.str(env_key, ''):
return existing_secret
logger.warning(f'Warning: {env_key} not found in environment variables. Will generate a random key.')
new_secret = get_random_secret_key()
if is_collectstatic():
logger.info(
'Random SECRET_KEY was generated, but it is not being persisted because this is a collectstatic run'
)
return new_secret
try:
# SECRET_KEY also signs JWTs, so the file must not be readable by other local users fd = os.open(env_filepath, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
with os.fdopen(fd, 'a') as f:
f.write(f'\n{env_key}={new_secret}\n') # nosec
except Exception as e:
logger.warning(
f'Warning: failed to write {env_key} to .env file: {e}, new key will be regenerated on every '
f'server restart. If this key is used for signing, it will invalidate all existing sessions '
f'or tokens. Please set {env_key} in your environment variables to avoid this warning.'
)
os.environ[env_key] = new_secret
return new_secret
python-decouple
Looks up settings in environment variables and INI or dotenv files, with defaults and explicit casts.
Downloads / mo
7.3M
Stars
3.0K
Last release
3.8
License
MIT
Strengths
Environment values take precedence.Environment variables override matching settings-file values.
Casts values at lookup.Apply bool, int, or custom casts when retrieving a setting.
Limitations
Values start as strings.Request explicit casts when booleans, numbers, or lists are needed.
Missing required values raise errors.Provide a default or handle UndefinedValueError for missing settings.
@shared_task(name="follow_send_payment", time_limit=180, soft_time_limit=175)
def follow_send_payment(hash):
"""Sends sats to buyer, continuous update"""
from datetime import timedelta
from decouple import config
from django.utils import timezone
from api.lightning.node import LNNode
from api.models import LNPayment
if config("DEBUG_PERMISSIONED_PAYOUTS", cast=bool, default=False):
return
lnpayment = LNPayment.objects.get(payment_hash=hash)
lnpayment.last_routing_time = timezone.now()
lnpayment.save(update_fields=["last_routing_time"])
# Checked against the lightning node before every attempt; a payout that fails it # is held (and retried in an hour) until the coordinator looks at it. from api.logics import payout_problem
problem = payout_problem(lnpayment)
if problem:
print(f"PAYOUT HELD {hash}: {problem}", flush=True)
from api.models import Order
order = Order.objects.filter(payout=lnpayment).first()
if order and "PAYOUT HELD" not in (order.logs or ""):
order.log(f"PAYOUT HELD: {problem}", level="WARN")
lnpayment.last_routing_time = timezone.now() + timedelta(hours=1)
lnpayment.save(update_fields=["last_routing_time"])
return
# Default is 0ppm. Set by the user over API. Client's default is 1000 ppm. fee_limit_sat = int(
float(lnpayment.num_satoshis) * float(lnpayment.routing_budget_ppm) / 1_000_000
)
timeout_seconds = config("PAYOUT_TIMEOUT_SECONDS", cast=int, default=90)
try:
results = LNNode.follow_send_payment(lnpayment, fee_limit_sat, timeout_seconds)
except SoftTimeLimitExceeded:
# If the 175 seconds have been consumed without follow_send_payment() # returning, we set the last routing time as 'in 10 minutes' # so the next check happens in 10 minutes, instead of right now. lnpayment.last_routing_time = timezone.now() + timedelta(minutes=10)
lnpayment.save(update_fields=["last_routing_time"])
print(
f"Order: {lnpayment.order_paid_LN.id} SOFT TIME LIMIT REACHED. Hash: {hash}"
)
results = {}
return results
FAQ
Pydantic Settings suits applications that validate settings against a typed model. python-dotenv suits scripts that only need the values from a .env file. OmegaConf and Hydra suit nested configurations with command-line overrides.
python-dotenv reads key-value pairs from a .env file and sets them as environment variables. It does not build typed settings models or merge nested configuration.
Pydantic Settings loads settings into typed models from environment variables, dotenv files, secrets files, and custom sources. It validates each value against the declared field types.
OmegaConf builds hierarchical configuration objects with interpolation between values, structured schemas, and recursive merging. Hydra builds configuration composition on top of it.
Hydra composes an application's configuration from modular groups and command-line overrides. It runs on OmegaConf and adds launch and multirun workflows.
For coding agents
Found your configuration library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.