Skip to content

fix: expand ~ in find_dotenv and the %dotenv magic - #714

Merged
theskumar merged 2 commits into
mainfrom
fix/find-dotenv-expanduser
Oct 1, 2026
Merged

theskumar merged 2 commits into
mainfrom
fix/find-dotenv-expanduser

Conversation

@theskumar

Copy link
Copy Markdown
Owner

Follow-up to #615 (#525), which made dotenv_path and the CLI --file option expand a leading ~. Two entry points still didn't:

HOME/.env exists before after
find_dotenv("~/.env") '' '<home>/.env'
IPython %dotenv ~/.env nothing loaded loaded

Why it's a separate PR: find_dotenv searches upward for filename, so expanding ~ changes what a search function does with its argument. It already returns an absolute filename unchanged when it exists (os.path.join(dir, "/abs") is "/abs"), and this treats ~/... the same way. The only behaviour change is that find_dotenv("~/.env") no longer looks for a literal ~ directory in each parent, which seems very unlikely to be intended.

Change: one line at the top of find_dotenv, plus a docstring note. The README's %dotenv section gets a ~/path/to/.env example.

Tests: test_find_dotenv_expands_user and test_ipython_path_expands_user both fail without the fix and pass with it. Both set HOME and USERPROFILE so they work on Windows. Locally: 288 passed, ruff and format are clean, and mypy passes on 3.10 and 3.14.

find_dotenv joins filename onto each directory it searches, so an absolute
filename is already returned as is when it exists, but `~/.env` was
searched for literally. Expand it first, which also fixes IPython's
`%dotenv ~/.env`. Follows #615, which did the same for dotenv_path and
the CLI --file option.
@theskumar
theskumar merged commit 0b28805 into main Oct 1, 2026
9 checks passed
@theskumar
theskumar deleted the fix/find-dotenv-expanduser branch October 1, 2026 07:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant