python-dotenv icon indicating copy to clipboard operation
python-dotenv copied to clipboard

Do you plan to call os.path.expandvars?

Open Hajime-Saitou opened this issue 3 years ago • 1 comments

I request to be able to fill in the environment variable name by calling os.path.environmentvars when setting the value in main.py#L98.

An environment variable name is, for example, %TEMP% (in Windows).

[.env]
LOG_DIR=%TEMP%\log

If possible, it would be nice if it could be called recursively. os.path.expandvars will only expand the environment variable name once.

def expandvarsRecursive(value):.
    expanded = os.path.expandvars(value)
    return value if expanded == value else expandvarsRecursive(expanded)

The reason for this is that if it is called recursively, we don't have to keep track of the same values.

[.env]
PROJECT_HOME=C:\project
LOG_DIR=%PROJECT_HOME%\log
TRACE_LOG_DIR=%LOG_DIR%\trace

Please consider this.

Hajime-Saitou avatar May 12 '23 14:05 Hajime-Saitou

For the examples here, you can use python-dotenv's existing ${NAME} interpolation, including on Windows, rather than %NAME%:

PROJECT_HOME=C:\project
LOG_DIR=${PROJECT_HOME}\log
TRACE_LOG_DIR=${LOG_DIR}\trace
TEMP_LOG_DIR=${TEMP}\log

With no conflicting environment values, this resolves LOG_DIR to C:\project\log and TRACE_LOG_DIR to C:\project\log\trace. ${TEMP} can reference the existing process environment variable. These are literal .env file contents, not a Python string; the example uses unquoted paths.

I verified this on Windows with Python 3.12.14 and python-dotenv 1.2.4. %TEMP% remains literal, while the ${...} version and the chain above resolve as shown.

Two caveats:

  • Define file variables before referencing them. This supports the chain in your example, but is not arbitrary recursive expansion or forward-reference resolution.
  • load_dotenv() defaults to override=False: existing environment variables take precedence, including during interpolation. load_dotenv(override=True) and dotenv_values() give earlier file definitions precedence instead. dotenv_values() returns a dictionary without modifying the process environment.

See the documented variable expansion rules. This is an alternative using the current API, not a statement about plans to add os.path.expandvars().

Master-Norna avatar Oct 13 '26 10:10 Master-Norna