or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdconstants.mdconvolution.mdcoordinates.mdcosmology.mdfits-io.mdindex.mdmodeling.mdnddata.mdsamp.mdstatistics.mdtables.mdtime.mdtimeseries.mduncertainty.mdunits-quantities.mdutils.mdvisualization.mdwcs.md

configuration.mddocs/

0

# Configuration

1

2

Package configuration system and structured logging for astronomical applications with persistent settings and runtime control.

3

4

## Capabilities

5

6

### Configuration Classes

7

8

Configuration system for managing package settings with validation, persistence, and hierarchical organization.

9

10

```python { .api }

11

class ConfigNamespace:

12

"""

13

Base class for configuration namespaces containing ConfigItem members.

14

15

Provides hierarchical organization of configuration parameters

16

with automatic file persistence and runtime modification.

17

"""

18

def __init__(self): ...

19

20

def reload(self, attr=None):

21

"""Reload configuration from file."""

22

23

def reset(self, attr=None):

24

"""Reset configuration to defaults."""

25

26

def set_temp(self, attr, value):

27

"""Temporarily set configuration value."""

28

29

class ConfigItem:

30

"""

31

Individual configuration parameter with validation and persistence.

32

33

Parameters:

34

- defaultvalue: default parameter value

35

- description: parameter description

36

- cfgtype: configuration type specification

37

- module: module this item belongs to

38

- aliases: alternative names for this parameter

39

"""

40

def __init__(self, defaultvalue='', description='', cfgtype=None,

41

module=None, aliases=None): ...

42

43

def set(self, value):

44

"""Set configuration value with validation."""

45

46

def reload(self):

47

"""Reload value from configuration file."""

48

49

def reset(self):

50

"""Reset to default value."""

51

52

@property

53

def description(self):

54

"""Parameter description."""

55

56

@property

57

def cfgtype(self):

58

"""Configuration type."""

59

60

@property

61

def module(self):

62

"""Associated module."""

63

64

@property

65

def aliases(self):

66

"""Parameter aliases."""

67

```

68

69

### Configuration Management Functions

70

71

Functions for managing configuration files, directories, and global settings.

72

73

```python { .api }

74

def get_config(packageormod=None, reload=False, rootname='astropy'):

75

"""

76

Get configuration object for package or module.

77

78

Parameters:

79

- packageormod: package/module or name

80

- reload: reload from file

81

- rootname: root configuration name

82

83

Returns:

84

ConfigNamespace: configuration object

85

"""

86

87

def reload_config(packageormod=None, rootname='astropy'):

88

"""

89

Reload configuration from file.

90

91

Parameters:

92

- packageormod: package/module to reload

93

- rootname: root configuration name

94

"""

95

96

def generate_config(pkgname='astropy', filename=None, verbose=False):

97

"""

98

Generate configuration file from ConfigItems.

99

100

Parameters:

101

- pkgname: package name

102

- filename: output filename (default: auto-generated)

103

- verbose: print verbose output

104

105

Returns:

106

str: generated configuration content

107

"""

108

109

def create_config_file(pkg, rootname='astropy', overwrite=False):

110

"""

111

Create configuration file for package.

112

113

Parameters:

114

- pkg: package object

115

- rootname: root configuration name

116

- overwrite: overwrite existing file

117

"""

118

119

def get_config_dir(rootname='astropy'):

120

"""

121

Get configuration directory path.

122

123

Parameters:

124

- rootname: root name for configuration

125

126

Returns:

127

str: configuration directory path

128

"""

129

130

def get_cache_dir(rootname='astropy'):

131

"""

132

Get cache directory path.

133

134

Parameters:

135

- rootname: root name for cache

136

137

Returns:

138

str: cache directory path

139

"""

140

141

def set_temp_config(path=None, delete=False):

142

"""

143

Context manager for temporary configuration directory.

144

145

Parameters:

146

- path: temporary directory path

147

- delete: delete directory on exit

148

149

Returns:

150

context manager

151

"""

152

153

def set_temp_cache(path=None, delete=False):

154

"""

155

Context manager for temporary cache directory.

156

157

Parameters:

158

- path: temporary directory path

159

- delete: delete directory on exit

160

161

Returns:

162

context manager

163

"""

164

```

165

166

### Logging System

167

168

Structured logging system for astronomical applications with configurable output and filtering.

169

170

```python { .api }

171

# Access main logger

172

from astropy import log

173

174

# Logger configuration

175

log.setLevel('INFO') # Set logging level

176

log.addHandler(handler) # Add custom handler

177

log.removeHandler(handler) # Remove handler

178

179

# Logging methods

180

log.debug("Debug message")

181

log.info("Info message")

182

log.warning("Warning message")

183

log.error("Error message")

184

log.critical("Critical message")

185

186

# Exception logging

187

try:

188

# Some operation

189

pass

190

except Exception as e:

191

log.exception("Operation failed")

192

193

# Logging with context

194

with log.log_to_file('output.log'):

195

log.info("This goes to file")

196

197

# Disable/enable logging

198

log.disable_warnings_logging()

199

log.enable_warnings_logging()

200

```

201

202

### Configuration Examples

203

204

Built-in configuration parameters for common astropy settings.

205

206

```python { .api }

207

# Main astropy configuration

208

from astropy import conf

209

210

# Display and output settings

211

conf.unicode_output: ConfigItem # Use Unicode characters in output

212

conf.use_color: ConfigItem # Use ANSI color codes

213

conf.max_lines: ConfigItem # Maximum display lines

214

conf.max_width: ConfigItem # Maximum display width

215

216

# Download and caching

217

conf.download_cache_timeout: ConfigItem # Download timeout

218

conf.delete_temporary_downloads_at_exit: ConfigItem # Cleanup temp files

219

conf.compute_hash_block_size: ConfigItem # Hash computation block size

220

221

# Example usage

222

conf.unicode_output = True

223

conf.max_lines = 50

224

```

225

226

## Usage Examples

227

228

### Basic Configuration Management

229

230

```python

231

from astropy import config

232

from astropy.config import ConfigItem, ConfigNamespace

233

234

# Create custom configuration namespace

235

class MyConfig(ConfigNamespace):

236

# Define configuration items

237

data_dir = ConfigItem(

238

'/tmp/data',

239

'Directory for data files',

240

cfgtype='string'

241

)

242

243

max_files = ConfigItem(

244

100,

245

'Maximum number of files to process',

246

cfgtype='integer'

247

)

248

249

verbose = ConfigItem(

250

False,

251

'Enable verbose output',

252

cfgtype='boolean'

253

)

254

255

# Use configuration

256

my_conf = MyConfig()

257

print(f"Data directory: {my_conf.data_dir}")

258

print(f"Max files: {my_conf.max_files}")

259

260

# Modify configuration

261

my_conf.verbose = True

262

my_conf.max_files = 200

263

```

264

265

### Configuration Files

266

267

```python

268

from astropy.config import generate_config, get_config_dir

269

import os

270

271

# Get configuration directory

272

config_dir = get_config_dir()

273

print(f"Configuration directory: {config_dir}")

274

275

# Generate configuration file content

276

config_content = generate_config('astropy', verbose=True)

277

print("Generated configuration:")

278

print(config_content[:500] + "...")

279

280

# Write custom configuration

281

config_file = os.path.join(config_dir, 'astropy.cfg')

282

with open(config_file, 'w') as f:

283

f.write("""

284

[astropy]

285

unicode_output = True

286

use_color = True

287

max_lines = 100

288

289

[coordinates]

290

auto_download_sites = True

291

""")

292

293

# Reload configuration

294

from astropy import conf

295

conf.reload()

296

```

297

298

### Temporary Configuration Changes

299

300

```python

301

from astropy import conf

302

from astropy.config import set_temp_config

303

import tempfile

304

305

# Temporary configuration values

306

print(f"Original max_lines: {conf.max_lines}")

307

308

with conf.set_temp('max_lines', 25):

309

print(f"Temporary max_lines: {conf.max_lines}")

310

# Configuration change is active here

311

312

print(f"Restored max_lines: {conf.max_lines}")

313

314

# Temporary configuration directory

315

with set_temp_config() as temp_dir:

316

print(f"Using temporary config dir: {temp_dir}")

317

# Custom configuration active in this block

318

```

