Python EnvCFG
Python EnvCFG (python-envcfg) provides a 'magic module' for accessing environment variables as attributes, automatically converting them to common Python types (str, int, float, bool). It also supports loading configuration from YAML files. The current version is 0.2.0, released in 2017, and the project appears to be no longer actively maintained.
Common errors
-
AttributeError: 'EnvProxy' object has no attribute 'YOUR_UNDEFINED_VARIABLE'
cause Attempting to access an environment variable using `env.YOUR_UNDEFINED_VARIABLE` when the variable is not set and no default value is provided.fixUse `env.YOUR_UNDEFINED_VARIABLE('default_value')` to provide a fallback, or ensure the environment variable is set before access. -
ValueError: invalid literal for int() with base 10: 'abc' (or similar for float/bool)
cause EnvCFG's automatic type conversion attempted to convert an environment variable string (e.g., 'abc') to an integer, but the string was not a valid representation for the target type.fixEnsure the environment variable's value matches the expected type for automatic conversion, or explicitly retrieve it as a string using a string default value: `env.VAR_NAME('abc')` if 'abc' should be a string.
Warnings
- gotcha Project Abandonment: `python-envcfg` has not been updated since 2017 and is no longer actively maintained. This means no new features, bug fixes, or security updates are to be expected.
- gotcha Potential Python Version Incompatibility: While `0.2.0` listed Python 3 support, it has not been tested or updated for modern Python versions (e.g., 3.9+). Users may encounter unexpected runtime errors or deprecated syntax issues.
- gotcha Implicit Type Conversion Risks: EnvCFG automatically converts environment variable strings to `bool`, `int`, or `float`. This can lead to unexpected values (e.g., '0' becoming `False`, 'false' becoming `False`) if the intended value was a string.
Install
-
pip install python-envcfg
Imports
- env
from envcfg import env
- from_yaml
from envcfg import from_yaml
Quickstart
import os
from envcfg import env
# Simulate setting environment variables for demonstration
os.environ['DATABASE_URL'] = 'postgres://user:password@host:port/database'
os.environ['DEBUG'] = 'true'
os.environ['PORT'] = '8000'
print(f"Database URL: {env.DATABASE_URL} (type: {type(env.DATABASE_URL)})")
print(f"Debug Mode: {env.DEBUG} (type: {type(env.DEBUG)})") # Auto-converts 'true' to True
print(f"Port Number: {env.PORT} (type: {type(env.PORT)})") # Auto-converts '8000' to 8000
# Accessing an undefined variable with a default
app_env = env.APP_ENV('development')
print(f"App Environment: {app_env} (type: {type(app_env)})")
# Example of retrieving an explicitly string value:
string_port = env.PORT('default_string_port') # Ensures string type
print(f"Port as String: {string_port} (type: {type(string_port)})")