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

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

# -*- coding: utf-8 -*- 

# http://pyrocko.org - GPLv3 

# 

# The Pyrocko Developers, 21st Century 

# ---|P------/S----------~Lg---------- 

'''Lightweight declarative YAML and XML data binding for Python.''' 

from __future__ import absolute_import, print_function 

 

import datetime 

import calendar 

import re 

import sys 

import types 

import copy 

import os.path as op 

from collections import defaultdict 

 

from io import BytesIO 

 

try: 

import numpy as num 

except ImportError: 

num = None 

 

import yaml 

try: 

from yaml import CSafeLoader as SafeLoader, CSafeDumper as SafeDumper 

except ImportError: 

from yaml import SafeLoader, SafeDumper 

 

from .util import time_to_str, str_to_time, TimeStrError, hpfloat, \ 

get_time_class 

 

try: 

newstr = unicode 

range = xrange 

except NameError: 

newstr = str 

 

try: 

# needed for py2/py3 compatibility to allow 

# from pyrocko.guts import FileNotFoundError 

FileNotFoundError = FileNotFoundError 

except NameError: 

class FileNotFoundError(EnvironmentError): 

pass 

 

 

ALLOW_INCLUDE = False 

 

 

class GutsSafeDumper(SafeDumper): 

pass 

 

 

class GutsSafeLoader(SafeLoader): 

pass 

 

 

try: 

unicode 

except NameError: 

unicode = str 

 

 

g_iprop = 0 

 

g_deferred = {} 

g_deferred_content = {} 

 

g_tagname_to_class = {} 

g_xmltagname_to_class = {} 

g_guessable_xmlns = {} 

 

guts_types = [ 

'Object', 'SObject', 'String', 'Unicode', 'Int', 'Float', 

'Complex', 'Bool', 'Timestamp', 'DateTimestamp', 'StringPattern', 

'UnicodePattern', 'StringChoice', 'List', 'Dict', 'Tuple', 'Union', 

'Choice', 'Any'] 

 

us_to_cc_regex = re.compile(r'([a-z])_([a-z])') 

 

 

class literal(str): 

pass 

 

 

class folded(str): 

pass 

 

 

class singlequoted(str): 

pass 

 

 

class doublequoted(str): 

pass 

 

 

def make_str_presenter(style): 

def presenter(dumper, data): 

return dumper.represent_scalar( 

'tag:yaml.org,2002:str', str(data), style=style) 

 

return presenter 

 

 

str_style_map = { 

None: lambda x: x, 

'|': literal, 

'>': folded, 

"'": singlequoted, 

'"': doublequoted} 

 

for (style, cls) in str_style_map.items(): 

if style: 

GutsSafeDumper.add_representer(cls, make_str_presenter(style)) 

 

 

class uliteral(unicode): 

pass 

 

 

class ufolded(unicode): 

pass 

 

 

class usinglequoted(unicode): 

pass 

 

 

class udoublequoted(unicode): 

pass 

 

 

def make_unicode_presenter(style): 

def presenter(dumper, data): 

return dumper.represent_scalar( 

'tag:yaml.org,2002:str', unicode(data), style=style) 

 

return presenter 

 

 

unicode_style_map = { 

None: lambda x: x, 

'|': literal, 

'>': folded, 

"'": singlequoted, 

'"': doublequoted} 

 

for (style, cls) in unicode_style_map.items(): 

if style: 

GutsSafeDumper.add_representer(cls, make_unicode_presenter(style)) 

 

 

class blist(list): 

pass 

 

 

class flist(list): 

pass 

 

 

list_style_map = { 

None: list, 

'block': blist, 

'flow': flist} 

 

 

def make_list_presenter(flow_style): 

def presenter(dumper, data): 

return dumper.represent_sequence( 

'tag:yaml.org,2002:seq', data, flow_style=flow_style) 

 

return presenter 

 

 

GutsSafeDumper.add_representer(blist, make_list_presenter(False)) 

GutsSafeDumper.add_representer(flist, make_list_presenter(True)) 

 

if num: 

def numpy_float_presenter(dumper, data): 

return dumper.represent_float(float(data)) 

 

def numpy_int_presenter(dumper, data): 

return dumper.represent_int(int(data)) 

 

for dtype in (num.float64, num.float32): 

GutsSafeDumper.add_representer(dtype, numpy_float_presenter) 

 

for dtype in (num.int32, num.int64): 

GutsSafeDumper.add_representer(dtype, numpy_int_presenter) 

 

 

def us_to_cc(s): 

return us_to_cc_regex.sub(lambda pat: pat.group(1)+pat.group(2).upper(), s) 

 

 

cc_to_us_regex1 = re.compile(r'([a-z])([A-Z]+)([a-z]|$)') 

cc_to_us_regex2 = re.compile(r'([A-Z])([A-Z][a-z])') 

 

 

def cc_to_us(s): 

return cc_to_us_regex2.sub('\\1_\\2', cc_to_us_regex1.sub( 

'\\1_\\2\\3', s)).lower() 

 

 

re_frac = re.compile(r'\.[1-9]FRAC') 

frac_formats = dict([('.%sFRAC' % x, '%.'+x+'f') for x in '123456789']) 

 

 

def encode_utf8(s): 

return s.encode('utf-8') 

 

 

def no_encode(s): 

return s 

 

 

def make_xmltagname_from_name(name): 

return us_to_cc(name) 

 

 

def make_name_from_xmltagname(xmltagname): 

return cc_to_us(xmltagname) 

 

 

def make_content_name(name): 

if name.endswith('_list'): 

return name[:-5] 

elif name.endswith('s'): 

return name[:-1] 

else: 

return name 

 

 

def classnames(cls): 

if isinstance(cls, tuple): 

return '(%s)' % ', '.join(x.__name__ for x in cls) 

else: 

return cls.__name__ 

 

 

def expand_stream_args(mode): 

def wrap(f): 

'''Decorator to enhance functions taking stream objects. 

 

Wraps a function f(..., stream, ...) so that it can also be called as 

f(..., filename='myfilename', ...) or as f(..., string='mydata', ...). 

''' 

 

def g(*args, **kwargs): 

stream = kwargs.pop('stream', None) 

filename = kwargs.get('filename', None) 

if mode != 'r': 

filename = kwargs.pop('filename', None) 

string = kwargs.pop('string', None) 

 

assert sum(x is not None for x in (stream, filename, string)) <= 1 

 

if stream is not None: 

kwargs['stream'] = stream 

return f(*args, **kwargs) 

 

elif filename is not None: 

stream = open(filename, mode+'b') 

kwargs['stream'] = stream 

retval = f(*args, **kwargs) 

if isinstance(retval, types.GeneratorType): 

def wrap_generator(gen): 

try: 

for x in gen: 

yield x 

 

except GeneratorExit: 

pass 

 

stream.close() 

 

return wrap_generator(retval) 

 

else: 

stream.close() 

return retval 

 

elif string is not None: 

assert mode == 'r', \ 

'Keyword argument string=... cannot be used in dumper ' \ 

'function.' 

 

kwargs['stream'] = BytesIO(string.encode('utf-8')) 

return f(*args, **kwargs) 

 

else: 

assert mode == 'w', \ 

'Use keyword argument stream=... or filename=... in ' \ 

'loader function.' 

 

sout = BytesIO() 

f(stream=sout, *args, **kwargs) 

return sout.getvalue().decode('utf-8') 

 

return g 

 

return wrap 

 

 

class Defer(object): 

def __init__(self, classname, *args, **kwargs): 

global g_iprop 

if kwargs.get('position', None) is None: 

kwargs['position'] = g_iprop 

 

g_iprop += 1 

 

self.classname = classname 

self.args = args 

self.kwargs = kwargs 

 

 

class TBase(object): 

 

strict = False 

multivalued = None 

force_regularize = False 

propnames = [] 

 

@classmethod 

def init_propertystuff(cls): 

cls.properties = [] 

cls.xmltagname_to_name = {} 

cls.xmltagname_to_name_multivalued = {} 

cls.xmltagname_to_class = {} 

cls.content_property = None 

 

def __init__( 

self, 

default=None, 

optional=False, 

xmlstyle='element', 

xmltagname=None, 

xmlns=None, 

help=None, 

position=None): 

 

global g_iprop 

if position is not None: 

self.position = position 

else: 

self.position = g_iprop 

 

g_iprop += 1 

self._default = default 

if isinstance(self._default, DefaultMaker): 

self._default_cmp = self._default.make() 

else: 

self._default_cmp = self._default 

 

self.optional = optional 

self.name = None 

self._xmltagname = xmltagname 

self._xmlns = xmlns 

self.parent = None 

self.xmlstyle = xmlstyle 

self.help = help 

 

def default(self): 

return make_default(self._default) 

 

def is_default(self, val): 

if self._default_cmp is None: 

return val is None 

else: 

return self._default_cmp == val 

 

def has_default(self): 

return self._default is not None 

 

def xname(self): 

if self.name is not None: 

return self.name 

elif self.parent is not None: 

return 'element of %s' % self.parent.xname() 

else: 

return '?' 

 

def set_xmlns(self, xmlns): 

if self._xmlns is None and not self.xmlns: 

self._xmlns = xmlns 

 

if self.multivalued: 

self.content_t.set_xmlns(xmlns) 

 

def get_xmlns(self): 

return self._xmlns or self.xmlns 

 

def get_xmltagname(self): 

if self._xmltagname is not None: 

return self.get_xmlns() + ' ' + self._xmltagname 

elif self.name: 

return self.get_xmlns() + ' ' \ 

+ make_xmltagname_from_name(self.name) 

elif self.xmltagname: 

return self.get_xmlns() + ' ' + self.xmltagname 

else: 

assert False 

 

@classmethod 

def get_property(cls, name): 

for prop in cls.properties: 

if prop.name == name: 

return prop 

 

raise ValueError() 

 

@classmethod 

def remove_property(cls, name): 

 

prop = cls.get_property(name) 

 

if not prop.multivalued: 

del cls.xmltagname_to_class[prop.effective_xmltagname] 

del cls.xmltagname_to_name[prop.effective_xmltagname] 

else: 

del cls.xmltagname_to_class[prop.content_t.effective_xmltagname] 

del cls.xmltagname_to_name_multivalued[ 

prop.content_t.effective_xmltagname] 

 

if cls.content_property is prop: 

cls.content_property = None 

 

cls.properties.remove(prop) 

cls.propnames.remove(name) 

 

return prop 

 

@classmethod 

def add_property(cls, name, prop): 

 

prop.instance = prop 

prop.name = name 

prop.set_xmlns(cls.xmlns) 

 

if isinstance(prop, Choice.T): 

for tc in prop.choices: 

tc.effective_xmltagname = tc.get_xmltagname() 

cls.xmltagname_to_class[tc.effective_xmltagname] = tc.cls 

cls.xmltagname_to_name[tc.effective_xmltagname] = prop.name 

elif not prop.multivalued: 

prop.effective_xmltagname = prop.get_xmltagname() 

cls.xmltagname_to_class[prop.effective_xmltagname] = prop.cls 

cls.xmltagname_to_name[prop.effective_xmltagname] = prop.name 

else: 

prop.content_t.name = make_content_name(prop.name) 

prop.content_t.effective_xmltagname = \ 

prop.content_t.get_xmltagname() 

cls.xmltagname_to_class[ 

prop.content_t.effective_xmltagname] = prop.content_t.cls 

cls.xmltagname_to_name_multivalued[ 

prop.content_t.effective_xmltagname] = prop.name 

 

cls.properties.append(prop) 

 

cls.properties.sort(key=lambda x: x.position) 

 

cls.propnames = [p.name for p in cls.properties] 

 

if prop.xmlstyle == 'content': 

cls.content_property = prop 

 

@classmethod 

def ivals(cls, val): 

for prop in cls.properties: 

yield getattr(val, prop.name) 

 

@classmethod 

def ipropvals(cls, val): 

for prop in cls.properties: 

yield prop, getattr(val, prop.name) 

 

@classmethod 

def inamevals(cls, val): 

for prop in cls.properties: 

yield prop.name, getattr(val, prop.name) 

 

@classmethod 

def ipropvals_to_save(cls, val, xmlmode=False): 

for prop in cls.properties: 

v = getattr(val, prop.name) 

if v is not None and ( 

not (prop.optional or (prop.multivalued and not v)) 

or (not prop.is_default(v))): 

 

if xmlmode: 

yield prop, prop.to_save_xml(v) 

else: 

yield prop, prop.to_save(v) 

 

@classmethod 

def inamevals_to_save(cls, val, xmlmode=False): 

for prop, v in cls.ipropvals_to_save(val, xmlmode): 

yield prop.name, v 

 

@classmethod 

def translate_from_xml(cls, list_of_pairs, strict): 

d = {} 

for k, v in list_of_pairs: 

if k in cls.xmltagname_to_name_multivalued: 

k2 = cls.xmltagname_to_name_multivalued[k] 

if k2 not in d: 

d[k2] = [] 

 

d[k2].append(v) 

elif k in cls.xmltagname_to_name: 

k2 = cls.xmltagname_to_name[k] 

if k2 in d: 

raise ArgumentError( 

'Unexpectedly found more than one child element "%s" ' 

'within "%s".' % (k, cls.tagname)) 

 

d[k2] = v 

elif k is None: 

if cls.content_property: 

k2 = cls.content_property.name 

d[k2] = v 

else: 

if strict: 

raise ArgumentError( 

'Unexpected child element "%s" found within "%s".' % ( 

k, cls.tagname)) 

 

return d 

 

def validate(self, val, regularize=False, depth=-1): 

if self.optional and val is None: 

return val 

 

is_derived = isinstance(val, self.cls) 

is_exact = type(val) == self.cls 

 

not_ok = not self.strict and not is_derived or \ 

self.strict and not is_exact 

 

if not_ok or self.force_regularize: 

if regularize: 

try: 

val = self.regularize_extra(val) 

except ValueError: 

raise ValidationError( 

'%s: could not convert "%s" to type %s' % ( 

self.xname(), val, classnames(self.cls))) 

else: 

raise ValidationError( 

'%s: "%s" (type: %s) is not of type %s' % ( 

self.xname(), val, type(val), classnames(self.cls))) 

 

validator = self 

if isinstance(self.cls, tuple): 

clss = self.cls 

else: 

clss = (self.cls,) 

 

for cls in clss: 

try: 

if type(val) != cls and isinstance(val, cls): 

validator = val.T.instance 

 

except AttributeError: 

pass 

 

validator.validate_extra(val) 

 

if depth != 0: 

val = validator.validate_children(val, regularize, depth) 

 

return val 

 

def regularize_extra(self, val): 

return self.cls(val) 

 

def validate_extra(self, val): 

pass 

 

def validate_children(self, val, regularize, depth): 

for prop, propval in self.ipropvals(val): 

newpropval = prop.validate(propval, regularize, depth-1) 

if regularize and (newpropval is not propval): 

setattr(val, prop.name, newpropval) 

 

return val 

 

def to_save(self, val): 

return val 

 

def to_save_xml(self, val): 

return self.to_save(val) 

 

def extend_xmlelements(self, elems, v): 

if self.multivalued: 

for x in v: 

elems.append((self.content_t.effective_xmltagname, x)) 

else: 

elems.append((self.effective_xmltagname, v)) 

 

def deferred(self): 

return [] 

 

def classname_for_help(self, strip_module=''): 

if self.dummy_cls in guts_plain_dummy_types: 

return '``%s``' % self.cls.__name__ 

else: 

if isinstance(self.cls, tuple): 

return 'fixme!' 

 

mod = self.cls.__module__ 

cls = self.cls.__name__ 

if self.dummy_cls is not self.cls: 

if self.dummy_cls.__module__ == strip_module: 

sadd = ' (:py:class:`%s`)' % ( 

self.dummy_cls.__name__) 

else: 

sadd = ' (:py:class:`%s.%s`)' % ( 

self.dummy_cls.__module__, self.dummy_cls.__name__) 

else: 

sadd = '' 

 

if mod == '__builtin__': 

return '``%s``%s' % (cls, sadd) 

 

elif self.cls.__module__ == strip_module: 

return ':py:class:`%s`%s' % (cls, sadd) 

 

else: 

return ':py:class:`%s.%s`%s' % (mod, cls, sadd) 

 

@classmethod 

def props_help_string(cls): 

baseprops = [] 

for base in cls.dummy_cls.__bases__: 

if hasattr(base, 'T'): 

baseprops.extend(base.T.properties) 

 

hlp = [] 

hlp.append('') 

for prop in cls.properties: 

if prop in baseprops: 

continue 

 

descr = [ 

prop.classname_for_help(strip_module=cls.dummy_cls.__module__)] 

 

if prop.optional: 

descr.append('*optional*') 

 

d = prop.default() 

if d is not None: 

descr.append('*default:* ``%s``' % repr(d)) 

 

hlp.append(' .. py:gattribute:: %s' % prop.name) 

hlp.append('') 

hlp.append(' %s' % ', '.join(descr)) 

hlp.append(' ') 

if prop.help is not None: 

hlp.append(' %s' % prop.help) 

hlp.append('') 

 

return '\n'.join(hlp) 

 

@classmethod 

def class_help_string(cls): 

return cls.dummy_cls.__doc_template__ 

 

@classmethod 

def class_signature(cls): 

r = [] 

for prop in cls.properties: 

d = prop.default() 

if d is not None: 

arg = repr(d) 

 

elif prop.optional: 

arg = 'None' 

 

else: 

arg = '...' 

 

r.append('%s=%s' % (prop.name, arg)) 

 

return '(%s)' % ', '.join(r) 

 

@classmethod 

def help(cls): 

return cls.props_help_string() 

 

 

class ObjectMetaClass(type): 

def __new__(meta, classname, bases, class_dict): 

cls = type.__new__(meta, classname, bases, class_dict) 

if classname != 'Object': 

t_class_attr_name = '_%s__T' % classname 

if not hasattr(cls, t_class_attr_name): 

if hasattr(cls, 'T'): 

class T(cls.T): 

pass 

else: 

class T(TBase): 

pass 

 

setattr(cls, t_class_attr_name, T) 

 

T = getattr(cls, t_class_attr_name) 

 

if cls.dummy_for is not None: 

T.cls = cls.dummy_for 

else: 

T.cls = cls 

 

T.dummy_cls = cls 

 

if hasattr(cls, 'xmltagname'): 

T.xmltagname = cls.xmltagname 

else: 

T.xmltagname = classname 

 

mod = sys.modules[cls.__module__] 

 

if hasattr(cls, 'xmlns'): 

T.xmlns = cls.xmlns 

elif hasattr(mod, 'guts_xmlns'): 

T.xmlns = mod.guts_xmlns 

else: 

T.xmlns = '' 

 

if T.xmlns and hasattr(cls, 'guessable_xmlns'): 

g_guessable_xmlns[T.xmltagname] = cls.guessable_xmlns 

 

if hasattr(mod, 'guts_prefix'): 

if mod.guts_prefix: 

T.tagname = mod.guts_prefix + '.' + classname 

else: 

T.tagname = classname 

else: 

if cls.__module__ != '__main__': 

T.tagname = cls.__module__ + '.' + classname 

else: 

T.tagname = classname 

 

T.classname = classname 

 

T.init_propertystuff() 

 

for k in dir(cls): 

prop = getattr(cls, k) 

 

if k.endswith('__'): 

k = k[:-2] 

 

if isinstance(prop, TBase): 

if prop.deferred(): 

for defer in prop.deferred(): 

g_deferred_content.setdefault( 

defer.classname[:-2], []).append((prop, defer)) 

g_deferred.setdefault( 

defer.classname[:-2], []).append((T, k, prop)) 

 

else: 

T.add_property(k, prop) 

 

elif isinstance(prop, Defer): 

g_deferred.setdefault(prop.classname[:-2], []).append( 

(T, k, prop)) 

 

if classname in g_deferred_content: 

for prop, defer in g_deferred_content[classname]: 

prop.process_deferred( 

defer, T(*defer.args, **defer.kwargs)) 

 

del g_deferred_content[classname] 

 

if classname in g_deferred: 

for (T_, k_, prop_) in g_deferred.get(classname, []): 

if isinstance(prop_, Defer): 

prop_ = T(*prop_.args, **prop_.kwargs) 

 

if not prop_.deferred(): 

T_.add_property(k_, prop_) 

 

del g_deferred[classname] 

 

g_tagname_to_class[T.tagname] = cls 

if hasattr(cls, 'xmltagname'): 

g_xmltagname_to_class[T.xmlns + ' ' + T.xmltagname] = cls 

 

cls.T = T 

T.instance = T() 

 

cls.__doc_template__ = cls.__doc__ 

cls.__doc__ = T.class_help_string() 

 

if cls.__doc__ is None: 

cls.__doc__ = 'Undocumented.' 

 

cls.__doc__ += '\n' + T.props_help_string() 

 

return cls 

 

 

class ValidationError(Exception): 

pass 

 

 

class ArgumentError(Exception): 

pass 

 

 

def make_default(x): 

if isinstance(x, DefaultMaker): 

return x.make() 

elif isinstance(x, Object): 

return clone(x) 

else: 

return x 

 

 

class DefaultMaker(object): 

def __init__(self, cls, args, kwargs): 

self.cls = cls 

self.args = args 

self.kwargs = kwargs 

 

def make(self): 

return self.cls( 

*[make_default(x) for x in self.args], 

**dict((k, make_default(v)) for (k, v) in self.kwargs.items())) 

 

 

def with_metaclass(meta, *bases): 

# inlined py2/py3 compat solution from python-future 

class metaclass(meta): 

__call__ = type.__call__ 

__init__ = type.__init__ 

 

def __new__(cls, name, this_bases, d): 

if this_bases is None: 

return type.__new__(cls, name, (), d) 

return meta(name, bases, d) 

 

return metaclass('temp', None, {}) 

 

 

class Object(with_metaclass(ObjectMetaClass, object)): 

dummy_for = None 

 

def __init__(self, **kwargs): 

if not kwargs.get('init_props', True): 

return 

 

for prop in self.T.properties: 

k = prop.name 

if k in kwargs: 

setattr(self, k, kwargs.pop(k)) 

else: 

if not prop.optional and not prop.has_default(): 

raise ArgumentError('Missing argument to %s: %s' % ( 

self.T.tagname, prop.name)) 

else: 

setattr(self, k, prop.default()) 

 

if kwargs: 

raise ArgumentError('Invalid argument to %s: %s' % ( 

self.T.tagname, ', '.join(list(kwargs.keys())))) 

 

@classmethod 

def D(cls, *args, **kwargs): 

return DefaultMaker(cls, args, kwargs) 

 

def validate(self, regularize=False, depth=-1): 

self.T.instance.validate(self, regularize, depth) 

 

def regularize(self, depth=-1): 

self.validate(regularize=True, depth=depth) 

 

def dump(self, stream=None, filename=None, header=False): 

return dump(self, stream=stream, filename=filename, header=header) 

 

def dump_xml( 

self, stream=None, filename=None, header=False, ns_ignore=False): 

return dump_xml( 

self, stream=stream, filename=filename, header=header, 

ns_ignore=ns_ignore) 

 

@classmethod 

def load(cls, stream=None, filename=None, string=None): 

return load(stream=stream, filename=filename, string=string) 

 

@classmethod 

def load_xml(cls, stream=None, filename=None, string=None, ns_hints=None, 

ns_ignore=False): 

 

if ns_hints is None: 

ns_hints = [cls.T.instance.get_xmlns()] 

 

return load_xml( 

stream=stream, 

filename=filename, 

string=string, 

ns_hints=ns_hints, 

ns_ignore=ns_ignore) 

 

def __str__(self): 

return self.dump() 

 

 

def to_dict(obj): 

''' 

Get dict of guts object attributes. 

 

:param obj: :py:class`Object` object 

''' 

 

return dict(obj.T.inamevals(obj)) 

 

 

class SObject(Object): 

 

class __T(TBase): 

def regularize_extra(self, val): 

if isinstance(val, (str, newstr)): 

return self.cls(val) 

 

return val 

 

def to_save(self, val): 

return str(val) 

 

def to_save_xml(self, val): 

return str(val) 

 

 

class Any(Object): 

 

class __T(TBase): 

def validate(self, val, regularize=False, depth=-1): 

if isinstance(val, Object): 

val.validate(regularize, depth) 

 

return val 

 

 

class Int(Object): 

dummy_for = int 

 

class __T(TBase): 

strict = True 

 

def to_save_xml(self, value): 

return repr(value) 

 

 

class Float(Object): 

dummy_for = float 

 

class __T(TBase): 

strict = True 

 

def to_save_xml(self, value): 

return repr(value) 

 

 

class Complex(Object): 

dummy_for = complex 

 

class __T(TBase): 

strict = True 

 

def regularize_extra(self, val): 

 

if isinstance(val, list) or isinstance(val, tuple): 

assert len(val) == 2 

val = complex(*val) 

 

elif not isinstance(val, complex): 

val = complex(val) 

 

return val 

 

def to_save(self, value): 

return repr(value) 

 

def to_save_xml(self, value): 

return repr(value) 

 

 

class Bool(Object): 

dummy_for = bool 

 

class __T(TBase): 

strict = True 

 

def regularize_extra(self, val): 

if isinstance(val, (str, newstr)): 

if val.lower().strip() in ('0', 'false'): 

return False 

 

return bool(val) 

 

def to_save_xml(self, value): 

return repr(bool(value)).lower() 

 

 

class String(Object): 

dummy_for = str 

 

class __T(TBase): 

def __init__(self, *args, **kwargs): 

yamlstyle = kwargs.pop('yamlstyle', None) 

TBase.__init__(self, *args, **kwargs) 

self.style_cls = str_style_map[yamlstyle] 

 

def to_save(self, val): 

return self.style_cls(val) 

 

 

class Unicode(Object): 

dummy_for = newstr 

 

class __T(TBase): 

def __init__(self, *args, **kwargs): 

yamlstyle = kwargs.pop('yamlstyle', None) 

TBase.__init__(self, *args, **kwargs) 

self.style_cls = unicode_style_map[yamlstyle] 

 

def to_save(self, val): 

return self.style_cls(val) 

 

 

guts_plain_dummy_types = (String, Unicode, Int, Float, Complex, Bool) 

 

 

class Dict(Object): 

dummy_for = dict 

 

class __T(TBase): 

multivalued = dict 

 

def __init__(self, key_t=Any.T(), content_t=Any.T(), *args, **kwargs): 

TBase.__init__(self, *args, **kwargs) 

assert isinstance(key_t, TBase) 

assert isinstance(content_t, TBase) 

self.key_t = key_t 

self.content_t = content_t 

self.content_t.parent = self 

 

def default(self): 

if self._default is not None: 

return dict( 

(make_default(k), make_default(v)) 

for (k, v) in self._default.items()) 

 

if self.optional: 

return None 

else: 

return {} 

 

def has_default(self): 

return True 

 

def validate(self, val, regularize, depth): 

return TBase.validate(self, val, regularize, depth+1) 

 

def validate_children(self, val, regularize, depth): 

for key, ele in list(val.items()): 

newkey = self.key_t.validate(key, regularize, depth-1) 

newele = self.content_t.validate(ele, regularize, depth-1) 

if regularize: 

if newkey is not key or newele is not ele: 

del val[key] 

val[newkey] = newele 

 

return val 

 

def to_save(self, val): 

return dict((self.key_t.to_save(k), self.content_t.to_save(v)) 

for (k, v) in val.items()) 

 

def to_save_xml(self, val): 

raise NotImplementedError() 

 

def classname_for_help(self, strip_module=''): 

return '``dict`` of %s objects' % \ 

self.content_t.classname_for_help(strip_module=strip_module) 

 

 

class List(Object): 

dummy_for = list 

 

class __T(TBase): 

multivalued = list 

 

def __init__(self, content_t=Any.T(), *args, **kwargs): 

yamlstyle = kwargs.pop('yamlstyle', None) 

TBase.__init__(self, *args, **kwargs) 

assert isinstance(content_t, TBase) or isinstance(content_t, Defer) 

self.content_t = content_t 

self.content_t.parent = self 

self.style_cls = list_style_map[yamlstyle] 

 

def default(self): 

if self._default is not None: 

return [make_default(x) for x in self._default] 

if self.optional: 

return None 

else: 

return [] 

 

def has_default(self): 

return True 

 

def validate(self, val, regularize, depth): 

return TBase.validate(self, val, regularize, depth+1) 

 

def validate_children(self, val, regularize, depth): 

for i, ele in enumerate(val): 

newele = self.content_t.validate(ele, regularize, depth-1) 

if regularize and newele is not ele: 

val[i] = newele 

 

return val 

 

def to_save(self, val): 

return self.style_cls(self.content_t.to_save(v) for v in val) 

 

def to_save_xml(self, val): 

return [self.content_t.to_save_xml(v) for v in val] 

 

def deferred(self): 

if isinstance(self.content_t, Defer): 

return [self.content_t] 

 

return [] 

 

def process_deferred(self, defer, t_inst): 

if defer is self.content_t: 

self.content_t = t_inst 

 

def classname_for_help(self, strip_module=''): 

return '``list`` of %s objects' % \ 

self.content_t.classname_for_help(strip_module=strip_module) 

 

 

def make_typed_list_class(t): 

class TL(List): 

class __T(List.T): 

def __init__(self, *args, **kwargs): 

List.T.__init__(self, content_t=t.T(), *args, **kwargs) 

 

return TL 

 

 

class Tuple(Object): 

dummy_for = tuple 

 

class __T(TBase): 

multivalued = tuple 

 

def __init__(self, n=None, content_t=Any.T(), *args, **kwargs): 

TBase.__init__(self, *args, **kwargs) 

assert isinstance(content_t, TBase) 

self.content_t = content_t 

self.content_t.parent = self 

self.n = n 

 

def default(self): 

if self._default is not None: 

return tuple( 

make_default(x) for x in self._default) 

 

elif self.optional: 

return None 

else: 

if self.n is not None: 

return tuple( 

self.content_t.default() for x in range(self.n)) 

else: 

return tuple() 

 

def has_default(self): 

return True 

 

def validate(self, val, regularize, depth): 

return TBase.validate(self, val, regularize, depth+1) 

 

def validate_extra(self, val): 

if self.n is not None and len(val) != self.n: 

raise ValidationError( 

'%s should have length %i' % (self.xname(), self.n)) 

 

def validate_children(self, val, regularize, depth): 

if not regularize: 

for ele in val: 

self.content_t.validate(ele, regularize, depth-1) 

 

return val 

else: 

newval = [] 

isnew = False 

for ele in val: 

newele = self.content_t.validate(ele, regularize, depth-1) 

newval.append(newele) 

if newele is not ele: 

isnew = True 

 

if isnew: 

return tuple(newval) 

else: 

return val 

 

def to_save(self, val): 

return tuple(self.content_t.to_save(v) for v in val) 

 

def to_save_xml(self, val): 

return [self.content_t.to_save_xml(v) for v in val] 

 

def classname_for_help(self, strip_module=''): 

if self.n is not None: 

return '``tuple`` of %i %s objects' % ( 

self.n, self.content_t.classname_for_help( 

strip_module=strip_module)) 

else: 

return '``tuple`` of %s objects' % ( 

self.content_t.classname_for_help( 

strip_module=strip_module)) 

 

 

re_tz = re.compile(r'(Z|([+-][0-2][0-9])(:?([0-5][0-9]))?)$') 

 

 

class Timestamp(Object): 

dummy_for = (hpfloat, float) 

dummy_for_description = 'time_float' 

 

class __T(TBase): 

 

def regularize_extra(self, val): 

 

time_float = get_time_class() 

 

if isinstance(val, datetime.datetime): 

tt = val.utctimetuple() 

val = time_float(calendar.timegm(tt)) + val.microsecond * 1e-6 

 

elif isinstance(val, datetime.date): 

tt = val.timetuple() 

val = time_float(calendar.timegm(tt)) 

 

elif isinstance(val, (str, newstr)): 

val = val.strip() 

tz_offset = 0 

 

m = re_tz.search(val) 

if m: 

sh = m.group(2) 

sm = m.group(4) 

tz_offset = (int(sh)*3600 if sh else 0) \ 

+ (int(sm)*60 if sm else 0) 

 

val = re_tz.sub('', val) 

 

if len(val) > 10 and val[10] == 'T': 

val = val.replace('T', ' ', 1) 

 

try: 

val = str_to_time(val) - tz_offset 

except TimeStrError: 

raise ValidationError( 

'%s: cannot parse time/date: %s' % (self.xname(), val)) 

 

elif isinstance(val, (int, float)): 

val = time_float(val) 

 

else: 

raise ValidationError( 

'%s: cannot convert "%s" to type %s' % ( 

self.xname(), val, time_float)) 

 

return val 

 

def to_save(self, val): 

return time_to_str(val, format='%Y-%m-%d %H:%M:%S.9FRAC')\ 

.rstrip('0').rstrip('.') 

 

def to_save_xml(self, val): 

return time_to_str(val, format='%Y-%m-%dT%H:%M:%S.9FRAC')\ 

.rstrip('0').rstrip('.') + 'Z' 

 

 

class DateTimestamp(Object): 

dummy_for = (hpfloat, float) 

dummy_for_description = 'time_float' 

 

class __T(TBase): 

 

def regularize_extra(self, val): 

 

time_float = get_time_class() 

 

if isinstance(val, datetime.datetime): 

tt = val.utctimetuple() 

val = time_float(calendar.timegm(tt)) + val.microsecond * 1e-6 

 

elif isinstance(val, datetime.date): 

tt = val.timetuple() 

val = time_float(calendar.timegm(tt)) 

 

elif isinstance(val, (str, newstr)): 

val = str_to_time(val, format='%Y-%m-%d') 

 

elif isinstance(val, int): 

val = time_float(val) 

 

return val 

 

def to_save(self, val): 

return time_to_str(val, format='%Y-%m-%d') 

 

def to_save_xml(self, val): 

return time_to_str(val, format='%Y-%m-%d') 

 

 

class StringPattern(String): 

 

'''Any ``str`` matching pattern ``%(pattern)s``.''' 

 

dummy_for = str 

pattern = '.*' 

 

class __T(String.T): 

def __init__(self, pattern=None, *args, **kwargs): 

String.T.__init__(self, *args, **kwargs) 

 

if pattern is not None: 

self.pattern = pattern 

else: 

self.pattern = self.dummy_cls.pattern 

 

def validate_extra(self, val): 

pat = self.pattern 

if not re.search(pat, val): 

raise ValidationError('%s: "%s" does not match pattern %s' % ( 

self.xname(), val, repr(pat))) 

 

@classmethod 

def class_help_string(cls): 

dcls = cls.dummy_cls 

doc = dcls.__doc_template__ or StringPattern.__doc_template__ 

return doc % {'pattern': repr(dcls.pattern)} 

 

 

class UnicodePattern(Unicode): 

 

'''Any ``unicode`` matching pattern ``%(pattern)s``.''' 

 

dummy_for = newstr 

pattern = '.*' 

 

class __T(TBase): 

def __init__(self, pattern=None, *args, **kwargs): 

TBase.__init__(self, *args, **kwargs) 

 

if pattern is not None: 

self.pattern = pattern 

else: 

self.pattern = self.dummy_cls.pattern 

 

def validate_extra(self, val): 

pat = self.pattern 

if not re.search(pat, val, flags=re.UNICODE): 

raise ValidationError('%s: "%s" does not match pattern %s' % ( 

self.xname(), val, repr(pat))) 

 

@classmethod 

def class_help_string(cls): 

dcls = cls.dummy_cls 

doc = dcls.__doc_template__ or UnicodePattern.__doc_template__ 

return doc % {'pattern': repr(dcls.pattern)} 

 

 

class StringChoice(String): 

 

'''Any ``str`` out of ``%(choices)s``.''' 

 

dummy_for = str 

choices = [] 

ignore_case = False 

 

class __T(String.T): 

def __init__(self, choices=None, ignore_case=None, *args, **kwargs): 

String.T.__init__(self, *args, **kwargs) 

 

if choices is not None: 

self.choices = choices 

else: 

self.choices = self.dummy_cls.choices 

 

if ignore_case is not None: 

self.ignore_case = ignore_case 

else: 

self.ignore_case = self.dummy_cls.ignore_case 

 

if self.ignore_case: 

self.choices = [x.upper() for x in self.choices] 

 

def validate_extra(self, val): 

if self.ignore_case: 

val = val.upper() 

 

if val not in self.choices: 

raise ValidationError( 

'%s: "%s" is not a valid choice out of %s' % ( 

self.xname(), val, repr(self.choices))) 

 

@classmethod 

def class_help_string(cls): 

dcls = cls.dummy_cls 

doc = dcls.__doc_template__ or StringChoice.__doc_template__ 

return doc % {'choices': repr(dcls.choices)} 

 

 

# this will not always work... 

class Union(Object): 

members = [] 

dummy_for = str 

 

class __T(TBase): 

def __init__(self, members=None, *args, **kwargs): 

TBase.__init__(self, *args, **kwargs) 

if members is not None: 

self.members = members 

else: 

self.members = self.dummy_cls.members 

 

def validate(self, val, regularize=False, depth=-1): 

assert self.members 

e2 = None 

for member in self.members: 

try: 

return member.validate(val, regularize, depth=depth) 

except ValidationError as e: 

e2 = e 

 

raise e2 

 

 

class Choice(Object): 

choices = [] 

 

class __T(TBase): 

def __init__(self, choices=None, *args, **kwargs): 

TBase.__init__(self, *args, **kwargs) 

if choices is not None: 

self.choices = choices 

else: 

self.choices = self.dummy_cls.choices 

 

self.cls_to_xmltagname = dict( 

(t.cls, t.get_xmltagname()) for t in self.choices) 

 

def validate(self, val, regularize=False, depth=-1): 

if self.optional and val is None: 

return val 

 

t = None 

for tc in self.choices: 

is_derived = isinstance(val, tc.cls) 

is_exact = type(val) == tc.cls 

if not (not tc.strict and not is_derived or 

tc.strict and not is_exact): 

 

t = tc 

break 

 

if t is None: 

if regularize: 

ok = False 

for tc in self.choices: 

try: 

val = tc.regularize_extra(val) 

ok = True 

t = tc 

break 

except (ValidationError, ValueError): 

pass 

 

if not ok: 

raise ValidationError( 

'%s: could not convert "%s" to any type out of ' 

'(%s)' % (self.xname(), val, ','.join( 

classnames(x.cls) for x in self.choices))) 

else: 

raise ValidationError( 

'%s: "%s" (type: %s) is not of any type out of ' 

'(%s)' % (self.xname(), val, type(val), ','.join( 

classnames(x.cls) for x in self.choices))) 

 

validator = t 

 

if isinstance(t.cls, tuple): 

clss = t.cls 

else: 

clss = (t.cls,) 

 

for cls in clss: 

try: 

if type(val) != cls and isinstance(val, cls): 

validator = val.T.instance 

 

except AttributeError: 

pass 

 

validator.validate_extra(val) 

 

if depth != 0: 

val = validator.validate_children(val, regularize, depth) 

 

return val 

 

def extend_xmlelements(self, elems, v): 

elems.append(( 

self.cls_to_xmltagname[type(v)].split(' ', 1)[-1], v)) 

 

 

def _dump( 

object, stream, 

header=False, 

Dumper=GutsSafeDumper, 

_dump_function=yaml.dump): 

 

if not getattr(stream, 'encoding', None): 

enc = encode_utf8 

else: 

enc = no_encode 

 

if header: 

stream.write(enc(u'%YAML 1.1\n')) 

if isinstance(header, (str, newstr)): 

banner = u'\n'.join('# ' + x for x in header.splitlines()) + '\n' 

stream.write(enc(banner)) 

 

_dump_function( 

object, 

stream=stream, 

encoding='utf-8', 

explicit_start=True, 

Dumper=Dumper) 

 

 

def _dump_all(object, stream, header=True, Dumper=GutsSafeDumper): 

_dump(object, stream=stream, header=header, _dump_function=yaml.dump_all) 

 

 

def _load(stream, 

Loader=GutsSafeLoader, allow_include=None, filename=None, 

included_files=None): 

 

class _Loader(Loader): 

_filename = filename 

_allow_include = allow_include 

_included_files = included_files or [] 

 

return yaml.load(stream=stream, Loader=_Loader) 

 

 

def _load_all(stream, 

Loader=GutsSafeLoader, allow_include=None, filename=None): 

 

class _Loader(Loader): 

_filename = filename 

_allow_include = allow_include 

 

return list(yaml.load_all(stream=stream, Loader=_Loader)) 

 

 

def _iload_all(stream, 

Loader=GutsSafeLoader, allow_include=None, filename=None): 

 

class _Loader(Loader): 

_filename = filename 

_allow_include = allow_include 

 

return yaml.load_all(stream=stream, Loader=_Loader) 

 

 

def multi_representer(dumper, data): 

node = dumper.represent_mapping( 

'!'+data.T.tagname, data.T.inamevals_to_save(data), flow_style=False) 

 

return node 

 

 

# hack for compatibility with early GF Store versions 

re_compatibility = re.compile( 

r'^pyrocko\.(trace|gf\.(meta|seismosizer)|fomosto\.' 

r'(dummy|poel|qseis|qssp))\.' 

) 

 

 

def multi_constructor(loader, tag_suffix, node): 

tagname = str(tag_suffix) 

 

tagname = re_compatibility.sub('pf.', tagname) 

 

cls = g_tagname_to_class[tagname] 

kwargs = dict(iter(loader.construct_pairs(node, deep=True))) 

o = cls(**kwargs) 

o.validate(regularize=True, depth=1) 

return o 

 

 

def include_constructor(loader, node): 

allow_include = loader._allow_include \ 

if loader._allow_include is not None \ 

else ALLOW_INCLUDE 

 

if not allow_include: 

raise EnvironmentError( 

'Not allowed to include YAML. Load with allow_include=True') 

 

if isinstance(node, yaml.nodes.ScalarNode): 

inc_file = loader.construct_scalar(node) 

else: 

raise TypeError('Unsupported YAML node %s' % repr(node)) 

 

if loader._filename is not None and not op.isabs(inc_file): 

inc_file = op.join(op.dirname(loader._filename), inc_file) 

 

if not op.isfile(inc_file): 

raise FileNotFoundError(inc_file) 

 

included_files = list(loader._included_files) 

if loader._filename is not None: 

included_files.append(op.abspath(loader._filename)) 

 

for included_file in loader._included_files: 

if op.samefile(inc_file, included_file): 

raise ImportError( 

'Circular import of file "%s". Include path: %s' % ( 

op.abspath(inc_file), 

' -> '.join('"%s"' % s for s in included_files))) 

 

with open(inc_file) as f: 

return _load( 

f, 

Loader=loader.__class__, filename=inc_file, 

allow_include=True, 

included_files=included_files) 

 

 

def dict_noflow_representer(dumper, data): 

return dumper.represent_mapping( 

'tag:yaml.org,2002:map', data, flow_style=False) 

 

 

yaml.add_multi_representer(Object, multi_representer, Dumper=GutsSafeDumper) 

yaml.add_constructor('!include', include_constructor, Loader=GutsSafeLoader) 

yaml.add_multi_constructor('!', multi_constructor, Loader=GutsSafeLoader) 

yaml.add_representer(dict, dict_noflow_representer, Dumper=GutsSafeDumper) 

 

 

def newstr_representer(dumper, data): 

return dumper.represent_scalar( 

'tag:yaml.org,2002:str', unicode(data)) 

 

 

yaml.add_representer(newstr, newstr_representer, Dumper=GutsSafeDumper) 

 

 

class Constructor(object): 

def __init__(self, add_namespace_maps=False, strict=False, ns_hints=None, 

ns_ignore=False): 

 

self.stack = [] 

self.queue = [] 

self.namespaces = defaultdict(list) 

self.add_namespace_maps = add_namespace_maps 

self.strict = strict 

self.ns_hints = ns_hints 

self.ns_ignore = ns_ignore 

 

def start_element(self, ns_name, attrs): 

if self.ns_ignore: 

ns_name = ns_name.split(' ')[-1] 

 

if -1 == ns_name.find(' '): 

if self.ns_hints is None and ns_name in g_guessable_xmlns: 

self.ns_hints = g_guessable_xmlns[ns_name] 

 

if self.ns_hints: 

ns_names = [ 

ns_hint + ' ' + ns_name for ns_hint in self.ns_hints] 

 

elif self.ns_hints is None: 

ns_names = [' ' + ns_name] 

 

else: 

ns_names = [ns_name] 

 

for ns_name in ns_names: 

if self.stack and self.stack[-1][1] is not None: 

cls = self.stack[-1][1].T.xmltagname_to_class.get( 

ns_name, None) 

 

if isinstance(cls, tuple): 

cls = None 

else: 

if cls is not None and ( 

not issubclass(cls, Object) 

or issubclass(cls, SObject)): 

cls = None 

else: 

cls = g_xmltagname_to_class.get(ns_name, None) 

 

if cls: 

break 

 

self.stack.append((ns_name, cls, attrs, [], [])) 

 

def end_element(self, _): 

ns_name, cls, attrs, content2, content1 = self.stack.pop() 

 

ns = ns_name.split(' ', 1)[0] 

 

if cls is not None: 

content2.extend( 

(ns + ' ' + k if -1 == k.find(' ') else k, v) 

for (k, v) in attrs.items()) 

content2.append((None, ''.join(content1))) 

o = cls(**cls.T.translate_from_xml(content2, self.strict)) 

o.validate(regularize=True, depth=1) 

if self.add_namespace_maps: 

o.namespace_map = self.get_current_namespace_map() 

 

if self.stack and not all(x[1] is None for x in self.stack): 

self.stack[-1][-2].append((ns_name, o)) 

else: 

self.queue.append(o) 

else: 

content = [''.join(content1)] 

if self.stack: 

for c in content: 

self.stack[-1][-2].append((ns_name, c)) 

 

def characters(self, char_content): 

if self.stack: 

self.stack[-1][-1].append(char_content) 

 

def start_namespace(self, ns, uri): 

self.namespaces[ns].append(uri) 

 

def end_namespace(self, ns): 

self.namespaces[ns].pop() 

 

def get_current_namespace_map(self): 

return dict((k, v[-1]) for (k, v) in self.namespaces.items() if v) 

 

def get_queued_elements(self): 

queue = self.queue 

self.queue = [] 

return queue 

 

 

def _iload_all_xml( 

stream, 

bufsize=100000, 

add_namespace_maps=False, 

strict=False, 

ns_hints=None, 

ns_ignore=False): 

 

from xml.parsers.expat import ParserCreate 

 

parser = ParserCreate('UTF-8', namespace_separator=' ') 

 

handler = Constructor( 

add_namespace_maps=add_namespace_maps, 

strict=strict, 

ns_hints=ns_hints, 

ns_ignore=ns_ignore) 

 

parser.StartElementHandler = handler.start_element 

parser.EndElementHandler = handler.end_element 

parser.CharacterDataHandler = handler.characters 

parser.StartNamespaceDeclHandler = handler.start_namespace 

parser.EndNamespaceDeclHandler = handler.end_namespace 

 

while True: 

data = stream.read(bufsize) 

parser.Parse(data, bool(not data)) 

for element in handler.get_queued_elements(): 

yield element 

 

if not data: 

break 

 

 

def _load_all_xml(*args, **kwargs): 

return list(_iload_all_xml(*args, **kwargs)) 

 

 

def _load_xml(*args, **kwargs): 

g = _iload_all_xml(*args, **kwargs) 

return next(g) 

 

 

def _dump_all_xml(objects, stream, root_element_name='root', header=True): 

 

if not getattr(stream, 'encoding', None): 

enc = encode_utf8 

else: 

enc = no_encode 

 

_dump_xml_header(stream, header) 

 

beg = u'<%s>\n' % root_element_name 

end = u'</%s>\n' % root_element_name 

 

stream.write(enc(beg)) 

 

for ob in objects: 

_dump_xml(ob, stream=stream) 

 

stream.write(enc(end)) 

 

 

def _dump_xml_header(stream, banner=None): 

 

if not getattr(stream, 'encoding', None): 

enc = encode_utf8 

else: 

enc = no_encode 

 

stream.write(enc(u'<?xml version="1.0" encoding="UTF-8" ?>\n')) 

if isinstance(banner, (str, newstr)): 

stream.write(enc(u'<!-- %s -->\n' % banner)) 

 

 

def _dump_xml( 

obj, stream, depth=0, ns_name=None, header=False, ns_map=[], 

ns_ignore=False): 

 

from xml.sax.saxutils import escape, quoteattr 

 

if not getattr(stream, 'encoding', None): 

enc = encode_utf8 

else: 

enc = no_encode 

 

if depth == 0 and header: 

_dump_xml_header(stream, header) 

 

indent = ' '*depth*2 

if ns_name is None: 

ns_name = obj.T.instance.get_xmltagname() 

 

if -1 != ns_name.find(' '): 

ns, name = ns_name.split(' ') 

else: 

ns, name = '', ns_name 

 

if isinstance(obj, Object): 

obj.validate(depth=1) 

attrs = [] 

elems = [] 

 

added_ns = False 

if not ns_ignore and ns and (not ns_map or ns_map[-1] != ns): 

attrs.append(('xmlns', ns)) 

ns_map.append(ns) 

added_ns = True 

 

for prop, v in obj.T.ipropvals_to_save(obj, xmlmode=True): 

if prop.xmlstyle == 'attribute': 

assert not prop.multivalued 

assert not isinstance(v, Object) 

attrs.append((prop.effective_xmltagname, v)) 

 

elif prop.xmlstyle == 'content': 

assert not prop.multivalued 

assert not isinstance(v, Object) 

elems.append((None, v)) 

 

else: 

prop.extend_xmlelements(elems, v) 

 

attr_str = '' 

if attrs: 

attr_str = ' ' + ' '.join( 

'%s=%s' % (k.split(' ')[-1], quoteattr(str(v))) 

for (k, v) in attrs) 

 

if not elems: 

stream.write(enc(u'%s<%s%s />\n' % (indent, name, attr_str))) 

else: 

oneline = len(elems) == 1 and elems[0][0] is None 

stream.write(enc(u'%s<%s%s>%s' % ( 

indent, 

name, 

attr_str, 

'' if oneline else '\n'))) 

 

for (k, v) in elems: 

if k is None: 

stream.write(enc(escape(newstr(v), {'\0': '&#00;'}))) 

else: 

_dump_xml(v, stream, depth+1, k, False, ns_map, ns_ignore) 

 

stream.write(enc(u'%s</%s>\n' % ( 

'' if oneline else indent, name))) 

 

if added_ns: 

ns_map.pop() 

 

else: 

stream.write(enc(u'%s<%s>%s</%s>\n' % ( 

indent, 

name, 

escape(newstr(obj), {'\0': '&#00;'}), 

name))) 

 

 

def walk(x, typ=None, path=()): 

if typ is None or isinstance(x, typ): 

yield path, x 

 

if isinstance(x, Object): 

for (prop, val) in x.T.ipropvals(x): 

if prop.multivalued: 

if val is not None: 

for iele, ele in enumerate(val): 

for y in walk(ele, typ, 

path=path + ((prop.name, iele),)): 

yield y 

else: 

for y in walk(val, typ, path=path+(prop.name,)): 

yield y 

 

 

def clone(x, pool=None): 

''' 

Clone guts object tree. 

 

Traverses guts object tree and recursively clones all guts attributes, 

falling back to :py:func:`copy.deepcopy` for non-guts objects. Objects 

deriving from :py:class:`Object` are instantiated using their respective 

init function. Multiply referenced objects in the source tree are multiply 

referenced also in the destination tree. 

 

This function can be used to clone guts objects ignoring any contained 

run-time state, i.e. any of their attributes not defined as a guts 

property. 

''' 

 

if pool is None: 

pool = {} 

 

if id(x) in pool: 

x_copy = pool[id(x)] 

 

else: 

if isinstance(x, Object): 

d = {} 

for (prop, y) in x.T.ipropvals(x): 

if y is not None: 

if not prop.multivalued: 

y_copy = clone(y, pool) 

elif prop.multivalued is dict: 

y_copy = dict( 

(clone(zk, pool), clone(zv, pool)) 

for (zk, zv) in y.items()) 

else: 

y_copy = type(y)(clone(z, pool) for z in y) 

else: 

y_copy = y 

 

d[prop.name] = y_copy 

 

x_copy = x.__class__(**d) 

 

else: 

x_copy = copy.deepcopy(x) 

 

pool[id(x)] = x_copy 

return x_copy 

 

 

class YPathError(Exception): 

'''This exception is raised for invalid ypath specifications.''' 

pass 

 

 

def _parse_yname(yname): 

ident = r'[a-zA-Z][a-zA-Z0-9_]*' 

rint = r'-?[0-9]+' 

m = re.match( 

r'^(%s)(\[((%s)?(:)(%s)?|(%s))\])?$' 

% (ident, rint, rint, rint), yname) 

 

if not m: 

raise YPathError('Syntax error in component: "%s"' % yname) 

 

d = dict( 

name=m.group(1)) 

 

if m.group(2): 

if m.group(5): 

istart = iend = None 

if m.group(4): 

istart = int(m.group(4)) 

if m.group(6): 

iend = int(m.group(6)) 

 

d['slice'] = (istart, iend) 

else: 

d['index'] = int(m.group(7)) 

 

return d 

 

 

def _decend(obj, ynames): 

if ynames: 

for sobj in iter_elements(obj, ynames): 

yield sobj 

else: 

yield obj 

 

 

def iter_elements(obj, ypath): 

''' 

Generator yielding elements matching a given ypath specification. 

 

:param obj: guts :py:class:`Object` instance 

:param ypath: Dot-separated object path (e.g. 'root.child.child'). 

To access list objects use slice notatation (e.g. 

'root.child[:].child[1:3].child[1]'). 

 

Raises :py:exc:`YPathError` on failure. 

''' 

 

try: 

if isinstance(ypath, str): 

ynames = ypath.split('.') 

else: 

ynames = ypath 

 

yname = ynames[0] 

ynames = ynames[1:] 

d = _parse_yname(yname) 

if d['name'] not in obj.T.propnames: 

raise AttributeError(d['name']) 

 

obj = getattr(obj, d['name']) 

 

if 'index' in d: 

sobj = obj[d['index']] 

for ssobj in _decend(sobj, ynames): 

yield ssobj 

 

elif 'slice' in d: 

for i in range(*slice(*d['slice']).indices(len(obj))): 

sobj = obj[i] 

for ssobj in _decend(sobj, ynames): 

yield ssobj 

else: 

for sobj in _decend(obj, ynames): 

yield sobj 

 

except (AttributeError, IndexError) as e: 

raise YPathError('Invalid ypath: "%s" (%s)' % (ypath, str(e))) 

 

 

def get_elements(obj, ypath): 

''' 

Get all elements matching a given ypath specification. 

 

:param obj: guts :py:class:`Object` instance 

:param ypath: Dot-separated object path (e.g. 'root.child.child'). 

To access list objects use slice notatation (e.g. 

'root.child[:].child[1:3].child[1]'). 

 

Raises :py:exc:`YPathError` on failure. 

''' 

return list(iter_elements(obj, ypath)) 

 

 

def set_elements(obj, ypath, value, validate=False, regularize=False): 

''' 

Set elements matching a given ypath specification. 

 

:param obj: guts :py:class:`Object` instance 

:param ypath: Dot-separated object path (e.g. 'root.child.child'). 

To access list objects use slice notatation (e.g. 

'root.child[:].child[1:3].child[1]'). 

:param value: All matching elements will be set to `value`. 

:param validate: Whether to validate affected subtrees. 

:param regularize: Whether to regularize affected subtrees. 

 

Raises :py:exc:`YPathError` on failure. 

''' 

 

ynames = ypath.split('.') 

try: 

d = _parse_yname(ynames[-1]) 

for sobj in iter_elements(obj, ynames[:-1]): 

if d['name'] not in sobj.T.propnames: 

raise AttributeError(d['name']) 

 

if 'index' in d: 

ssobj = getattr(sobj, d['name']) 

ssobj[d['index']] = value 

elif 'slice' in d: 

ssobj = getattr(sobj, d['name']) 

for i in range(*slice(*d['slice']).indices(len(ssobj))): 

ssobj[i] = value 

else: 

setattr(sobj, d['name'], value) 

if regularize: 

sobj.regularize() 

if validate: 

sobj.validate() 

 

except (AttributeError, IndexError, YPathError) as e: 

raise YPathError('Invalid ypath: "%s" (%s)' % (ypath, str(e))) 

 

 

def zip_walk(x, typ=None, path=(), stack=()): 

if typ is None or isinstance(x, typ): 

yield path, stack + (x,) 

 

if isinstance(x, Object): 

for (prop, val) in x.T.ipropvals(x): 

if prop.multivalued: 

if val is not None: 

for iele, ele in enumerate(val): 

for y in zip_walk( 

ele, typ, 

path=path + ((prop.name, iele),), 

stack=stack + (x,)): 

 

yield y 

else: 

for y in zip_walk(val, typ, 

path=path+(prop.name,), 

stack=stack + (x,)): 

yield y 

 

 

def path_element(x): 

if isinstance(x, tuple): 

return '%s[%i]' % x 

else: 

return x 

 

 

def path_to_str(path): 

return '.'.join(path_element(x) for x in path) 

 

 

@expand_stream_args('w') 

def dump(*args, **kwargs): 

return _dump(*args, **kwargs) 

 

 

@expand_stream_args('r') 

def load(*args, **kwargs): 

return _load(*args, **kwargs) 

 

 

def load_string(s, *args, **kwargs): 

return load(string=s, *args, **kwargs) 

 

 

@expand_stream_args('w') 

def dump_all(*args, **kwargs): 

return _dump_all(*args, **kwargs) 

 

 

@expand_stream_args('r') 

def load_all(*args, **kwargs): 

return _load_all(*args, **kwargs) 

 

 

@expand_stream_args('r') 

def iload_all(*args, **kwargs): 

return _iload_all(*args, **kwargs) 

 

 

@expand_stream_args('w') 

def dump_xml(*args, **kwargs): 

return _dump_xml(*args, **kwargs) 

 

 

@expand_stream_args('r') 

def load_xml(*args, **kwargs): 

kwargs.pop('filename', None) 

return _load_xml(*args, **kwargs) 

 

 

def load_xml_string(s, *args, **kwargs): 

return load_xml(string=s, *args, **kwargs) 

 

 

@expand_stream_args('w') 

def dump_all_xml(*args, **kwargs): 

return _dump_all_xml(*args, **kwargs) 

 

 

@expand_stream_args('r') 

def load_all_xml(*args, **kwargs): 

kwargs.pop('filename', None) 

return _load_all_xml(*args, **kwargs) 

 

 

@expand_stream_args('r') 

def iload_all_xml(*args, **kwargs): 

kwargs.pop('filename', None) 

return _iload_all_xml(*args, **kwargs) 

 

 

__all__ = guts_types + [ 

'guts_types', 'TBase', 'ValidationError', 

'ArgumentError', 'Defer', 

'dump', 'load', 

'dump_all', 'load_all', 'iload_all', 

'dump_xml', 'load_xml', 

'dump_all_xml', 'load_all_xml', 'iload_all_xml', 

'load_string', 

'load_xml_string', 

'make_typed_list_class', 'walk', 'zip_walk', 'path_to_str' 

]