Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

# 

# LSST Data Management System 

# Copyright 2008-2015 AURA/LSST. 

# 

# This product includes software developed by the 

# LSST Project (http://www.lsst.org/). 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the LSST License Statement and 

# the GNU General Public License along with this program. If not, 

# see <https://www.lsstcorp.org/LegalNotices/>. 

# 

__all__ = ("Config", "Field", "FieldValidationError") 

 

import io 

import os 

import re 

import sys 

import math 

import copy 

import tempfile 

import shutil 

 

from .comparison import getComparisonName, compareScalars, compareConfigs 

from .callStack import getStackFrame, getCallStack 

 

 

def _joinNamePath(prefix=None, name=None, index=None): 

""" 

Utility function for generating nested configuration names 

""" 

41 ↛ 42line 41 didn't jump to line 42, because the condition on line 41 was never true if not prefix and not name: 

raise ValueError("Invalid name: cannot be None") 

43 ↛ 44line 43 didn't jump to line 44, because the condition on line 43 was never true elif not name: 

name = prefix 

45 ↛ 48line 45 didn't jump to line 48, because the condition on line 45 was never false elif prefix and name: 

name = prefix + "." + name 

 

48 ↛ 49line 48 didn't jump to line 49, because the condition on line 48 was never true if index is not None: 

return "%s[%r]" % (name, index) 

else: 

return name 

 

 

def _autocast(x, dtype): 

""" 

If appropriate perform type casting of value x to type dtype, 

otherwise return the original value x 

""" 

if dtype == float and isinstance(x, int): 

return float(x) 

return x 

 

 

def _typeStr(x): 

""" 

Utility function to generate a fully qualified type name. 

 

This is used primarily in writing config files to be 

executed later upon 'load'. 

""" 

if hasattr(x, '__module__') and hasattr(x, '__name__'): 

xtype = x 

else: 

xtype = type(x) 

75 ↛ 76line 75 didn't jump to line 76, because the condition on line 75 was never true if (sys.version_info.major <= 2 and xtype.__module__ == '__builtin__') or xtype.__module__ == 'builtins': 

return xtype.__name__ 

else: 

return "%s.%s" % (xtype.__module__, xtype.__name__) 

 

 

class ConfigMeta(type): 

"""A metaclass for Config 

 

Adds a dictionary containing all Field class attributes 

as a class attribute called '_fields', and adds the name of each field as 

an instance variable of the field itself (so you don't have to pass the 

name of the field to the field constructor). 

""" 

def __init__(cls, name, bases, dict_): 

type.__init__(cls, name, bases, dict_) 

cls._fields = {} 

cls._source = getStackFrame() 

 

def getFields(classtype): 

fields = {} 

bases = list(classtype.__bases__) 

bases.reverse() 

for b in bases: 

fields.update(getFields(b)) 

 

for k, v in classtype.__dict__.items(): 

if isinstance(v, Field): 

fields[k] = v 

return fields 

 

fields = getFields(cls) 

for k, v in fields.items(): 

setattr(cls, k, copy.deepcopy(v)) 

 

def __setattr__(cls, name, value): 

if isinstance(value, Field): 

value.name = name 

cls._fields[name] = value 

type.__setattr__(cls, name, value) 

 

 

class FieldValidationError(ValueError): 

""" 

Custom exception class which holds additional information useful to 

debuggin Config errors: 

- fieldType: type of the Field which incurred the error 

- fieldName: name of the Field which incurred the error 

- fullname: fully qualified name of the Field instance 

- history: full history of all changes to the Field instance 

- fieldSource: file and line number of the Field definition 

""" 

def __init__(self, field, config, msg): 

self.fieldType = type(field) 

self.fieldName = field.name 

self.fullname = _joinNamePath(config._name, field.name) 

self.history = config.history.setdefault(field.name, []) 

self.fieldSource = field.source 

self.configSource = config._source 

error = "%s '%s' failed validation: %s\n"\ 

"For more information read the Field definition at:\n%s"\ 

"And the Config definition at:\n%s" % \ 

(self.fieldType.__name__, self.fullname, msg, 

self.fieldSource.format(), self.configSource.format()) 

ValueError.__init__(self, error) 

 

 

class Field: 

"""A field in a a Config. 

 

Instances of Field should be class attributes of Config subclasses: 

Field only supports basic data types (int, float, complex, bool, str) 

 

class Example(Config): 

myInt = Field(int, "an integer field!", default=0) 

""" 

# Must be able to support str and future str as we can not guarantee that 

