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

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

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

r""" 

Sage Input Formatting 

 

This module provides the function :func:`sage_input` that takes an 

arbitrary sage value and produces a sequence of commands that, if typed 

at the ``sage:`` prompt, will recreate the value. If this is not 

implemented for a particular value, then an exception is raised instead. 

This might be useful in understanding a part of Sage, or for debugging. 

For instance, if you have a value produced in a complicated way in the 

middle of a debugging session, you could use :func:`sage_input` to find 

a simple way to produce the same value. We attempt to produce commands 

that are readable and idiomatic.:: 

 

sage: sage_input(3) 

3 

sage: sage_input((polygen(RR) + RR(pi))^2, verify=True) 

# Verified 

R.<x> = RR[] 

x^2 + 6.2831853071795862*x + 9.869604401089358 

 

With ``verify=True``, :func:`sage_input` also verifies the results, by 

calling :func:`~sage.misc.sage_eval.sage_eval` on the result and 

verifying that it is equal to the input.:: 

 

sage: sage_input(GF(2)(1), verify=True) 

# Verified 

GF(2)(1) 

 

We can generate code that works without the preparser, with 

``preparse=False``; or we can generate code that will work whether or 

not the preparser is enabled, with ``preparse=None``. Generating code 

with ``preparse=False`` may be useful to see how to create a certain 

value in a Python or Cython source file.:: 

 

sage: sage_input(5, verify=True) 

# Verified 

5 

sage: sage_input(5, preparse=False) 

ZZ(5) 

sage: sage_input(5, preparse=None) 

ZZ(5) 

sage: sage_input(5r, verify=True) 

# Verified 

5r 

sage: sage_input(5r, preparse=False) 

5 

sage: sage_input(5r, preparse=None) 

int(5) 

 

Adding :func:`sage_input` support to your own classes is 

straightforward. You need to add a :func:`_sage_input_` method which 

returns a :class:`SageInputExpression` (henceforth abbreviated as SIE) 

which will reconstruct this instance of your class. 

 

A ``_sage_input_`` method takes two parameters, conventionally named 

``sib`` and ``coerced``. The first argument is a 

:class:`SageInputBuilder`; it has methods to build SIEs. The second 

argument, ``coerced``, is a boolean. This is only useful if your class 

is a subclass of :class:`Element` (although it is always present). If 

``coerced`` is ``False``, then your method must generate an expression 

which will evaluate to a value of the correct type with the correct 

parent. If ``coerced`` is ``True``, then your method may generate an 

expression of a type that has a canonical coercion to your type; and if 

``coerced`` is 2, then your method may generate an expression of a type 

that has a conversion to your type. 

 

Let's work through some examples. We'll build a sequence of functions 

that would be acceptable as ``_sage_input_`` methods for the 

:class:`~sage.rings.rational.Rational` class. 

 

Here's the first and simplest version.:: 

 

sage: def qq_sage_input_v1(self, sib, coerced): 

....: return sib(self.numerator())/sib(self.denominator()) 

 

We see that given a :class:`SageInputBuilder` ``sib``, you can construct 

a SIE for a value ``v`` simply with ``sib(v)``, and you can construct a 

SIE for a quotient with the division operator. Of course, the other 

operators also work, and so do function calls, method calls, subscripts, 

etc. 

 

We'll test with the following code, which you don't need to understand. 

(It produces a list of 8 results, showing the formatted versions of -5/7 

and 3, with the preparser either enabled or disabled and either with or 

without an automatic coercion to QQ.):: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: def test_qq_formatter(fmt): 

....: results = [] 

....: for v in [-5/7, QQ(3)]: 

....: for pp in [False, True]: 

....: for coerced in [False, True]: 

....: sib = SageInputBuilder(preparse=pp) 

....: results.append(sib.result(fmt(v, sib, coerced))) 

....: return results 

 

sage: test_qq_formatter(qq_sage_input_v1) 

[-ZZ(5)/ZZ(7), -ZZ(5)/ZZ(7), -5/7, -5/7, ZZ(3)/ZZ(1), ZZ(3)/ZZ(1), 3/1, 3/1] 

 

Let's try for some shorter, perhaps nicer-looking output. We'll start 

by getting rid of the ``ZZ`` in the denominators; even without the 

preparser, ``-ZZ(5)/7 == -ZZ(5)/ZZ(7)``.:: 

 

sage: def qq_sage_input_v2(self, sib, coerced): 

....: return sib(self.numerator())/sib.int(self.denominator()) 

 

The ``int`` method on :class:`SageInputBuilder` returns a SIE for an 

integer that is always represented in the simple way, without coercions. 

(So, depending on the preparser mode, it might read in as an 

:class:`~sage.rings.integer.Integer`, an ``int``, or a ``long``.):: 

 

sage: test_qq_formatter(qq_sage_input_v2) 

[-ZZ(5)/7, -ZZ(5)/7, -5/7, -5/7, ZZ(3)/1, ZZ(3)/1, 3/1, 3/1] 

 

Next let us get rid of the divisions by 1. These are more complicated, 

since if we are not careful we will get results in `\ZZ` instead of `\QQ`:: 

 

sage: def qq_sage_input_v3(self, sib, coerced): 

....: if self.denominator() == 1: 

....: if coerced: 

....: return sib.int(self.numerator()) 

....: else: 

....: return sib.name('QQ')(sib.int(self.numerator())) 

....: return sib(self.numerator())/sib.int(self.denominator()) 

 

We see that the \method{name} method gives an SIE representing a \sage 

constant or function.:: 

 

sage: test_qq_formatter(qq_sage_input_v3) 

[-ZZ(5)/7, -ZZ(5)/7, -5/7, -5/7, QQ(3), 3, QQ(3), 3] 

 

This is the prettiest output we're going to get, but let's make one 

further refinement. Other :class:`_sage_input_` methods, like the one 

for polynomials, analyze the structure of SIEs; they work better (give 

prettier output) if negations are at the outside. If the above code 

were used for rationals, then ``sage_input(polygen(QQ) - 2/3)`` would 

produce ``x + (-2/3)``; if we change to the following code, then we 

would get ``x - 2/3`` instead.:: 

 

sage: def qq_sage_input_v4(self, sib, coerced): 

....: num = self.numerator() 

....: neg = (num < 0) 

....: if neg: num = -num 

....: if self.denominator() == 1: 

....: if coerced: 

....: v = sib.int(num) 

....: else: 

....: v = sib.name('QQ')(sib.int(num)) 

....: else: 

....: v = sib(num)/sib.int(self.denominator()) 

....: if neg: v = -v 

....: return v 

 

sage: test_qq_formatter(qq_sage_input_v4) 

[-ZZ(5)/7, -ZZ(5)/7, -5/7, -5/7, QQ(3), 3, QQ(3), 3] 

 

AUTHORS: 

 

- Carl Witty (2008-04): new file 

 

- Vincent Delecroix (2015-02): documentation formatting 

""" 

 

#***************************************************************************** 

# Copyright (C) 2008 Carl Witty <Carl.Witty@gmail.com> 

# 2015 Vincent Delecroix <20100.delecroix@gmail.com> 

# 

# 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 2 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

 

from __future__ import print_function, absolute_import 

 

from six import itervalues, iteritems, integer_types, string_types 

 

 

def sage_input(x, preparse=True, verify=False, allow_locals=False): 

r""" 

Return a sequence of commands that can be used to rebuild the object ``x``. 

 

INPUT: 

 

- ``x`` - the value we want to find an input form for 

 

- ``preparse`` - (default ``True``) Whether to generate code that requires 

the preparser. With ``True``, generated code requires the preparser. 

With ``False``, generated code requires that the preparser not be used. 

With ``None``, generated code will work whether or not the preparser is 

used. 

 

- ``verify`` - (default ``False``) If ``True``, then the answer will be 

evaluated with :func:`sage_eval`, and an exception will be raised if the 

result is not equal to the original value. (In fact, for ``verify=True``, 

:func:`sage_input` is effectively run three times, with ``preparse`` set 

to ``True``, ``False``, and ``None``, and all three results are checked.) 

This is particularly useful for doctests. 

 

- ``allow_locals`` - (default ``False``) If ``True``, then values that 

:func:`sage_input` cannot handle are returned in a dictionary, and the 

returned code assumes that this dictionary is passed as the ``locals`` 

parameter of :func:`sage_eval`. (Otherwise, if :func:`sage_input` cannot 

handle a value, an exception is raised.) 

 

EXAMPLES:: 

 

sage: sage_input(GF(2)(1)) 

GF(2)(1) 

sage: sage_input((GF(2)(0), GF(2)(1)), verify=True) 

# Verified 

GF_2 = GF(2) 

(GF_2(0), GF_2(1)) 

 

When the preparser is enabled, we use the \sage generator syntax.:: 

 

sage: K.<x> = GF(5)[] 

sage: sage_input(x^3 + 2*x, verify=True) 

# Verified 

R.<x> = GF(5)[] 

x^3 + 2*x 

sage: sage_input(x^3 + 2*x, preparse=False) 

R = GF(5)['x'] 

x = R.gen() 

x**3 + 2*x 

 

The result of :func:`sage_input` is actually a pair of strings with a 

special ``__repr__`` method to print nicely.:: 

 

sage: r = sage_input(RealField(20)(pi), verify=True) 

sage: r 

# Verified 

RealField(20)(3.1415939) 

sage: isinstance(r, tuple) 

True 

sage: len(r) 

2 

sage: tuple(r) 

('# Verified\n', 'RealField(20)(3.1415939)') 

 

We cannot find an input form for a function.:: 

 

sage: sage_input((3, lambda x: x)) 

Traceback (most recent call last): 

... 

ValueError: Can't convert <function <lambda> at 0x...> to sage_input form 

 

But we can have :func:`sage_input` continue anyway, and return an input form 

for the rest of the expression, with ``allow_locals=True``.:: 

 

sage: r = sage_input((3, lambda x: x), verify=True, allow_locals=True) 

sage: r 

LOCALS: 

_sil1: <function <lambda> at 0x...> 

# Verified 

(3, _sil1) 

sage: tuple(r) 

('# Verified\n', '(3, _sil1)', {'_sil1': <function <lambda> at 0x...>}) 

""" 

if not verify: 

sib = SageInputBuilder(allow_locals=allow_locals, preparse=preparse) 

return sib.result(sib(x)) 

 

# In verify mode, we actually compute and verify the answer with 

# all three settings of preparse. 

 

for pp in (True, False, None): 

sib = SageInputBuilder(allow_locals=allow_locals, preparse=pp) 

ans = sib.result(sib(x)) 

verify_si_answer(x, ans, pp) 

if pp == preparse: 

ans_l = list(ans) 

ans_l[0] = '# Verified\n' + ans_l[0] 

final_answer = SageInputAnswer(*ans_l) 

 

return final_answer 

 

class SageInputBuilder: 

r""" 

An instance of this class is passed to ``_sage_input_`` methods. 

It keeps track of the current state of the ``_sage_input_`` process, 

and contains many utility methods for building :class:`SageInputExpression` 

objects. 

 

In normal use, instances of :class:`SageInputBuilder` are created 

internally by :func:`sage_input`, but it may be useful to create 

an instance directly for testing or doctesting. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

We can create a :class:`SageInputBuilder`, use it to create some 

:class:`SageInputExpression` s, and get a result. (As mentioned 

above, this is only useful for testing or doctesting; normally 

you would just use :func:`sage_input`.):: 

 

sage: sib = SageInputBuilder() 

sage: sib.result((sib(3) + sib(4)) * (sib(5) + sib(6))) 

(3 + 4)*(5 + 6) 

""" 

 

def __init__(self, allow_locals=False, preparse=True): 

r""" 

Initialize an instance of :class:`SageInputBuilder`. 

 

In normal use, instances of :class:`SageInputBuilder` are created 

internally by :func:`sage_input`, but it may be useful to create 

an instance directly for testing or doctesting. 

 

INPUT: 

 

- ``allow_locals`` - (default ``False``) If true, then values 

that cannot be converted to input form will be stored in 

a dictionary, which must be passed as the ``locals`` 

when evaluating the result. 

 

- ``preparse`` -- (default ``True``) If true, then the result 

will assume that the preparser is enabled. If false, then 

the result will assume that the preparser is disabled. 

If ``None``, then the result will work whether or 

not the preparser is enabled. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: SageInputBuilder().preparse() 

True 

sage: SageInputBuilder(preparse=False).preparse() 

False 

""" 

self._allow_locals = allow_locals 

self._preparse = preparse 

self._cached_types = set() 

self._cache = {} 

self._id_cache = {} 

self._parent_gens = {} 

self._next_local = 1 

self._locals = {} 

 

def __call__(self, x, coerced=False): 

r""" 

Tries to convert an arbitrary value ``x`` into a 

:class:`SageInputExpression` (an SIE). 

 

We first check to see if an SIE has been cached for ``x``; 

if so, we return it. If ``x`` is already an SIE, we return 

it unchanged. 

 

If ``x`` has a \method{_sage_input_} method, we call that 

method. 

 

Otherwise, if ``x`` is a value of some Python type that 

we know how to deal with, we convert it directly. 

 

Finally, for values we don't know how to convert, if 

``self._allow_locals`` is true, we add it to a 

``locals`` dictionary. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib(sib(3))) 

3 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib(GF(17)(5))) 

GF(17)(5) 

 

The argument ``coerced=True`` or ``coerced=2`` will get 

passed to the \method{_sage_input_} method of the argument.:: 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib(GF(17)(5), True)) 

5 

sage: sib.result(sib(RealField(200)(1.5), True)) 

1.5000000000000000000000000000000000000000000000000000000000000 

sage: sib.result(sib(RealField(200)(1.5), 2)) 

1.5 

 

Since :func:`sage_input` directly calls this method, all 

of the following are indirect doctests.:: 

 

sage: sage_input(True) 

True 

sage: sage_input(-5r, verify=True) 

# Verified 

-5r 

sage: sage_input(7r, preparse=False, verify=True) 

# Verified 

7 

sage: sage_input(-11r, preparse=None, verify=True) 

# Verified 

-int(11) 

sage: sage_input(long(-5), verify=True) 

# Verified 

-long(5) 

sage: sage_input(long(-7), preparse=False, verify=True) 

# Verified 

-7L 

sage: sage_input(long(11), preparse=None, verify=True) 

# Verified 

long(11) 

sage: sage_input(long(2^70), verify=True) 

# Verified 

1180591620717411303424r 

sage: sage_input(-long(2^80), preparse=False, verify=True) 

# Verified 

-1208925819614629174706176 

sage: sage_input(long(2^75), preparse=None, verify=True) 

# Verified 

long(37778931862957161709568) 

sage: sage_input(float(-infinity), preparse=True, verify=True) 

# Verified 

-float(infinity) 

sage: sage_input(float(NaN), preparse=True, verify=True) 

# Verified 

float(NaN) 

sage: sage_input(float(-pi), preparse=True, verify=True) 

# Verified 

float(-RR(3.1415926535897931)) 

sage: sage_input(float(42), preparse=True, verify=True) 

# Verified 

float(42) 

sage: sage_input("Hello, world\n", verify=True) 

# Verified 

'Hello, world\n' 

sage: sage_input("'", verify=True) 

# Verified 

"'" 

sage: sage_input('"', verify=True) 

# Verified 

'"' 

sage: sage_input(''' "'Hi,' she said." ''', verify=True) 

# Verified 

' "\'Hi,\' she said." ' 

sage: sage_input('Icky chars: \0\n\t\b\'\"\200\300\234', verify=True) 

# Verified 

'Icky chars: \x00\n\t\x08\'"\x80\xc0\x9c' 

sage: sage_input(u'unicode with spectral: \u1234\U00012345', verify=True) 

# Verified 

u'unicode with spectral: \u1234\U00012345' 

sage: sage_input((2, 3.5, 'Hi'), verify=True) 

# Verified 

(2, 3.5, 'Hi') 

sage: sage_input(lambda x: x) 

Traceback (most recent call last): 

... 

ValueError: Can't convert <function <lambda> at 0x...> to sage_input form 

sage: sage_input(lambda x: x, allow_locals=True, verify=True) 

LOCALS: 

_sil1: <function <lambda> at 0x...> 

# Verified 

_sil1 

""" 

# We want to look up x in our cache, to see if we've seen it before. 

# However, we don't want to assume that hashing x is always 

# efficient, so we only try the lookup if some value of the same 

# type as x has been cached. 

from sage.structure.all import parent 

 

if type(x) in self._cached_types: 

v = self._cache.get((parent(x), x)) 

if v is not None: return v 

 

v = self._id_cache.get(id(x)) 

if v is not None: return v[1] 

 

if isinstance(x, SageInputExpression): 

return x 

 

if hasattr(x, '_sage_input_'): 

return x._sage_input_(self, coerced) 

 

if x is None: 

return SIE_literal_stringrep(self, 'None') 

 

if isinstance(x, bool): 

return SIE_literal_stringrep(self, str(x)) 

 

if (isinstance(x, int) or 

(isinstance(x, integer_types) and not isinstance(int(x), int))): 

# For longs that don't fit in an int, we just use the int 

# code; it will get extended to long automatically. 

if self._preparse is True: 

if x < 0: 

return -SIE_literal_stringrep(self, str(-x) + 'r') 

else: 

return SIE_literal_stringrep(self, str(x) + 'r') 

elif self._preparse is False: 

return self.int(x) 

else: 

tyname = 'int' if isinstance(x, int) else 'long' 

if x < 0: 

return -self.name(tyname)(self.int(-x)) 

else: 

return self.name(tyname)(self.int(x)) 

 

if isinstance(x, integer_types): 

# This must be a long that does fit in an int, so we need either 

# long(x) or an 'L' suffix. 

# With the current preparser, 1Lr does not work. 

# 1rL does work; but that's just ugly, so I don't use it. 

if self._preparse is False: 

if x < 0: 

return -SIE_literal_stringrep(self, str(-x) + 'L') 

else: 

return SIE_literal_stringrep(self, str(x) + 'L') 

else: 

if x < 0: 

return -self.name('long')(self.int(-x)) 

else: 

return self.name('long')(self.int(x)) 

 

if isinstance(x, float): 

# floats could often have prettier output, 

# but I think they're rare enough in Sage that it's not 

# worth the effort. 

from sage.all import RR, ZZ, infinity 

if x == float(infinity): 

return self.name('float')(self.name('infinity')) 

if x != x: 

return self.name('float')(self.name('NaN')) 

if x == -float(infinity): 

return -self.name('float')(self.name('infinity')) 

if self._preparse is False and float(str(x)) == x: 

if x < 0: 

return -SIE_literal_stringrep(self, str(-x)) 

else: 

return SIE_literal_stringrep(self, str(x)) 

rrx = RR(x) 

if rrx in ZZ and abs(rrx) < (1 << 53): 

return self.name('float')(self.int(ZZ(rrx))) 

return self.name('float')(RR(x)) 

 

if isinstance(x, string_types): 

return SIE_literal_stringrep(self, repr(x)) 

 

if isinstance(x, tuple): 

return SIE_tuple(self, [self(_) for _ in x], False) 

 

if isinstance(x, list): 

return SIE_tuple(self, [self(_) for _ in x], True) 

 

if isinstance(x, dict): 

return self.dict(x) 

 

if self._allow_locals: 

loc = self._next_local 

self._next_local += 1 

loc_name = '_sil%d' % loc 

self._locals[loc_name] = x 

return SIE_literal_stringrep(self, loc_name) 

else: 

raise ValueError("Can't convert {} to sage_input form".format(x)) 

 

def preparse(self): 

r""" 

Checks the preparse status. 

 

It returns ``True`` if the preparser will be enabled, ``False`` if it 

will be disabled, and ``None`` if the result must work whether or not 

the preparser is enabled. 

 

For example, this is useful in the \method{_sage_input_} 

methods of :class:`~sage.rings.integer.Integer` and :class:`RealNumber`; but most 

\method{_sage_input_} methods will not need to examine this. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: SageInputBuilder().preparse() 

True 

sage: SageInputBuilder(preparse=False).preparse() 

False 

""" 

return self._preparse 

 

def int(self, n): 

r""" 

Return a raw SIE from the integer ``n`` 

 

As it is raw, it may read back as a Sage Integer, a Python int or a 

Python long, depending on its size and whether the preparser is enabled. 

 

INPUT: 

 

- ``n`` - a Sage Integer, a Python int or a Python long 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.int(-3^50)) 

-717897987691852588770249 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.int(long(2^65))) 

36893488147419103232 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.int(-42r)) 

-42 

""" 

if n < 0: 

return -SIE_literal_stringrep(self, -n) 

else: 

return SIE_literal_stringrep(self, n) 

 

def float_str(self, n): 

r""" 

Given a string representing a floating-point number, 

produces a :class:`SageInputExpression` that formats as that 

string. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.float_str(repr(RR(e)))) 

2.71828182845905 

""" 

return SIE_literal_stringrep(self, n) 

 

def name(self, n): 

r""" 

Given a string representing a Python name, 

produces a :class:`SageInputExpression` for that name. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.name('pi') + sib.name('e')) 

pi + e 

""" 

return SIE_literal_stringrep(self, n) 

 

def cache(self, x, sie, name): 

r""" 

INPUT: 

 

- ``x`` - an arbitrary value 

 

- ``sie`` - a :class:`SageInputExpression` 

 

- ``name`` - a requested variable name 

 

Enters ``x`` and ``sie`` in a cache, so that subsequent calls 

``self(x)`` will directly return ``sie``. Also, marks the 

requested name of this ``sie`` to be ``name``. 

 

This should almost always be called as part of the 

\method{_sage_input_} method of a parent. It may also be called 

on values of an arbitrary type, which may be useful if the values 

are both large and likely to be used multiple times in a single 

expression. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie42 = sib(GF(101)(42)) 

sage: sib.cache(GF(101)(42), sie42, 'the_ultimate_answer') 

sage: sib.result(sib(GF(101)(42)) + sib(GF(101)(42))) 

the_ultimate_answer = GF(101)(42) 

the_ultimate_answer + the_ultimate_answer 

 

Note that we don't assign the result to a variable if the value 

is only used once.:: 

 

sage: sib = SageInputBuilder() 

sage: sie42 = sib(GF(101)(42)) 

sage: sib.cache(GF(101)(42), sie42, 'the_ultimate_answer') 

sage: sib.result(sib(GF(101)(42)) + sib(GF(101)(43))) 

GF_101 = GF(101) 

GF_101(42) + GF_101(43) 

""" 

from sage.structure.all import parent 

 

self._cached_types.add(type(x)) 

self._cache[(parent(x), x)] = sie 

sie._sie_preferred_varname = name 

 

def id_cache(self, x, sie, name): 

r""" 

INPUT: 

 

- ``x`` - an arbitrary value 

 

- ``sie`` - a :class:`SageInputExpression` 

 

- ``name`` - a requested variable name 

 

Enters ``x`` and ``sie`` in a cache, so that subsequent calls 

``self(x)`` will directly return ``sie``. Also, marks the 

requested name of this ``sie`` to be ``name``. Differs from 

the \method{cache} method in that the cache is keyed by 

``id(x)`` instead of by ``x``. 

 

This may be called on values of an arbitrary type, which may 

be useful if the values are both large and likely to be used 

multiple times in a single expression; it should be preferred to 

\method{cache} if equality on the values is difficult or impossible 

to compute. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: x = polygen(ZZ) 

sage: sib = SageInputBuilder() 

sage: my_42 = 42*x 

sage: sie42 = sib(my_42) 

sage: sib.id_cache(my_42, sie42, 'the_ultimate_answer') 

sage: sib.result(sib(my_42) + sib(my_42)) 

R.<x> = ZZ[] 

the_ultimate_answer = 42*x 

the_ultimate_answer + the_ultimate_answer 

 

Since id_cache keys off of object identity ("is"), the 

following does not trigger the cache.:: 

 

sage: sib.result(sib(42*x) + sib(42*x)) 

42*x + 42*x 

 

Note that we don't assign the result to a variable if the value 

is only used once.:: 

 

sage: sib = SageInputBuilder() 

sage: my_42 = 42*x 

sage: sie42 = sib(my_42) 

sage: sib.id_cache(my_42, sie42, 'the_ultimate_answer') 

sage: sib.result(sib(my_42) + sib(43*x)) 

R.<x> = ZZ[] 

42*x + 43*x 

""" 

# If we just mapped id(x) -> sie, then it's possible that x could 

# be freed and another value allocated at the same position, 

# corrupting the cache. But since we store x, that can't happen; 

# we don't even have to look at x when we read the cache. 

self._id_cache[id(x)] = (x, sie) 

sie._sie_preferred_varname = name 

 

def import_name(self, module, name, alt_name=None): 

r""" 

INPUT: 

 

- ``module``, ``name``, ``alt_name`` -- strings 

 

Creates an expression that will import a name from a module and 

then use that name. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: v1 = sib.import_name('sage.foo.bar', 'baz') 

sage: v2 = sib.import_name('sage.foo.bar', 'ZZ', 'not_the_real_ZZ') 

sage: sib.result(v1+v2) 

from sage.foo.bar import baz 

from sage.foo.bar import ZZ as not_the_real_ZZ 

baz + not_the_real_ZZ 

 

We adjust the names if there is a conflict.:: 

 

sage: sib = SageInputBuilder() 

sage: v1 = sib.import_name('sage.foo', 'poly') 

sage: v2 = sib.import_name('sage.bar', 'poly') 

sage: sib.result(v1+v2) 

from sage.foo import poly as poly1 

from sage.bar import poly as poly2 

poly1 + poly2 

""" 

return SIE_import_name(self, module, name, alt_name) 

 

def assign(self, e, val): 

r""" 

Constructs a command that performs the assignment ``e=val``. 

 

Can only be used as an argument to the ``command`` method. 

 

INPUT: 

 

- ``e``, ``val`` -- SageInputExpression 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: circular = sib([None]) 

sage: sib.command(circular, sib.assign(circular[0], circular)) 

sage: sib.result(circular) 

si = [None] 

si[0] = si 

si 

""" 

e = self(e) 

val = self(val) 

 

return SIE_assign(self, e, val) 

 

def command(self, v, cmd): 

r""" 

INPUT: 

 

- ``v``, ``cmd`` -- SageInputExpression 

 

Attaches a command to v, which will be executed before v is used. 

Multiple commands will be executed in the order added. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: incr_list = sib([]) 

sage: sib.command(incr_list, incr_list.append(1)) 

sage: sib.command(incr_list, incr_list.extend([2, 3])) 

sage: sib.result(incr_list) 

si = [] 

si.append(1) 

si.extend([2, 3]) 

si 

""" 

v = self(v) 

cmd = self(cmd) 

 

v._sie_commands.append(cmd) 

 

def dict(self, entries): 

r""" 

Given a dictionary, or a list of (key, value) pairs, 

produces a :class:`SageInputExpression` representing 

the dictionary. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.dict({1:1, 2:5/2, 3:100/3})) 

{1:1, 2:5/2, 3:100/3} 

sage: sib.result(sib.dict([('hello', 'sunshine'), ('goodbye', 'rain')])) 

{'hello':'sunshine', 'goodbye':'rain'} 

""" 

if isinstance(entries, dict): 

entries = list(entries.items()) 

entries = [(self(key),self(val)) for (key,val) in entries] 

return SIE_dict(self, entries) 

 

def getattr(self, sie, attr): 

r""" 

Given a :class:`SageInputExpression` representing ``foo`` 

and an attribute name bar, produce a :class:`SageInputExpression` 

representing ``foo.bar``. Normally, you could just use 

attribute-access syntax, but that doesn't work if bar 

is some attribute that bypasses __getattr__ (such as if 

bar is '__getattr__' itself). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.getattr(ZZ, '__getattr__') 

{getattr: {atomic:ZZ}.__getattr__} 

sage: sib.getattr(sib.name('foo'), '__new__') 

{getattr: {atomic:foo}.__new__} 

""" 

return SIE_getattr(self, self(sie), attr) 

 

def empty_subscript(self, parent): 

r""" 

Given a :class:`SageInputExpression` representing ``foo``, 

produces a :class:`SageInputExpression` representing ``foo[]``. 

Since this is not legal Python syntax, it is useful only for 

producing the \sage generator syntax for a polynomial ring. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.empty_subscript(sib(2) + sib(3))) 

(2 + 3)[] 

 

The following calls this method indirectly.:: 

 

sage: sage_input(polygen(ZZ['y'])) 

R.<x> = ZZ['y'][] 

x 

""" 

return SIE_subscript(self, parent, None) 

 

def use_variable(self, sie, name): 

r""" 

Marks the :class:`SageInputExpression` ``sie`` to use a variable 

even if it is only referenced once. (If ``sie`` is the final 

top-level expression, though, it will not use a variable.) 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: e = sib.name('MatrixSpace')(ZZ, 10, 10) 

sage: sib.use_variable(e, 'MS') 

sage: sib.result(e.zero_matrix()) 

MS = MatrixSpace(ZZ, 10, 10) 

MS.zero_matrix() 

 

Without the call to use_variable, we get this instead:: 

 

sage: sib = SageInputBuilder() 

sage: e = sib.name('MatrixSpace')(ZZ, 10, 10) 

sage: sib.result(e.zero_matrix()) 

MatrixSpace(ZZ, 10, 10).zero_matrix() 

 

And even with the call to use_variable, we don't use a variable here:: 

 

sage: sib = SageInputBuilder() 

sage: e = sib.name('MatrixSpace')(ZZ, 10, 10) 

sage: sib.use_variable(e, 'MS') 

sage: sib.result(e) 

MatrixSpace(ZZ, 10, 10) 

""" 

sie._sie_preferred_varname = name 

sie._sie_request_use_var = True 

 

def share(self, sie): 

r""" 

Mark the given expression as sharable, so that it will be replaced 

by a variable if it occurs multiple times in the expression. 

(Most non-single-token expressions are already sharable.) 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

Without explicitly using .share(), string literals are not shared:: 

 

sage: sib = SageInputBuilder() 

sage: e = sib('hello') 

sage: sib.result(sib((e, e))) 

('hello', 'hello') 

 

See the difference if we use .share():: 

 

sage: sib = SageInputBuilder() 

sage: e = sib('hello') 

sage: sib.share(e) 

sage: sib.result(sib((e, e))) 

si = 'hello' 

(si, si) 

""" 

sie._sie_share = True 

 

def parent_with_gens(self, parent, sie, gen_names, name, gens_syntax=None): 

r""" 

This method is used for parents with generators, to manage the 

\sage preparser generator syntax (like ``K.<x> = QQ[]``). 

 

The \method{_sage_input_} method of a parent class with 

generators should construct a :class:`SageInputExpression` for 

the parent, and then call this method with the parent itself, 

the constructed SIE, a sequence containing the names of the 

generators, and (optionally) another SIE to use if the \sage 

generator syntax is used; typically this will be the same as 

the first SIE except omitting a ``names`` parameter. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

 

sage: def test_setup(use_gens=True, preparse=True): 

....: sib = SageInputBuilder(preparse=preparse) 

....: gen_names=('foo', 'bar') 

....: parent = "some parent" 

....: normal_sie = sib.name('make_a_parent')(names=gen_names) 

....: if use_gens: 

....: gens_sie = sib.name('make_a_parent')() 

....: else: 

....: gens_sie = None 

....: name = 'the_thing' 

....: result = sib.parent_with_gens(parent, normal_sie, 

....: gen_names, name, 

....: gens_syntax=gens_sie) 

....: return sib, result 

 

sage: sib, par_sie = test_setup() 

sage: sib.result(par_sie) 

make_a_parent(names=('foo', 'bar')) 

 

sage: sib, par_sie = test_setup() 

sage: sib.result(sib(3) * sib.gen("some parent", 0)) 

the_thing.<foo,bar> = make_a_parent() 

3*foo 

 

sage: sib, par_sie = test_setup(preparse=False) 

sage: sib.result(par_sie) 

make_a_parent(names=('foo', 'bar')) 

 

sage: sib, par_sie = test_setup(preparse=False) 

sage: sib.result(sib(3) * sib.gen("some parent", 0)) 

the_thing = make_a_parent(names=('foo', 'bar')) 

foo,bar = the_thing.gens() 

ZZ(3)*foo 

 

sage: sib, par_sie = test_setup(use_gens=False) 

sage: sib.result(par_sie) 

make_a_parent(names=('foo', 'bar')) 

 

sage: sib, par_sie = test_setup(use_gens=False) 

sage: sib.result(sib(3) * sib.gen("some parent", 0)) 

the_thing = make_a_parent(names=('foo', 'bar')) 

foo,bar = the_thing.gens() 

3*foo 

 

sage: sib, par_sie = test_setup() 

sage: sib.result(par_sie - sib.gen("some parent", 1)) 

the_thing.<foo,bar> = make_a_parent() 

the_thing - bar 

""" 

v = SIE_gens_constructor(self, sie, gen_names, gens_syntax=gens_syntax) 

self.cache(parent, v, name) 

gens = [SIE_gen(self, v, n) for n in gen_names] 

self._parent_gens[parent] = gens 

v._sie_gens = gens 

return v 

 

def gen(self, parent, n=0): 

r""" 

Given a parent, returns a :class:`SageInputExpression` for 

the `n`-th (default 0) generator of the parent. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.gen(ZZ['y'])) 

R.<y> = ZZ[] 

y 

""" 

if not parent in self._parent_gens: 

self(parent) 

if not parent in self._parent_gens: 

raise ValueError("{} did not register generators for sage_input".format(parent)) 

 

gens = self._parent_gens[parent] 

 

if n > len(gens): 

raise ValueError("{} registered only {} generators for sage_input".format(parent, len(gens))) 

 

return gens[n] 

 

def prod(self, factors, simplify=False): 

r""" 

Given a sequence, returns a :class:`SageInputExpression` 

for the product of the elements. 

 

With ``simplify=True``, performs some simplifications 

first. If any element is formatted as a string ``'0'``, 

then that element is returned directly. If any element is 

formatted as a string ``'1'``, then it is removed 

from the sequence (unless it is the only element in the sequence). 

And any negations are removed from the elements and moved to the 

outside of the product. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.prod([-1, 0, 1, -2])) 

-1*0*1*-2 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.prod([-1, 0, 1, 2], simplify=True)) 

0 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.prod([-1, 2, -3, -4], simplify=True)) 

-2*3*4 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.prod([-1, 1, -1, -1], simplify=True)) 

-1 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.prod([1, 1, 1], simplify=True)) 

1 

""" 

neg = False 

factors = [self(factor) for factor in factors] 

if simplify: 

i = 0 

while i < len(factors): 

factor = factors[i] 

while isinstance(factor, SIE_unary) and factor._sie_op == '-': 

neg = not neg 

factor = factor._sie_operand 

factors[i] = factor 

if isinstance(factor, SIE_literal_stringrep) and factor._sie_value == '0': 

factors = [factor] 

neg = False 

break 

if isinstance(factor, SIE_literal_stringrep) and factor._sie_value == '1': 

factors[i:i+1] = [] 

else: 

i += 1 

if len(factors) == 0: 

factors.append(SIE_literal_stringrep(self, '1')) 

 

prod = factors[0] 

for factor in factors[1:]: 

prod = prod * factor 

if neg: 

prod = -prod 

return prod 

 

def sum(self, terms, simplify=False): 

r""" 

Given a sequence, returns a :class:`SageInputExpression` 

for the product of the elements. 

 

With ``simplify=True``, performs some simplifications 

first. If any element is formatted as a string ``'0'``, 

then it is removed from the sequence (unless it is the only 

element in the sequence); and any instances of ``a + -b`` 

are changed to ``a - b``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.sum([-1, 0, 1, 0, -1])) 

-1 + 0 + 1 + 0 + -1 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.sum([-1, 0, 1, 0, -1], simplify=True)) 

-1 + 1 - 1 

 

sage: sib = SageInputBuilder() 

sage: sib.result(sib.sum([0, 0, 0], simplify=True)) 

0 

""" 

terms = [self(term) for term in terms] 

if simplify: 

i = 0 

while i < len(terms): 

term = terms[i] 

if isinstance(term, SIE_literal_stringrep) and term._sie_value == '0': 

terms[i:i+1] = [] 

else: 

i += 1 

if len(terms) == 0: 

terms.append(SIE_literal_stringrep(self, '0')) 

 

sum = terms[0] 

for term in terms[1:]: 

negate = False 

while simplify and isinstance(term, SIE_unary) and term._sie_op == '-': 

negate = not negate 

term = term._sie_operand 

if negate: 

sum = sum - term 

else: 

sum = sum + term 

return sum 

 

def result(self, e): 

r""" 

Given a :class:`SageInputExpression` constructed using ``self``, 

returns a tuple of a list of commands and an expression 

(and possibly a dictionary of local variables) suitable for 

:func:`sage_eval`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: r = sib.result(sib(6) * sib(7)); r 

6*7 

sage: tuple(r) 

('', '6*7') 

""" 

sif = SageInputFormatter() 

 

# Even if use_variable was called on e, don't automatically 

# use a variable for it. 

e._sie_request_use_var = False 

 

e._sie_prepare(sif) 

 

s = sif.format(e, 0) 

 

locals = self._locals 

if len(locals): 

return SageInputAnswer(sif._commands, sif.format(e, 0), locals) 

else: 

return SageInputAnswer(sif._commands, sif.format(e, 0)) 

 

# Python's precedence levels. Hand-transcribed from section 5.14 of 

# the Python reference manual. 

_prec_lambda = 2 

_prec_or = 4 

_prec_and = 6 

_prec_not = 8 

_prec_membership = 10 

_prec_identity = 12 

_prec_comparison = 14 

_prec_bitor = 16 

_prec_bitxor = 18 

_prec_bitand = 20 

_prec_shift = 22 

_prec_addsub = 24 

_prec_muldiv = 26 

_prec_negate = 28 

_prec_bitnot = 30 

_prec_exponent = 32 

_prec_attribute = 34 

_prec_subscript = 36 

_prec_slicing = 38 

_prec_funcall = 40 

_prec_atomic = 42 

 

class SageInputExpression(object): 

r""" 

Subclasses of this class represent expressions for :func:`sage_input`. 

\sage classes should define a \method{_sage_input_} method, which 

will return an instance of :class:`SageInputExpression`, created using 

methods of :class:`SageInputBuilder`. 

 

To the extent possible, operations on :class:`SageInputExpression` objects 

construct a new :class:`SageInputExpression` representing that operation. 

That is, if ``a`` is a :class:`SageInputExpression`, then ``a + b`` 

constructs a :class:`SageInputExpression` representing this sum. 

This also works for attribute access, function calls, subscripts, etc. 

Since arbitrary attribute accesses might be used to construct a new 

attribute-access expression, all internal attributes and methods 

have names that begin with ``_sie_`` to reduce the chance of 

collisions. 

 

It is expected that instances of this class will not be directly 

created outside this module; instead, instances will be created 

using methods of :class:`SageInputBuilder` and :class:`SageInputExpression`. 

 

Values of type :class:`SageInputExpression` print in a fairly ugly 

way, that reveals the internal structure of the expression tree. 

""" 

 

def __init__(self, sib): 

r""" 

Initialize a :class:`SageInputExpression`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) # indirect doctest 

sage: sie 

{atomic:3} 

sage: sie._sie_builder is sib 

True 

""" 

self._sie_refcount = 0 

self._sie_builder = sib 

self._sie_context = None 

self._sie_preferred_varname = None 

self._sie_varname = None 

self._sie_request_use_var = False 

self._sie_use_var = False 

self._sie_requested_varname = False 

self._sie_commands = [] 

 

def _sie_is_simple(self): 

r""" 

Returns ``True`` if this :class:`SageInputExpression` is simple 

enough that duplicate uses are not worth caching. Normally 

this will be true if the expression represents a single token. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sib.name('QQ')._sie_is_simple() 

True 

sage: sib(GF(2))._sie_is_simple() 

False 

""" 

return False 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SageInputExpression`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: len(sib(GF(2))._sie_referenced()) 

2 

sage: sib(5)._sie_referenced() 

[] 

""" 

return [] 

 

def _sie_prepare(self, sif): 

r""" 

We traverse the entire expression DAG to prepare for printing. 

Here, we notice nodes with more than one parent, and mark them 

to replace with a variable (rather than generating the value 

multiple times). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: pair = sib((GF(2), GF(2))) 

sage: single = sib(GF(2)) 

sage: single._sie_refcount 

0 

sage: single._sie_use_var 

False 

sage: sib((GF(2), GF(2)))._sie_prepare(sif) 

sage: single._sie_refcount 

2 

sage: single._sie_use_var 

True 

""" 

if self._sie_context is not sif: 

self._sie_context = sif 

self._sie_refcount = 0 

self._sie_refcount += 1 

if self._sie_request_use_var: 

self._sie_require_varname(sif) 

self._sie_use_var = True 

if not self._sie_is_simple(): 

if self._sie_refcount == 2: 

self._sie_require_varname(sif) 

self._sie_use_var = True 

if self._sie_refcount == 1: 

for r in self._sie_referenced(): 

r._sie_prepare(sif) 

for r in self._sie_commands: 

r._sie_prepare(sif) 

 

def _sie_require_varname(self, sif): 

r""" 

Mark this :class:`SageInputExpression` as requiring a variable name, 

and register it with a :class:`SageInputFormatter` (which will 

allocate a variable name at the end of the preparatory phase). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib(3) 

sage: sie._sie_require_varname(sif) 

sage: sie._sie_requested_varname 

True 

""" 

if not self._sie_requested_varname: 

sif.register_name(self._sie_preferred_varname) 

self._sie_requested_varname = True 

self._sie_generated = False 

 

def _sie_get_varname(self, sif): 

r""" 

Get the variable name that the :class:`SageInputFormatter` allocated 

for this :class:`SageInputExpression`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib(3) 

sage: sie._sie_require_varname(sif) 

sage: sie._sie_get_varname(sif) 

'si' 

""" 

if self._sie_varname is None: 

self._sie_varname = sif.get_name(self._sie_preferred_varname) 

 

return self._sie_varname 

 

def _sie_is_negation(self): 

r""" 

Test whether a :class:`SageInputExpression` is a negation. 

 

Despite the obscure name, this is intended to be a public method. 

 

See the documentation for \method{SIE_unary._sie_is_negation} 

for useful examples. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('foo') 

sage: sie._sie_is_negation() 

False 

""" 

return False 

 

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

r""" 

Given a :class:`SageInputExpression`, build a new 

:class:`SageInputExpression` representing a function call node 

(with ``self`` as the function). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie(4) 

{call: {atomic:3}({atomic:4})} 

""" 

args = [self._sie_builder(_) for _ in args] 

for k in kwargs: 

kwargs[k] = self._sie_builder(kwargs[k]) 

return SIE_call(self._sie_builder, self, args, kwargs) 

 

def __getitem__(self, key): 

r""" 

Given a :class:`SageInputExpression`, build a new 

:class:`SageInputExpression` representing a subscript expression 

(with ``self`` as the value being subscripted). 

 

Currently, slices are not supported. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie[4] 

{subscr: {atomic:3}[{atomic:4}]} 

sage: sie[sib.name('x'), sib.name('y')] 

{subscr: {atomic:3}[{tuple: ({atomic:x}, {atomic:y})}]} 

""" 

skey = self._sie_builder(key) 

return SIE_subscript(self._sie_builder, self, skey) 

 

def __getattr__(self, attr): 

r""" 

Given a :class:`SageInputExpression`, build a new 

:class:`SageInputExpression` representing an attribute access. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('x') 

sage: sie.foo 

{getattr: {atomic:x}.foo} 

sage: sie.foo() 

{call: {getattr: {atomic:x}.foo}()} 

""" 

return SIE_getattr(self._sie_builder, self, attr) 

 

def _rich_repr_(self, display_manager, **kwds): 

""" 

Disable rich output. 

 

This is necessary because otherwise our :meth:`__getattr__` 

would be called. 

 

EXAMPLES:: 

 

sage: from sage.repl.rich_output import get_display_manager 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('x') 

sage: sie._rich_repr_(get_display_manager()) is None 

True 

""" 

return None 

 

def __pow__(self, other): 

r""" 

Compute an expression tree for ``self ** other``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie ^ 4 

{binop:** {atomic:3} {atomic:4}} 

""" 

return self._sie_binop('**', other) 

 

def __mul__(self, other): 

r""" 

Compute an expression tree for ``self * other``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie * 4 

{binop:* {atomic:3} {atomic:4}} 

""" 

return self._sie_binop('*', other) 

 

def __truediv__(self, other): 

r""" 

Compute an expression tree for ``self / other``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie / 4 

{binop:/ {atomic:3} {atomic:4}} 

""" 

return self._sie_binop('/', other) 

 

__div__ = __truediv__ 

 

def __add__(self, other): 

r""" 

Compute an expression tree for ``self + other``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie + 4 

{binop:+ {atomic:3} {atomic:4}} 

""" 

return self._sie_binop('+', other) 

 

def __sub__(self, other): 

r""" 

Compute an expression tree for ``self - other``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie - 4 

{binop:- {atomic:3} {atomic:4}} 

""" 

return self._sie_binop('-', other) 

 

def _sie_binop(self, op, other): 

r""" 

Compute an expression tree for ``self OP other``, 

where OP is a string representing a binary operator (such as 

'+' or '**'). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: v = sib.name('x')._sie_binop('%', sib.name('y')) 

sage: type(v) 

<class 'sage.misc.sage_input.SIE_binary'> 

sage: (v)._sie_op 

'%' 

sage: v 

{binop:% {atomic:x} {atomic:y}} 

""" 

return SIE_binary(self._sie_builder, op, self, self._sie_builder(other)) 

 

def __neg__(self): 

r""" 

Compute an expression tree for ``-self``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: -sie 

{unop:- {atomic:3}} 

""" 

return self._sie_unop('-') 

 

def __invert__(self): 

r""" 

Compute an expression tree for ``~self``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: ~sie 

{unop:~ {atomic:3}} 

""" 

return self._sie_unop('~') 

 

def __abs__(self): 

r""" 

Compute an expression tree for ``abs(self)``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: abs(sie) 

{call: {atomic:abs}({atomic:3})} 

""" 

return self._sie_builder.name('abs')(self) 

 

def _sie_unop(self, op): 

r""" 

Compute an expression tree for ``OP self``, 

where OP is a string representing a unary operator (such as 

'-' or '~'). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: v = sie._sie_unop('~') 

sage: type(v) 

<class 'sage.misc.sage_input.SIE_unary'> 

sage: (v)._sie_op 

'~' 

sage: v 

{unop:~ {atomic:3}} 

""" 

return SIE_unary(self._sie_builder, op, self) 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this expression, and the 

precedence of the top-level operator in the expression. 

 

EXAMPLES: 

 

Actually, all of these are examples of the \method{_sie_format} 

method on subclasses of :class:`SageInputExpression`; 

:class:`SageInputExpression` itself is an abstract base class 

(that cannot be instantiated).:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib(3) 

 

sage: for v in (sie, sie+7, sie/5): 

....: v._sie_prepare(sif) 

....: v._sie_format(sif) 

('3', 42) 

('3 + 7', 24) 

('3/5', 26) 

sage: v = sib.assign(sib.name('foo').x, 3) 

sage: v._sie_prepare(sif) 

sage: v._sie_format(sif) 

Traceback (most recent call last): 

... 

ValueError: Cannot format SIE_assign as expression 

""" 

raise NotImplementedError 

 

def _sie_format_statement(self, sif): 

r""" 

Return the formatted string value of this expression, when 

used as a statement. 

 

On most :class:`SageInputExpression`s, this forwards directly 

to the \method{_sie_format} method. However, on 

:class:`SageInputExpression`s that actually represent 

statements (such as :class:`SIE_assign`), this method 

has an implementation and \method{_sie_format} raises 

an error. (This is to prevent accidental use of 

:class:`SIE_assign` as a value.) 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: v = sib(3) 

sage: v._sie_prepare(sif) 

sage: v._sie_format_statement(sif) 

'3' 

sage: v = sib.assign(sib.name('foo').x, 3) 

sage: v._sie_prepare(sif) 

sage: v._sie_format_statement(sif) 

'foo.x = 3' 

""" 

result, prec = self._sie_format(sif) 

return result 

 

class SIE_literal(SageInputExpression): 

r""" 

An abstract base class for ``literals`` (basically, values which 

consist of a single token). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SIE_literal 

 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie 

{atomic:3} 

sage: isinstance(sie, SIE_literal) 

True 

""" 

 

def _sie_is_simple(self): 

r""" 

Report that :class:`SIE_literal` values are not worth replacing by 

variables (for ``common subexpression elimination``) even if they 

occur multiple times in an expression. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib(3) 

sage: sie._sie_is_simple() 

True 

 

sage: sib.share(sie) 

sage: sie._sie_is_simple() 

False 

sage: sie._sie_share 

True 

""" 

# Perhaps this should actually look at the formatted length of self, 

# and sometimes return false? If some 50-digit integer occurs multiple 

# times in an expression, it might be better to do the replacement. 

return not self._sie_share 

 

class SIE_literal_stringrep(SIE_literal): 

r""" 

Values in this class are leaves in a :func:`sage_input` expression 

tree. Typically they represent a single token, and consist of the 

string representation of that token. They are used for integer, 

floating-point, and string literals, and for name expressions. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SIE_literal_stringrep 

 

sage: sib = SageInputBuilder() 

sage: isinstance(sib(3), SIE_literal_stringrep) 

True 

sage: isinstance(sib(3.14159, True), SIE_literal_stringrep) 

True 

sage: isinstance(sib.name('pi'), SIE_literal_stringrep) 

True 

sage: isinstance(sib(False), SIE_literal_stringrep) 

True 

sage: sib(False) 

{atomic:False} 

""" 

 

def __init__(self, sib, n): 

r""" 

Initialize a :class:`SIE_literal_stringrep` value. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``n`` - a string; the value to be printed for this expression 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib(3) 

{atomic:3} 

sage: sib(3)._sie_value 

'3' 

""" 

super(SIE_literal_stringrep, self).__init__(sib) 

self._sie_value = str(n) 

self._sie_share = False 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_literal_stringrep` 

value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib(3) 

{atomic:3} 

sage: sib("\n") 

{atomic:'\n'} 

""" 

return "{atomic:%s}" % self._sie_value 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this expression, and an indication 

that it is ``atomic`` (never needs to be parenthesized). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib(True) 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

('True', 42) 

""" 

return self._sie_value, _prec_atomic 

 

class SIE_call(SageInputExpression): 

r""" 

This class represents a function-call node in a :func:`sage_input` 

expression tree. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('GF') 

sage: sie(49) 

{call: {atomic:GF}({atomic:49})} 

""" 

 

def __init__(self, sib, func, args, kwargs): 

r""" 

Initialize an instance of :class:`SIE_call`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``func`` - a :class:`SageInputExpression` representing a function 

 

- ``args`` - a list of :class:`SageInputExpression`s representing the 

positional arguments 

 

- ``kwargs`` -- a dictionary mapping strings to 

:class:`SageInputExpression`s representing the keyword arguments 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib('RealField')(53, rnd='RNDZ') 

""" 

super(SIE_call, self).__init__(sib) 

self._sie_func = func 

self._sie_args = args 

self._sie_kwargs = kwargs 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_call` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib('RealField')(53, rnd='RNDZ') 

""" 

func = repr(self._sie_func) 

args = [repr(arg) for arg in self._sie_args] 

kwargs = sorted(k + '=' + repr(v) 

for k, v in iteritems(self._sie_kwargs)) 

all_args = ', '.join(args + kwargs) 

return "{call: %s(%s)}" % (func, all_args) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this :class:`SIE_call`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib('RealField')(53, rnd='RNDZ') 

sage: sie._sie_referenced() 

[{atomic:53}, {atomic:'RealField'}, {atomic:'RNDZ'}] 

""" 

refs = self._sie_args[:] 

refs.append(self._sie_func) 

refs.extend(itervalues(self._sie_kwargs)) 

return refs 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this expression, and an indication 

that it is a function call. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.name('RealField')(53, rnd='RNDZ') 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

("RealField(53, rnd='RNDZ')", 40) 

""" 

func = sif.format(self._sie_func, _prec_attribute) 

args = [sif.format(arg, 0) for arg in self._sie_args] 

kwargs = sorted(k + '=' + sif.format(v, 0) 

for k, v in iteritems(self._sie_kwargs)) 

all_args = ', '.join(args + kwargs) 

return ('%s(%s)' % (func, all_args), _prec_funcall) 

 

 

class SIE_subscript(SageInputExpression): 

r""" 

This class represents a subscript node in a :func:`sage_input` 

expression tree. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('QQ')['x,y'] 

sage: sie 

{subscr: {atomic:QQ}[{atomic:'x,y'}]} 

""" 

 

def __init__(self, sib, coll, key): 

r""" 

Initialize an instance of :class:`SIE_subscript`. 

 

INPUT: 

 

- ``sib`` -- a :class:`SageInputBuilder` 

 

- ``coll`` -- a :class:`SageInputExpression` representing a collection 

 

- ``key`` -- a :class:`SageInputExpression` representing the subscript/key 

 

As a special case, ``key`` may be ``None``; this represents an 

empty subscript. This is not legal Python syntax, but it is legal 

in the \sage preparser in examples like ``K.<x> = QQ[]``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.name('QQ')['x'] 

{subscr: {atomic:QQ}[{atomic:'x'}]} 

sage: sib.name('x')[1,2,3] 

{subscr: {atomic:x}[{tuple: ({atomic:1}, {atomic:2}, {atomic:3})}]} 

sage: sib.empty_subscript(sib.name('QQ')) 

{subscr: {atomic:QQ}[]} 

""" 

super(SIE_subscript, self).__init__(sib) 

self._sie_coll = coll 

self._sie_key = key 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_subscript` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.name('ZZ')['x,y'] 

{subscr: {atomic:ZZ}[{atomic:'x,y'}]} 

""" 

coll = repr(self._sie_coll) 

if self._sie_key is None: 

key = '' 

else: 

key = repr(self._sie_key) 

return "{subscr: %s[%s]}" % (coll, key) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SIE_subscript`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('GF')(5)['x,y'] 

sage: sie._sie_referenced() 

[{call: {atomic:GF}({atomic:5})}, {atomic:'x,y'}] 

""" 

refs = [self._sie_coll] 

if self._sie_key is not None: 

refs.append(self._sie_key) 

return refs 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this expression, and an 

indication that it is a subscript. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.name('QQ')['x'] 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

("QQ['x']", 36) 

""" 

coll = sif.format(self._sie_coll, _prec_attribute) 

if self._sie_key is None: 

key = '' 

else: 

key = sif.format(self._sie_key, 0) 

return '%s[%s]' % (coll, key), _prec_subscript 

 

class SIE_getattr(SageInputExpression): 

r""" 

This class represents a getattr node in a :func:`sage_input` 

expression tree. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('CC').gen() 

sage: sie 

{call: {getattr: {atomic:CC}.gen}()} 

""" 

def __init__(self, sib, obj, attr): 

r""" 

Initialize an instance of :class:`SIE_getattr`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``obj`` - a :class:`SageInputExpression` representing an object 

 

- ``attr`` - a string; the attribute name 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.name('QQbar').zeta(5) 

{call: {getattr: {atomic:QQbar}.zeta}({atomic:5})} 

""" 

super(SIE_getattr, self).__init__(sib) 

self._sie_obj = obj 

self._sie_attr = attr 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_getattr` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.name('AA')(3).sqrt() 

{call: {getattr: {call: {atomic:AA}({atomic:3})}.sqrt}()} 

""" 

obj = repr(self._sie_obj) 

return "{getattr: %s.%s}" % (obj, self._sie_attr) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SIE_subscript`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('CDF').gen 

sage: sie._sie_referenced() 

[{atomic:CDF}] 

""" 

return [self._sie_obj] 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this expression, and an 

indication that it is an attribute reference. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.name('AA').common_polynomial 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

('AA.common_polynomial', 34) 

""" 

obj = sif.format(self._sie_obj, _prec_exponent) 

return '%s.%s' % (obj, self._sie_attr), _prec_attribute 

 

 

class SIE_tuple(SageInputExpression): 

r""" 

This class represents a tuple or list node in a :func:`sage_input` 

expression tree. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib((1, 'howdy')) 

{tuple: ({atomic:1}, {atomic:'howdy'})} 

sage: sib(["lists"]) 

{list: ({atomic:'lists'})} 

""" 

 

def __init__(self, sib, values, is_list): 

r""" 

Initialize an instance of :class:`SIE_tuple`. 

 

INPUT: 

 

- ``sib`` -- a :class:`SageInputBuilder` 

 

- ``values`` -- a list of :class:`SageInputExpression`s representing the 

elements of this tuple 

 

- ``is_list`` -- is True if this class represents a list, False for a 

tuple 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib((3.5, -2)) 

{tuple: ({atomic:3.5}, {unop:- {atomic:2}})} 

sage: sib(["Hello", "world"]) 

{list: ({atomic:'Hello'}, {atomic:'world'})} 

""" 

super(SIE_tuple, self).__init__(sib) 

self._sie_values = values 

self._sie_is_list = is_list 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_tuple` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib((2,3,5)) 

{tuple: ({atomic:2}, {atomic:3}, {atomic:5})} 

sage: sib(["Hello", "world"]) 

{list: ({atomic:'Hello'}, {atomic:'world'})} 

""" 

kind = "list" if self._sie_is_list else "tuple" 

return "{%s: (%s)}" % \ 

(kind, ', '.join([repr(v) for v in self._sie_values])) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SIE_tuple`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib((ZZ, GF(5))) 

sage: sie._sie_referenced() 

[{atomic:ZZ}, {call: {atomic:GF}({atomic:5})}] 

""" 

return self._sie_values 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this tuple or list, and an 

indication that it is atomic (never needs to be parenthesized). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: for v in ((), (1,), (1,2), [], [1], [1,2]): 

....: sie = sib(v) 

....: sie._sie_prepare(sif) 

....: sie._sie_format(sif) 

('()', 42) 

('(1,)', 42) 

('(1, 2)', 42) 

('[]', 42) 

('[1]', 42) 

('[1, 2]', 42) 

""" 

values = [sif.format(val, 0) for val in self._sie_values] 

if self._sie_is_list: 

return '[%s]' % ', '.join(values), _prec_atomic 

else: 

if len(values) == 1: 

return '(%s,)' % values[0], _prec_atomic 

else: 

return '(%s)' % ', '.join(values), _prec_atomic 

 

class SIE_dict(SageInputExpression): 

r""" 

This class represents a dict node in a :func:`sage_input` 

expression tree. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.dict([('TeX', RR(pi)), ('Metafont', RR(e))]) 

{dict: {{atomic:'TeX'}:{call: {atomic:RR}({atomic:3.1415926535897931})}, {atomic:'Metafont'}:{call: {atomic:RR}({atomic:2.7182818284590451})}}} 

sage: sib.dict({-40:-40, 0:32, 100:212}) 

{dict: {{unop:- {atomic:40}}:{unop:- {atomic:40}}, {atomic:0}:{atomic:32}, {atomic:100}:{atomic:212}}} 

""" 

 

def __init__(self, sib, entries): 

r""" 

Initialize an instance of :class:`SIE_dict`. 

 

INPUT: 

 

- ``sib`` -- a :class:`SageInputBuilder` 

 

- ``entries`` -- a list of pairs of :class:`SageInputExpression`s 

representing the entries of this dict 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.dict({'us':'good', 'them':'bad'}) 

{dict: {{atomic:'them'}:{atomic:'bad'}, {atomic:'us'}:{atomic:'good'}}} 

sage: sib.dict([(10, 'PS2'), (12, 'PS2'), (13, 'PS3')]) 

{dict: {{atomic:10}:{atomic:'PS2'}, {atomic:12}:{atomic:'PS2'}, {atomic:13}:{atomic:'PS3'}}} 

""" 

super(SIE_dict, self).__init__(sib) 

self._sie_entries = entries 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_dict` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.dict({'keaton':'general', 'chan':'master'}) 

{dict: {{atomic:'keaton'}:{atomic:'general'}, {atomic:'chan'}:{atomic:'master'}}} 

""" 

return "{dict: {%s}}" % \ 

', '.join([repr(key) + ':' + repr(val) 

for key,val in self._sie_entries]) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SIE_dict`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.dict({1:'beguilement', 2:'legacy', 3:'passage'}) 

sage: sie._sie_referenced() 

[{atomic:1}, {atomic:2}, {atomic:3}, {atomic:'beguilement'}, {atomic:'legacy'}, {atomic:'passage'}] 

""" 

return [k for k,v in self._sie_entries] + [v for k,v in self._sie_entries] 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this dict, and an 

indication that it is atomic (never needs to be parenthesized). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.dict({'carnivores':1, 'thinking':2, 'triumph':3}) 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

("{'carnivores':1, 'thinking':2, 'triumph':3}", 42) 

""" 

return "{%s}" %\ 

', '.join(sif.format(k, 0)+':'+sif.format(v, 0) for k,v in self._sie_entries), _prec_atomic 

 

 

class SIE_binary(SageInputExpression): 

r""" 

This class represents an arithmetic expression with a binary operator 

and its two arguments, in a :func:`sage_input` expression tree. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib(3)+5 

{binop:+ {atomic:3} {atomic:5}} 

""" 

 

def __init__(self, sib, op, lhs, rhs): 

r""" 

Initialize an instance of :class:`SIE_binary`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``op`` - a string representing a binary operator, such as '*' or '%' 

 

- ``lhs`` - a :class:`SageInputExpression` 

 

- ``rhs`` - a :class:`SageInputExpression` 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib(3)*5 

{binop:* {atomic:3} {atomic:5}} 

 

""" 

super(SIE_binary, self).__init__(sib) 

self._sie_op = op 

self._sie_operands = (lhs, rhs) 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_binary` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib(7)/9 

{binop:/ {atomic:7} {atomic:9}} 

""" 

return "{binop:%s %s %s}" % (self._sie_op, repr(self._sie_operands[0]), repr(self._sie_operands[1])) 

 

def _sie_referenced(self): 

r""" 

Returns a tuple of the immediate subexpressions of this 

:class:`SIE_binary`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.name('x') + 5 

sage: sie._sie_referenced() 

({atomic:x}, {atomic:5}) 

""" 

return self._sie_operands 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this expression, 

and the precedence of the top-level operator in the expression. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: x = sib.name('x') 

sage: y = sib.name('y') 

sage: for v in (x+y, x*y, x**y): 

....: v._sie_prepare(sif) 

....: v._sie_format(sif) 

('x + y', 24) 

('x*y', 26) 

('x^y', 32) 

 

Note that the printing for $x^y$ varies depending on whether the 

preparser is enabled.:: 

 

sage: sibnp = SageInputBuilder(preparse=False) 

sage: sif = SageInputFormatter() 

sage: v = x**y 

sage: v._sie_prepare(sif) 

sage: v._sie_format(sif) 

('x^y', 32) 

 

TESTS:: 

 

sage: x = sib.name('x') 

sage: y = sib.name('y') 

sage: z = sib.name('z') 

sage: sib.result((x+y)+z) 

x + y + z 

sage: sib.result(x+(y+z)) 

x + (y + z) 

sage: sib.result((x*y)*z) 

x*y*z 

sage: sib.result(x*(y*z)) 

x*(y*z) 

sage: sib.result(x+(y*z)) 

x + y*z 

sage: sib.result((x+y)*z) 

(x + y)*z 

sage: sib.result((x^y)^z) 

(x^y)^z 

sage: sib.result(x^(y^z)) 

x^y^z 

""" 

op = self._sie_op 

fop = op 

if op == '**': 

lhs = sif.format(self._sie_operands[0], _prec_exponent+1) 

rhs = sif.format(self._sie_operands[1], _prec_exponent) 

if self._sie_builder.preparse(): 

return '%s^%s' % (lhs, rhs), _prec_exponent 

else: 

return '%s**%s' % (lhs, rhs), _prec_exponent 

 

if op == '*': 

prec = _prec_muldiv 

elif op == '/': 

prec = _prec_muldiv 

elif op == '+': 

fop = ' + ' 

prec = _prec_addsub 

elif op == '-': 

fop = ' - ' 

prec = _prec_addsub 

else: 

raise ValueError('Unhandled op {} in SIE_binary'.format(op)) 

 

lhs = sif.format(self._sie_operands[0], prec) 

rhs = sif.format(self._sie_operands[1], prec+1) 

return '%s%s%s' % (lhs, fop, rhs), prec 

 

class SIE_unary(SageInputExpression): 

r""" 

This class represents an arithmetic expression with a unary operator 

and its argument, in a :func:`sage_input` expression tree. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: -sib(256) 

{unop:- {atomic:256}} 

""" 

 

def __init__(self, sib, op, operand): 

r""" 

Initialize an instance of :class:`SIE_unary`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``op`` - a string representing a unary operator, such as '-' 

 

- ``operand`` -- a :class:`SageInputExpression` 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: -sib(3) 

{unop:- {atomic:3}} 

""" 

super(SIE_unary, self).__init__(sib) 

self._sie_op = op 

self._sie_operand = operand 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_unary` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: -sib(15) 

{unop:- {atomic:15}} 

""" 

return "{unop:%s %s}" % (self._sie_op, repr(self._sie_operand)) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SIE_unary`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = -sib.name('x') 

sage: sie._sie_referenced() 

[{atomic:x}] 

""" 

return [self._sie_operand] 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this expression, 

and the precedence of the top-level operator in the expression. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: x = sib.name('x') 

sage: v = -x 

sage: v._sie_prepare(sif) 

sage: v._sie_format(sif) 

('-x', 28) 

sage: v = ~x 

sage: v._sie_prepare(sif) 

sage: v._sie_format(sif) 

('~x', 30) 

 

TESTS:: 

 

sage: x = sib.name('x') 

sage: y = sib.name('y') 

sage: sib.result((-x)+y) 

-x + y 

sage: sib.result(x+(-y)) 

x + -y 

sage: sib.result(-(x+y)) 

-(x + y) 

sage: sib.result(-(-x)) 

--x 

sage: sib.result(x-(-y)) 

x - -y 

 

We assume that -(x*y) is always equal to (-x)*y. Using this 

assumption, we print -(x*y) as -x*y, which parses as (-x)*y.:: 

 

sage: sib.result(-(x*y)) 

-x*y 

sage: sib.result((-x)*y) 

-x*y 

sage: sib.result(x*(-y)) 

x*-y 

""" 

op = self._sie_op 

fop = op 

rprec = None 

if op == '-': 

# We print -(a*b) as -a*b, even though that will parse as 

# (-a)*b. 

prec = _prec_muldiv 

rprec = _prec_negate 

elif op == '~': 

prec = _prec_bitnot 

else: 

raise ValueError('Unhandled op {} in SIE_unary'.format(op)) 

 

if rprec is None: rprec = prec 

 

return '%s%s' % (fop, sif.format(self._sie_operand, prec)), rprec 

 

def _sie_is_negation(self): 

r""" 

Test whether a :class:`SageInputExpression` is a negation. 

 

Despite the obscure name, this is intended to be a public method. 

 

This is used in the \method{_sage_input_} method for 

:class:`ComplexNumber`, so that ``sage_input(CC(-3))`` will 

produce ``-CC(3)`` instead of ``CC(-3)``. (This is preferred 

so that you get ``x - CC(3)`` instead of ``x + CC(-3)``.) 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: x = sib.name('x') 

sage: v = -x 

 

sage: def mk_CC(b): 

....: if b._sie_is_negation(): 

....: return -sib.name('CC')(b._sie_operand) 

....: else: 

....: return sib.name('CC')(b) 

 

sage: mk_CC(x) 

{call: {atomic:CC}({atomic:x})} 

sage: mk_CC(v) 

{unop:- {call: {atomic:CC}({atomic:x})}} 

""" 

return self._sie_op == '-' 

 

class SIE_gens_constructor(SageInputExpression): 

r""" 

This class represents an expression that can create a \sage parent 

with named generators, optionally using the \sage preparser 

generators syntax (like ``K.<x> = QQ[]``). 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: qq = sib.name('QQ') 

sage: sib.parent_with_gens("some parent", qq['x'], 

....: ('x',), 'QQx', 

....: gens_syntax=sib.empty_subscript(qq)) 

{constr_parent: {subscr: {atomic:QQ}[{atomic:'x'}]} with gens: ('x',)} 

""" 

 

def __init__(self, sib, constr, gen_names, gens_syntax=None): 

r""" 

Initialize an instance of :class:`SIE_gens_constructor`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``constr`` - a :class:`SageInputExpression` for constructing this 

parent ``normally`` 

 

- ``gen_names`` - a tuple of generator names 

 

- ``gens_syntax`` -- an optional :class:`SageInputExpression` for 

constructing this parent using the \sage preparser generators syntax 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: qq = sib.name('QQ') 

sage: sib.parent_with_gens("some parent", qq['x'], 

....: ('x',), 'QQx', 

....: gens_syntax=sib.empty_subscript(qq)) 

{constr_parent: {subscr: {atomic:QQ}[{atomic:'x'}]} with gens: ('x',)} 

""" 

super(SIE_gens_constructor, self).__init__(sib) 

self._sie_constr = constr 

self._sie_gen_names = gen_names 

self._sie_gens = None # will be overwritten from .parent_with_gens() 

self._sie_gens_constr = gens_syntax 

self._sie_assign_gens = False 

self._sie_generated = False 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_gens_constructor` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: qq = sib.name('QQ') 

sage: sib.parent_with_gens("some parent", qq['x'], 

....: ('x',), 'QQx', 

....: gens_syntax=sib.empty_subscript(qq)) 

{constr_parent: {subscr: {atomic:QQ}[{atomic:'x'}]} with gens: ('x',)} 

""" 

return "{constr_parent: %s with gens: %s}" % (repr(self._sie_constr), self._sie_gen_names) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SIE_gens_constructor`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: qq = sib.name('QQ') 

sage: gc = sib.parent_with_gens("some parent", qq['x'], 

....: ('x',), 'QQx', 

....: gens_syntax=sib.empty_subscript(qq)) 

sage: gc._sie_referenced() 

[{subscr: {atomic:QQ}[{atomic:'x'}]}] 

""" 

# This is used to determine if some expressions should be replaced 

# by variables (if the expression has more than one parent in 

# the expression DAG). We assume that all expressions in 

# self._sie_gens_constr also occur in self._sie_constr. 

return [self._sie_constr] 

 

def _sie_gens_referenced(self, sif): 

r""" 

Mark that at least one of the generators in this 

:class:`SIE_gens_constructor` is used. (This means we will actually 

construct all of the generators.) 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: qq = sib.name('QQ') 

sage: gc = sib.parent_with_gens("some parent", qq['x'], 

....: ('x',), 'QQx', 

....: gens_syntax=sib.empty_subscript(qq)) 

sage: gc._sie_assign_gens 

False 

sage: gc._sie_gens_referenced(sif) 

sage: gc._sie_assign_gens 

True 

""" 

self._sie_assign_gens = True 

self._sie_require_varname(sif) 

for gen in self._sie_gens: 

gen._sie_require_varname(sif) 

 

def _sie_add_command(self, sif): 

r""" 

Build commands to construct this parent and (if necessary) 

its associated generators. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: qq = sib.name('QQ') 

sage: gc = sib.parent_with_gens("some parent", qq['x'], 

....: ('x',), 'QQx', 

....: gens_syntax=sib.empty_subscript(qq)) 

sage: gc._sie_gens_referenced(sif) 

sage: gc._sie_prepare(sif) 

sage: gc._sie_add_command(sif) 

sage: sif._commands 

'QQx.<x> = QQ[]\n' 

 

TESTS: 

 

There are several tricky cases here. 

 

We prefer the \sage preparser generators syntax:: 

 

sage: sage_input(polygen(ZZ)) 

R.<x> = ZZ[] 

x 

 

But of course we can't use that without the preparser:: 

 

sage: sage_input(polygen(ZZ), preparse=False) 

R = ZZ['x'] 

x = R.gen() 

x 

 

We also can't use the preparser syntax if there is a conflict 

between generator names. For example, this works:: 

 

sage: sage_input((polygen(ZZ), polygen(GF(17), 'y'))) 

R1.<x> = ZZ[] 

R2.<y> = GF(17)[] 

(x, y) 

 

but this can't use the preparser syntax.:: 

 

sage: sage_input((polygen(ZZ), polygen(GF(17)))) 

R1 = ZZ['x'] 

x1 = R1.gen() 

R2 = GF(17)['x'] 

x2 = R2.gen() 

(x1, x2) 

 

If we never use the generators, then we don't bother with the 

preparser syntax.:: 

 

sage: sage_input((ZZ['x'], ZZ['x'], GF(17)['y'])) 

R = ZZ['x'] 

(R, R, GF(17)['y']) 

""" 

if not self._sie_generated: 

if self._sie_builder.preparse() and \ 

self._sie_gens_constr is not None and \ 

all(g._sie_got_preferred(sif) for g in self._sie_gens): 

s, _ = self._sie_gens_constr._sie_format(sif) 

sif._commands += '%s.<%s> = %s\n' % (self._sie_get_varname(sif), ','.join(self._sie_gen_names), s) 

else: 

s, _ = self._sie_constr._sie_format(sif) 

sif._commands += '%s = %s\n' % (self._sie_get_varname(sif), s) 

if self._sie_assign_gens: 

if len(self._sie_gens) == 1: 

sif._commands += '%s = %s.gen()\n' % (self._sie_gens[0]._sie_get_varname(sif), self._sie_get_varname(sif)) 

else: 

sif._commands += '%s = %s.gens()\n' % (','.join([g._sie_get_varname(sif) for g in self._sie_gens]), self._sie_get_varname(sif)) 

self._sie_generated = True 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this parent-construction 

expression, and its precedence. 

 

As a side effect, if the generators of this parent are used, 

this adds commands to assign the generators to names. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: qq = sib.name('QQ') 

sage: gc = sib.parent_with_gens("some parent", qq['x'], 

....: ('x',), 'QQx', 

....: gens_syntax=sib.empty_subscript(qq)) 

sage: gc._sie_gens_referenced(sif) 

sage: gc._sie_prepare(sif) 

sage: gc._sie_format(sif) 

('QQx', 42) 

sage: sif._commands 

'QQx.<x> = QQ[]\n' 

""" 

if self._sie_assign_gens: 

self._sie_add_command(sif) 

return self._sie_get_varname(sif), _prec_atomic 

 

return self._sie_constr._sie_format(sif) 

 

class SIE_gen(SageInputExpression): 

r""" 

This class represents a named generator of a parent with named 

generators. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.gen(ZZ['x']) 

{gen:x {constr_parent: {subscr: {atomic:ZZ}[{atomic:'x'}]} with gens: ('x',)}} 

""" 

 

def __init__(self, sib, parent, name): 

r""" 

Initializes an instance of :class:`SIE_gen`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``parent`` - a :class:`SIE_gens_constructor` 

 

- ``name`` - a string with the name of this generator 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.gen(ZZ['x']) # indirect doctest 

{gen:x {constr_parent: {subscr: {atomic:ZZ}[{atomic:'x'}]} with gens: ('x',)}} 

""" 

super(SIE_gen, self).__init__(sib) 

self._sie_parent = parent 

self._sie_preferred_varname = name 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_gen` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.gen(ZZ['x']) # indirect doctest 

{gen:x {constr_parent: {subscr: {atomic:ZZ}[{atomic:'x'}]} with gens: ('x',)}} 

""" 

return "{gen:%s %s}" % (self._sie_preferred_varname, repr(self._sie_parent)) 

 

def _sie_is_simple(self): 

r""" 

Report that :class:`SIE_gen` values are single tokens. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.gen(ZZ['x'])._sie_is_simple() 

True 

""" 

return True 

 

def _sie_prepare(self, sif): 

r""" 

We override the \method{_sie_prepare} method from 

:class:`SageInputExpression` to additionally mark the parent of this 

generator that the generator names must be assigned. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.gen(GF(13)['z']) 

sage: sie._sie_parent._sie_assign_gens 

False 

sage: sie._sie_prepare(sif) 

sage: sie._sie_parent._sie_assign_gens 

True 

""" 

super(SIE_gen, self)._sie_prepare(sif) 

self._sie_parent._sie_gens_referenced(sif) 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this named generator, 

and an indication that it is atomic. 

 

As a side effect, this generates commands to assign the generators 

of the parent to variables. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.gen(GF(41)['x']) 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

('x', 42) 

sage: sif._commands 

'R.<x> = GF(41)[]\n' 

""" 

self._sie_parent._sie_add_command(sif) 

return self._sie_get_varname(sif), _prec_atomic 

 

def _sie_got_preferred(self, sif): 

r""" 

Check whether the :class:`SageInputFormatter` assigned us a 

variable name which is the same as the name of the generator 

name. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

First we verify that if we use two generators with different 

names, then they get their preferred names.:: 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: v = sib.gen(GF(2)['x']); w = sib.gen(GF(3)['y']) 

sage: v._sie_prepare(sif); w._sie_prepare(sif) 

sage: v._sie_got_preferred(sif) 

True 

sage: w._sie_got_preferred(sif) 

True 

 

Now, we repeat the experiment, except that the generators now 

have the same names. In this case, the :class:`SageInputFormatter` 

will not use the generator name as the variable name, because 

of this conflict.:: 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: v = sib.gen(GF(2)['x']); w = sib.gen(GF(3)['x']) 

sage: v._sie_prepare(sif); w._sie_prepare(sif) 

sage: v._sie_got_preferred(sif) 

False 

sage: w._sie_got_preferred(sif) 

False 

""" 

return self._sie_get_varname(sif) == self._sie_preferred_varname 

 

class SIE_import_name(SageInputExpression): 

r""" 

This class represents a name which has been imported from a module. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.import_name('sage.rings.integer', 'make_integer') 

{import:sage.rings.integer/make_integer} 

sage: sib.import_name('sage.foo', 'happy', 'sad') 

{import:sage.foo/happy as sad} 

""" 

 

def __init__(self, sib, module, name, alt_name=None): 

r""" 

Initializes an instance of :class:`SIE_import_name`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``module`` - a module name 

 

- ``name`` - an object name 

 

- ``alt_name`` - an alternate object name, or None (the default) 

to use name 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.import_name('sage.rings.integer', 'make_integer') # indirect doctest 

{import:sage.rings.integer/make_integer} 

sage: sib.import_name('sage.foo', 'happy', 'sad') 

{import:sage.foo/happy as sad} 

""" 

super(SIE_import_name, self).__init__(sib) 

self._sie_formatted = False 

self._sie_module_name = module 

self._sie_object_name = name 

if alt_name is None: 

self._sie_preferred_varname = name 

else: 

self._sie_preferred_varname = alt_name 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_import_name` value. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.import_name('sage.rings.integer', 'make_integer') # indirect doctest 

{import:sage.rings.integer/make_integer} 

sage: sib.import_name('sage.foo', 'happy', 'sad') 

{import:sage.foo/happy as sad} 

""" 

return "{import:%s/%s%s}" % (self._sie_module_name, self._sie_object_name, 

"" if self._sie_object_name == self._sie_preferred_varname else " as %s" % self._sie_preferred_varname) 

 

def _sie_is_simple(self): 

r""" 

Report that :class:`SIE_import_name` values are single tokens. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.import_name('sage.rings.integer', 'make_integer')._sie_is_simple() 

True 

""" 

return True 

 

def _sie_prepare(self, sif): 

r""" 

We override the \method{_sie_prepare} method from 

:class:`SageInputExpression` to request a variable name. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.import_name('sage.rings.integer', 'make_integer') 

sage: sie._sie_requested_varname 

False 

sage: sie._sie_prepare(sif) 

sage: sie._sie_requested_varname 

True 

""" 

super(SIE_import_name, self)._sie_prepare(sif) 

self._sie_require_varname(sif) 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this import, 

and an indication that it is atomic. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: v1 = sib.import_name('sage.rings.integer', 'make_integer') 

sage: v2 = sib.import_name('sage.foo', 'happy', 'sad') 

sage: sie = v1(v2) 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

('make_integer(sad)', 40) 

sage: print(sif._commands) 

from sage.rings.integer import make_integer 

from sage.foo import happy as sad 

""" 

name = self._sie_get_varname(sif) 

if self._sie_formatted: 

# Only run the import command once 

return name, _prec_atomic 

self._sie_formatted = True 

rename = '' 

if name != self._sie_object_name: 

rename = ' as ' + name 

sif._commands += 'from %s import %s%s\n' % (self._sie_module_name, 

self._sie_object_name, 

rename) 

return name, _prec_atomic 

 

class SIE_assign(SageInputExpression): 

r""" 

This class represents an assignment command. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.assign(sib.name('foo').x, sib.name('pi')) 

{assign: {getattr: {atomic:foo}.x} {atomic:pi}} 

""" 

 

def __init__(self, sib, lhs, rhs): 

r""" 

Initializes an instance of :class:`SIE_assign`. 

 

INPUT: 

 

- ``sib`` - a :class:`SageInputBuilder` 

 

- ``lhs`` - the left-hand side of the assignment 

 

- ``rhs`` - the right-hand side of the assignment 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.assign(sib.name('foo').x, sib.name('pi')) 

{assign: {getattr: {atomic:foo}.x} {atomic:pi}} 

""" 

super(SIE_assign, self).__init__(sib) 

self._sie_lhs = lhs 

self._sie_rhs = rhs 

 

def __repr__(self): 

r""" 

Returns a string representing this :class:`SIE_assign` command. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sib.assign(sib.name('foo').x, sib.name('pi')) 

{assign: {getattr: {atomic:foo}.x} {atomic:pi}} 

""" 

return "{assign: %s %s}" % (repr(self._sie_lhs), repr(self._sie_rhs)) 

 

def _sie_referenced(self): 

r""" 

Returns a list of the immediate subexpressions of this 

:class:`SIE_assign`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder 

 

sage: sib = SageInputBuilder() 

sage: sie = sib.assign(sib.name('foo').x, sib.name('pi')) 

sage: sie._sie_referenced() 

[{getattr: {atomic:foo}.x}, {atomic:pi}] 

""" 

return [self._sie_lhs, self._sie_rhs] 

 

def _sie_format(self, sif): 

r""" 

Return the formatted string value of this :class:`SIE_assign` 

as an expression. Since an assignment is a statement, not 

an expression, always raises an error. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.assign(sib.name('foo').x, sib.name('pi')) 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format(sif) 

Traceback (most recent call last): 

... 

ValueError: Cannot format SIE_assign as expression 

""" 

raise ValueError("Cannot format SIE_assign as expression") 

 

def _sie_format_statement(self, sif): 

r""" 

Return the formatted string of this :class:`SIE_assign` 

as a statement. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.assign(sib.name('foo').x, sib.name('pi')) 

sage: sie._sie_prepare(sif) 

sage: sie._sie_format_statement(sif) 

'foo.x = pi' 

""" 

return '%s = %s' % (sif.format(self._sie_lhs, 0), sif.format(self._sie_rhs, 0)) 

 

class SageInputFormatter: 

r""" 

An instance of this class is used to keep track of variable names 

and a sequence of generated commands during the :func:`sage_input` 

formatting process. 

""" 

 

def __init__(self): 

r""" 

Initialize an instance of :class:`SageInputFormatter`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputFormatter 

sage: sif = SageInputFormatter() 

""" 

self._commands = '' 

self._names = set() 

self._dup_names = {} 

 

def format(self, e, prec): 

r""" 

Format a Sage input expression into a string. 

 

INPUT: 

 

- ``e`` - a :class:`SageInputExpression` 

 

- ``prec`` - an integer representing a precedence level 

 

First, we check to see if ``e`` should be replaced by a variable. 

If so, we generate the command to assign the variable, and return 

the name of the variable. 

 

Otherwise, we format the expression by calling its \method{_sie_format} 

method, and add parentheses if necessary. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputBuilder, SageInputFormatter 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib(GF(5)) 

 

Here we ``cheat`` by calling \method{_sie_prepare} twice, to make it 

use a variable.:: 

 

sage: sie._sie_prepare(sif) 

sage: sie._sie_prepare(sif) 

sage: sif._commands 

'' 

sage: sif.format(sie, 0) 

'GF_5' 

sage: sif._commands 

'GF_5 = GF(5)\n' 

 

We demonstrate the use of commands, by showing how to construct 

code that will produce a random matrix:: 

 

sage: sib = SageInputBuilder() 

sage: sif = SageInputFormatter() 

sage: sie = sib.name('matrix')(sib.name('ZZ'), 10, 10) 

sage: sib.command(sie, sie.randomize()) 

sage: sie._sie_prepare(sif) 

sage: sif._commands 

'' 

sage: sif.format(sie, 0) 

'si' 

sage: sif._commands 

'si = matrix(ZZ, 10, 10)\nsi.randomize()\n' 

""" 

if e._sie_use_var: 

if not e._sie_generated: 

s, _ = e._sie_format(self) 

# In complicated situations, this can get called 

# recursively... 

if not e._sie_generated: 

self._commands += '%s = %s\n' % (e._sie_get_varname(self), s) 

e._sie_generated = True 

 

formatted = e._sie_get_varname(self) 

else: 

s, iprec = e._sie_format(self) 

if iprec < prec: 

s = '(' + s + ')' 

formatted = s 

 

commands = e._sie_commands 

e._sie_commands = [] 

 

for cmd in commands: 

s_cmd = cmd._sie_format_statement(self) 

self._commands += s_cmd + '\n' 

 

return formatted 

 

def register_name(self, name): 

r""" 

Register that some value would like to use a given name. 

If only one request for a name is received, then we will use the 

requested name; otherwise, we will add numbers to the end of the 

name to make it unique. 

 

If the input name is ``None``, then it is treated as a name of 

``'si'``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputFormatter 

 

sage: sif = SageInputFormatter() 

sage: sif._names, sif._dup_names 

(set(), {}) 

sage: sif.register_name('x') 

sage: sif.register_name('y') 

sage: sif._names, sif._dup_names 

({'x', 'y'}, {}) 

sage: sif.register_name('x') 

sage: sif._names, sif._dup_names 

({'x', 'y'}, {'x': 0}) 

""" 

if name is None: name = 'si' 

 

if name in self._names: 

self._dup_names[name] = 0 

else: 

self._names.add(name) 

 

def get_name(self, name): 

r""" 

Return a name corresponding to a given requested name. 

If only one request for a name is received, then we will use the 

requested name; otherwise, we will add numbers to the end of the 

name to make it unique. 

 

If the input name is ``None``, then it is treated as a name of 

``'si'``. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputFormatter 

 

sage: sif = SageInputFormatter() 

sage: names = ('x', 'x', 'y', 'z') 

sage: for n in names: sif.register_name(n) 

sage: for n in names: sif.get_name(n) 

'x1' 

'x2' 

'y' 

'z' 

""" 

if name is None: name = 'si' 

 

if name in self._dup_names: 

next = self._dup_names[name] + 1 

self._dup_names[name] = next 

return name + str(next) 

else: 

return name 

 

def verify_same(a, b): 

r""" 

Verify that two Sage values are the same. This is an extended equality 

test; it checks that the values are equal and that their parents are equal. 

(For values which are not Elements, the types are checked instead.) 

 

If the values are the same, we return ``None``; otherwise, 

we raise an exception. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import verify_same 

sage: verify_same(1, 1) 

sage: verify_same(1, 2) 

Traceback (most recent call last): 

... 

AssertionError: Expected 1 == 2 

sage: verify_same(1, 1r) 

Traceback (most recent call last): 

... 

AttributeError: 'int' object has no attribute 'parent' 

sage: verify_same(1r, 1) 

Traceback (most recent call last): 

... 

assert(type(a) == type(b)) 

AssertionError 

sage: verify_same(5, GF(7)(5)) 

Traceback (most recent call last): 

... 

assert(a.parent() == b.parent()) 

AssertionError 

""" 

from sage.structure.element import is_Element 

if is_Element(a): 

assert(a.parent() == b.parent()) 

else: 

assert(type(a) is type(b)) 

from sage.rings.real_mpfi import is_RealIntervalFieldElement 

from sage.rings.complex_interval import is_ComplexIntervalFieldElement 

if is_RealIntervalFieldElement(a) or is_ComplexIntervalFieldElement(a): 

assert(a.endpoints() == b.endpoints()), "Expected %s == %s" % (a, b) 

return 

 

if not (a == b): 

# Verification failed => raise an AssertionError. 

# 

# There is an important exception: the IEEE-754 standard 

# recommends that NaN != NaN. So this comparison will fail for 

# any object involving NaN. 

# 

# If this case occurs, then a and b do not compare equal to 

# itself. In that case, we compare the string representations of 

# a and b. 

if not (a == a) and not (b == b): 

if repr(a) == repr(b): 

return # Good! 

raise AssertionError("Expected %r == %r" % (a, b)) 

 

 

def verify_si_answer(x, answer, preparse): 

r""" 

Verify that evaluating ``answer`` gives a value equal to ``x`` 

(with the same parent/type). If ``preparse`` is ``True`` or 

``False``, then we evaluate ``answer`` with the preparser 

enabled or disabled, respectively; if ``preparse`` is ``None``, 

then we evaluate ``answer`` both with the preparser enabled and 

disabled and check both results. 

 

On success, we return ``None``; on failure, we raise an exception. 

 

INPUT: 

 

- ``x`` - an arbitrary Sage value 

 

- ``answer`` - a string, or a :class:`SageInputAnswer` 

 

- ``preparse`` -- ``True``, ``False``, or ``None`` 

 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import verify_si_answer 

sage: verify_si_answer(1, '1', True) 

sage: verify_si_answer(1, '1', False) 

Traceback (most recent call last): 

... 

AttributeError: 'int' object has no attribute 'parent' 

sage: verify_si_answer(1, 'ZZ(1)', None) 

""" 

from sage.misc.sage_eval import sage_eval 

if preparse is None: 

verify_same(x, sage_eval(answer, preparse=True)) 

verify_same(x, sage_eval(answer, preparse=False)) 

else: 

verify_same(x, sage_eval(answer, preparse=preparse)) 

 

class SageInputAnswer(tuple): 

r""" 

This class inherits from tuple, so it acts like a tuple when passed 

to :func:`sage_eval`; but it prints as a sequence of commands. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputAnswer 

sage: v = SageInputAnswer('x = 22\n', 'x/7'); v 

x = 22 

x/7 

sage: isinstance(v, tuple) 

True 

sage: v[0] 

'x = 22\n' 

sage: v[1] 

'x/7' 

sage: len(v) 

2 

sage: v = SageInputAnswer('', 'sin(3.14)', {'sin': math.sin}); v 

LOCALS: 

sin: <built-in function sin> 

sin(3.14) 

sage: v[0] 

'' 

sage: v[1] 

'sin(3.14)' 

sage: v[2] 

{'sin': <built-in function sin>} 

""" 

 

def __new__(cls, cmds, expr, locals=None): 

r""" 

Construct an instance of :class:`SageInputAnswer`. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputAnswer 

sage: v = SageInputAnswer('', 'sin(3.14)', {'sin': math.sin}); v 

LOCALS: 

sin: <built-in function sin> 

sin(3.14) 

sage: v[0] 

'' 

sage: v[1] 

'sin(3.14)' 

sage: v[2] 

{'sin': <built-in function sin>} 

""" 

if locals: 

return tuple.__new__(cls, (cmds, expr, locals)) 

else: 

return tuple.__new__(cls, (cmds, expr)) 

 

def __repr__(self): 

r""" 

Return a string representation for a :class:`SageInputAnswer`, 

such that if you evaluate this :class:`SageInputAnswer` at the 

\sage command line, you get a result in a nice form ready to 

copy-and-paste. 

 

EXAMPLES:: 

 

sage: from sage.misc.sage_input import SageInputAnswer 

sage: v = SageInputAnswer('', 'sin(3.14)', {'sin': math.sin}); v 

LOCALS: 

sin: <built-in function sin> 

sin(3.14) 

""" 

if len(self) == 2: 

return self[0] + self[1] 

 

locals = self[2] 

locals_text = ''.join(' %s: %r\n' % (k, v) 

for k, v in iteritems(locals)) 

return 'LOCALS:\n' + locals_text + self[0] + self[1]