Skip to content

Instantly share code, notes, and snippets.

@lorenzoantei
Created October 31, 2022 15:20
Show Gist options
  • Save lorenzoantei/7c9481c7c8a02ded724d9aa4c7d8563c to your computer and use it in GitHub Desktop.
Save lorenzoantei/7c9481c7c8a02ded724d9aa4c7d8563c to your computer and use it in GitHub Desktop.
python dotenv smart boolean
import os
from pathlib import Path
from dotenv import load_dotenv
def get_variable(var_name: str) -> bool: #semplificazione lettura bools .env
TRUE_=('true', '1', 't') # Add more entries if you want, like: `y`, `yes`, ...
FALSE_=('false', '0', 'f')
value = os.getenv(var_name, 'False').lower() # return `False` if variable is not set. To raise an error, change `'False'` to `None`
if value not in TRUE_ + FALSE_:
raise ValueError(f'Invalid value `{value}` for variable `{var_name}`')
return value in TRUE_
#print("reading up env vars")
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment