|
6 | 6 | import hashlib |
7 | 7 | import logging |
8 | 8 | from abc import ABC |
9 | | -from typing import List, Optional, Dict, Tuple, Any, Mapping |
| 9 | +from typing import List, Optional, Dict, Tuple, Any, Mapping, Callable |
10 | 10 | from ._models import FeatureFlag, Variant, VariantAssignmentReason, TargetingContext, EvaluationEvent, VariantReference |
11 | 11 |
|
12 | 12 |
|
@@ -77,6 +77,7 @@ def __init__(self, configuration: Mapping[str, Any], **kwargs: Any): |
77 | 77 | self._cache: Dict[str, Optional[FeatureFlag]] = {} |
78 | 78 | self._copy = configuration.get(FEATURE_MANAGEMENT_KEY) |
79 | 79 | self._on_feature_evaluated = kwargs.pop("on_feature_evaluated", None) |
| 80 | + self._targeting_context_accessor: Optional[Callable[[],TargetingContext]] = kwargs.pop("targeting_context_accessor", None) |
80 | 81 |
|
81 | 82 | @staticmethod |
82 | 83 | def _assign_default_disabled_variant(evaluation_event: EvaluationEvent) -> None: |
@@ -229,9 +230,17 @@ def _build_targeting_context(self, args: Tuple[Any]) -> TargetingContext: |
229 | 230 | if len(args) == 1: |
230 | 231 | arg = args[0] |
231 | 232 | if isinstance(arg, str): |
| 233 | + # If the user_id is provided, return a TargetingContext with the user_id |
232 | 234 | return TargetingContext(user_id=arg, groups=[]) |
233 | 235 | if isinstance(arg, TargetingContext): |
| 236 | + # If a TargetingContext is provided, return it |
234 | 237 | return arg |
| 238 | + elif self._targeting_context_accessor and callable(self._targeting_context_accessor): |
| 239 | + # If a targeting_context_accessor is provided, return the TargetingContext from it |
| 240 | + targeting_context = self._targeting_context_accessor() |
| 241 | + if targeting_context and isinstance(targeting_context, TargetingContext): |
| 242 | + return targeting_context |
| 243 | + logging.warning("targeting_context_accessor did not return a TargetingContext") |
235 | 244 | return TargetingContext() |
236 | 245 |
|
237 | 246 | def _assign_allocation(self, evaluation_event: EvaluationEvent, targeting_context: TargetingContext) -> None: |
|
0 commit comments