Safe Init

raw JSON →
1.4.0 verified Fri May 01 auth: no python

Safe Init is a Python library that enhances AWS Lambda functions with advanced error handling, logging, monitoring, and resilience features. Version 1.4.0 (released 2025-04-02) adds automatic JSON serialization checks and uses uv for dependency management. The library requires Python <3.12 and >=3.11, and integrates with Sentry, Slack, AWS Secrets Manager, and Redis.

pip install safe-init
error safe_init.exceptions.SafeInitConfigurationError: Slack webhook URL not configured
cause Slack notifications are enabled but no webhook URL is set via context variable.
fix
Use safe_init.set_slack_webhook('https://hooks.slack.com/...') before calling the handler.
error safe_init.exceptions.SafeInitSerializationError: Return value is not JSON serializable: UUID('...')
cause Lambda handler returns an object like UUID that is not JSON serializable.
fix
Convert the return value to a JSON-serializable format, e.g., str(uuid).
error ImportError: cannot import name 'SafeInit' from 'safe_init'
cause Safe Init is not installed or version does not export the class.
fix
Run 'pip install safe-init' and ensure version >=1.0.0.
breaking Slack webhook URLs and custom loggers via monkey patching removed in v1.2.0. Use ContextVars instead.
fix Use safe_init.set_slack_webhook() and safe_init.set_custom_logger() via context variables instead of monkey patching.
gotcha Lambda return value JSON serialization check introduced in v1.4.0 may cause unexpected behavior if you rely on non-serializable objects like UUIDs. The check reports to Sentry but does not break execution.
fix Ensure your Lambda returns JSON-serializable objects, or configure the check if you need different behavior.
gotcha The .env.json file feature (v1.3.0) reads environment variables from a JSON file. This file must be deployed with your Lambda and correctly formatted.
fix Create a .env.json file in your Lambda deployment package with key-value pairs.
deprecated Python 3.11 support is required; Python >=3.12 is not supported. The project may not work with newer Python runtimes.
fix Use Python 3.11 runtime in AWS Lambda.
gotcha AWS Secrets Manager secret ARN prefix feature: Safe Init will not add the configured prefix if the value already contains a prefix. This can lead to double-prefix if not careful.
fix Ensure your secret ARN either includes the full ARN or only the name without prefix.

Wrap your Lambda handler with the @safe_init.lambda_handler decorator to automatically capture errors and report to Sentry.

from safe_init import SafeInit

# Initialize with Sentry DSN (use environment variable)
safe_init = SafeInit(dsn=os.environ.get('SENTRY_DSN', ''))

@safe_init.lambda_handler
def lambda_handler(event, context):
    return {'statusCode': 200, 'body': 'Hello from Safe Init!'}