Convert Figma logo to code with AI

theskumar logopython-dotenv

Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.

7,581
426
7,581
65

Top Related Projects

6,597

A Ruby gem to load environment variables from `.env`.

A Go port of Ruby's dotenv library (Loads environment variables from .env files)

13,146

Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.

12,422

unclutter your .profile

Quick Overview

Python-dotenv is a popular Python library that reads key-value pairs from a .env file and sets them as environment variables. It simplifies the process of managing configuration in Python applications, especially when dealing with sensitive information like API keys or database credentials.

Pros

  • Easy to use and integrate into existing Python projects
  • Supports multiple file formats (.env, .ini, .yaml)
  • Provides both command-line interface and programmatic usage
  • Helps keep sensitive information separate from source code

Cons

  • May introduce security risks if .env files are not properly protected
  • Can lead to configuration management complexity in large projects
  • Requires discipline to ensure .env files are not accidentally committed to version control
  • Limited functionality compared to more comprehensive configuration management solutions

Code Examples

  1. Loading environment variables from a .env file:
from dotenv import load_dotenv

load_dotenv()  # This loads the .env file in the current directory
  1. Accessing environment variables:
import os
from dotenv import load_dotenv

load_dotenv()

database_url = os.getenv("DATABASE_URL")
api_key = os.getenv("API_KEY")
  1. Using dotenv in a Flask application:
from flask import Flask
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')

@app.route('/')
def hello():
    return "Hello, World!"
  1. Overriding existing environment variables:
from dotenv import load_dotenv

load_dotenv(override=True)

Getting Started

  1. Install python-dotenv:

    pip install python-dotenv
    
  2. Create a .env file in your project root:

    DATABASE_URL=postgresql://user:password@localhost/dbname
    API_KEY=your_secret_api_key
    
  3. In your Python script:

    from dotenv import load_dotenv
    import os
    
    load_dotenv()
    
    database_url = os.getenv("DATABASE_URL")
    api_key = os.getenv("API_KEY")
    
    # Use the variables in your application
    print(f"Connecting to database: {database_url}")
    print(f"Using API key: {api_key}")
    

This setup allows you to easily manage environment-specific configuration without hardcoding sensitive information in your source code.

Competitor Comparisons

6,597

A Ruby gem to load environment variables from `.env`.

Pros of dotenv

  • Written in Ruby, making it a native solution for Ruby projects
  • Supports loading environment variables from multiple files
  • Includes a CLI tool for working with .env files

Cons of dotenv

  • Limited to Ruby ecosystem, not suitable for Python projects
  • Lacks some advanced features like variable expansion and type casting

Code Comparison

python-dotenv:

from dotenv import load_dotenv
load_dotenv()
import os
database_url = os.getenv("DATABASE_URL")

dotenv:

require 'dotenv'
Dotenv.load
database_url = ENV['DATABASE_URL']

Key Differences

  1. Language: python-dotenv is for Python, while dotenv is for Ruby
  2. Functionality: python-dotenv offers more advanced features like variable expansion
  3. Ecosystem: Each library is tailored to its respective language ecosystem
  4. Usage: python-dotenv is more commonly used in Python web frameworks, while dotenv is popular in Ruby on Rails projects

Conclusion

Both libraries serve similar purposes but are designed for different programming languages. Choose python-dotenv for Python projects and dotenv for Ruby projects. Consider the specific features and ecosystem integration when making your decision.

A Go port of Ruby's dotenv library (Loads environment variables from .env files)

Pros of godotenv

  • Written in Go, offering better performance and native compilation
  • Supports loading environment variables from multiple files
  • Provides a simple API for parsing .env files without modifying the actual environment

Cons of godotenv

  • Limited to Go projects, whereas python-dotenv can be used in Python ecosystems
  • Lacks some advanced features like variable expansion and overloading

Code Comparison

python-dotenv:

from dotenv import load_dotenv
load_dotenv()
import os
secret_key = os.getenv("SECRET_KEY")

godotenv:

import "github.com/joho/godotenv"
godotenv.Load()
secretKey := os.Getenv("SECRET_KEY")

Both libraries provide similar functionality for loading environment variables from .env files. The main differences lie in the language ecosystem and specific features each library offers.

python-dotenv is more suitable for Python projects and offers additional features like variable expansion and overloading. It's widely used in the Python community and integrates well with various Python frameworks.

godotenv, on the other hand, is ideal for Go projects. It provides a straightforward way to load environment variables in Go applications, with the added benefit of Go's performance characteristics. While it may have fewer advanced features, it serves its purpose efficiently in the Go ecosystem.

The choice between these libraries primarily depends on the programming language of your project and the specific features you require for environment variable management.

13,146

Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.

Pros of phpdotenv

  • Supports PHP 5.3+, offering broader compatibility
  • Includes a Loader class for more granular control over environment loading
  • Provides built-in variable expansion functionality

Cons of phpdotenv

  • Limited to PHP environments, unlike python-dotenv's cross-platform support
  • Lacks some advanced features like variable overwriting prevention
  • Does not support inline comments in .env files

Code Comparison

phpdotenv:

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$s3_bucket = $_ENV['S3_BUCKET'];

python-dotenv:

from dotenv import load_dotenv
load_dotenv()
s3_bucket = os.getenv('S3_BUCKET')

Both libraries serve similar purposes but cater to different ecosystems. phpdotenv is tailored for PHP applications, offering PHP-specific features and broader version compatibility. python-dotenv, on the other hand, provides a more versatile solution for Python projects across various platforms.

While phpdotenv includes some unique features like the Loader class and variable expansion, python-dotenv offers advantages such as cross-platform support and the ability to prevent variable overwriting. The choice between the two largely depends on the programming language and specific project requirements.

12,422

unclutter your .profile

Pros of direnv

  • Language-agnostic, works with any shell and programming language
  • Automatically loads/unloads environment variables when entering/leaving directories
  • Supports more complex scripting and environment setup beyond just env vars

Cons of direnv

  • Requires installation and shell integration, not as portable
  • Steeper learning curve for advanced features
  • May introduce security risks if not properly configured

Code Comparison

python-dotenv:

from dotenv import load_dotenv
load_dotenv()
import os
secret_key = os.getenv("SECRET_KEY")

direnv:

# .envrc file
export SECRET_KEY="your_secret_key"

Key Differences

  1. Scope: python-dotenv is Python-specific, while direnv is language-agnostic.
  2. Activation: python-dotenv requires explicit loading in code, direnv activates automatically when entering a directory.
  3. Functionality: direnv offers more advanced features like directory-specific shell commands and environment setup.
  4. Security: direnv requires more careful configuration to prevent potential security issues.
  5. Portability: python-dotenv is more portable as it doesn't require system-wide installation or shell integration.

Both tools serve the purpose of managing environment variables, but cater to different use cases and development workflows. Choose based on your specific needs and project requirements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

python-dotenv

Build Status PyPI version

Python-dotenv reads key-value pairs from a .env file and can set them as environment variables. It helps in the development of applications following the 12-factor principles.

Getting Started

pip install python-dotenv

If your application takes its configuration from environment variables, like a 12-factor application, launching it in development is not very practical because you have to set those environment variables yourself.

To help you with that, you can add Python-dotenv to your application to make it load the configuration from a .env file when it is present (e.g. in development) while remaining configurable via the environment:

from dotenv import load_dotenv

load_dotenv()  # take environment variables

# Code of your application, which uses environment variables (e.g. from `os.environ` or
# `os.getenv`) as if they came from the actual environment.

By default, load_dotenv doesn't override existing environment variables and looks for a .env file in same directory as python script or searches for it incrementally higher up.

To configure the development environment, add a .env in the root directory of your project:

.
├── .env
└── foo.py

The syntax of .env files supported by python-dotenv is similar to that of Bash:

# Development settings
DOMAIN=example.org
ADMIN_EMAIL=admin@${DOMAIN}
ROOT_URL=${DOMAIN}/app

If you use variables in values, ensure they are surrounded with { and }, like ${DOMAIN}, as bare variables such as $DOMAIN are not expanded.

You will probably want to add .env to your .gitignore, especially if it contains secrets like a password.

See the section "File format" below for more information about what you can write in a .env file.

Other Use Cases

Load configuration without altering the environment

The function dotenv_values works more or less the same way as load_dotenv, except it doesn't touch the environment, it just returns a dict with the values parsed from the .env file.

from dotenv import dotenv_values

config = dotenv_values(".env")  # config = {"USER": "foo", "EMAIL": "foo@example.org"}

This notably enables advanced configuration management:

import os
from dotenv import dotenv_values

config = {
    **dotenv_values(".env.shared"),  # load shared development variables
    **dotenv_values(".env.secret"),  # load sensitive variables
    **os.environ,  # override loaded values with environment variables
}

Parse configuration as a stream

load_dotenv and dotenv_values accept streams via their stream argument. It is thus possible to load the variables from sources other than the filesystem (e.g. the network).

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

You can use dotenv in IPython. By default, it will use find_dotenv to search for a .env file:

%load_ext dotenv
%dotenv

You can also specify a path:

%dotenv relative/or/absolute/path/to/.env

Optional flags:

  • -o to override existing variables.
  • -v for increased verbosity.

Command-line Interface

A CLI interface dotenv is also included, which helps you manipulate the .env file without manually opening it.

$ pip install "python-dotenv[cli]"
$ dotenv set USER foo
$ dotenv set EMAIL foo@example.org
$ dotenv list
USER=foo
EMAIL=foo@example.org
$ dotenv list --format=json
{
  "USER": "foo",
  "EMAIL": "foo@example.org"
}
$ dotenv run -- python foo.py

Run dotenv --help for more information about the options and subcommands.

File format

The format is not formally specified and still improves over time. That being said, .env files should mostly look like Bash files.

Keys can be unquoted or single-quoted. Values can be unquoted, single- or double-quoted. Spaces before and after keys, equal signs, and values are ignored. Values can be followed by a comment. Lines can start with the export directive, which does not affect their interpretation.

Allowed escape sequences:

  • in single-quoted values: \\, \'
  • in double-quoted values: \\, \', \", \a, \b, \f, \n, \r, \t, \v

Multiline values

It is possible for single- or double-quoted values to span multiple lines. The following examples are equivalent:

FOO="first line
second line"
FOO="first line\nsecond line"

Variable without a value

A variable can have no value:

FOO

It results in dotenv_values associating that variable name with the value None (e.g. {"FOO": None}. load_dotenv, on the other hand, simply ignores such variables.

This shouldn't be confused with FOO=, in which case the variable is associated with the empty string.

Variable expansion

Python-dotenv can interpolate variables using POSIX variable expansion.

With load_dotenv(override=True) or dotenv_values(), the value of a variable is the first of the values defined in the following list:

  • Value of that variable in the .env file.
  • Value of that variable in the environment.
  • Default value, if provided.
  • Empty string.

With load_dotenv(override=False), the value of a variable is the first of the values defined in the following list:

  • Value of that variable in the environment.
  • Value of that variable in the .env file.
  • Default value, if provided.
  • Empty string.

Related Projects

Acknowledgements

This project is currently maintained by Saurabh Kumar and Bertrand Bonnefoy-Claudet and would not have been possible without the support of these awesome people.