Skip to content

Instantly share code, notes, and snippets.

@AlTosterino
Created June 14, 2024 12:24
Show Gist options
  • Save AlTosterino/b749b1cc5003dada31ac6d58081ae339 to your computer and use it in GitHub Desktop.
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
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