# code will pass in a future str type on Python 2 

supportedTypes = set((str, bool, float, int, complex)) 

 

def __init__(self, doc, dtype, default=None, check=None, optional=False): 

"""Initialize a Field. 

 

dtype ------ Data type for the field. 

doc -------- Documentation for the field. 

default ---- A default value for the field. 

check ------ A callable to be called with the field value that returns 

False if the value is invalid. More complex inter-field 

validation can be written as part of Config validate() 

method; this will be ignored if set to None. 

optional --- When False, Config validate() will fail if value is None 

""" 

167 ↛ 168line 167 didn't jump to line 168, because the condition on line 167 was never true if dtype not in self.supportedTypes: 

raise ValueError("Unsupported Field dtype %s" % _typeStr(dtype)) 

 

source = getStackFrame() 

self._setup(doc=doc, dtype=dtype, default=default, check=check, optional=optional, source=source) 

 

def _setup(self, doc, dtype, default, check, optional, source): 

""" 

Convenience function provided to simplify initialization of derived 

Field types 

""" 

self.dtype = dtype 

self.doc = doc 

self.__doc__ = doc+" (`"+dtype.__name__+"`, default "+'``{0!r}``'.format(default)+")" 

self.default = default 

self.check = check 

self.optional = optional 

self.source = source 

 

def rename(self, instance): 

""" 

Rename an instance of this field, not the field itself. 

This is invoked by the owning config object and should not be called 

directly 

 

Only useful for fields which hold sub-configs. 

Fields which hold subconfigs should rename each sub-config with 

the full field name as generated by _joinNamePath 

""" 

pass 

 

def validate(self, instance): 

""" 

Base validation for any field. 

Ensures that non-optional fields are not None. 

Ensures type correctness 

Ensures that user-provided check function is valid 

Most derived Field types should call Field.validate if they choose 

to re-implement validate 

""" 

value = self.__get__(instance) 

if not self.optional and value is None: 

raise FieldValidationError(self, instance, "Required value cannot be None") 

 

def freeze(self, instance): 

""" 

Make this field read-only. 

Only important for fields which hold sub-configs. 

Fields which hold subconfigs should freeze each sub-config. 

""" 

pass 

 

def _validateValue(self, value): 

""" 

Validate a value that is not None 

 

This is called from __set__ 

This is not part of the Field API. However, simple derived field types 

may benefit from implementing _validateValue 

""" 

227 ↛ 228line 227 didn't jump to line 228, because the condition on line 227 was never true if value is None: 

return 

 

230 ↛ 231line 230 didn't jump to line 231, because the condition on line 230 was never true if not isinstance(value, self.dtype): 

msg = "Value %s is of incorrect type %s. Expected type %s" % \ 

(value, _typeStr(value), _typeStr(self.dtype)) 

raise TypeError(msg) 

234 ↛ 235line 234 didn't jump to line 235, because the condition on line 234 was never true if self.check is not None and not self.check(value): 

msg = "Value %s is not a valid value" % str(value) 

raise ValueError(msg) 

 

def save(self, outfile, instance): 

""" 

Saves an instance of this field to file. 

This is invoked by the owning config object, and should not be called 

directly 

 

outfile ---- an open output stream. 

""" 

value = self.__get__(instance) 

fullname = _joinNamePath(instance._name, self.name) 

 

# write full documentation string as comment lines (i.e. first character is #) 

doc = "# " + str(self.doc).replace("\n", "\n# ") 

251 ↛ 253line 251 didn't jump to line 253, because the condition on line 251 was never true if isinstance(value, float) and (math.isinf(value) or math.isnan(value)): 

# non-finite numbers need special care 

outfile.write(u"{}\n{}=float('{!r}')\n\n".format(doc, fullname, value)) 

else: 

outfile.write(u"{}\n{}={!r}\n\n".format(doc, fullname, value)) 

 

def toDict(self, instance): 

""" 

Convert the field value so that it can be set as the value of an item 

in a dict. 

This is invoked by the owning config object and should not be called 

directly 

 

Simple values are passed through. Complex data structures must be 

manipulated. For example, a field holding a sub-config should, instead 

of the subconfig object, return a dict where the keys are the field 

names in the subconfig, and the values are the field values in the 

subconfig. 

""" 

return self.__get__(instance) 

 

def __get__(self, instance, owner=None, at=None, label="default"): 

