Last active
December 2, 2024 18:40
-
-
Save costa86/6111dbb7edd1651d5e849888246adce1 to your computer and use it in GitHub Desktop.
Feature flags from json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
def read_json_file(file_path: str) -> dict: | |
""" | |
Reads a JSON file and returns a dictionary containing its data. | |
Args: | |
file_path: The path to the JSON file to read. | |
Returns: | |
A dictionary containing the data from the JSON file. | |
""" | |
with open(file_path, "r") as file: | |
data = json.load(file) | |
return data | |
feature_flags = read_json_file("data.json") | |
def get_feature_flag_state(feature_name: str, feature_flags: dict) -> bool: | |
""" | |
Checks if a feature is enabled or not. | |
Args: | |
feature_name: The name of the feature to check. | |
feature_flags: The dictionary of all feature flags. | |
Returns: | |
A boolean indicating if the feature is enabled or not. | |
""" | |
return feature_flags["features"].get(feature_name, False) | |
def feature_1(number: int): | |
print(f"Feature 1 with number {number}") | |
def feature_2(number: int): | |
print(f"Feature 2 with number {number}") | |
def feature_flag(feature: str, feature_flags: dict = feature_flags): | |
""" | |
A decorator that will swap the function with another one based on a feature flag. | |
Args: | |
feature: The name of the feature flag to check. | |
feature_flags: The dictionary with all the feature flags. | |
Returns: | |
A function that will be called with the same arguments as the original function. | |
If the feature flag is turned on, it will call the function associated with that | |
feature instead of the original function. | |
""" | |
choices = {"feature_1": feature_1, "feature_2": feature_2} | |
def outer(func): | |
def inner(*args, **kwargs): | |
if not get_feature_flag_state(feature, feature_flags): | |
func(*args, **kwargs) | |
return | |
choices[feature](*args, **kwargs) | |
return inner | |
return outer | |
@feature_flag("feature_1") | |
def main(number: int): | |
print(f"Current feature with number {number}") | |
main(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment