### Getting Started Quickly Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/GENERATION_SUMMARY.txt For a quick start, begin with `README.md` for an overview, then consult `quick-reference.md` for common patterns. You can copy and modify the provided examples as needed. ```APIDOC ## Quick Start Guide ### Overview 1. Read `README.md` for an overview. ### Common Patterns 2. See `quick-reference.md` for common patterns. ### Examples 3. Copy and modify examples as needed. ``` -------------------------------- ### Basic Notebook Setup Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Demonstrates the initial setup in a Jupyter notebook: loading the extension and then loading the .env file. Shows how to access a loaded environment variable. ```python # In a Jupyter notebook cell %load_ext dotenv %dotenv # Now all variables from .env are available import os print(os.environ.get("DATABASE_URL")) ``` -------------------------------- ### Serve Documentation Locally with mkdocs Source: https://github.com/theskumar/python-dotenv/blob/main/CONTRIBUTING.md Build and serve the project documentation locally using `mkdocs`. This requires installing documentation dependencies and the project itself. ```shell $ uv pip install -r requirements-docs.txt $ uv pip install -e . $ uv run mkdocs serve ``` -------------------------------- ### Basic %dotenv Usage Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Load environment variables from a .env file located in the current or parent directories. This is the simplest way to get started. ```python # Load .env from the current directory or parent directories %dotenv ``` -------------------------------- ### Install pre-commit Hooks Source: https://github.com/theskumar/python-dotenv/blob/main/CONTRIBUTING.md Install `pre-commit` hooks to maintain code quality and consistency. This command should be run within the development environment. ```shell $ uv run precommit install ``` -------------------------------- ### Install python-dotenv Source: https://github.com/theskumar/python-dotenv/blob/main/docs/index.md Install the python-dotenv package via pip to start managing environment variables. ```shell pip install python-dotenv ``` -------------------------------- ### Full Interpolation Workflow Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-variables.md Demonstrates a complete interpolation process. It simulates environment and .env values, then interpolates each value using `parse_variables` and `atom.resolve`. ```python from dotenv.variables import parse_variables # Simulate environment and .env values env = { "DOMAIN": "example.org", "DEBUG": "true", } # Values from .env file dotenv_values = { "DOMAIN": "example.org", "ADMIN_EMAIL": "admin@${DOMAIN}", "ROOT_URL": "${DOMAIN}/app", "LOG_LEVEL": "${LOG_LEVEL:-info}", } # Interpolate each value interpolated = {} for key, value in dotenv_values.items(): if value is None: interpolated[key] = None else: atoms = parse_variables(value) interpolated[key] = "".join(atom.resolve(env) for atom in atoms) print(interpolated) # Output: # { # 'DOMAIN': 'example.org', # 'ADMIN_EMAIL': 'admin@example.org', # 'ROOT_URL': 'example.org/app', # 'LOG_LEVEL': 'info' # } ``` -------------------------------- ### Run Tests with uv Source: https://github.com/theskumar/python-dotenv/blob/main/CONTRIBUTING.md Execute tests and linters using the `uv` command. Ensure you have installed dependencies and the project in editable mode. ```shell $ uv venv $ uv pip install -r requirements.txt $ uv pip install -e . $ uv ruff check . $ uv format . $ uv run pytest ``` -------------------------------- ### Verbose Loading Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Demonstrates loading a .env file with the verbose flag enabled. The output will provide details about the loading process, including file location and any warnings. ```python # Load with verbose output to see what's being loaded %load_ext dotenv %dotenv -v # Output will show: # - File location if found # - Warnings about parsing errors # - Confirmation of variables set ``` -------------------------------- ### Interactive Configuration Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Demonstrates how to use %dotenv interactively to load a shared configuration file first, and then override specific settings with a local .env file in a subsequent step. This allows for layered configuration. ```python # Cell 1: Load base configuration %load_ext dotenv %dotenv .env.shared -v # Cell 2: Override specific variables for this session %dotenv .env.local -o # Now the notebook uses shared settings with local overrides ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/START_HERE.md Demonstrates common commands for the python-dotenv command-line interface, including listing variables, setting variables, and running scripts with loaded environment variables. ```bash dotenv list dotenv set KEY value dotenv run python app.py ``` -------------------------------- ### CLI Configuration Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/configuration.md Manage .env file configurations using the command-line interface. Supports setting variables with automatic quoting, exporting as a bash script, and viewing configuration in JSON format. ```bash # Set values with automatic quoting dotenv -q auto set SIMPLE_VAR simple dotenv -q auto set COMPLEX_VAR "value with spaces" # Export as bash script dotenv -e list > config.sh source config.sh # View current configuration in JSON dotenv list --format json | python -m json.tool ``` -------------------------------- ### Python-dotenv CLI Usage Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-cli.md Demonstrates common commands for the dotenv CLI, including specifying a file, setting quote behavior, and listing variables with export statements. ```bash dotenv [OPTIONS] COMMAND [ARGS]... ``` ```bash dotenv -f /etc/myapp/.env list dotenv --quote auto set KEY value dotenv -e list # Output with export statements ``` -------------------------------- ### Typical Data Science Workflow Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Illustrates a common data science workflow in a Jupyter notebook: setting up the environment by loading .env variables, loading necessary libraries, and then connecting to a database using the loaded credentials. ```python # Cell 1: Setup environment %load_ext dotenv %dotenv # Cell 2: Load libraries with configured parameters import os import pandas as pd from sqlalchemy import create_engine db_url = os.environ.get("DATABASE_URL") api_key = os.environ.get("API_KEY") # Cell 3: Connect to database engine = create_engine(db_url) # Cell 4: Analysis df = pd.read_sql("SELECT * FROM table", engine) df.head() ``` -------------------------------- ### Automated Configuration Setup with dotenv CLI Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-cli.md Shows how to automatically set environment variables in a configuration file using values from the CI environment and system commands like `date`. ```bash #!/bin/bash # Set up configuration from environment dotenv -f .env.auto set BUILD_ID "${CI_BUILD_ID}" dotenv -f .env.auto set COMMIT_SHA "${CI_COMMIT_SHA}" dotenv -f .env.auto set BUILD_TIME "$(date -u +%Y-%m-%dT%H:%M:%SZ)" # List final configuration dotenv -f .env.auto list --format json ``` -------------------------------- ### Run Applications with dotenv CLI Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-cli.md Examples of running applications using the `dotenv run` command, specifying different configuration files for development, production, and testing environments. ```bash # Development with hot-reload dotenv -f .env.development run python -m uvicorn app:app --reload # Production with specific config dotenv -f .env.production run gunicorn wsgi:app --workers 4 # Run tests with test environment dotenv -f .env.test run pytest tests/ ``` -------------------------------- ### Development with Environment Isolation Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Shows loading a specific development .env file with verbose output in one cell, and then using the loaded variables in a subsequent cell. Assumes a .env.development file exists. ```python # Notebook cell 1: Load development configuration %load_ext dotenv %dotenv .env.development -v # Notebook cell 2: Use the loaded variables import os db_url = os.environ.get("DATABASE_URL") api_key = os.environ.get("API_KEY") # Create client with loaded configuration # client = MyClient(db_url=db_url, api_key=api_key) ``` -------------------------------- ### Run Tests with tox Source: https://github.com/theskumar/python-dotenv/blob/main/CONTRIBUTING.md An alternative method to run tests using `tox` if it is installed. ```shell $ tox ``` -------------------------------- ### API Reference Navigation Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/GENERATION_SUMMARY.txt To find information about a specific function, start with INDEX.md in the Function Reference section and click the link to the corresponding api-reference-*.md file. Each file contains the function's signature, parameters, return value, behavior, and examples. ```APIDOC ## API Reference ### Navigation 1. Start at `INDEX.md` (Function Reference section). 2. Click the link to `api-reference-*.md` for the desired function. ### File Contents Each API reference file includes: - Signature - Parameters - Return Value - Behavior - Examples ``` -------------------------------- ### .env File Comments Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/quick-reference.md Lines starting with '#' are comments. Inline comments are also supported. ```bash # This is a comment KEY=value # Inline comment ``` -------------------------------- ### Get Configuration as Dictionary Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/START_HERE.md Retrieve all key-value pairs from a .env file as a Python dictionary. This is useful for accessing configuration without modifying the environment. ```python from dotenv import dotenv_values config = dotenv_values(".env") print(config["DATABASE_URL"]) ``` -------------------------------- ### Error Handling Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Shows how the %dotenv command handles cases where the specified .env file does not exist. The command prints an informative message but does not raise an error, allowing execution to continue. ```python # In a Jupyter notebook %load_ext dotenv %dotenv .env.missing # File doesn't exist # Prints: "cannot find .env file" # Execution continues without error ``` -------------------------------- ### find_dotenv with usecwd=True Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-find_dotenv.md Explicitly starts the search for a .env file from the current working directory, regardless of the script's location. Requires changing the directory first. ```python from dotenv import find_dotenv import os os.chdir("/home/user/myproject") path = find_dotenv(usecwd=True) # Starts searching from /home/user/myproject upward ``` -------------------------------- ### Extract Configuration with Error Handling Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-parser.md Parse a stream of environment variable definitions and extract them into a dictionary. This example demonstrates handling quoted values and basic error checking by only adding bindings with both a key and a value. ```python from io import StringIO from dotenv.parser import parse_stream stream = StringIO(""" export DATABASE_URL='postgres://localhost' API_KEY="secret123" DEBUG=true """) config = {} for binding in parse_stream(stream): if not binding.error and binding.key is not None and binding.value is not None: config[binding.key] = binding.value print(config) # Output: {'DATABASE_URL': 'postgres://localhost', 'API_KEY': 'secret123', 'DEBUG': 'true'} ``` -------------------------------- ### Command-line interface for .env manipulation Source: https://github.com/theskumar/python-dotenv/blob/main/README.md Provides a CLI tool to manage .env files, including setting variables, listing them, and running scripts with loaded environment variables. Requires installing with the 'cli' extra. ```shell pip install "python-dotenv[cli]" ``` ```shell $ dotenv set USER foo ``` ```shell $ dotenv set EMAIL foo@example.org ``` ```shell $ dotenv list ``` ```shell $ dotenv list --format=json { "USER": "foo", "EMAIL": "foo@example.org" } ``` ```shell $ dotenv run -- python foo.py ``` -------------------------------- ### Core Functions Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/README.md These are the primary functions for interacting with .env files. They allow loading, parsing, finding, getting, setting, and unsetting values. ```APIDOC ## Core Functions ### `load_dotenv()` ### Description Loads variables from a .env file into the environment. ### Purpose Load `.env` into `os.environ` ### `dotenv_values()` ### Description Parses a .env file and returns its contents as a dictionary. ### Purpose Parse `.env` as dictionary ### `find_dotenv()` ### Description Locates the nearest .env file in the directory hierarchy. ### Purpose Locate `.env` file ### `get_key()` ### Description Retrieves a specific value from a .env file. ### Purpose Get single value ### `set_key()` ### Description Sets or updates a specific key-value pair in a .env file. ### Purpose Set/update value ### `unset_key()` ### Description Removes a specific key-value pair from a .env file. ### Purpose Remove value ``` -------------------------------- ### DotEnv class Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/INDEX.md Represents a .env file and provides methods for interacting with its contents, such as getting values or setting them as environment variables. ```APIDOC ## DotEnv class ### Description Represents a .env file and provides methods for interacting with its contents. ### Methods - `set_as_environment_variables()`: Sets variables from the .env file into the environment. Returns True if variables were set. - `dict()`: Returns the parsed configuration as a dictionary. - `get(key)`: Retrieves the value for a given key. Returns the value or None if not found. ### Return Values - `set_as_environment_variables()`: bool - True if variables were set. - `dict()`: Dict[str, Optional[str]] - Parsed configuration dictionary. - `get()`: Optional[str] - Value or None. ``` -------------------------------- ### Override System Environment Example Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Loads a specific .env file with the override option, ensuring that variables defined in the .env file take precedence over any existing system environment variables. Verifies the override by printing a variable. ```python # Load a specific .env file and override system environment %load_ext dotenv %dotenv -o .env.test # Now test environment variables take precedence import os print(os.environ.get("ENVIRONMENT")) # "test" ``` -------------------------------- ### Define Multiline Values in .env Source: https://github.com/theskumar/python-dotenv/blob/main/README.md Demonstrates how to define multiline strings within a .env file using double quotes. The two examples show how to use literal newlines or escape sequences to represent multiline content. ```bash FOO="first line second line" ``` ```bash FOO="first line\nsecond line" ``` -------------------------------- ### Retrieve a Specific Environment Variable Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-DotEnv.md Get the value of a specific environment variable defined in the .env file using the `get()` method. ```python from dotenv.main import DotEnv dotenv = DotEnv(".env") database_url = dotenv.get("DATABASE_URL") if database_url: print(f"Connecting to {database_url}") ``` -------------------------------- ### Get Environment Variable (CLI) Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/quick-reference.md Retrieves the value of an environment variable using the dotenv CLI. ```bash dotenv get API_KEY ``` -------------------------------- ### Configuration Options Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/GENERATION_SUMMARY.txt Detailed information about all configuration parameters can be found in `configuration.md`. Each parameter entry includes its type, default value, and guidance on when to use it. The file format section explains the .env syntax. ```APIDOC ## Configuration Details ### Parameters Refer to `configuration.md` for all parameters. Each parameter lists: - Type - Default value - When to use ### File Format See the file format section for `.env` syntax explanation. ``` -------------------------------- ### Get Single Value from .env Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/quick-reference.md Retrieves a specific value for a given key from a .env file. Returns None if the key is not found. ```python from dotenv import get_key value = get_key(".env", "API_KEY") # Returns None if not found ``` -------------------------------- ### Manage Configuration Files with dotenv CLI Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-cli.md Demonstrates copying a template .env file, populating it with default values using `dotenv set`, and viewing the configuration in JSON format. ```bash # Copy from template cp .env.example .env # Populate with defaults dotenv set ENVIRONMENT "development" dotenv set LOG_LEVEL "debug" # View configuration dotenv list --format json | jq . ``` -------------------------------- ### Basic Usage of DotEnv Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-DotEnv.md Instantiate DotEnv with a file path and retrieve all variables as a dictionary. ```python from dotenv.main import DotEnv dotenv = DotEnv(".env") values = dotenv.dict() print(values) # {"KEY": "value", "DEBUG": "true", ...} ``` -------------------------------- ### parse_key Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-parser.md Parses and extracts a key from the current position in a Reader. It supports single-quoted and unquoted keys and returns None if the line starts with a comment. ```APIDOC ## parse_key(reader: Reader) -> Optional[str] ### Description Parses a key from the current position. ### Returns The key string, or `None` if the line is a comment (starts with `#`). ### Supports - Single-quoted keys: `'MY_KEY'` - Unquoted keys: `MY_KEY` ### Example ```python from io import StringIO from dotenv.parser import Reader, parse_key reader = Reader(StringIO("MY_KEY=value")) key = parse_key(reader) print(key) # "MY_KEY" ``` ``` -------------------------------- ### Basic find_dotenv Usage Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-find_dotenv.md Finds the .env file starting from the current directory and searching upwards. Prints the absolute path of the found file. ```python from dotenv import find_dotenv path = find_dotenv() print(path) # "/path/to/project/.env" ``` -------------------------------- ### Trigger IOError if starting path does not exist Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/errors.md Illustrates the scenario where find_dotenv raises an IOError because the initial directory for traversal does not exist. This is rare in normal usage. ```python from dotenv import find_dotenv # Raises IOError if the caller's script directory doesn't exist path = find_dotenv() ``` -------------------------------- ### find_dotenv in REPL Context Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-find_dotenv.md Shows that when find_dotenv is called from an interactive Python session (REPL), it defaults to starting the search from the current working directory (os.getcwd()). ```python # When called from an interactive Python session: from dotenv import find_dotenv path = find_dotenv() # Starts from current working directory (os.getcwd()) ``` -------------------------------- ### List .env variables in simple format Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-cli.md Displays all key-value pairs from the .env file in a simple KEY=value format. This is the default output format. ```bash $ dotenv list ``` -------------------------------- ### Basic .env File Format Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/quick-reference.md Standard key-value pairs for environment variables. ```bash KEY=value DEBUG=true DATABASE_URL=postgres://localhost/db ``` -------------------------------- ### Build Configuration with Defaults Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-variables.md Constructs configuration dictionaries by resolving template strings that include environment variables and default values. This pattern is effective for generating application settings dynamically. ```python from dotenv.variables import parse_variables # .env-like values env_values = { "PROJECT": "myapp", "VERSION": "1.0", "BUILD_NUMBER": None, # Not set } # Configuration templates templates = { "build_tag": "${PROJECT}:${VERSION:-latest}", "build_id": "${PROJECT}-${BUILD_NUMBER:-dev}", "log_prefix": "[${PROJECT}] ", } config = {} for key, template in templates.items(): atoms = parse_variables(template) resolved = "".join(atom.resolve(env_values) for atom in atoms) config[key] = resolved print(config) # Output: # { # 'build_tag': 'myapp:1.0', # 'build_id': 'myapp-dev', # 'log_prefix': '[myapp] ' # } ``` -------------------------------- ### Get Key from .env File Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-get_key.md Use this to retrieve the value of a specific environment variable from a .env file. Ensure the .env file exists in the specified path. ```python from dotenv import get_key value = get_key(".env", "DATABASE_URL") print(value) # "postgres://localhost/mydb" ``` -------------------------------- ### Parse Unquoted Value and Remove Comments Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-parser.md Use `parse_unquoted_value` to extract an unquoted value, stripping any trailing comment text starting with '#' and removing whitespace from the end. ```python from io import StringIO from dotenv.parser import Reader, parse_unquoted_value reader = Reader(StringIO("value # comment text")) value = parse_unquoted_value(reader) print(value) # "value" ``` -------------------------------- ### Build Configuration with Defaults Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-variables.md Shows how to use `parse_variables` to build configuration values, incorporating default values for variables that might not be set. ```APIDOC ## Build Configuration with Defaults ### Description Use `parse_variables` to construct configuration settings, providing default values for environment variables that may not be defined. ### Usage ```python from dotenv.variables import parse_variables # .env-like values env_values = { "PROJECT": "myapp", "VERSION": "1.0", "BUILD_NUMBER": None, # Not set } # Configuration templates templates = { "build_tag": "${PROJECT}:${VERSION:-latest}", "build_id": "${PROJECT}-${BUILD_NUMBER:-dev}", "log_prefix": "[${PROJECT}] ", } config = {} for key, template in templates.items(): atoms = parse_variables(template) resolved = "".join(atom.resolve(env_values) for atom in atoms) config[key] = resolved print(config) # Output: # { # 'build_tag': 'myapp:1.0', # 'build_id': 'myapp-dev', # 'log_prefix': '[myapp] ' # } ``` ``` -------------------------------- ### Variable Expansion with Defaults Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-load_dotenv.md Demonstrates how variable expansion works with default values. If a referenced environment variable is not set, the specified default value is used. ```text # In .env file: # DOMAIN=example.com # API_URL=${BASE_URL:-https://api.example.com} ``` ```python from dotenv import load_dotenv load_dotenv() # If BASE_URL is not set, API_URL will be "https://api.example.com" ``` -------------------------------- ### load_dotenv() Execution Flow Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/module-overview.md Illustrates the sequence of operations when load_dotenv() is called, from checking environment variables to setting them in os.environ. ```text load_dotenv() ├─ Check PYTHON_DOTENV_DISABLED ├─ If dotenv_path not provided: │ └─ find_dotenv() ├─ Create DotEnv instance │ ├─ Initialize with parameters │ └─ Open stream (file or provided stream) ├─ Call set_as_environment_variables() │ ├─ Parse stream (parse_stream) │ ├─ Resolve variables (if interpolate=True) │ │ └─ parse_variables for each value │ ├─ Filter and cache results │ └─ Set os.environ entries └─ Return success boolean ``` -------------------------------- ### get(key: str) Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-DotEnv.md Retrieves a single key's value from the parsed configuration. Logs a warning if `verbose=True` and the key is not found. Returns values from the cached dictionary. ```APIDOC ## get(key: str) ### Description Retrieves a single key's value from the parsed configuration. ### Parameters #### Path Parameters - **key** (str) - Required - The environment variable name to retrieve. ### Returns Optional[str] - The string value if the key exists, `None` otherwise. ### Behavior - Logs a warning if `verbose=True` and the key is not found - Returns values from the cached dictionary (parsed once) ### Example ```python from dotenv.main import DotEnv dotenv = DotEnv(".env", verbose=True) api_key = dotenv.get("API_KEY") ``` ``` -------------------------------- ### Load .env file with override, verbose, and specific path Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/configuration.md Combine options to load from a specific .env file, override existing variables, and enable verbose output. ```python # Both options %dotenv -o -v .env.production ``` -------------------------------- ### Handling Errors with unset_key Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-unset_key.md Shows how to handle potential errors when using unset_key, specifically when the key is not found or the .env file does not exist. It checks if the success status is None to identify these cases. ```python from dotenv import unset_key success, key = unset_key(".env", "API_KEY") if success: print(f"Removed {key}") elif success is None: print(f"Key {key} not found or file does not exist") ``` -------------------------------- ### Detect Variable References in a String Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-variables.md Shows how to extract all variable names referenced within a string value. It uses `parse_variables` to get atoms and checks if an atom is a `Variable` instance. ```python from dotenv.variables import parse_variables, Variable def extract_variable_names(value: str): """Extract all variable names referenced in a value.""" names = set() for atom in parse_variables(value): if isinstance(atom, Variable): names.add(atom.name) return names value = "prefix-${VAR1}-middle-${VAR2:-default}" names = extract_variable_names(value) print(names) # {'VAR1', 'VAR2'} ``` -------------------------------- ### Entry Points Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/README.md Ways to interact with the python-dotenv library through different interfaces. ```APIDOC ## Entry Points ### Python ```python from dotenv import load_dotenv, dotenv_values ``` ### CLI ```bash dotenv list dotenv set dotenv run ``` ### IPython ```ipython %load_ext dotenv %dotenv ``` ``` -------------------------------- ### System Overview Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/GENERATION_SUMMARY.txt To understand the overall system architecture and data flow of python-dotenv, read the `module-overview.md` file. This provides insights into how data moves from files to the environment and the relationships between different modules. ```APIDOC ## System Understanding ### Overview Read `module-overview.md` for architecture details. ### Data Flow Understand how data flows from file to environment. ### Module Relationships Comprehend the relationships between different modules. ``` -------------------------------- ### Load Environment Variables with StrPath Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/types.md Demonstrates loading environment variables using the load_dotenv function with both string and PathLike path arguments. ```python from pathlib import Path from dotenv import load_dotenv # String path load_dotenv(".env") # PathLike object load_dotenv(Path(".env")) ``` -------------------------------- ### Get environment variable from .env file Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-cli.md Retrieves the value of a specific key from the .env file. Exits with code 0 if the key is found and prints its value, or exits with code 1 if the key is not found. ```bash $ dotenv get DATABASE_URL postgres://localhost/mydb $ dotenv get MISSING_KEY # Exits with code 1 ``` -------------------------------- ### load_ipython_extension(ipython) Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md This function serves as the entry point for IPython when the `dotenv` extension is loaded. It is responsible for registering the necessary magics with the IPython shell. ```APIDOC ## load_ipython_extension(ipython) ### Description Entry point called by IPython when the extension is loaded with `%load_ext dotenv`. Registers the `IPythonDotEnv` magics class. ### Method Python Function (Internal to extension loading) ### Endpoint `load_ipython_extension(ipython)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ipython** (IPython.core.interactiveshell.InteractiveShell) - The IPython shell instance. ### Request Example ```python # This function is called internally by IPython # when %load_ext dotenv is executed. ``` ### Response #### Success Response Registers the `IPythonDotEnv` magics class with the provided IPython instance, enabling the `%dotenv` magic command. ``` -------------------------------- ### Load .env file with IPython extension Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/configuration.md Use the %dotenv magic command to load environment variables from a .env file. The -v flag enables verbose output. ```python %load_ext dotenv # Load from current directory, verbose %dotenv -v ``` -------------------------------- ### CLI Exit Code 1 (Command Failed) Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/errors.md Exit code 1 is returned when a CLI command fails, such as a key not being found for 'get' or 'unset', or execution failures for 'run'. Check the exit code using '$?'. ```bash $ dotenv get MISSING_KEY $ echo $? 1 ``` ```bash $ dotenv unset NONEXISTENT_KEY $ echo $? 1 ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-DotEnv.md Instantiate DotEnv with `verbose=True` to log warnings for file not found or parsing errors. ```python from dotenv.main import DotEnv dotenv = DotEnv(".env", verbose=True) dotenv.set_as_environment_variables() # Logs warnings if file not found or parsing errors occur ``` -------------------------------- ### Parse .env and get all key-value pairs as a dictionary Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-DotEnv.md Use this method to retrieve all parsed key-value pairs from the .env file as a Python dictionary. Results are cached after the first call. Variable interpolation is applied if enabled. ```python from dotenv.main import DotEnv dotenv = DotEnv(".env") config = dotenv.dict() print(config["DATABASE_URL"]) ``` -------------------------------- ### Use dotenv CLI Source: https://github.com/theskumar/python-dotenv/blob/main/docs/index.md Manage .env files and run scripts with environment variables using the dotenv command-line interface. ```shell pip install "python-dotenv[cli]" dotenv set USER foo dotenv set EMAIL foo@example.org dotenv list dotenv run -- python foo.py ``` -------------------------------- ### Basic Usage of set_key Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-set_key.md Use this to add a new key-value pair to a .env file or update an existing one. The file will be created if it doesn't exist. ```python from dotenv import set_key set_key(".env", "DATABASE_URL", "postgres://localhost/mydb") ``` -------------------------------- ### Basic Usage of unset_key Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-unset_key.md Demonstrates the basic usage of the unset_key function to remove a variable from the .env file. It checks the success status and prints a confirmation message. ```python from dotenv import unset_key success, key = unset_key(".env", "OLD_VARIABLE") if success: print(f"Successfully removed {key}") ``` -------------------------------- ### load_dotenv Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/INDEX.md Parses a .env file and loads its variables into os.environ. Returns True if variables were set. Use this for typical application startup. ```APIDOC ## load_dotenv ### Description Parses a .env file and loads its variables into `os.environ`. Returns True if variables were set. Use this for typical application startup. ### Signature `load_dotenv(dotenv_path=None, stream=None, verbose=False, override=False, interpolate=True, encoding="utf-8") -> bool` ### Parameters - **dotenv_path** (str, optional) - Path to the .env file. - **stream** (io.TextIOBase, optional) - A readable text stream. - **verbose** (bool, optional) - If true, print messages to stderr when loading. - **override** (bool, optional) - If true, override existing environment variables. - **interpolate** (bool, optional) - If true, expand variable references within the .env file. - **encoding** (str, optional) - Encoding to use when reading the file. ### Returns - **bool** - True if variables were set, False otherwise. ``` -------------------------------- ### Loading the IPython Extension Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Before using the `%dotenv` magic command, you need to load the IPython extension. This is typically done once at the beginning of your IPython or Jupyter session. ```APIDOC ## Loading the Extension ### Description Registers the `%dotenv` magic command with the running IPython kernel or notebook. ### Method IPython Magic Command ### Endpoint `%load_ext dotenv` ### Parameters None ### Request Example ```python %load_ext dotenv ``` ### Response #### Success Response The `dotenv` extension is loaded, making the `%dotenv` magic command available. #### Response Example (No direct response body, the magic command becomes available.) ``` -------------------------------- ### Load dotenv from file Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/module-overview.md Imports for loading dotenv files and accessing their values. ```python from dotenv import load_dotenv, dotenv_values, find_dotenv from dotenv import get_key, set_key, unset_key from dotenv import get_cli_string, load_ipython_extension ``` -------------------------------- ### Using find_dotenv with load_dotenv Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-find_dotenv.md Demonstrates how to use find_dotenv to locate an environment file and then pass its path to load_dotenv. This is equivalent to calling load_dotenv() without arguments. ```python from dotenv import load_dotenv, find_dotenv # Equivalent to calling load_dotenv() with no arguments dotenv_path = find_dotenv() load_dotenv(dotenv_path) ``` -------------------------------- ### Parse configuration from a stream Source: https://github.com/theskumar/python-dotenv/blob/main/docs/index.md Load environment variables from a stream object instead of a physical file using the stream argument. ```python from io import StringIO from dotenv import load_dotenv config = StringIO("USER=foo\nEMAIL=foo@example.org") load_dotenv(stream=config) ``` -------------------------------- ### Load .env files in IPython Source: https://github.com/theskumar/python-dotenv/blob/main/README.md Uses IPython magic commands to load .env files. It can automatically find the .env file or load from a specified path, with options to override existing variables and increase verbosity. ```python %load_ext dotenv %dotenv ``` ```python %dotenv relative/or/absolute/path/to/.env ``` -------------------------------- ### Load .env from a Specific Path Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-load_dotenv.md Specify an absolute or relative path to a .env file if it's not in the default location or has a custom name. This allows loading configuration from a specific file. ```python from dotenv import load_dotenv # Load from a specific file load_dotenv("/path/to/.env.production") ``` -------------------------------- ### Load .env from Current or Parent Directories Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-load_dotenv.md Use this to load environment variables from a .env file located in the current directory or any parent directory. No arguments are needed if the .env file follows the default naming convention. ```python from dotenv import load_dotenv # Load from .env in current directory or parent directories load_dotenv() ``` -------------------------------- ### set_key() Execution Flow Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/module-overview.md Explains the process of modifying a specific key-value pair within a .env file using set_key(). ```text set_key() ├─ Validate quote_mode parameter ├─ Format value with quoting ├─ Optionally add export prefix ├─ Use rewrite() context manager │ ├─ Open source file (or empty StringIO if not exists) │ ├─ Create temp file in same directory │ ├─ Parse source with parse_stream() │ ├─ Write lines to temp file │ │ ├─ Replace matching key line │ │ └─ Append if not found │ ├─ Set file permissions │ ├─ Replace original with temp (atomic on Unix) │ └─ Cleanup on error └─ Return (success, key, value) tuple ``` -------------------------------- ### DotEnv Class Constructor Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-DotEnv.md Initializes a new instance of the DotEnv class. This constructor allows for fine-grained control over how .env files are loaded and processed, including specifying the file path, using streams, enabling verbose logging, setting character encoding, enabling interpolation, and controlling overrides. ```APIDOC ## `DotEnv` Constructor ### Description Initializes a new instance of the DotEnv class. This constructor allows for fine-grained control over how .env files are loaded and processed, including specifying the file path, using streams, enabling verbose logging, setting character encoding, enabling interpolation, and controlling overrides. ### Parameters #### Constructor Parameters - **dotenv_path** (Union[str, os.PathLike[str], None]) - Required - Path to the `.env` file. Can be a string path, `os.PathLike` object, or None if using a stream. - **stream** (IO[str], None) - Optional - Text stream (e.g., `io.StringIO`) containing `.env` content. Used if `dotenv_path` is None. - **verbose** (bool) - Optional - When True, logs informational and warning messages. Defaults to `False`. - **encoding** (str, None) - Optional - Character encoding for file reading. If None, uses system default. - **interpolate** (bool) - Optional - When True, enables POSIX variable expansion. Defaults to `True`. - **override** (bool) - Optional - When True, values from the file override environment variables. When False, environment variables take precedence. Defaults to `True`. ``` -------------------------------- ### run_command(command: List[str], env: Dict[str, str]) Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-cli.md Executes a command with a modified environment. It copies the current environment, updates it with provided variables, and then executes the command. ```APIDOC ## run_command(command: List[str], env: Dict[str, str]) ### Description Executes a command with a modified environment. ### Parameters #### Path Parameters - **command** (List[str]) - Required - The command and its arguments (e.g., `["python", "app.py"]`). - **env** (Dict[str, str]) - Required - Additional environment variables to set. ### Behavior - Creates a copy of `os.environ` and updates it with variables from `env` - On Windows: Uses `Popen` and waits for process completion - On Unix: Uses `os.execvpe` to replace the current process - Exits with code 1 if the command is not found - Returns the command's exit code (Windows) or doesn't return (Unix, process replaced) ### Example ```python from dotenv.cli import run_command run_command(["python", "script.py"], {"API_KEY": "secret123"}) ``` ``` -------------------------------- ### IPython Extension Entry Point Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/INDEX.md The entry point function for loading the python-dotenv extension in IPython or Jupyter environments. This enables the %dotenv magic command. ```python load_ipython_extension(ipython) ``` -------------------------------- ### Merge multiple configuration sources Source: https://github.com/theskumar/python-dotenv/blob/main/docs/index.md Combine multiple .env files and existing environment variables into a single configuration dictionary. ```python import os from dotenv import dotenv_values config = { **dotenv_values(".env.shared"), **dotenv_values(".env.secret"), **os.environ, } ``` -------------------------------- ### Define .env file format Source: https://github.com/theskumar/python-dotenv/blob/main/docs/index.md The .env file supports key-value pairs and variable expansion using the ${VAR} syntax. ```bash # Development settings DOMAIN=example.org ADMIN_EMAIL=admin@${DOMAIN} ROOT_URL=${DOMAIN}/app ``` -------------------------------- ### Load IPython Extension Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-ipython.md Use this command in IPython or Jupyter to register the %dotenv magic command with the current session. ```python %load_ext dotenv ``` -------------------------------- ### List Environment Variables (CLI) Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/quick-reference.md Lists environment variables using the dotenv CLI. Supports JSON and export formats. ```bash dotenv list dotenv list --format json dotenv list --format export ``` -------------------------------- ### CLI Module Imports Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/module-overview.md Imports for the CLI module, including the main entry point. ```python from dotenv.cli import cli from dotenv.__main__ import cli # Entry point ``` -------------------------------- ### Load environment variables from a stream Source: https://github.com/theskumar/python-dotenv/blob/main/README.md Loads environment variables from a stream (e.g., StringIO) instead of a file. This allows loading configuration from various sources like network data. ```python from io import StringIO from dotenv import load_dotenv config = StringIO("USER=foo\nEMAIL=foo@example.org") load_dotenv(stream=config) ``` -------------------------------- ### .env File Keys with No Value Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/quick-reference.md Keys can be defined without a value, resulting in an empty string or null depending on the context. ```bash FEATURE_FLAG EMPTY= ``` -------------------------------- ### Using Custom Encoding with unset_key Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/api-reference-unset_key.md Demonstrates how to specify a custom encoding when removing a key from a .env file, useful for files not using the default UTF-8 encoding. ```python from dotenv import unset_key # Remove from a file with UTF-16 encoding unset_key(".env", "TEMP_VAR", encoding="utf-16") ``` -------------------------------- ### Parse .env Stream with Binding Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/types.md Parses a stream of .env content and iterates over the resulting Binding objects. Shows how to access key, value, and error status from each binding. ```python from io import StringIO from dotenv.parser import parse_stream stream = StringIO("KEY=value") for binding in parse_stream(stream): print(f"key={binding.key}, value={binding.value}, error={binding.error}") ``` -------------------------------- ### find_dotenv() Execution Flow Source: https://github.com/theskumar/python-dotenv/blob/main/_autodocs/module-overview.md Outlines the logic for locating a .env file by searching up the directory hierarchy. ```text find_dotenv() ├─ Determine starting directory: │ ├─ If usecwd: use os.getcwd() │ ├─ If interactive (REPL/IPython): use os.getcwd() │ ├─ If debugger attached: use os.getcwd() │ ├─ If frozen: use os.getcwd() │ └─ Otherwise: use caller's script directory ├─ Walk up directory hierarchy │ └─ _walk_to_root() ├─ Check each directory for filename │ └─ _is_file_or_fifo() ├─ Return path if found └─ Return empty string or raise IOError ```