LaunchDarkly Python Server SDK

9.15.0 · active · verified Wed Apr 08

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the LaunchDarkly client, define a user, evaluate a feature flag, and properly shut down the client. It uses an environment variable for the SDK key for security. In production, ensure the client is initialized and shut down gracefully with your application's lifecycle.

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()

view raw JSON →