or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdenvironment-loading.mdfile-manipulation.mdindex.mdipython.mdutilities.md

environment-loading.mddocs/

0

# Environment Loading

1

2

Core functionality for loading environment variables from .env files with automatic file discovery, variable expansion, and flexible configuration options.

3

4

## Capabilities

5

6

### Loading Environment Variables

7

8

Load environment variables from .env files directly into the system environment, with support for override control and variable interpolation.

9

10

```python { .api }

11

def load_dotenv(

12

dotenv_path: Optional[Union[str, os.PathLike[str]]] = None,

13

stream: Optional[IO[str]] = None,

14

verbose: bool = False,

15

override: bool = False,

16

interpolate: bool = True,

17

encoding: Optional[str] = "utf-8"

18

) -> bool:

19

"""

20

Parse a .env file and then load all the variables found as environment variables.

21

22

Parameters:

23

dotenv_path: Absolute or relative path to .env file

24

stream: Text stream (such as io.StringIO) with .env content, used if dotenv_path is None

25

verbose: Whether to output a warning if the .env file is missing

26

override: Whether to override the system environment variables with variables from the .env file

27

interpolate: Whether to interpolate variables using POSIX variable expansion

28

encoding: Encoding to be used to read the file

29

30

Returns:

31

bool: True if at least one environment variable is set, else False

32

"""

33

```

34

35

Usage examples:

36

37

```python

38

from dotenv import load_dotenv

39

import os

40

41

# Load from default .env file

42

load_dotenv()

43

44

# Load from specific file

45

load_dotenv('/path/to/custom.env')

46

47

# Override existing environment variables

48

load_dotenv(override=True)

49

50

# Load from string stream

51

from io import StringIO

52

config = StringIO("DATABASE_URL=sqlite:///app.db\nDEBUG=True")

53

load_dotenv(stream=config)

54

55

# Disable variable interpolation

56

load_dotenv(interpolate=False)

57

```

58

59

### Parsing Without Environment Modification

60

61

Parse .env files and return their contents as a dictionary without modifying the system environment.

62

63

```python { .api }

64

def dotenv_values(

65

dotenv_path: Optional[Union[str, os.PathLike[str]]] = None,

66

stream: Optional[IO[str]] = None,

67

verbose: bool = False,

68

interpolate: bool = True,

69

encoding: Optional[str] = "utf-8"

70

) -> Dict[str, Optional[str]]:

71

"""

72

Parse a .env file and return its content as a dict.

73

74

The returned dict will have None values for keys without values in the .env file.

75

For example, 'foo=bar' results in {"foo": "bar"} whereas 'foo' alone results in {"foo": None}

76

77

Parameters:

78

dotenv_path: Absolute or relative path to the .env file

79

stream: StringIO object with .env content, used if dotenv_path is None

80

verbose: Whether to output a warning if the .env file is missing

81

interpolate: Whether to interpolate variables using POSIX variable expansion

82

encoding: Encoding to be used to read the file

83

84

Returns:

85

dict: Dictionary with keys and values from the .env file

86

"""

87

```

88

89

Usage examples:

90

91

```python

92

from dotenv import dotenv_values

93

import os

94

95

# Parse .env file to dictionary

96

config = dotenv_values(".env")

97

database_url = config.get('DATABASE_URL')

98

99

# Advanced configuration management

100

config = {

101

**dotenv_values(".env.shared"), # load shared development variables

102

**dotenv_values(".env.secret"), # load sensitive variables

103

**os.environ, # override loaded values with environment variables

104

}

105

106

# Parse from stream

107

from io import StringIO

108

env_stream = StringIO("USER=foo\nEMAIL=foo@example.org")

109

config = dotenv_values(stream=env_stream)

110

# Returns: {"USER": "foo", "EMAIL": "foo@example.org"}

111

```

112

113

### File Discovery

114

115

Automatically discover .env files by searching in increasingly higher folders from the current directory or script location.

116

117

```python { .api }

118

def find_dotenv(

119

filename: str = ".env",

120

raise_error_if_not_found: bool = False,

121

usecwd: bool = False

122

) -> str:

123

"""

124

Search in increasingly higher folders for the given file.

125

126

Parameters:

127

filename: Name of the file to search for (default: ".env")

128

raise_error_if_not_found: Whether to raise IOError if file is not found

129

usecwd: Whether to start search from current working directory instead of script location

130

131

Returns:

132

str: Path to the file if found, or an empty string otherwise

133

134

Raises:

135

IOError: If raise_error_if_not_found is True and file is not found

136

"""

137

```

138

139

Usage examples:

140

141

```python

142

from dotenv import find_dotenv, load_dotenv

143

144

# Find .env file automatically

145

env_path = find_dotenv()

146

if env_path:

147

load_dotenv(env_path)

148

149

# Search for custom filename

150

config_path = find_dotenv('.config')

151

152

# Raise error if not found

153

try:

154

env_path = find_dotenv(raise_error_if_not_found=True)

155

load_dotenv(env_path)

156

except IOError:

157

print("No .env file found")

158

159

# Search from current working directory

160

env_path = find_dotenv(usecwd=True)

161

```

162

163

## Variable Expansion

164

165

python-dotenv supports POSIX-style variable expansion using `${VAR}` syntax with optional default values:

166

167

```bash

168

# .env file example

169

DOMAIN=example.org

170

ADMIN_EMAIL=admin@${DOMAIN}

171

ROOT_URL=${DOMAIN}/app

172

API_KEY=${SECRET_KEY:-default-key}

173

174

# More complex examples

175

DATABASE_HOST=localhost

176

DATABASE_PORT=5432

177

DATABASE_NAME=myapp

178

DATABASE_URL=postgresql://${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}

179

180

# Using defaults for optional configuration

181

REDIS_URL=${REDIS_HOST:-localhost}:${REDIS_PORT:-6379}

182

LOG_LEVEL=${DEBUG:-false}

183

MAX_WORKERS=${WORKER_COUNT:-4}

184

185

# Nested variable expansion

186

APP_ENV=production

187

CONFIG_FILE=config.${APP_ENV}.json

188

CONFIG_PATH=/etc/myapp/${CONFIG_FILE}

189

```

190

191

With `load_dotenv(override=True)` or `dotenv_values()`, variable resolution follows this priority:

192

1. Value of that variable in the .env file

193

2. Value of that variable in the environment

194

3. Default value (if provided with `:-` syntax)

195

4. Empty string

196

197

With `load_dotenv(override=False)`, the priority is:

198

1. Value of that variable in the environment

199

2. Value of that variable in the .env file

200

3. Default value (if provided with `:-` syntax)

201

4. Empty string