Created
June 14, 2024 12:24
-
-
Save AlTosterino/b749b1cc5003dada31ac6d58081ae339 to your computer and use it in GitHub Desktop.
Access env variable in enum manner -- useful for feature flags based on environment variables
This file contains 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 os | |
from enum import Flag | |
from typing import Any | |
class EnvFlag: # Descriptor | |
def __init__(self, name: str) -> None: | |
self.name = name | |
def __get__(self, instance: Any, owner: Any) -> bool: | |
return bool(os.environ.get(self.name, False)) | |
class FeatureFlag(Flag): | |
LOGIN = EnvFlag("LOGIN") | |
# No LOGIN env variable set | |
print("No env:", FeatureFlag.LOGIN) | |
os.environ["LOGIN"] = "1" | |
print("Env as '1':", FeatureFlag.LOGIN) | |
os.environ["LOGIN"] = "True" | |
print("Env as 'True':", FeatureFlag.LOGIN) | |
os.environ["LOGIN"] = "" | |
print("Env as '':", FeatureFlag.LOGIN) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment