-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetenv.py
61 lines (47 loc) · 1.46 KB
/
getenv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from __future__ import annotations
import os
from typing import Callable
from typing import overload
from typing import Type
from typing import TypeVar
ENV_FILE_COMMENT = '#'
T = TypeVar('T')
_MISSING = object()
@overload
def getenv(name: str, *, default: str = None) -> str: ...
@overload
def getenv(name: str, *, as_: Type[bool], default: bool) -> bool: ...
@overload
def getenv(name: str, *, as_: Type[str] = str, default: str) -> str: ...
@overload
def getenv(name: str, *, as_: Callable[[str], T]) -> T: ...
def getenv(
name: str,
*,
as_: Callable[[str], T] | Type[bool] | Type[str] = str,
default: T | bool | str | None = None,
) -> T | bool | str:
if os.environ.get(name, _MISSING) == _MISSING and default is not None:
return default
value = os.environ[name]
if isinstance(as_, type) and issubclass(as_, bool):
if value.lower() in ('false', ''):
return False
else:
return True
return as_(value)
def load_env_file(path: str = '.env') -> None:
try:
with open(path) as f:
for line in f:
if not line.strip():
continue
if line.startswith(ENV_FILE_COMMENT):
continue
key, value = [item.strip() for item in line.split('=', maxsplit=1)]
os.environ[key] = value
except ValueError as e:
raise ValueError(line)
except IOError as e:
print(e)
load_env_file()