Skip to content

Add start_dir argument to find_dotenv - #752

Open
GloballyOptimized wants to merge 1 commit into
theskumar:mainfrom
GloballyOptimized:feat/494-find-dotenv-start
Open

GloballyOptimized wants to merge 1 commit into
theskumar:mainfrom
GloballyOptimized:feat/494-find-dotenv-start

Conversation

@GloballyOptimized

Copy link
Copy Markdown

Closes #494

Adds an optional start_dir argument to find_dotenv to choose where the upward search starts:

find_dotenv(start_dir="services/api")
find_dotenv(start_dir=__file__)  # a file works too; its directory is used

On the earlier question in #494 ("does load_dotenv('/path/to/.env') not solve it?"): an exact path works when you know where the file is, but not when you want the usual upward search starting from somewhere other than the caller's file, e.g. several projects in one repo sharing a .env in a parent folder. It also gives callers a deterministic way around the stack-frame detection, which is behind reports like #499, #531 and #596.

When start_dir is given, the stack isn't inspected at all, and it takes precedence over usecwd. ~ is expanded, and a start path that doesn't exist raises the same "Starting path not found" error as before. Calls without start_dir are unchanged.

Tests: 7 new cases in tests/test_main.py, covering upward search, str/Path/file inputs, no stack inspection, precedence over usecwd, ~ expansion, not found, and a missing start path. They fail without the change and pass with it. The rest of the suite passes locally on Windows / Python 3.11, apart from CLI tests that pick up an older global dotenv on my PATH, which is unrelated to this change. ruff and mypy are clean.

If adding a parameter here isn't the direction you want for find_dotenv, no problem: let me know and I'll close this PR.

This was prepared with AI assistance (Claude Code); I reviewed and tested it.

find_dotenv() either searches from the current directory (usecwd=True or
an interactive session) or infers the caller's file by walking the stack.
There was no way to say where the search should start, short of changing
the working directory.

`start_dir` sets the starting point explicitly: a directory, or a file
whose directory is used (e.g. `find_dotenv(start_dir=__file__)`). When it
is given, the stack is not inspected at all, so the search no longer
depends on how the code was invoked. `~` is expanded, and a start path
that does not exist raises the same IOError as before.

Closes theskumar#494

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Consider allowing directory to search for in find_dotenv

1 participant