Skip to content

Commit

Permalink
Add function decorator for feature flags.
Browse files Browse the repository at this point in the history
  • Loading branch information
aholmes committed Oct 17, 2024
1 parent 3426b8f commit d5d2242
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/platform/Ligare/platform/feature_flag/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from .caching_feature_flag_router import FeatureFlag as CacheFeatureFlag
from .db_feature_flag_router import DBFeatureFlagRouter
from .db_feature_flag_router import FeatureFlag as DBFeatureFlag
from .decorators import feature_flag
from .feature_flag_router import FeatureFlag, FeatureFlagChange, FeatureFlagRouter

__all__ = (
Expand All @@ -12,4 +13,5 @@
"CacheFeatureFlag",
"DBFeatureFlag",
"FeatureFlagChange",
"feature_flag",
)
40 changes: 40 additions & 0 deletions src/platform/Ligare/platform/feature_flag/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from typing import Any, Callable

from injector import Injector, inject
from typing_extensions import overload

from .feature_flag_router import FeatureFlag, FeatureFlagRouter


@overload
def feature_flag(
feature_flag_name: str, *, enabled_callback: Callable[..., Any]
) -> Callable[..., Callable[..., Any]]: ...
@overload
def feature_flag(
feature_flag_name: str, *, disabled_callback: Callable[..., Any]
) -> Callable[..., Callable[..., Any]]: ...


def feature_flag(
feature_flag_name: str,
*,
enabled_callback: Callable[..., None] = lambda: None,
disabled_callback: Callable[..., None] = lambda: None,
) -> Callable[..., Callable[..., Any]]:
def decorator(fn: Callable[..., Any]):
@inject
def wrapper(
feature_flag_router: FeatureFlagRouter[FeatureFlag],
injector: Injector,
):
if feature_flag_router.feature_is_enabled(feature_flag_name):
enabled_callback()
else:
disabled_callback()

return injector.call_with_injection(fn)

return wrapper

return decorator

0 comments on commit d5d2242

Please sign in to comment.