or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-data.mdconfiguration.mdcore-parsing.mdcustom-parsers.mdfile-secrets.mdframework-integration.mdindex.mdspecialized-types.mdvalidation.md

specialized-types.mddocs/

0

# Specialized Types

1

2

Parsing of temporal types, paths, identifiers, URLs, enums, and other specialized data types with format validation and automatic conversion to appropriate Python objects.

3

4

## Capabilities

5

6

### Date and Time Parsing

7

8

Parse ISO-formatted date and time strings into Python datetime objects with timezone support.

9

10

```python { .api }

11

def datetime(self, name: str, default=..., *, validate=None, **kwargs):

12

"""

13

Parse environment variable as datetime.

14

15

Parameters:

16

- name: str, environment variable name

17

- default: datetime, default value if variable not set (optional)

18

- validate: callable or list of callables for validation (optional)

19

- **kwargs: additional marshmallow field arguments (format, etc.)

20

21

Returns:

22

datetime.datetime: Parsed datetime object

23

24

Raises:

25

EnvValidationError: If value is not a valid datetime format

26

"""

27

28

def date(self, name: str, default=..., *, validate=None, **kwargs):

29

"""

30

Parse environment variable as date.

31

32

Parameters:

33

- name: str, environment variable name

34

- default: date, default value if variable not set (optional)

35

- validate: callable or list of callables for validation (optional)

36

- **kwargs: additional marshmallow field arguments (format, etc.)

37

38

Returns:

39

datetime.date: Parsed date object

40

"""

41

42

def time(self, name: str, default=..., *, validate=None, **kwargs):

43

"""

44

Parse environment variable as time.

45

46

Parameters:

47

- name: str, environment variable name

48

- default: time, default value if variable not set (optional)

49

- validate: callable or list of callables for validation (optional)

50

- **kwargs: additional marshmallow field arguments (format, etc.)

51

52

Returns:

53

datetime.time: Parsed time object

54

"""

55

```

56

57

Usage examples:

58

59

```python

60

import os

61

from environs import env

62

from datetime import datetime, date, time

63

64

# DateTime parsing

65

os.environ["CREATED_AT"] = "2023-12-25T10:30:00"

66

created_at = env.datetime("CREATED_AT") # => datetime(2023, 12, 25, 10, 30)

67

68

# Date parsing

69

os.environ["BIRTH_DATE"] = "1990-05-15"

70

birth_date = env.date("BIRTH_DATE") # => date(1990, 5, 15)

71

72

# Time parsing

73

os.environ["DAILY_BACKUP_TIME"] = "02:30:00"

74

backup_time = env.time("DAILY_BACKUP_TIME") # => time(2, 30)

75

```

76

77

### Time Delta Parsing

78

79

Parse duration strings into Python timedelta objects with support for multiple formats including GEP-2257 duration specification.

80

81

```python { .api }

82

def timedelta(self, name: str, default=..., *, validate=None, **kwargs):

83

"""

84

Parse environment variable as timedelta.

85

86

Parameters:

87

- name: str, environment variable name

88

- default: timedelta, default value if variable not set (optional)

89

- validate: callable or list of callables for validation (optional)

90

- **kwargs: additional marshmallow field arguments

91

92

Returns:

93

datetime.timedelta: Parsed duration

94

95

Supported formats:

96

- Seconds as number: "42"

97

- GEP-2257 duration strings: "1h30m", "2d4h", "30s", "500ms"

98

- Standard timedelta formats

99

"""

100

```

101

102

Usage examples:

103

104

```python

105

import os

106

from environs import env

107

108

# Simple seconds

109

os.environ["SESSION_TIMEOUT"] = "1800" # 30 minutes in seconds

110

timeout = env.timedelta("SESSION_TIMEOUT") # => timedelta(seconds=1800)

111

112

# GEP-2257 duration strings

113

os.environ["CACHE_TTL"] = "1h30m"

114

cache_ttl = env.timedelta("CACHE_TTL") # => timedelta(hours=1, minutes=30)

115

116

os.environ["RETRY_DELAY"] = "500ms"

117

retry_delay = env.timedelta("RETRY_DELAY") # => timedelta(milliseconds=500)

118

119

os.environ["BACKUP_INTERVAL"] = "2d4h"

120

backup_interval = env.timedelta("BACKUP_INTERVAL") # => timedelta(days=2, hours=4)

121

```

122

123

### Path Parsing

124

125

Parse string paths into Python pathlib.Path objects with validation and normalization.

126

127

```python { .api }

128

def path(self, name: str, default=..., *, validate=None, **kwargs):

129

"""

130

Parse environment variable as Path.

131

132

Parameters:

133

- name: str, environment variable name

134

- default: Path or str, default value if variable not set (optional)

135

- validate: callable or list of callables for validation (optional)

136

- **kwargs: additional marshmallow field arguments

137

138

Returns:

139

pathlib.Path: Parsed path object

140

"""

141

```

142

143

Usage examples:

144

145

```python

146

import os

147

from environs import env

148

from pathlib import Path

149

150

# File paths

151

os.environ["LOG_FILE"] = "/var/log/app.log"

152

log_file = env.path("LOG_FILE") # => Path('/var/log/app.log')

153

154

# Directory paths

155

os.environ["DATA_DIR"] = "~/data"

156

data_dir = env.path("DATA_DIR") # => Path('~/data')

157

158

# Relative paths

159

os.environ["CONFIG_FILE"] = "./config/settings.json"

160

config_file = env.path("CONFIG_FILE") # => Path('./config/settings.json')

161

162

# Path operations

163

if log_file.exists():

164

print(f"Log file size: {log_file.stat().st_size}")

165

```

166

167

### UUID Parsing

168

169

Parse UUID strings into Python UUID objects with format validation.

170

171

```python { .api }

172

def uuid(self, name: str, default=..., *, validate=None, **kwargs):

173

"""

174

Parse environment variable as UUID.

175

176

Parameters:

177

- name: str, environment variable name

178

- default: UUID or str, default value if variable not set (optional)

179

- validate: callable or list of callables for validation (optional)

180

- **kwargs: additional marshmallow field arguments

181

182

Returns:

183

uuid.UUID: Parsed UUID object

184

185

Raises:

186

EnvValidationError: If value is not a valid UUID format

187

"""

188

```

189

190

Usage examples:

191

192

```python

193

import os

194

from environs import env

195

import uuid

196

197

# Standard UUID parsing

198

os.environ["REQUEST_ID"] = "550e8400-e29b-41d4-a716-446655440000"

199

request_id = env.uuid("REQUEST_ID") # => UUID('550e8400-e29b-41d4-a716-446655440000')

200

201

# UUID operations

202

print(f"Request ID: {request_id}")

203

print(f"UUID version: {request_id.version}")

204

```

205

206

### URL Parsing

207

208

Parse URL strings into urllib.parse.ParseResult objects with validation and component access.

209

210

```python { .api }

211

def url(self, name: str, default=..., *, validate=None, **kwargs):

212

"""

213

Parse environment variable as URL.

214

215

Parameters:

216

- name: str, environment variable name

217

- default: str or ParseResult, default value if variable not set (optional)

218

- validate: callable or list of callables for validation (optional)

219

- **kwargs: additional marshmallow field arguments

220

221

Returns:

222

urllib.parse.ParseResult: Parsed URL with components

223

224

Raises:

225

EnvValidationError: If value is not a valid URL format

226

"""

227

```

228

229

Usage examples:

230

231

```python

232

import os

233

from environs import env

234

235

# HTTP URL parsing

236

os.environ["API_URL"] = "https://api.example.com:8080/v1/users?limit=10"

237

api_url = env.url("API_URL")

238

239

print(f"Scheme: {api_url.scheme}") # => "https"

240

print(f"Hostname: {api_url.hostname}") # => "api.example.com"

241

print(f"Port: {api_url.port}") # => 8080

242

print(f"Path: {api_url.path}") # => "/v1/users"

243

print(f"Query: {api_url.query}") # => "limit=10"

244

245

# Database URL parsing

246

os.environ["DATABASE_URL"] = "postgresql://user:pass@localhost:5432/mydb"

247

db_url = env.url("DATABASE_URL")

248

print(f"Database: {db_url.path[1:]}") # => "mydb" (strip leading /)

249

```

250

251

### Logging Level Parsing

252

253

Parse logging level names or numbers into Python logging constants.

254

255

```python { .api }

256

def log_level(self, name: str, default=..., *, validate=None, **kwargs):

257

"""

258

Parse environment variable as logging level.

259

260

Parameters:

261

- name: str, environment variable name

262

- default: int or str, default value if variable not set (optional)

263

- validate: callable or list of callables for validation (optional)

264

- **kwargs: additional marshmallow field arguments

265

266

Returns:

267

int: Logging level constant

268

269

Supported values:

270

- Level names: "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" (case-insensitive)

271

- Level numbers: 10, 20, 30, 40, 50

272

"""

273

```

274

275

Usage examples:

276

277

```python

278

import os

279

import logging

280

from environs import env

281

282

# Level name parsing

283

os.environ["LOG_LEVEL"] = "DEBUG"

284

log_level = env.log_level("LOG_LEVEL") # => 10 (logging.DEBUG)

285

286

# Level number parsing

287

os.environ["APP_LOG_LEVEL"] = "30"

288

app_log_level = env.log_level("APP_LOG_LEVEL") # => 30 (logging.WARNING)

289

290

# Configure logging

291

logging.basicConfig(level=log_level)

292

logger = logging.getLogger(__name__)

293

logger.debug("This will be visible if LOG_LEVEL is DEBUG")

294

```

295

296

### Enum Parsing

297

298

Parse string values into Python enum instances with validation against enum members.

299

300

```python { .api }

301

def enum(self, name: str, default=..., *, enum, by_value=False, validate=None, **kwargs):

302

"""

303

Parse environment variable as enum.

304

305

Parameters:

306

- name: str, environment variable name

307

- default: enum instance, default value if variable not set (optional)

308

- enum: enum class to parse into

309

- by_value: bool, whether to match by value instead of name (default: False)

310

- validate: callable or list of callables for validation (optional)

311

- **kwargs: additional marshmallow field arguments

312

313

Returns:

314

enum instance: Parsed enum member

315

316

Raises:

317

EnvValidationError: If value is not a valid enum member

318

"""

319

```

320

321

Usage examples:

322

323

```python

324

import os

325

from environs import env

326

from enum import Enum

327

328

class Environment(Enum):

329

DEVELOPMENT = "dev"

330

STAGING = "stage"

331

PRODUCTION = "prod"

332

333

class LogFormat(Enum):

334

JSON = 1

335

TEXT = 2

336

337

# Parse by enum name

338

os.environ["ENV"] = "DEVELOPMENT"

339

environment = env.enum("ENV", enum=Environment) # => Environment.DEVELOPMENT

340

341

# Parse by enum value

342

os.environ["APP_ENV"] = "prod"

343

app_env = env.enum("APP_ENV", enum=Environment, by_value=True) # => Environment.PRODUCTION

344

345

# Numeric enum parsing

346

os.environ["LOG_FORMAT"] = "1"

347

log_format = env.enum("LOG_FORMAT", enum=LogFormat, by_value=True) # => LogFormat.JSON

348

```

349

350

## Types

351

352

```python { .api }

353

import datetime as dt

354

import uuid

355

from pathlib import Path

356

from urllib.parse import ParseResult

357

from enum import Enum

358

from typing import Type, TypeVar

359

360

EnumType = TypeVar('EnumType', bound=Enum)

361

```