Skip to content

Commit efcad26

Browse files
committed
fix: apply expanduser to dotenv_path (#525)
Apply os.path.expanduser() / Path.expanduser() to dotenv_path so that ~ is properly expanded to the user's home directory. The fix preserves the original type (str stays str, Path stays Path) and is applied in DotEnv.__init__, set_key, and unset_key.
1 parent 09d7cee commit efcad26

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

src/dotenv/main.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ def __init__(
5353
override: bool = True,
5454
) -> None:
5555
self.dotenv_path: Optional[StrPath] = dotenv_path
56+
if isinstance(dotenv_path, str):
57+
self.dotenv_path = os.path.expanduser(dotenv_path)
58+
elif dotenv_path is not None:
59+
self.dotenv_path = pathlib.Path(dotenv_path).expanduser()
5660
self.stream: Optional[IO[str]] = stream
5761
self._dict: Optional[Dict[str, Optional[str]]] = None
5862
self.verbose: bool = verbose
@@ -174,6 +178,10 @@ def set_key(
174178
If the .env path given doesn't exist, fails instead of risking creating
175179
an orphan .env somewhere in the filesystem
176180
"""
181+
if isinstance(dotenv_path, str):
182+
dotenv_path = os.path.expanduser(dotenv_path)
183+
else:
184+
dotenv_path = pathlib.Path(dotenv_path).expanduser()
177185
if quote_mode not in ("always", "auto", "never"):
178186
raise ValueError(f"Unknown quote_mode: {quote_mode}")
179187

@@ -220,6 +228,10 @@ def unset_key(
220228
If the .env path given doesn't exist, fails.
221229
If the given key doesn't exist in the .env, fails.
222230
"""
231+
if isinstance(dotenv_path, str):
232+
dotenv_path = os.path.expanduser(dotenv_path)
233+
else:
234+
dotenv_path = pathlib.Path(dotenv_path).expanduser()
223235
if not os.path.exists(dotenv_path):
224236
logger.warning("Can't delete from %s - it doesn't exist.", dotenv_path)
225237
return None, key_to_unset

0 commit comments

Comments
 (0)