OpenFeature Python SDK

0.8.4 · active · verified Sat Apr 11

The OpenFeature Python SDK is a vendor-agnostic abstraction library for evaluating feature flags in Python applications. It supports multiple data types for flags (booleans, strings, numbers, objects), integrates with various backend providers, and offers hooks to extend the flag evaluation lifecycle. The current version is 0.8.4, with active development and regular minor releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the OpenFeature SDK with a basic in-memory provider, create a client, and evaluate a boolean and a string feature flag. It also shows how to provide an evaluation context for flag targeting. In a production environment, you would replace `InMemoryProvider` with a specific feature flag management system's provider (e.g., `FlagdProvider`, `LaunchDarklyProvider`).

from openfeature import api, EvaluationContext
from openfeature.provider.in_memory_provider import InMemoryFlag, InMemoryProvider
import os

# Configure a simple in-memory provider for demonstration
# In a real application, you would typically use an external provider (e.g., Flagd, LaunchDarkly)
my_flags = {
    "new-feature-enabled": InMemoryFlag("on", {"on": True, "off": False}),
    "welcome-message": InMemoryFlag("greeting", {"greeting": "Hello, OpenFeature!", "default": "Welcome!"})
}
api.set_provider(InMemoryProvider(my_flags))

# Create a client, optionally with a domain
client = api.get_client()

# Define an evaluation context for targeting
user_id = os.environ.get('USER_ID', 'default_user')
eval_context = EvaluationContext(targeting_key=user_id, attributes={"region": "us-east-1"})

# Evaluate a boolean flag
is_new_feature_enabled = client.get_boolean_value("new-feature-enabled", False, eval_context)
if is_new_feature_enabled:
    print(f"New feature is enabled for user {user_id}!")
else:
    print(f"New feature is disabled for user {user_id}.")

# Evaluate a string flag
message = client.get_string_value("welcome-message", "Fallback Message", eval_context)
print(f"Retrieved message: {message}")

# It's good practice to shut down providers gracefully
api.shutdown()

view raw JSON →