Skip to main content

simplified environment variable parsing

Project description

environs: simplified environment variable parsing

Latest version Build Status marshmallow 2/3 compatible Black code style

environs is a Python library for parsing environment variables. It allows you to store configuration separate from your code, as per The Twelve-Factor App methodology.



  • Type-casting
  • Read .env files into os.environ (useful for local development)
  • Validation
  • Define custom parser behavior
  • Framework-agnostic, but integrates well with Flask and Django


pip install environs

Basic usage

With some environment variables set...

export GITHUB_USER=sloria
export SHIP_DATE='1984-06-25'
export TTL=42
export ENABLE_LOGIN=true
export GITHUB_REPOS=webargs,konch,ped
export COORDINATES=23.3,50.0

Parse them with environs...

from environs import Env

env = Env()
env.read_env()  # read .env file, if it exists
# required variables
gh_user = env("GITHUB_USER")  # => 'sloria'
secret = env("SECRET")  # => raises error if not set

# casting
max_connections ="MAX_CONNECTIONS")  # => 100
ship_date ="SHIP_DATE")  # =>, 6, 25)
ttl = env.timedelta("TTL")  # => datetime.timedelta(0, 42)
log_level = env.log_level("LOG_LEVEL")  # => logging.DEBUG

# providing a default value
enable_login = env.bool("ENABLE_LOGIN", False)  # => True
enable_feature_x = env.bool("ENABLE_FEATURE_X", False)  # => False

# parsing lists
gh_repos = env.list("GITHUB_REPOS")  # => ['webargs', 'konch', 'ped']
coords = env.list("COORDINATES", subcast=float)  # => [23.3, 50.0]

Supported types

The following are all type-casting methods of Env:

  • env.str
  • env.bool
  • env.float
  • env.decimal
  • env.list (accepts optional subcast keyword argument)
  • env.dict (accepts optional subcast keyword argument)
  • env.json
  • env.datetime
  • env.timedelta (assumes value is an integer in seconds)
  • env.url
  • env.uuid
  • env.log_level
  • env.path (casts to a pathlib.Path)

Reading .env files

# .env

Call Env.read_env before parsing variables.

from environs import Env

env = Env()
# Read .env into os.environ

env.bool("DEBUG")  # => True"PORT")  # => 4567

Reading a specific file

By default, Env.read_env will look for a .env file in current directory and (if no .env exists in the CWD) recurse upwards until a .env file is found.

You can also read a specific file:

from environs import Env

with open(".env.test", "w") as fobj:

env = Env()
env.read_env(".env.test", recurse=False)

assert env("A") == "foo"
assert"B") == 123

Handling prefixes

# export MYAPP_HOST=lolcathost
# export MYAPP_PORT=3000

with env.prefixed("MYAPP_"):
    host = env("HOST", "localhost")  # => 'lolcathost'
    port ="PORT", 5000)  # => 3000

# nested prefixes are also supported:

# export MYAPP_DB_HOST=lolcathost
# export MYAPP_DB_PORT=10101

with env.prefixed("MYAPP_"):
    with env.prefixed("DB_"):
        db_host = env("HOST", "lolcathost")
        db_port ="PORT", 10101)

Proxied variables

# export MAILGUN_LOGIN=sloria

smtp_login = env("SMTP_LOGIN")  # =>'sloria'


# export TTL=-2
# export NODE_ENV='invalid'
# export EMAIL='^_^'

# simple validator"TTL", validate=lambda n: n > 0)
# => Environment variable "TTL" invalid: ['Invalid value.']

# using marshmallow validators
from marshmallow.validate import OneOf

        ["production", "development"], error="NODE_ENV must be one of: {choices}"
# => Environment variable "NODE_ENV" invalid: ['NODE_ENV must be one of: production, development']

# multiple validators
from marshmallow.validate import Length, Email

env.str("EMAIL", validate=[Length(min=4), Email()])
# => Environment variable "EMAIL" invalid: ['Shorter than minimum length 4.', 'Not a valid email address.']


# serialize to a dictionary of simple types (numbers and strings)
# {'COORDINATES': [23.3, 50.0],
# 'GITHUB_REPOS': ['webargs', 'konch', 'ped'],
# 'GITHUB_USER': 'sloria',
# 'MYAPP_HOST': 'lolcathost',
# 'MYAPP_PORT': 3000,
# 'SHIP_DATE': '1984-06-25',
# 'TTL': 42}

Defining custom parser behavior

# export DOMAIN=''
# export COLOR=invalid

from furl import furl

# Register a new parser method for paths
def furl_parser(value):
    return furl(value)

domain = env.furl("DOMAIN")  # => furl('')

# Custom parsers can take extra keyword arguments
def enum_parser(value, choices):
    if value not in choices:
        raise environs.EnvError("Invalid!")
    return value

color = env.enum("COLOR", choices=["black"])  # => raises EnvError

Usage with Flask

# myapp/

from environs import Env

env = Env()

# Override in .env for local development
DEBUG = env.bool("FLASK_DEBUG", default=False)
# SECRET_KEY is required

Load the configuration after you initialize your app.

# myapp/

from flask import Flask

app = Flask(__name__)

For local development, use a .env file to override the default configuration.

# .env
SECRET_KEY="not so secret"

Note: Because environs depends on python-dotenv, the flask CLI will automatically read .env and .flaskenv files.

Usage with Django

environs includes a number of helpers for parsing connection URLs. To install environs with django support: :

pip install environs[django]

Use env.dj_db_url and env.dj_email_url to parse the DATABASE_URL and EMAIL_URL environment variables, respectively.

# myproject/
from environs import Env

env = Env()

# Override in .env for local development
DEBUG = env.bool("DEBUG", default=False)
# SECRET_KEY is required

# Parse database URLs, e.g.  "postgres://localhost:5432/mydb"
DATABASES = {"default": env.dj_db_url("DATABASE_URL")}

# Parse email URLs, e.g. "smtp://"
email = env.dj_email_url("EMAIL_URL", default="smtp://")

For local development, use a .env file to override the default configuration.

# .env
SECRET_KEY="not so secret"

For a more complete example, see in the examples/ directory.


Why envvars?

See The 12-factor App section on configuration.

Why not os.environ?

While os.environ is enough for simple use cases, a typical application will need a way to manipulate and validate raw environment variables. environs abstracts common tasks for handling environment variables.

environs will help you

  • cast envvars to the correct type
  • specify required envvars
  • define default values
  • validate envvars
  • parse list and dict values
  • parse dates, datetimes, and timedeltas
  • parse proxied variables
  • serialize your configuration to JSON, YAML, etc.

Why another library?

There are many great Python libraries for parsing environment variables. In fact, most of the credit for environs' public API goes to the authors of envparse and django-environ.

environs aims to meet three additional goals:

  1. Make it easy to extend parsing behavior and develop plugins.
  2. Leverage the deserialization and validation functionality provided by a separate library (marshmallow).
  3. Clean up redundant API.

See this GitHub issue which details specific differences with envparse.


MIT licensed. See the LICENSE file for more details.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for environs, version 5.2.1
Filename, size File type Python version Upload date Hashes
Filename, size environs-5.2.1-py2.py3-none-any.whl (9.8 kB) File type Wheel Python version py2.py3 Upload date Hashes View hashes
Filename, size environs-5.2.1.tar.gz (12.5 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page