Skip to content

Instantly share code, notes, and snippets.

@doubledare704
Created August 23, 2021 08:33
Show Gist options
  • Save doubledare704/516c42beb5465f5722053ebc6b0dda7e to your computer and use it in GitHub Desktop.
Save doubledare704/516c42beb5465f5722053ebc6b0dda7e to your computer and use it in GitHub Desktop.
decorator for properties, that will try to get ENV variable or return value from property method.
import os
from typing import Optional, Any
def get_env_var(var_name: str) -> Optional[str]:
return os.environ.get(var_name)
def env_prop(fn=None, name=None):
def env_prop_decorator(func):
env_name = name or func.__name__.upper()
def wrapper(*args: Any, **kwargs: Any) -> Optional[str]:
return get_env_var(env_name) or func(*args, **kwargs)
return property(wrapper)
if fn is None:
return env_prop_decorator
return env_prop_decorator(fn)
# example
class LocalConf:
@env_prop
def debug(self) -> bool:
return True
@env_prop
def host(self) -> str:
return '0.0.0.0'
@env_prop
def port(self) -> int:
return 80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment