or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

exception-handling.mdfile-operations.mdindex.mdinterpolation.mdoption-access.mdparser-classes.mdsection-management.md

option-access.mddocs/

0

# Option Access

1

2

Methods for accessing, setting, and managing configuration options with comprehensive type conversion support. These methods provide the primary interface for reading and writing configuration values.

3

4

## Capabilities

5

6

### Getting Option Values

7

8

Retrieve configuration values with support for type conversion, fallback values, and variable interpolation.

9

10

```python { .api }

11

def get(section, option, *, raw=False, vars=None, fallback=_UNSET):

12

"""

13

Get an option value as a string.

14

15

Parameters:

16

- section: str, section name

17

- option: str, option name

18

- raw: bool, disable interpolation if True

19

- vars: dict, additional interpolation variables

20

- fallback: any, value to return if option doesn't exist

21

22

Returns:

23

str: option value after interpolation

24

25

Raises:

26

- NoSectionError: if section doesn't exist

27

- NoOptionError: if option doesn't exist and no fallback

28

"""

29

30

def getint(section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs):

31

"""

32

Get an option value as an integer.

33

34

Parameters:

35

- section: str, section name

36

- option: str, option name

37

- raw: bool, disable interpolation if True

38

- vars: dict, additional interpolation variables

39

- fallback: any, value to return if option doesn't exist

40

41

Returns:

42

int: option value converted to integer

43

44

Raises:

45

- NoSectionError: if section doesn't exist

46

- NoOptionError: if option doesn't exist and no fallback

47

- ValueError: if value cannot be converted to int

48

"""

49

50

def getfloat(section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs):

51

"""

52

Get an option value as a float.

53

54

Parameters:

55

- section: str, section name

56

- option: str, option name

57

- raw: bool, disable interpolation if True

58

- vars: dict, additional interpolation variables

59

- fallback: any, value to return if option doesn't exist

60

61

Returns:

62

float: option value converted to float

63

64

Raises:

65

- NoSectionError: if section doesn't exist

66

- NoOptionError: if option doesn't exist and no fallback

67

- ValueError: if value cannot be converted to float

68

"""

69

70

def getboolean(section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs):

71

"""

72

Get an option value as a boolean.

73

74

Parameters:

75

- section: str, section name

76

- option: str, option name

77

- raw: bool, disable interpolation if True

78

- vars: dict, additional interpolation variables

79

- fallback: any, value to return if option doesn't exist

80

81

Returns:

82

bool: option value converted to boolean

83

84

Raises:

85

- NoSectionError: if section doesn't exist

86

- NoOptionError: if option doesn't exist and no fallback

87

- ValueError: if value cannot be converted to bool

88

89

Notes:

90

- True values: '1', 'yes', 'true', 'on' (case-insensitive)

91

- False values: '0', 'no', 'false', 'off' (case-insensitive)

92

"""

93

```

94

95

### Setting Option Values

96

97

Methods to set and modify configuration option values.

98

99

```python { .api }

100

def set(section, option, value=None):

101

"""

102

Set an option value.

103

104

Parameters:

105

- section: str, section name

106

- option: str, option name

107

- value: str or None, option value

108

109

Returns:

110

None

111

112

Raises:

113

- NoSectionError: if section doesn't exist

114

- TypeError: if value is not string or None (when allow_no_value=True)

115

116

Notes:

117

- Value is converted to string if not None

118

- None values allowed only when allow_no_value=True

119

"""

120

```

121

122

### Option Validation and Listing

123

124

Methods to check option existence and retrieve option information.

125

126

```python { .api }

127

def has_option(section, option):

128

"""

129

Check if an option exists in a section.

130

131

Parameters:

132

- section: str, section name

133

- option: str, option name

134

135

Returns:

136

bool: True if option exists, False otherwise

137

138

Notes:

139

- Returns False if section doesn't exist

140

- Case-sensitive comparison

141

"""

142

143

def options(section):

144

"""

145

Return list of option names for a section.

146

147

Parameters:

148

- section: str, section name

149

150

Returns:

151

list of str: option names in the section

152

153

Raises:

154

- NoSectionError: if section doesn't exist

155

156

Notes:

157

- Includes options from DEFAULT section

158

- Returns options in order of appearance

159

"""

160

161

def items(section=_UNSET, raw=False, vars=None):

162

"""

163

Return list of (name, value) tuples for options or sections.

164

165

Parameters:

166

- section: str, section name (if provided, returns option-value pairs for that section)

167

- raw: bool, disable interpolation if True

168

- vars: dict, additional interpolation variables

169

170

Returns:

171

- If section specified: list of tuple (option_name, option_value) pairs for that section

172

- If section not specified: list of tuple (section_name, SectionProxy) pairs for all sections

173

174

Raises:

175

- NoSectionError: if specified section doesn't exist

176

177

Notes:

178

- When getting section items, includes options from DEFAULT section

179

- When getting all sections, includes DEFAULT section if it has options

180

"""

181

182

def remove_option(section, option):

183

"""

184

Remove an option from a section.

185

186

Parameters:

187

- section: str, section name

188

- option: str, option name to remove

189

190

Returns:

191

bool: True if option existed and was removed, False otherwise

192

193

Raises:

194

- NoSectionError: if section doesn't exist

195

"""

196

```

197

198

## Usage Examples

199

200

### Basic Value Retrieval

201

202

```python

203

from backports import configparser

204

205

config = configparser.ConfigParser()

206

config.read('config.ini')

207

208

# Get string values

209

host = config.get('database', 'host')

210

name = config.get('database', 'name', fallback='default_db')

211

212

# Get typed values

213

port = config.getint('database', 'port')

214

timeout = config.getfloat('database', 'timeout')

215

debug = config.getboolean('application', 'debug')

216

```

217

218

### Working with Fallback Values

219

220

```python

221

from backports import configparser

222

223

config = configparser.ConfigParser()

224

225

# Provide fallback for missing options

226

cache_size = config.getint('cache', 'size', fallback=1000)

227

enable_logging = config.getboolean('logging', 'enabled', fallback=True)

228

229

# Use None fallback to detect missing options

230

api_key = config.get('api', 'key', fallback=None)

231

if api_key is None:

232

print("API key not configured")

233

```

234

235

### Setting Option Values

236

237

```python

238

from backports import configparser

239

240

config = configparser.ConfigParser()

241

config.add_section('database')

242

243

# Set string values

244

config.set('database', 'host', 'localhost')

245

config.set('database', 'port', '5432')

246

247

# Set typed values (converted to strings)

248

config.set('database', 'timeout', str(30.5))

249

config.set('database', 'debug', str(True))

250

251

# Set None values (if allow_no_value=True)

252

config = configparser.ConfigParser(allow_no_value=True)

253

config.add_section('optional')

254

config.set('optional', 'empty_option', None)

255

```

256

257

### Boolean Value Handling

258

259

```python

260

from backports import configparser

261

262

config = configparser.ConfigParser()

263

config.read_string('''

264

[settings]

265

debug = yes

266

production = no

267

feature_flag = true

268

maintenance = false

269

enabled = 1

270

disabled = 0

271

''')

272

273

# All these return appropriate boolean values

274

debug = config.getboolean('settings', 'debug') # True

275

prod = config.getboolean('settings', 'production') # False

276

flag = config.getboolean('settings', 'feature_flag') # True

277

maint = config.getboolean('settings', 'maintenance') # False

278

enabled = config.getboolean('settings', 'enabled') # True

279

disabled = config.getboolean('settings', 'disabled') # False

280

```

281

282

### Option Validation and Listing

283

284

```python

285

from backports import configparser

286

287

config = configparser.ConfigParser()

288

config.read('config.ini')

289

290

# Check option existence

291

if config.has_option('database', 'password'):

292

password = config.get('database', 'password')

293

294

# List all options in a section

295

db_options = config.options('database')

296

print(f"Database options: {db_options}")

297

298

# Get all option-value pairs

299

db_items = config.items('database')

300

for name, value in db_items:

301

print(f"{name} = {value}")

302

```

303

304

### Variable Interpolation

305

306

```python

307

from backports import configparser

308

309

config = configparser.ConfigParser()

310

config.read_string('''

311

[DEFAULT]

312

base_url = http://localhost

313

port = 8080

314

315

[api]

316

endpoint = %(base_url)s:%(port)s/api

317

''')

318

319

# Get interpolated value

320

endpoint = config.get('api', 'endpoint') # 'http://localhost:8080/api'

321

322

# Disable interpolation

323

raw_endpoint = config.get('api', 'endpoint', raw=True) # '%(base_url)s:%(port)s/api'

324

325

# Provide additional variables

326

extra_vars = {'version': 'v2'}

327

versioned_endpoint = config.get('api', 'endpoint', vars=extra_vars)

328

```

329

330

### Error Handling

331

332

```python

333

from backports import configparser

334

335

config = configparser.ConfigParser()

336

337

try:

338

value = config.get('nonexistent', 'option')

339

except configparser.NoSectionError:

340

print("Section doesn't exist")

341

342

try:

343

value = config.get('existing_section', 'nonexistent_option')

344

except configparser.NoOptionError:

345

print("Option doesn't exist")

346

347

try:

348

number = config.getint('section', 'not_a_number')

349

except ValueError:

350

print("Value cannot be converted to integer")

351

```

352

353

### SectionProxy Option Access

354

355

```python

356

from backports import configparser

357

358

config = configparser.ConfigParser()

359

config.read('config.ini')

360

361

# Access options through section proxy

362

db_section = config['database']

363

host = db_section['host']

364

port = db_section.getint('port')

365

debug = db_section.getboolean('debug', fallback=False)

366

367

# Set options through section proxy

368

db_section['new_option'] = 'new_value'

369

del db_section['old_option']

370

```