LaunchDarkly Python Server SDK
The LaunchDarkly SDK for Python provides functionality to integrate feature flags into your Python applications. It enables developers to control feature rollouts, perform A/B testing, and manage configurations without redeploying code. The library is actively maintained with frequent minor and patch releases, typically every 1-2 months, to introduce new features, improvements, and bug fixes.
Warnings
- breaking Python 3.9 is no longer supported starting with version 9.15.0.
- breaking Python 3.8 is no longer supported starting with version 9.12.0.
- gotcha The `ChangeSet` object in the file data source now strictly requires a `Selector` for updates.
- gotcha SDK key validation was added, which performs a basic format check on initialization. Providing an invalid SDK key format may lead to immediate client initialization failure.
- gotcha It is crucial to call `ld_client.close()` when your application is shutting down to ensure all pending events are flushed and resources are released. Failing to do so can lead to lost analytics events or resource leaks.
Install
-
pip install launchdarkly-server-sdk
Imports
- LdClient
from launchdarkly_server_sdk import LdClient, Config
Quickstart
import os
from launchdarkly_server_sdk import LdClient, Config
# Replace with your actual SDK key from LaunchDarkly
SDK_KEY = os.environ.get('LAUNCHDARKLY_SDK_KEY', 'YOUR_SDK_KEY_HERE')
if not SDK_KEY or SDK_KEY == 'YOUR_SDK_KEY_HERE':
print("Warning: LAUNCHDARKLY_SDK_KEY environment variable not set or default used. Client will be in offline mode.")
# In a real application, you might raise an error or handle this differently.
config = Config(offline=True)
else:
config = Config()
# Initialize the LaunchDarkly client
ld_client = LdClient(SDK_KEY, config)
# Wait for the client to be initialized (recommended for server-side apps)
if ld_client.is_initialized():
print("LaunchDarkly client initialized!")
# Define a user for flag evaluation
user = {
"key": "example-user-key",
"name": "Example User",
"custom": {
"group": "beta_testers"
}
}
# Evaluate a feature flag
flag_value = ld_client.variation("my-feature-flag", user, False)
print(f"Feature flag 'my-feature-flag' is: {flag_value} for user {user['key']}")
# Don't forget to shut down the client when your application exits
ld_client.close()
print("LaunchDarkly client closed.")
else:
print("LaunchDarkly client failed to initialize.")
# Ensure the client is closed even if initialization fails
ld_client.close()