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

feat: unlink_after_load - unlink .env file after calling load_dotenv

Open sha1cybr opened this issue 2 months ago • 0 comments

Add unlink_after_load parameter to load_dotenv() function

Summary

This PR adds a new optional boolean parameter unlink_after_load to the load_dotenv() function that allows users to automatically remove the .env file after it has been successfully loaded into the environment.

Motivation

This feature is useful for scenarios where:

  • Temporary .env files are created programmatically and need cleanup after use
  • Security-sensitive environments where .env files should be removed after loading to prevent exposure
  • CI/CD pipelines that generate temporary configuration files
  • Applications that process multiple .env files and want to clean up after each one

Changes

API Changes

Added a new parameter to load_dotenv():

  • unlink_after_load (bool, default: False): Whether to remove the .env file after successfully loading it

Implementation Details

  • File removal only occurs after successful loading of environment variables
  • Only works when dotenv_path is provided (ignored when using stream parameter)
  • Handles errors gracefully - file removal failures don't affect the loading process
  • Includes debug logging for both successful removals and failures
  • Maintains full backward compatibility (default behavior unchanged)

Usage Examples

Basic Usage

from dotenv import load_dotenv

# Load .env file and remove it after loading
load_dotenv('.env.temp', unlink_after_load=True)

With Other Parameters

# Load with custom encoding and remove file
load_dotenv(
    dotenv_path='config.env',
    encoding='utf-8',
    override=True,
    unlink_after_load=True
)

Temporary Configuration Pattern

import tempfile
from dotenv import load_dotenv

# Create temporary .env file
with tempfile.NamedTemporaryFile(mode='w', suffix='.env', delete=False) as f:
    f.write('DATABASE_URL=postgresql://localhost/mydb\n')
    f.write('DEBUG=True\n')
    temp_env_path = f.name

# Load and automatically clean up
load_dotenv(temp_env_path, unlink_after_load=True)
# File is now removed, but environment variables are set

Error Handling

The function handles various edge cases gracefully:

  • Non-existent files: No error, function returns False as usual
  • Permission errors: File removal failure is logged but doesn't affect the return value
  • Stream usage: unlink_after_load parameter is ignored when using stream instead of dotenv_path

Testing

Added comprehensive test suite covering:

  • ✅ Basic functionality (file removal when unlink_after_load=True)
  • ✅ Default behavior preservation (no removal when unlink_after_load=False)
  • ✅ Edge cases (non-existent files, empty files)
  • ✅ Stream usage (parameter ignored)
  • ✅ Error handling (permission errors)
  • ✅ Verbose logging verification
  • ✅ Backward compatibility

All existing tests continue to pass, ensuring no breaking changes.

Backward Compatibility

This change is fully backward compatible:

  • Default value is False, maintaining existing behavior
  • No changes to existing function signatures or return values
  • All existing code continues to work without modification

Documentation

  • Updated function docstring with parameter description
  • Added clear examples in this PR description
  • Parameter is self-documenting with descriptive name

Type: Enhancement
Breaking Change: No
Tests Added: Yes (8 new test cases)
Documentation Updated: Yes

sha1cybr avatar Oct 19 '25 06:10 sha1cybr