319

320

### Logging Configuration

321

322

```python

323

from astropy import log

324

import logging

325

326

# Set logging level

327

log.setLevel('DEBUG')

328

329

# Log messages at different levels

330

log.debug("Detailed debugging information")

331

log.info("General information")

332

log.warning("Something might be wrong")

333

log.error("An error occurred")

334

335

# Configure log format

336

logging.basicConfig(

337

format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',

338

level=logging.INFO

339

)

340

341

# Log to file

342

with log.log_to_file('astropy.log', filter_level='INFO'):

343

log.info("This message goes to file")

344

log.debug("This debug message is filtered out")

345

346

# Capture warnings

347

import warnings

348

with log.enable_warnings_logging():

349

warnings.warn("This warning will be logged")

350

```

351

352

### Advanced Configuration Patterns

353

354

```python

355

from astropy.config import ConfigItem, ConfigNamespace

356

from astropy import units as u

357

358

# Configuration with units and validation

359

class ObservatoryConfig(ConfigNamespace):

360

latitude = ConfigItem(

361

0.0 * u.degree,

362

'Observatory latitude',

363

cfgtype='angle'

364

)

365

366

longitude = ConfigItem(

367

0.0 * u.degree,

368

'Observatory longitude',

369

cfgtype='angle'

370

)

371

372

elevation = ConfigItem(

373

0.0 * u.meter,

374

'Observatory elevation',

375

cfgtype='length'

376

)

377

378

def validate_coordinates(self):

379

\"\"\"Validate observatory coordinates.\"\"\"

380

if abs(self.latitude) > 90 * u.degree:

381

raise ValueError("Invalid latitude")

382

if abs(self.longitude) > 180 * u.degree:

383

raise ValueError("Invalid longitude")

384

385

# Use with validation

386

obs_conf = ObservatoryConfig()

387

obs_conf.latitude = 37.2431 * u.degree # Lick Observatory

388

obs_conf.longitude = -121.6369 * u.degree

389

obs_conf.elevation = 1283 * u.meter

390

obs_conf.validate_coordinates()

391

```

392

393

### Package-Specific Configuration

394

395

```python

396

# Access configuration for specific astropy subpackages

397

from astropy.table import conf as table_conf

398

from astropy.coordinates import conf as coord_conf

399

from astropy.units import conf as units_conf

400

401

# Table configuration

402

print(f"Table max lines: {table_conf.max_lines}")

403

print(f"Table max width: {table_conf.max_width}")

404

405

# Coordinates configuration

406

print(f"Auto download sites: {coord_conf.auto_download_sites}")

407

408

# Units configuration

409

print(f"Enabled equivalencies: {units_conf.enable_equivalencies}")

410

411

# Modify subpackage configuration

412

table_conf.max_lines = 25

413

coord_conf.auto_download_sites = False

414

```

415

416

### Configuration in Scripts and Applications

417

418

```python

419

#!/usr/bin/env python

420

\"\"\"

421

Example script using astropy configuration system.

422

\"\"\"

423

424

from astropy.config import ConfigNamespace, ConfigItem

425

from astropy import log

426

import sys

427

428

class ScriptConfig(ConfigNamespace):

429

input_file = ConfigItem(

430

'data.fits',

431

'Input FITS file to process'

432

)

433

434

output_dir = ConfigItem(

435

'./output',

436

'Output directory for results'

437

)

438

439

debug = ConfigItem(

440

False,

441

'Enable debug output'

442

)

443

444

def main():

445

# Initialize configuration

446

conf = ScriptConfig()

447

448

# Set logging level based on configuration

449

if conf.debug:

450

log.setLevel('DEBUG')

451

else:

452

log.setLevel('INFO')

453

454

log.info(f"Processing file: {conf.input_file}")

455

log.info(f"Output directory: {conf.output_dir}")

456

457

# Process data using configuration values

458

# ...

459

460

if __name__ == '__main__':

461

main()

462

```