EnvGuard for Python
A lightweight, efficient utility for validating serverless function environment variables against defined schemas at cold start.
Features
- 🚀 Optimized for serverless cold starts
- 🛡️ Strong type validation using Pydantic models
- 🔍 Clear, structured error messages
- 💻 Simple, intuitive API
- ⚡ Fail-fast approach for robust serverless functions
Installation
pip install envguard-python
Quick Start
from pydantic import BaseModel, EmailStr
from envguard_python import load_env_or_fail
class AppConfig(BaseModel):
# Required environment variables
DATABASE_URL: str
API_KEY: str
ADMIN_EMAIL: EmailStr
# Optional environment variables with defaults
DEBUG: bool = False
PORT: int = 8000
ENVIRONMENT: str = "development"
try:
# Validate environment variables at cold start
config = load_env_or_fail(AppConfig)
# Use the validated configuration
print(f"Running on port {config.PORT}")
print(f"Debug mode: {config.DEBUG}")
except EnvGuardValidationError as e:
print("Environment validation failed:")
print(e) # Prints detailed error messages
raise # Re-raise to fail the function
Usage Examples
Basic Usage
from pydantic import BaseModel
from envguard_python import load_env_or_fail
class DatabaseConfig(BaseModel):
DB_HOST: str
DB_PORT: int
DB_NAME: str
DB_USER: str
DB_PASSWORD: str
# Will raise EnvGuardValidationError if any required variables are missing
# or if type validation fails (e.g., if DB_PORT is not a valid integer)
db_config = load_env_or_fail(DatabaseConfig)
With Pydantic Validators
from pydantic import BaseModel, field_validator
from envguard_python import load_env_or_fail
class APIConfig(BaseModel):
API_URL: str
API_TIMEOUT: int = 30
API_RETRIES: int = 3
@field_validator("API_TIMEOUT", "API_RETRIES")
def validate_positive(cls, v: int) -> int:
if v <= 0:
raise ValueError("must be positive")
return v
# Will use Pydantic's validation system
api_config = load_env_or_fail(APIConfig)
Error Handling
from envguard_python import load_env_or_fail, EnvGuardValidationError
try:
config = load_env_or_fail(AppConfig)
except EnvGuardValidationError as e:
# Access structured error information
for var_name, error in e.errors.items():
print(f"Error in {var_name}: {error}")
# Or use the formatted string representation
print(e) # Includes all errors in a readable format
# Handle the error (e.g., log to error monitoring, fail fast)
raise
API Reference
load_env_or_fail
def load_env_or_fail(
schema_model: Type[SupportsEnvironmentValidation],
**kwargs: Any
) -> Any:
"""
Load and validate environment variables against a schema model.
Args:
schema_model: A Pydantic model class defining the environment schema
**kwargs: Additional keyword arguments passed to Pydantic's model_validate
Returns:
An instance of the schema model populated with validated environment variables
Raises:
EnvGuardValidationError: If environment variables fail validation
"""
EnvGuardValidationError
class EnvGuardValidationError(Exception):
"""
Raised when environment variable validation fails.
Attributes:
message (str): Human-readable error message
errors (Dict[str, Any]): Dictionary of validation errors
"""
Best Practices
- Fail Fast: Validate environment variables at cold start before any other initialization.
- Type Safety: Use appropriate Pydantic field types for strong validation.
- Default Values: Provide sensible defaults for non-critical configuration.
- Documentation: Include examples of required environment variables in your project's README.
- Error Handling: Always catch and handle validation errors appropriately.
Contributing
Contributions are welcome! Please see the main project Contributing Guidelines.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Metadata
Release files for envguard-python 0.1.5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| envguard_python-0.1.5.tar.gz | 6.4 kB | Without provenance | Details for envguard_python-0.1.5.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| envguard_python-0.1.5-py3-none-any.whl | Python 3 | none | any | Details for envguard_python-0.1.5-py3-none-any.whl |
Total release size: 12.2 kB
Release files / envguard_python-0.1.5.tar.gz
| Download URL | envguard_python-0.1.5.tar.gz |
|---|---|
| Size | 6.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
630df78e8ed2c0dffbae445cb38673cfd4c4dcd32a3be298bd1d352d493fed15
|
|
BLAKE2b-256 checksum How to use checksums |
e1b113364264f2667d89b3690c7288530713782007484b00d2ec3a835c382313
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.11
|
Release files / envguard_python-0.1.5-py3-none-any.whl
| Download URL | envguard_python-0.1.5-py3-none-any.whl |
|---|---|
| Size | 5.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9886dff0b9026c31fdd25d902760adc7f4f95737f5cf10b2843ea175a1c626ba
|
|
BLAKE2b-256 checksum How to use checksums |
d5e057abf0b9236f4afe8e1fe090e76d12f379f2f7ed86e06bfc0f9f696b4c2e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.11
|
Security for envguard-python 0.1.5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.