Advanced Usage
This guide covers advanced patterns and best practices for using the Toggly Python SDK.
Feature Evaluation
Basic Evaluation
from toggly import TogglyClient, TogglyConfig
client = TogglyClient(TogglyConfig(app_key="your-app-key"))
client.init()
# Simple check
if client.is_enabled("my-feature"):
print("Feature enabled!")
# With default value
enabled = client.is_enabled("unknown-feature", default=True)
With Context
from toggly import EvaluationContext
context = EvaluationContext(
identity="user-123",
groups=["beta-testers", "premium"],
traits={
"plan": "enterprise",
"country": "US",
"signup_date": "2024-01-15",
}
)
if client.is_enabled("premium-feature", context):
print("Premium feature for this user!")
Feature Gates
Evaluate multiple features at once:
from toggly import FeatureRequirement
# All features must be enabled
if client.evaluate_gate(
["feature-a", "feature-b"],
FeatureRequirement.ALL,
context
):
print("All features enabled!")
# Any feature must be enabled
if client.evaluate_gate(
["premium", "trial"],
FeatureRequirement.ANY,
context
):
print("User has access!")
# Negate the result
if client.evaluate_gate(
["maintenance-mode"],
FeatureRequirement.ALL,
context,
negate=True
):
print("Not in maintenance mode!")
Get All Flags
# Get all feature flags as a dictionary
flags = client.feature_flags
for key, enabled in flags.items():
print(f"{key}: {'enabled' if enabled else 'disabled'}")
Async Support
AsyncTogglyClient
import asyncio
from toggly import AsyncTogglyClient, TogglyConfig
async def main():
config = TogglyConfig(app_key="your-app-key")
client = AsyncTogglyClient(config)
await client.init()
if await client.is_enabled("async-feature"):
print("Feature enabled!")
await client.close()
asyncio.run(main())
Context Manager
async with AsyncTogglyClient(config) as client:
await client.init()
enabled = await client.is_enabled("my-feature")
With FastAPI
For native middleware and gate dependencies, use the synchronous client in the FastAPI lifespan example. For direct async evaluation, own the async client's lifespan and await every check:
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from toggly import AsyncTogglyClient, TogglyConfig
@asynccontextmanager
async def lifespan(app: FastAPI):
client = AsyncTogglyClient(TogglyConfig(
app_key=os.environ.get("TOGGLY_APP_KEY"),
))
await client.init()
app.state.feature_client = client
try:
yield
finally:
await client.close()
app = FastAPI(lifespan=lifespan)
@app.get("/feature")
async def feature(request: Request):
enabled = await request.app.state.feature_client.is_enabled("async-feature")
return {"enabled": enabled}