0
# Environs
1
2
A Python library for parsing environment variables with type casting, validation, and framework integration. Environs allows you to store configuration separate from your code, following the Twelve-Factor App methodology, with comprehensive type support and validation capabilities.
3
4
## Package Information
5
6
- **Package Name**: environs
7
- **Language**: Python
8
- **Installation**: `pip install environs`
9
10
## Core Imports
11
12
```python
13
from environs import Env
14
```
15
16
Convenience import for the singleton instance:
17
18
```python
19
from environs import env
20
```
21
22
For validation and exception handling:
23
24
```python
25
from environs import validate, ValidationError, EnvError, EnvValidationError
26
```
27
28
## Basic Usage
29
30
```python
31
from environs import env
32
import os
33
34
# Set some environment variables
35
os.environ["API_KEY"] = "secret123"
36
os.environ["MAX_CONNECTIONS"] = "100"
37
os.environ["ENABLE_FEATURE"] = "true"
38
os.environ["COORDINATES"] = "23.3,50.0"
39
40
# Read .env file if it exists
41
env.read_env()
42
43
# Parse environment variables with type casting
44
api_key = env.str("API_KEY") # => "secret123"
45
max_connections = env.int("MAX_CONNECTIONS") # => 100
46
enable_feature = env.bool("ENABLE_FEATURE") # => True
47
48
# Provide default values
49
timeout = env.int("TIMEOUT", 30) # => 30 (default)
50
51
# Parse lists with type casting
52
coords = env.list("COORDINATES", subcast=float) # => [23.3, 50.0]
53
```
54
55
## Architecture
56
57
Environs provides two main classes and a comprehensive type system:
58
59
- **Env**: Main environment variable reader with lazy validation
60
- **FileAwareEnv**: Extended reader supporting Docker-style secret files
61
- **Type System**: Built-in parsers for all common Python types plus custom parser registration
62
- **Validation**: Marshmallow-powered validation with deferred error collection
63
- **Framework Integration**: Specialized parsers for Django URL configurations
64
65
The library uses marshmallow fields internally for validation and type conversion, enabling consistent error handling and extensive customization capabilities.
66
67
## Capabilities
68
69
### Core Environment Parsing
70
71
Basic type parsing including strings, integers, booleans, floats, and raw values. These fundamental parsers handle the most common environment variable use cases with optional default values and validation.
72
73
```python { .api }
74
def __call__(name: str, default=..., subcast=None, *, validate=None, **kwargs): ...
75
def str(name: str, default=..., *, validate=None, **kwargs): ...
76
def int(name: str, default=..., *, validate=None, **kwargs): ...
77
def bool(name: str, default=..., *, validate=None, **kwargs): ...
78
def float(name: str, default=..., *, validate=None, **kwargs): ...
79
def decimal(name: str, default=..., *, validate=None, **kwargs): ...
80
```
81
82
[Core Parsing](./core-parsing.md)
83
84
### Advanced Data Structures
85
86
Parsing of complex data structures including lists, dictionaries, and JSON with support for nested type casting and custom delimiters.
87
88
```python { .api }
89
def list(name: str, default=..., subcast=None, *, delimiter=",", validate=None, **kwargs): ...
90
def dict(name: str, default=..., *, subcast_keys=None, subcast_values=None,
91
delimiter=",", key_value_delimiter="=", validate=None, **kwargs): ...
92
def json(name: str, default=..., *, validate=None, **kwargs): ...
93
```
94
95
[Advanced Data Structures](./advanced-data.md)
96
97
### Date, Time, and Specialized Types
98
99
Parsing of temporal types, paths, UUIDs, URLs, enums, and logging levels with format validation and conversion.
100
101
```python { .api }
102
def datetime(name: str, default=..., *, validate=None, **kwargs): ...
103
def date(name: str, default=..., *, validate=None, **kwargs): ...
104
def time(name: str, default=..., *, validate=None, **kwargs): ...
105
def timedelta(name: str, default=..., *, validate=None, **kwargs): ...
106
def path(name: str, default=..., *, validate=None, **kwargs): ...
107
def uuid(name: str, default=..., *, validate=None, **kwargs): ...
108
def url(name: str, default=..., *, validate=None, **kwargs): ...
109
def log_level(name: str, default=..., *, validate=None, **kwargs): ...
110
def enum(name: str, default=..., *, enum, by_value=False, validate=None, **kwargs): ...
111
```
112
113
[Specialized Types](./specialized-types.md)
114
115
### Configuration Management
116
117
Environment configuration utilities including .env file reading, variable expansion, prefixed parsing, and validation management.
118
119
```python { .api }
120
@staticmethod
121
def read_env(path=None, recurse=True, verbose=False, override=False, return_path=False): ...
122
def prefixed(prefix: str): ...
123
def seal(): ...
124
def dump(): ...
125
```
126
127
[Configuration Management](./configuration.md)
128
129
### Validation
130
131
Comprehensive validation support using marshmallow validators to ensure environment variables meet specific criteria with custom validation functions and error handling.
132
133
```python { .api }
134
validate.OneOf(choices): ... # Choice validation
135
validate.Range(min, max): ... # Numeric range validation
136
validate.Length(min, max): ... # String/list length validation
137
validate.Email(): ... # Email format validation
138
validate.URL(): ... # URL format validation
139
```
140
141
[Validation](./validation.md)
142
143
### Custom Parsers
144
145
Registration and management of custom parsing methods with marshmallow field integration and parser customization.
146
147
```python { .api }
148
def add_parser(name: str, func: Callable): ...
149
def parser_for(name: str): ...
150
def add_parser_from_field(name: str, field_cls: Type[Field]): ...
151
```
152
153
[Custom Parsers](./custom-parsers.md)
154
155
### Framework Integration
156
157
Specialized parsers for Django framework integration including database URLs, email configuration, and cache settings.
158
159
```python { .api }
160
def dj_db_url(name: str, default=..., **kwargs): ... # Returns: dict
161
def dj_email_url(name: str, default=..., **kwargs): ... # Returns: dict
162
def dj_cache_url(name: str, default=..., **kwargs): ... # Returns: dict
163
```
164
165
[Framework Integration](./framework-integration.md)
166
167
### File-Based Secrets
168
169
Docker-style secret file support for reading sensitive configuration from mounted files instead of environment variables.
170
171
```python { .api }
172
class FileAwareEnv(Env):
173
def __init__(self, file_suffix="_FILE", **kwargs): ...
174
```
175
176
[File Secrets](./file-secrets.md)
177
178
## Core Types
179
180
```python { .api }
181
class Env:
182
def __init__(self, eager: bool = True, expand_vars: bool = False,
183
prefix: str | None = None): ...
184
185
class FileAwareEnv(Env):
186
def __init__(self, file_suffix: str = "_FILE", eager: bool = True,
187
expand_vars: bool = False, prefix: str | None = None): ...
188
189
class EnvError(ValueError): ...
190
191
class EnvValidationError(EnvError):
192
def __init__(self, message: str, error_messages): ...
193
error_messages: dict | list
194
195
class EnvSealedError(TypeError, EnvError): ...
196
197
class ParserConflictError(ValueError): ...
198
199
# Re-exported from marshmallow
200
class ValidationError(Exception): ...
201
202
# Validation functions (re-exported from marshmallow.validate)
203
validate: module # Contains validation functions like OneOf, Range, Email, etc.
204
```
205
206
## Global Instance
207
208
```python { .api }
209
env: Env # Singleton instance for convenience
210
```