Ship code continuously while controlling feature rollout with runtime flags.
Code Snippet
# feature_flags.py
import os
from functools import wraps
class FeatureFlags:
def __init__(self):
self._flags = {
"new_checkout": os.getenv("FF_NEW_CHECKOUT", "false") == "true",
"dark_mode": os.getenv("FF_DARK_MODE", "false") == "true",
}
def is_enabled(self, flag: str) -> bool:
return self._flags.get(flag, False)
flags = FeatureFlags()
# Usage in code
def get_checkout_page():
if flags.is_enabled("new_checkout"):
return render_new_checkout()
return render_legacy_checkout()
Why This Helps
- Enables continuous deployment without feature branches
- Instant rollback by toggling flag
- Gradual rollout to percentage of users
How to Test
- Toggle flag and verify behavior change
- Test both code paths in CI
When to Use
Large features, risky changes, A/B testing, gradual rollouts.
Performance/Security Notes
Clean up old flags regularly. Consider using a feature flag service for complex scenarios.
References
Try this tip in your next project and share your results in the comments!
Discover more from Code, Cloud & Context
Subscribe to get the latest posts sent to your email.