OpenFeature Python SDK
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
- breaking Python 3.8 support was dropped in OpenFeature Python SDK v0.8.0. Applications must be running Python 3.9 or newer to upgrade to v0.8.0 and beyond.
- breaking The signature of the `finally_after` hook stage changed in v0.7.5. It now requires `evaluation_details` as the second argument.
- gotcha The core `openfeature-sdk` package does not include any flag providers by default. A provider, which connects to a feature flag management system (like Flagd, LaunchDarkly, Split.io), must be installed and configured separately.
- gotcha If no provider is explicitly set, OpenFeature will default to a 'No-Op' provider. This provider always returns the default value provided in the flag evaluation call, which can lead to unexpected behavior if you expect flags to be dynamic.
- gotcha When providing an `EvaluationContext`, ensure a `targeting_key` is always included. Many providers rely on this for correct flag evaluation and targeting logic, and its absence can lead to incorrect or default flag values.
Install
-
pip install openfeature-sdk -
pip install openfeature-provider-flagd
Imports
- api
from openfeature import api
- InMemoryProvider
from openfeature.provider.in_memory_provider import InMemoryProvider
- EvaluationContext
from openfeature import EvaluationContext
Quickstart
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()