""" 

Define how attribute access should occur on the Config instance 

This is invoked by the owning config object and should not be called 

directly 

 

When the field attribute is accessed on a Config class object, it 

returns the field object itself in order to allow inspection of 

Config classes. 

 

When the field attribute is access on a config instance, the actual 

value described by the field (and held by the Config instance) is 

returned. 

""" 

286 ↛ 287line 286 didn't jump to line 287, because the condition on line 286 was never true if instance is None or not isinstance(instance, Config): 

return self 

else: 

return instance._storage[self.name] 

 

def __set__(self, instance, value, at=None, label='assignment'): 

""" 

Describe how attribute setting should occur on the config instance. 

This is invoked by the owning config object and should not be called 

directly 

 

Derived Field classes may need to override the behavior. When overriding 

__set__, Field authors should follow the following rules: 

* Do not allow modification of frozen configs 

* Validate the new value *BEFORE* modifying the field. Except if the 

new value is None. None is special and no attempt should be made to 

validate it until Config.validate is called. 

* Do not modify the Config instance to contain invalid values. 

* If the field is modified, update the history of the field to reflect the 

changes 

 

In order to decrease the need to implement this method in derived Field 

types, value validation is performed in the method _validateValue. If 

only the validation step differs in the derived Field, it is simpler to 

implement _validateValue than to re-implement __set__. More complicated 

behavior, however, may require a reimplementation. 

""" 

313 ↛ 314line 313 didn't jump to line 314, because the condition on line 313 was never true if instance._frozen: 

raise FieldValidationError(self, instance, "Cannot modify a frozen Config") 

 

history = instance._history.setdefault(self.name, []) 

317 ↛ 324line 317 didn't jump to line 324, because the condition on line 317 was never false if value is not None: 

value = _autocast(value, self.dtype) 

try: 

self._validateValue(value) 

except BaseException as e: 

raise FieldValidationError(self, instance, str(e)) 

 

instance._storage[self.name] = value 

325 ↛ 326line 325 didn't jump to line 326, because the condition on line 325 was never true if at is None: 

at = getCallStack() 

history.append((value, at, label)) 

 

def __delete__(self, instance, at=None, label='deletion'): 

""" 

Describe how attribute deletion should occur on the Config instance. 

This is invoked by the owning config object and should not be called 

directly 

""" 

if at is None: 

at = getCallStack() 

self.__set__(instance, None, at=at, label=label) 

 

def _compare(self, instance1, instance2, shortcut, rtol, atol, output): 

"""Helper function for Config.compare; used to compare two fields for equality. 

 

Must be overridden by more complex field types. 

 

@param[in] instance1 LHS Config instance to compare. 

@param[in] instance2 RHS Config instance to compare. 

@param[in] shortcut If True, return as soon as an inequality is found. 

@param[in] rtol Relative tolerance for floating point comparisons. 

@param[in] atol Absolute tolerance for floating point comparisons. 

@param[in] output If not None, a callable that takes a string, used (possibly repeatedly) 

to report inequalities. 

 

Floating point comparisons are performed by numpy.allclose; refer to that for details. 

""" 

v1 = getattr(instance1, self.name) 

v2 = getattr(instance2, self.name) 

name = getComparisonName( 

_joinNamePath(instance1._name, self.name), 

_joinNamePath(instance2._name, self.name) 

) 

return compareScalars(name, v1, v2, dtype=self.dtype, rtol=rtol, atol=atol, output=output) 

 

 

class RecordingImporter: 

"""An Importer (for sys.meta_path) that records which modules are being imported. 

 

Objects also act as Context Managers, so you can: 

with RecordingImporter() as importer: 

import stuff 

print("Imported: " + importer.getModules()) 

This ensures it is properly uninstalled when done. 

 

This class makes no effort to do any importing itself. 

""" 

def __init__(self): 

"""Create and install the Importer""" 

self._modules = set() 

 

def __enter__(self): 

 

self.origMetaPath = sys.meta_path 

sys.meta_path = [self] + sys.meta_path 

return self 

 

def __exit__(self, *args): 

self.uninstall() 

return False # Don't suppress exceptions 

 

def uninstall(self): 

"""Uninstall the Importer""" 

sys.meta_path = self.origMetaPath 

 

def find_module(self, fullname, path=None): 

"""Called as part of the 'import' chain of events. 

 

We return None because we don't do any importing. 

""" 

self._modules.add(fullname) 

return None 

 

def getModules(self): 

"""Return the set of modules that were imported.""" 

return self._modules 

 

 

class Config(metaclass=ConfigMeta): 

"""Base class for control objects. 

 

A Config object will usually have several Field instances as class 

attributes; these are used to define most of the base class behavior. 

Simple derived class should be able to be defined simply by setting those 

attributes. 

 

Config also emulates a dict of field name: field value 

""" 

 

def __iter__(self): 

"""!Iterate over fields 

""" 

return self._fields.__iter__() 

 

def keys(self): 

"""!Return the list of field names 

""" 

return list(self._storage.keys()) 

 

def values(self): 

"""!Return the list of field values 

""" 

return list(self._storage.values()) 

 

def items(self): 

"""!Return the list of (field name, field value) pairs 

""" 

return list(self._storage.items()) 

 

def iteritems(self): 

"""!Iterate over (field name, field value) pairs 

""" 

return iter(self._storage.items()) 

 

def itervalues(self): 

"""!Iterate over field values 

""" 

return iter(self.storage.values()) 

 

def iterkeys(self): 

"""!Iterate over field names 

""" 

return iter(self.storage.keys()) 

 

def __contains__(self, name): 

"""!Return True if the specified field exists in this config 

 

@param[in] name field name to test for 

""" 

return self._storage.__contains__(name) 

 

def __new__(cls, *args, **kw): 

"""!Allocate a new Config object. 

 

In order to ensure that all Config object are always in a proper 

state when handed to users or to derived Config classes, some 

attributes are handled at allocation time rather than at initialization 

 

This ensures that even if a derived Config class implements __init__, 

the author does not need to be concerned about when or even if he 

should call the base Config.__init__ 

""" 

name = kw.pop("__name", None) 

at = kw.pop("__at", getCallStack()) 

# remove __label and ignore it 

kw.pop("__label", "default") 

 

instance = object.__new__(cls) 

instance._frozen = False 

instance._name = name 

instance._storage = {} 

instance._history = {} 

instance._imports = set() 

# load up defaults 

for field in instance._fields.values(): 

instance._history[field.name] = [] 

field.__set__(instance, field.default, at=at + [field.source], label="default") 

# set custom default-overides 

instance.setDefaults() 

# set constructor overides 

instance.update(__at=at, **kw) 

return instance 

 

def __reduce__(self): 

"""Reduction for pickling (function with arguments to reproduce). 

 

We need to condense and reconstitute the Config, since it may contain lambdas 

(as the 'check' elements) that cannot be pickled. 

""" 

# The stream must be in characters to match the API but pickle requires bytes 

stream = io.StringIO() 

self.saveToStream(stream) 

return (unreduceConfig, (self.__class__, stream.getvalue().encode())) 

 

def setDefaults(self): 

""" 

Derived config classes that must compute defaults rather than using the 

Field defaults should do so here. 

To correctly use inherited defaults, implementations of setDefaults() 

must call their base class' setDefaults() 

""" 

pass 

 

def update(self, **kw): 

"""!Update values specified by the keyword arguments 

 

@warning The '__at' and '__label' keyword arguments are special internal 

keywords. They are used to strip out any internal steps from the 

history tracebacks of the config. Modifying these keywords allows users 

to lie about a Config's history. Please do not do so! 

""" 

at = kw.pop("__at", getCallStack()) 

label = kw.pop("__label", "update") 

 

for name, value in kw.items(): 

try: 

field = self._fields[name] 

field.__set__(self, value, at=at, label=label) 

except KeyError: 

raise KeyError("No field of name %s exists in config type %s" % (name, _typeStr(self))) 

 

def load(self, filename, root="config"): 

"""!Modify this config in place by executing the Python code in the named file. 

 

@param[in] filename name of file containing config override code 

@param[in] root name of variable in file that refers to the config being overridden 

 

For example: if the value of root is "config" and the file contains this text: 

"config.myField = 5" then this config's field "myField" is set to 5. 

 

@deprecated For purposes of backwards compatibility, older config files that use 

root="root" instead of root="config" will be loaded with a warning printed to sys.stderr. 

This feature will be removed at some point. 

""" 

with open(filename, "r") as f: 

code = compile(f.read(), filename=filename, mode="exec") 

self.loadFromStream(stream=code, root=root) 

 

def loadFromStream(self, stream, root="config", filename=None): 

"""!Modify this config in place by executing the python code in the provided stream. 

 

@param[in] stream open file object, string or compiled string containing config override code 

@param[in] root name of variable in stream that refers to the config being overridden 

@param[in] filename name of config override file, or None if unknown or contained 

in the stream; used for error reporting 

 

For example: if the value of root is "config" and the stream contains this text: 

"config.myField = 5" then this config's field "myField" is set to 5. 

 

@deprecated For purposes of backwards compatibility, older config files that use 

root="root" instead of root="config" will be loaded with a warning printed to sys.stderr. 

This feature will be removed at some point. 

""" 

with RecordingImporter() as importer: 

try: 

local = {root: self} 

exec(stream, {}, local) 

except NameError as e: 

if root == "config" and "root" in e.args[0]: 

if filename is None: 

# try to determine the file name; a compiled string has attribute "co_filename", 

# an open file has attribute "name", else give up 

filename = getattr(stream, "co_filename", None) 

if filename is None: 

filename = getattr(stream, "name", "?") 

sys.stderr.write(u"Config override file %r" % (filename,) + 

u" appears to use 'root' instead of 'config'; trying with 'root'") 

local = {"root": self} 

exec(stream, {}, local) 

else: 

raise 

 

self._imports.update(importer.getModules()) 

 

def save(self, filename, root="config"): 

"""!Save a python script to the named file, which, when loaded, reproduces this Config 

 

@param[in] filename name of file to which to write the config 

@param[in] root name to use for the root config variable; the same value must be used when loading 

""" 

d = os.path.dirname(filename) 

with tempfile.NamedTemporaryFile(mode="w", delete=False, dir=d) as outfile: 

self.saveToStream(outfile, root) 

# tempfile is hardcoded to create files with mode '0600' 

# for an explantion of these antics see: 

# https://stackoverflow.com/questions/10291131/how-to-use-os-umask-in-python 

umask = os.umask(0o077) 

os.umask(umask) 

os.chmod(outfile.name, (~umask & 0o666)) 

# chmod before the move so we get quasi-atomic behavior if the 

# source and dest. are on the same filesystem. 

# os.rename may not work across filesystems 

shutil.move(outfile.name, filename) 

 

def saveToStream(self, outfile, root="config"): 

"""!Save a python script to a stream, which, when loaded, reproduces this Config 

 

@param outfile [inout] open file object to which to write the config. Accepts strings not bytes. 

@param root [in] name to use for the root config variable; the same value must be used when loading 

""" 

tmp = self._name 

self._rename(root) 

try: 

configType = type(self) 

typeString = _typeStr(configType) 

outfile.write(u"import {}\n".format(configType.__module__)) 

outfile.write(u"assert type({})=={}, 'config is of type %s.%s ".format(root, typeString)) 

outfile.write(u"instead of {}' % (type({}).__module__, type({}).__name__)\n".format(typeString, 

root, 

root)) 

self._save(outfile) 

finally: 

self._rename(tmp) 

 

def freeze(self): 

"""!Make this Config and all sub-configs read-only 

""" 

self._frozen = True 

for field in self._fields.values(): 

field.freeze(self) 

 

def _save(self, outfile): 

"""!Save this Config to an open stream object 

""" 

631 ↛ 632line 631 didn't jump to line 632, because the loop on line 631 never started for imp in self._imports: 

if imp in sys.modules and sys.modules[imp] is not None: 

outfile.write(u"import {}\n".format(imp)) 

for field in self._fields.values(): 

field.save(outfile, self) 

 

def toDict(self): 

"""!Return a dict of field name: value 

 

Correct behavior is dependent on proper implementation of Field.toDict. If implementing a new 

Field type, you may need to implement your own toDict method. 

""" 

dict_ = {} 

for name, field in self._fields.items(): 

dict_[name] = field.toDict(self) 

return dict_ 

 

def names(self): 

"""!Return all the keys in a config recursively 

""" 

# 

# Rather than sort out the recursion all over again use the 

# pre-existing saveToStream() 

# 

with io.StringIO() as strFd: 

self.saveToStream(strFd, "config") 

contents = strFd.getvalue() 

strFd.close() 

# 

# Pull the names out of the dumped config 

# 

keys = [] 

for line in contents.split("\n"): 

if re.search(r"^((assert|import)\s+|\s*$|#)", line): 

continue 

 

mat = re.search(r"^(?:config\.)?([^=]+)\s*=\s*.*", line) 

if mat: 

keys.append(mat.group(1)) 

 

return keys 

 

def _rename(self, name): 

"""!Rename this Config object in its parent config 

 

@param[in] name new name for this config in its parent config 

 

Correct behavior is dependent on proper implementation of Field.rename. If implementing a new 

Field type, you may need to implement your own rename method. 

""" 

self._name = name 

for field in self._fields.values(): 

field.rename(self) 

 

def validate(self): 

"""!Validate the Config; raise an exception if invalid 

 

The base class implementation performs type checks on all fields by 

calling Field.validate(). 

 

Complex single-field validation can be defined by deriving new Field 

types. As syntactic sugar, some derived Field types are defined in 

this module which handle recursing into sub-configs 

(ConfigField, ConfigChoiceField) 

 

Inter-field relationships should only be checked in derived Config 

classes after calling this method, and base validation is complete 

""" 

for field in self._fields.values(): 

field.validate(self) 

 

def formatHistory(self, name, **kwargs): 

"""!Format the specified config field's history to a more human-readable format 

 

@param[in] name name of field whose history is wanted 

@param[in] kwargs keyword arguments for lsst.pex.config.history.format 

@return a string containing the formatted history 

""" 

import lsst.pex.config.history as pexHist 

return pexHist.format(self, name, **kwargs) 

 

""" 

Read-only history property 

""" 

715 ↛ exitline 715 didn't run the lambda on line 715 history = property(lambda x: x._history) 

 

def __setattr__(self, attr, value, at=None, label="assignment"): 

"""!Regulate which attributes can be set 

 

Unlike normal python objects, Config objects are locked such 

that no additional attributes nor properties may be added to them 

dynamically. 

 

Although this is not the standard Python behavior, it helps to 

protect users from accidentally mispelling a field name, or 

trying to set a non-existent field. 

""" 

if attr in self._fields: 

729 ↛ 732line 729 didn't jump to line 732, because the condition on line 729 was never false if at is None: 

at = getCallStack() 

# This allows Field descriptors to work. 

self._fields[attr].__set__(self, value, at=at, label=label) 

733 ↛ 735line 733 didn't jump to line 735, because the condition on line 733 was never true elif hasattr(getattr(self.__class__, attr, None), '__set__'): 

# This allows properties and other non-Field descriptors to work. 

return object.__setattr__(self, attr, value) 

736 ↛ 741line 736 didn't jump to line 741, because the condition on line 736 was never false elif attr in self.__dict__ or attr in ("_name", "_history", "_storage", "_frozen", "_imports"): 

# This allows specific private attributes to work. 

self.__dict__[attr] = value 

else: 

# We throw everything else. 

raise AttributeError("%s has no attribute %s" % (_typeStr(self), attr)) 

 

def __delattr__(self, attr, at=None, label="deletion"): 

if attr in self._fields: 

if at is None: 

at = getCallStack() 

self._fields[attr].__delete__(self, at=at, label=label) 

else: 

object.__delattr__(self, attr) 

 

def __eq__(self, other): 

752 ↛ 753line 752 didn't jump to line 753, because the condition on line 752 was never true if type(other) == type(self): 

for name in self._fields: 

thisValue = getattr(self, name) 

otherValue = getattr(other, name) 

if isinstance(thisValue, float) and math.isnan(thisValue): 

if not math.isnan(otherValue): 

return False 

elif thisValue != otherValue: 

return False 

return True 

return False 

 

def __ne__(self, other): 

return not self.__eq__(other) 

 

def __str__(self): 

return str(self.toDict()) 

 

def __repr__(self): 

return "%s(%s)" % ( 

_typeStr(self), 

", ".join("%s=%r" % (k, v) for k, v in self.toDict().items() if v is not None) 

) 

 

def compare(self, other, shortcut=True, rtol=1E-8, atol=1E-8, output=None): 

"""!Compare two Configs for equality; return True if equal 

 

If the Configs contain RegistryFields or ConfigChoiceFields, unselected Configs 

will not be compared. 

 

@param[in] other Config object to compare with self. 

@param[in] shortcut If True, return as soon as an inequality is found. 

@param[in] rtol Relative tolerance for floating point comparisons. 

@param[in] atol Absolute tolerance for floating point comparisons. 

@param[in] output If not None, a callable that takes a string, used (possibly repeatedly) 

to report inequalities. 

 

Floating point comparisons are performed by numpy.allclose; refer to that for details. 

""" 

name1 = self._name if self._name is not None else "config" 

name2 = other._name if other._name is not None else "config" 

name = getComparisonName(name1, name2) 

return compareConfigs(name, self, other, shortcut=shortcut, 

rtol=rtol, atol=atol, output=output) 

 

 

def unreduceConfig(cls, stream): 

config = cls() 

config.loadFromStream(stream) 

return config