Last active
July 29, 2019 01:30
-
-
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!
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
"""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} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
* IMUBVHCIO = In My Unassailable But Very Humble and Completely Impartial Opinion