Skip to content

Instantly share code, notes, and snippets.

@a-luna
Last active July 29, 2019 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-luna/ba1827d1c31105ac59588f8cfeee3d3c to your computer and use it in GitHub Desktop.
Save a-luna/ba1827d1c31105ac59588f8cfeee3d3c to your computer and use it in GitHub Desktop.
Parse the text of a .env file to a dictionary of environment variables using only the Python standard library. IMUBVHCIO*, the list/dict comprehensions perfectly straddle the line between an elegant use of syntax and an infinitely dense mass of code (the dreaded "neutron star effect"). And extra bonus: Type hints!
"""Parse .env file to a dictionary of environment variables."""
import errno
import os
from pathlib import Path
from typing import Dict, List
def parse_dotenv_file(filepath: Path) -> Dict[str, str]:
"""Parse .env file to a dictionary of environment variables."""
if not filepath.exists():
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filepath)
if not filepath.is_file():
raise TypeError(f"Unable to open file: {filepath}")
def sanitize_string(input: str) -> str:
return input.strip('"').strip("'").strip()
def parse_env_var_strings(filepath: Path) -> List[List[str]]:
return [
s.split("=") for s in [f for f in filepath.read_text().split("\n") if f and "=" in f]
]
return {v[0]: sanitize_string(v[1]) for v in parse_env_var_strings(filepath) if len(v) == 2}
@a-luna
Copy link
Author

a-luna commented Jul 27, 2019

* IMUBVHCIO = In My Unassailable But Very Humble and Completely Impartial Opinion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment