summaryrefslogtreecommitdiffstats
path: root/Doc/lib.tex
blob: b12e6e14f570faab4db55c751bbeccbe44cc03d3 (plain)
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
% Format this file with latex.

%\documentstyle[palatino,11pt,myformat]{article}
\documentstyle[11pt,myformat]{article}

\sloppy

\title{\bf
	Python Library Reference \\
	(DRAFT)
}

\author{
	Guido van Rossum \\
	Dept. CST, CWI, Kruislaan 413 \\
	1098 SJ Amsterdam, The Netherlands \\
	E-mail: {\tt guido@cwi.nl}
}

\begin{document}

\pagenumbering{roman}

\maketitle

\begin{abstract}

\noindent
This document describes the built-in types, exceptions and functions and
the standard modules that come with the {\Python} system.
It assumes basic knowledge about the {\Python} language.
For an informal introduction to the language, see the Tutorial document.
The Language Reference document (XXX not yet existing)
gives a more formal reference to the language.

\end{abstract}

\pagebreak

\tableofcontents

\pagebreak

\pagenumbering{arabic}

\section{Introduction}

The {\Python} library consists of three parts, with different levels of
integration with the interpreter.
Closest to the interpreter are built-in types, exceptions and functions.
Next are built-in modules, which are written in C and linked statically
with the interpreter.
Finally there are standard modules that are implemented entirely in
{\Python}, but are always available.
For efficiency, some standard modules may become built-in modules in
future versions of the interpreter.

\section{Built-in Types, Exceptions and Functions}

Names for built-in exceptions and functions are found in a separate
read-only symbol table which cannot be modified.
This table is searched last, so local and global user-defined names can
override built-in names.
Built-in types have no names but are created by syntactic constructs
(such as constants) or built-in functions.
They are described together here for easy reference.%
\footnote{
The descriptions sorely lack explanations of the exceptions that
may be raised---this will be fixed in a future version of this
document.
}

\subsection{Built-in Types}

The following sections describe the standard types that are built into the
interpreter.
\subsubsection{Numeric Types}

There are two numeric types: integers and floating point numbers.
Integers are implemented using {\tt long} in C, so they have at least 32
bits of precision.
Floating point numbers are implemented using {\tt double} in C.
All bets on precision are off.
Numbers are created by numeric constants or as the result of built-in
functions and operators.

Numeric types support the following operations:

\begin{center}
\begin{tabular}{|c|l|c|}
\hline
Operation & Result & Notes \\
\hline
{\tt abs}({\em x}) & absolute value of {\em x} & \\
{\tt int}({\em x}) & {\em x} converted to integer & (1) \\
{\tt float}({\em x}) & {\em x} converted to floating point & \\
{\tt -}{\em x} & {\em x} negated & \\
{\tt +}{\em x} & {\em x} unchanged & \\
{\em x}{\tt +}{\em y} & sum of {\em x} and {\em y} & \\
{\em x}{\tt -}{\em y} & difference of {\em x} and {\em y} & \\
{\em x}{\tt *}{\em y} & product of {\em x} and {\em y} & \\
{\em x}{\tt /}{\em y} & quotient of {\em x} and {\em y} & (2) \\
{\em x}{\tt \%}{\em y} & remainder of {\em x}{\tt /}{\em y} & (3) \\
\hline
\end{tabular}
\end{center}

\noindent
Notes:
\begin{description}
\item[(1)]
This may round or truncate as in C; see functions {\tt floor} and
{\tt ceil} in module {\tt math}.
\item[(2)]
Integer division is defined as in C: the result is an integer; with
positive operands, it truncates towards zero; with a negative operand,
the result is unspecified.
\item[(3)]
Only defined for integers.
\end{description}

Mixed arithmetic is not supported; both operands must have the same type.
Mixed comparisons return the wrong result (floats always compare smaller
than integers).%
\footnote{
These restrictions are bugs in the language definitions and will be
fixed in the future.
}
\subsubsection{Sequence Types}

There are three sequence types: strings, lists and tuples.
Strings constants are written in single quotes: {\tt 'xyzzy'}.
Lists are constructed with square brackets: {\tt [a,~b,~c]}.
Tuples are constructed by the comma operator or with an empty set of
parentheses: {\tt a,~b,~c} or {\tt ()}.

Sequence types support the following operations ({\em s} and {\em t} are
sequences of the same type; {\em n}, {\em i} and {\em j} are integers):

\begin{center}
\begin{tabular}{|c|l|c|}
\hline
Operation & Result & Notes \\
\hline
{\tt len}({\em s}) & length of {\em s} & \\
{\tt min}({\em s}) & smallest item of {\em s} & \\
{\tt max}({\em s}) & largest item of {\em s} & \\
{\em x} {\tt in} {\em s} &
	true if an item of {\em s} is equal to {\em x} & \\
{\em x} {\tt not} {\tt in} {\em s} &
	false if an item of {\em s} is equal to {\em x} & \\
{\em s}{\tt +}{\em t} & the concatenation of {\em s} and {\em t} & \\
{\em s}{\tt *}{\em n}, {\em n}*{\em s} &
	{\em n} copies of {\em s} concatenated & (1) \\
{\em s}[{\em i}] & {\em i}'th item of {\em s} & \\
{\em s}[{\em i}:{\em j}] &
	slice of {\em s} from {\em i} to {\em j} & (2) \\
\hline
\end{tabular}
\end{center}

\noindent
Notes:
\begin{description}
\item[(1)]
Sequence repetition is only supported for strings.
\item[(2)]
The slice of $s$ from $i$ to $j$ is defined as the sequence
of items with index $k$ such that $i \leq k < j$.
Special rules apply for negative and omitted indices; see the Tutorial
or the Reference Manual.
\end{description}

\paragraph{Mutable Sequence Types.}

List objects support additional operations that allow in-place
modification of the object.
These operations would be supported by other mutable sequence types
(when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created.
The following operations are defined on mutable sequence types (where
{\em x} is an arbitrary object):

\begin{center}
\begin{tabular}{|c|l|}
\hline
Operation & Result \\
\hline
{\em s}[{\em i}] = {\em x} &
	item {\em i} of {\em s} is replaced by {\em x} \\
{\em s}[{\em i}:{\em j}] = {\em t} &
	slice of {\em s} from {\em i} to {\em j} is replaced by {\em t} \\
{\tt del} {\em s}[{\em i}:{\em j}] &
	same as {\em s}[{\em i}:{\em j}] = [] \\
{\em s}.{\tt append}({\em x}) &
	same as {\em s}[{\tt len}({\em x}):{\tt len}({\em x})] = [{\em x}] \\
{\em s}.{\tt insert}({\em i}, {\em x}) &
	same as {\em s}[{\em i}:{\em i}] = [{\em x}] \\
{\em s}.{\tt sort}() &
	the items of {\em s} are permuted to satisfy \\
	&
	$s[i] \leq s[j]$ for $i < j$\\
\hline
\end{tabular}
\end{center}

\subsubsection{Mapping Types}

A
{\em mapping}
object maps values of one type (the key type) to arbitrary objects.
Mappings are mutable objects.
There is currently only one mapping type, the
{\em dictionary}.
A dictionary's keys are strings.
An empty dictionary is created by the expression \verb"{}".
An extension of this notation is used to display dictionaries when
written (see the example below).

The following operations are defined on mappings (where {\em a} is a
mapping, {\em k} is a key and {\em x} is an arbitrary object):

\begin{center}
\begin{tabular}{|c|l|c|}
\hline
Operation & Result & Notes\\
\hline
{\tt len}({\em a}) & the number of elements in {\em a} & \\
{\em a}[{\em k}] & the item of {\em a} with key {\em k} & \\
{\em a}[{\em k}] = {\em x} & set {\em a}[{\em k}] to {\em x} & \\
{\tt del} {\em a}[{\em k}] & remove {\em a}[{\em k}] from {\em a} & \\
{\em a}.{\tt keys}() & a copy of {\em a}'s list of keys & (1) \\
{\em a}.{\tt has\_key}({\em k}) & true if {\em a} has a key {\em k} & \\
\hline
\end{tabular}
\end{center}

\noindent
Notes:
\begin{description}
\item[(1)]
Keys are listed in random order.
\end{description}

A small example using a dictionary:
\begin{code}\begin{verbatim}
>>> tel = {}
>>> tel['jack'] = 4098
>>> tel['sape'] = 4139
>>> tel['guido'] = 4127
>>> tel['jack']
4098
>>> tel
{'sape': 4139; 'guido': 4127; 'jack': 4098}
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127; 'irv': 4127; 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
1
>>> 
\end{verbatim}\end{code}
\subsubsection{Other Built-in Types}

The interpreter supports several other kinds of objects.
Most of these support only one or two operations.

\paragraph{Modules.}

The only operation on a module is member acces: {\em m}{\tt .}{\em name},
where {\em m} is a module and {\em name} accesses a name defined in
{\em m}'s symbol table.
Module members can be assigned to.

\paragraph{Classes and Class Objects.}

XXX Classes will be explained at length in a later version of this
document.

\paragraph{Functions.}

Function objects are created by function definitions.
The only operation on a function object is to call it:
{\em func}({\em optional-arguments}).

Built-in functions have a different type than user-defined functions,
but they support the same operation.

\paragraph{Methods.}

Methods are functions that are called using the member acces notation.
There are two flavors: built-in methods (such as {\tt append()} on
lists) and class member methods.
Built-in methods are described with the types that support them.
XXX Class member methods will be described in a later version of this
document.

\paragraph{Type Objects.}

Type objects represent the various object types.
An object's type is accessed by the built-in function
{\tt type()}.
There are no operations on type objects.

\paragraph{The Null Object.}

This object is returned by functions that don't explicitly return a
value.
It supports no operations.
There is exactly one null object.

\paragraph{File Objects.}

File objects are implemented using C's
{\em stdio}
package and can be created with the built-in function
{\tt open()}.
They have the following methods:
\begin{description}
\item[{\tt close()}]
Closes the file.
A closed file cannot be read or written anymore.
\item[{\tt read(size)}]
Reads at most
{\tt size}
bytes from the file (less if the read hits EOF).
The bytes are returned as a string object.
An empty string is returned when EOF is hit immediately.
(For certain files, like ttys, it makes sense to continue reading after
an EOF is hit.)
\item[{\tt readline(size)}]
Reads a line of at most
{\tt size}
bytes from the file.
A trailing newline character, if present, is kept in the string.
The size is optional and defaults to a large number (but not infinity).
EOF is reported as by
{\tt read().}
\item[{\tt write(str)}]
Writes a string to the file.
Returns no value.
\end{description}

\subsection{Built-in Exceptions}

The following exceptions can be generated by the interpreter or
built-in functions.
Except where mentioned, they have a string argument (also known as the
`associated value' of an exception) indicating the detailed cause of the
error.
The strings listed with the exception names are their values when used
in an expression or printed.
\begin{description}
\item[{\tt EOFError = 'end-of-file read'} (no argument)]
%.br
Raised when a built-in function ({\tt input()} or {\tt raw\_input()})
hits an end-of-file condition (EOF) without reading any data.
(N.B.: the {\tt read()} and {\tt readline()} methods of file objects
return an empty string when they hit EOF.)
\item[{\tt KeyboardInterrupt = 'end-of-file read'} (no argument)]
%.br
Raised when the user hits the interrupt key (normally Control-C or DEL).
During execution, a check for interrupts is made regularly.
Interrupts typed when a built-in function ({\tt input()} or
{\tt raw\_input()}) is waiting for input also raise this exception.
\item[{\tt MemoryError = 'out of memory'}]
%.br
Raised when an operation runs out of memory but the situation
may still be rescued (by deleting some objects).
\item[{\tt NameError = 'undefined name'}]
%.br
Raised when a name is not found.
This applies to unqualified names, module names (on {\tt import}),
module members and object methods.
The string argument is the name that could not be found.
\item[{\tt RuntimeError = 'run-time error'}]
%.br
Raised for a variety of reasons, e.g., division by zero or index out of
range.
\item[{\tt SystemError = 'system error'}]
%.br
Raised when the interpreter finds an internal error, but the situation
does not look so serious to cause it to abandon all hope.
\item[{\tt TypeError = 'type error'}]
%.br
Raised when an operation or built-in function is applied to an object of
inappropriate type.
\end{description}

\subsection{Built-in Functions}

The {\Python} interpreter has a small number of functions built into it that
are always available.
They are listed here in alphabetical order.
\begin{description}
\item[{\tt abs(x)}]
Returns the absolute value of a number.
The argument may be an integer or floating point number.
\item[{\tt dir()}]
Without arguments, this function returns the list of names in the
current local symbol table, sorted alphabetically.
With a module object as argument, it returns the sorted list of names in
that module's global symbol table.
For example:
\begin{code}\begin{verbatim}
>>> import sys
>>> dir()
['sys']
>>> dir(sys)
['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
>>> 
\end{verbatim}\end{code}
\item[{\tt divmod(a, b)}]
%.br
Takes two integers as arguments and returns a pair of integers
consisting of their quotient and remainder.
For
\begin{code}\begin{verbatim}
q, r = divmod(a, b)
\end{verbatim}\end{code}
the invariants are:
\begin{code}\begin{verbatim}
a = q*b + r
abs(r) < abs(b)
r has the same sign as b
\end{verbatim}\end{code}
For example:
\begin{code}\begin{verbatim}
>>> divmod(100, 7)
(14, 2)
>>> divmod(-100, 7)
(-15, 5)
>>> divmod(100, -7)
(-15, -5)
>>> divmod(-100, -7)
(14, -2)
>>> 
\end{verbatim}\end{code}
\item[{\tt eval(s)}]
Takes a string as argument and parses and evaluates it as a {\Python}
expression.
The expression is executed using the current local and global symbol
tables.
Syntax errors are reported as exceptions.
For example:
\begin{code}\begin{verbatim}
>>> x = 1
>>> eval('x+1')
2
>>> 
\end{verbatim}\end{code}
\item[{\tt exec(s)}]
Takes a string as argument and parses and evaluates it as a sequence of
{\Python} statements.
The string should end with a newline (\verb"'\n'").
The statement is executed using the current local and global symbol
tables.
Syntax errors are reported as exceptions.
For example:
\begin{code}\begin{verbatim}
>>> x = 1
>>> exec('x = x+1\n')
>>> x
2
>>> 
\end{verbatim}\end{code}
\item[{\tt float(x)}]
Converts a number to floating point.
The argument may be an integer or floating point number.
\item[{\tt input(s)}]
Equivalent to
{\tt eval(raw\_input(s))}.
As for
{\tt raw\_input()},
the argument is optional.
\item[{\tt len(s)}]
Returns the length (the number of items) of an object.
The argument may be a sequence (string, tuple or list) or a mapping
(dictionary).
\item[{\tt max(s)}]
Returns the largest item of a non-empty sequence (string, tuple or list).
\item[{\tt min(s)}]
Returns the smallest item of a non-empty sequence (string, tuple or list).
\item[{\tt open(name, mode)}]
%.br
Returns a file object (described earlier under Built-in Types).
The string arguments are the same as for stdio's
{\tt fopen()}:
{\tt 'r'}
opens the file for reading,
{\tt 'w'}
opens it for writing (truncating an existing file),
{\tt 'a'}
opens it for appending.%
\footnote{
This function should go into a built-in module
{\tt io}.
}
\item[{\tt range()}]
This is a versatile function to create lists containing arithmetic
progressions of integers.
With two integer arguments, it returns the ascending sequence of
integers starting at the first and ending one before the second
argument.
A single argument is used as the end point of the sequence, with 0 used
as the starting point.
A third argument specifies the step size; negative steps are allowed and
work as expected, but don't specify a zero step.
The resulting list may be empty.
For example:
\begin{code}\begin{verbatim}
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 1+10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
>>> 
\end{verbatim}\end{code}
\item[{\tt raw\_input(s)}]
%.br
The argument is optional; if present, it is written to standard output
without a trailing newline.
The function then reads a line from input, converts it to a string
(stripping a trailing newline), and returns that.
EOF is reported as an exception.
For example:
\begin{code}\begin{verbatim}
>>> raw_input('Type anything: ')
Type anything: Teenage Mutant Ninja Turtles
'Teenage Mutant Ninja Turtles'
>>> 
\end{verbatim}\end{code}
\item[{\tt type(x)}]
Returns the type of an object.
Types are objects themselves:
the type of a type object is its own type.
\end{description}

\section{Built-in Modules}

The modules described in this section are built into the interpreter.
They must be imported using
{\tt import}.
Some modules are not always available; it is a configuration option to
provide them.
Details are listed with the descriptions, but the best way to see if
a module exists in a particular implementation is to attempt to import
it.

\subsection{Built-in Module {\tt sys}}

This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
It is always available.
\begin{description}
\item[{\tt argv}]
The list of command line arguments passed to a {\Python} script.
{\tt sys.argv[0]}
is the script name.
If no script name was passed to the {\Python} interpreter,
{\tt sys.argv}
is empty.
\item[{\tt exit(n)}]
Exits from {\Python} with numeric exit status
{\tt n}.
This closes all open files and performs other cleanup-actions required by
the interpreter (but
{\em finally clauses}
of
{\tt try}
statements are not executed!).
\item[{\tt modules}]
Gives the list of modules that have already been loaded.
This can be manipulated to force reloading of modules and other tricks.
\item[{\tt path}]
A list of strings that specifies the search path for modules.
Initialized from the environment variable {\tt PYTHONPATH}, or an
installation-dependent default.
\item[{\tt ps1,~ps2}]
Strings specifying the primary and secondary prompt of the interpreter.
These are only defined if the interpreter is in interactive mode.
Their initial values in this case are
{\tt '>>> '}
and
{\tt '... '}.
\item[{\tt stdin, stdout, stderr}]
%.br
File objects corresponding to the interpreter's standard input, output
and error streams.
{\tt sys.stdin}
is used for all interpreter input except for scripts but including calls
to
{\tt input()}
and
{\tt raw\_input()}.
{\tt sys.stdout}
is used for the output of
{\tt print} and expression statements
and for the prompts of
{\tt input()}
and
{\tt raw\_input()}.
The interpreter's own prompts and its error messages are written to
stderr.
Assigning to
{\tt sys.stderr}
has no effect on the interpreter; it can be used to write error messages
to stderr using
{\tt print}.
\end{description}

\subsection{Built-in Module {\tt math}}

This module is always available.
It provides access to the mathematical functions defined by the C
standard.
They are:
{\tt acos(x)},
{\tt asin(x)},
{\tt atan(x)},
{\tt atan2(x,y)},
{\tt ceil(x)},
{\tt cos(x)},
{\tt cosh(x)},
{\tt exp(x)},
{\tt fabs(x)},
{\tt floor(x)},
%{\tt fmod(...)}  XXX not yet
%{\tt frexp(...)} XXX not yet
%{\tt ldexp(...)} XXX not yet
{\tt log(x)},
{\tt log10(x)},
%{\tt modf(...)}  XXX not yet
{\tt pow(x,y)},
{\tt sin(x)},
{\tt sinh(x)},
{\tt sqrt(x)},
{\tt tan(x)},
{\tt tanh(x)}.

It also defines two mathematical constants:
{\tt pi}
and
{\tt e}.

\subsection{Built-in Module {\tt time}}

This module provides various time-related functions.
It is always available.
Functions are:
\begin{description}
\item[{\tt sleep(secs)}]
Suspends execution for the given number of seconds.
\item[{\tt time()}]
Returns the time in seconds since the Epoch (Thursday January 1,
00:00:00, 1970 UCT on \UNIX\ machines).
\end{description}

\noindent
In some versions (Amoeba, Mac) the following functions also exist:
\begin{description}
\item[{\tt millisleep(msecs)}]
Suspends execution for the given number of milliseconds.
\item[{\tt millitimer()}]
Returns the number of milliseconds of real time elapsed since some point
in the past that is fixed per execution of the python interpreter (but
may change in each following run).
\end{description}

\noindent
The granularity of the milliseconds functions may be more than a
millisecond (100 msecs on Amoeba, 1/60 sec on the Mac).

\subsection{Built-in Module {\tt posix}}

This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly diguised
{\UNIX} interface).
It is available in all {\Python} versions except on the Macintosh.
Errors are reported exceptions.
It defines the following items:
\begin{description}
\item[{\tt chdir(path)}]
Changes the current directory to
{\tt path}.
\item[{\tt chmod(path, mode)}]
Change the mode of
{\tt path}
to the numeric
{\tt mode}.
\item[{\tt environ}]
A dictionary representing the string environment at the time
the interpreter was started.
(Modifying this dictionary does not affect the string environment of the
interpreter.)
For example,
{\tt posix.environ['HOME']}
is the pathname of your home directory, equivalent to
{\tt getenv("HOME")}
in C.
\item[{\tt error = 'posix.error'}]
%.br
The exception raised when an POSIX function returns an error.
The value accompanying this exception is a pair containing the numeric
error code from
{\tt errno}
and the corresponding string, as would be printed by the C function
{\tt perror()}.
\item[{\tt getcwd()}]
Returns a string representing the current working directory.
\item[{\tt link(src, dst)}]
Creates a hard link pointing to
{\tt src}
named
{\tt dst}.
\item[{\tt listdir(path)}]
Returns a list containing the names of the entries in the
directory.
The list is in arbitrary order.
It includes the special entries
{\tt '.'}
and
{\tt '..'}
if they are present in the directory.
\item[{\tt mkdir(path, mode)}]
Creates a directory named
{\tt path}
with numeric mode
{\tt mode}.
\item[{\tt rename(src, dst)}]
Renames the file or directory
{\tt src}
to
{\tt dst}.
\item[{\tt rmdir(path)}]
Removes the directory
{\tt path}.
\item[{\tt stat(path)}]
Performs a
{\em stat}
system call on the given path.
The return value is a tuple of at least 10 integers giving the most
important (and portable) members of the
{\em stat}
structure, in the order
{\tt st\_mode},
{\tt st\_ino},
{\tt st\_dev},
{\tt st\_nlink},
{\tt st\_uid},
{\tt st\_gid},
{\tt st\_size},
{\tt st\_atime},
{\tt st\_mtime},
{\tt st\_ctime}.
More items may be added at the end by some implementations.
\item[{\tt system(command)}]
Executes the command (a string) in a subshell.
This is implemented by calling the Standard C function
{\tt system()},
and has the same limitations.
Changes to
{\tt posix.environ},
{\tt sys.stdin}
etc. are not reflected in the environment of the executed command.
The return value is the exit status of the process as returned by
Standard C
{\tt system()}.
\item[{\tt umask(mask)}]
Sets the current numeric umask and returns the previous umask.
\item[{\tt unlink(path)}]
Unlinks the file
{\tt path}.
\item[{\tt utimes(path, (atime, mtime))}]
%.br
Sets the access and modified time of the file to the given values.
(The second argument is a tuple of two items.)
\end{description}

The following functions are only available on systems that support
symbolic links:
\begin{description}
\item[{\tt lstat(path)}]
Like
{\tt stat()},
but does not follow symbolic links.
\item[{\tt readlink(path)}]
Returns a string representing the path to which the symbolic link
points.
\item[{\tt symlink(src, dst)}]
Creates a symbolic link pointing to
{\tt src}
named
{\tt dst}.
\end{description}

\subsection{Built-in Module {\tt stdwin}}

This module defines several new object types and functions that
provide access to the functionality of the Standard Window System
Interface, STDWIN [CWI report CR-R8817].
It is available on systems to which STDWIN has been ported (which is
most systems).
It is only available if the {\tt DISPLAY} environment variable is set
or an explicit `{\tt -display \it displayname}' argument is passed to
the interpreter.

Functions have names that usually resemble their C STDWIN counterparts
with the initial `w' dropped.
Points are represented by pairs of integers; rectangles
by pairs of points.
For a complete description of STDWIN please refer to the documentation
of STDWIN for C programmers (aforementioned CWI report).
\subsubsection{Functions Defined in Module {\tt stdwin}}

The following functions are defined in the {\tt stdwin} module:
\begin{description}
\item[{\tt open(title)}]
%.br
Opens a new window whose initial title is given by the string argument.
Returns a window object; window object methods are described below.%
\footnote{
The {\Python} version of STDWIN does not support draw procedures; all
drawing requests are reported as draw events.
}
\item[{\tt getevent()}]
%.br
Waits for and returns the next event.
An event is returned as a triple: the first element is the event
type, a small integer; the second element is the window object to which
the event applies, or
{\tt None}
if it applies to no window in particular;
the third element is type-dependent.
Names for event types and command codes are defined in the standard
module
{\tt stdwinevent}.
\item[{\tt setdefwinpos(h, v)}]
%.br
Sets the default window position.
\item[{\tt setdefwinsize(width, height)}]
%.br
Sets the default window size.
\item[{\tt menucreate(title)}]
%.br
Creates a menu object referring to a global menu (a menu that appears in
all windows).
Methods of menu objects are described below.
\item[{\tt fleep()}]
%.br
Causes a beep or bell (or perhaps a `visual bell' or flash, hence the
name).
\item[{\tt message(string)}]
%.br
Displays a dialog box containing the string.
The user must click OK before the function returns.
\item[{\tt askync(prompt, default)}]
%.br
Displays a dialog that prompts the user to answer a question with yes or
no.
The function returns 0 for no, 1 for yes.
If the user hits the Return key, the default (which must be 0 or 1) is
returned.
If the user cancels the dialog, the
{\tt KeyboardInterrupt}
exception is raised.
\item[{\tt askstr(prompt, default)}]
%.br
Displays a dialog that prompts the user for a string.
If the user hits the Return key, the default string is returned.
If the user cancels the dialog, the
{\tt KeyboardInterrupt}
exception is raised.
\item[{\tt askfile(prompt, default, new)}]
%.br
Asks the user to specify a filename.
If
{\tt new}
is zero it must be an existing file; otherwise, it must be a new file.
If the user cancels the dialog, the
{\tt KeyboardInterrupt}
exception is raised.
\item[{\tt setcutbuffer(i, string)}]
%.br
Stores the string in the system's cut buffer number
{\tt i},
where it can be found (for pasting) by other applications.
On X11, there are 8 cut buffers (numbered 0..7).
Cut buffer number 0 is the `clipboard' on the Macintosh.
\item[{\tt getcutbuffer(i)}]
%.br
Returns the contents of the system's cut buffer number
{\tt i}.
\item[{\tt rotatebutbuffers(n)}]
%.br
On X11, this rotates the 8 cut buffers by
{\tt n}.
Ignored on the Macintosh.
\item[{\tt getselection(i)}]
%.br
Returns X11 selection number
{\tt i.}
Selections are not cut buffers.
Selection numbers are defined in module
{\tt stdwinevents}.
Selection {\tt WS\_PRIMARY} is the
{\em primary}
selection (used by
xterm,
for instance);
selection {\tt WS\_SECONDARY} is the
{\em secondary}
selection; selection {\tt WS\_CLIPBOARD} is the
{\em clipboard}
selection (used by
xclipboard).
On the Macintosh, this always returns an empty string.
\item[{\tt resetselection(i)}]
%.br
Resets selection number
{\tt i},
if this process owns it.
(See window method
{\tt setselection()}).
\item[{\tt baseline()}]
%.br
Return the baseline of the current font (defined by STDWIN as the
vertical distance between the baseline and the top of the
characters).%
\footnote{
There is no way yet to set the current font.
This will change in a future version.
}
\item[{\tt lineheight()}]
%.br
Return the total line height of the current font.
\item[{\tt textbreak(str, width)}]
%.br
Return the number of characters of the string that fit into a space of
{\tt width}
bits wide when drawn in the curent font.
\item[{\tt textwidth(str)}]
%.br
Return the width in bits of the string when drawn in the current font.
\subsubsection{Window Object Methods}
\end{description}

Window objects are created by
{\tt stdwin.open()}.
There is no explicit function to close a window; windows are closed when
they are garbage-collected.
Window objects have the following methods:
\begin{description}
\item[{\tt begindrawing()}]
Returns a drawing object, whose methods (described below) allow drawing
in the window.
\item[{\tt change(rect)}]
Invalidates the given rectangle; this may cause a draw event.
\item[{\tt gettitle()}]
Returns the window's title string.
\item[{\tt getdocsize()}]
Returns a pair of integers giving the size of the document as set by
{\tt setdocsize()}.
\item[{\tt getorigin()}]
Returns a pair of integers giving the origin of the window with respect
to the document.
\item[{\tt getwinsize()}]
Returns a pair of integers giving the size of the window.
\item[{\tt menucreate(title)}]
Creates a menu object referring to a local menu (a menu that appears
only in this window).
Methods menu objects are described below.
\item[{\tt scroll(rect,~point)}]
Scrolls the given rectangle by the vector given by the point.
\item[{\tt setwincursor(name)}]
Sets the window cursor to a cursor of the given name.
It raises the
{\tt Runtime\-Error}
exception if no cursor of the given name exists.
Suitable names are
{\tt 'ibeam'},
{\tt 'arrow'},
{\tt 'cross'},
{\tt 'watch'}
and
{\tt 'plus'}.
On X11, there are many more (see
{\tt <X11/cursorfont.h>}).
\item[{\tt setdocsize(point)}]
Sets the size of the drawing document.
\item[{\tt setorigin(point)}]
Moves the origin of the window to the given point in the document.
\item[{\tt setselection(i, str)}]
Attempts to set X11 selection number
{\tt i}
to the string
{\tt str}.
(See stdwin method
{\tt getselection()}
for the meaning of
{\tt i}.)
Returns true if it succeeds.
If it succeeds, the window ``owns'' the selection until
(a) another applications takes ownership of the selection; or
(b) the window is deleted; or
(c) the application clears ownership by calling
{\tt stdwin.resetselection(i)}.
When another application takes ownership of the selection, a
{\tt WE\_LOST\_SEL}
event is received for no particular window and with the selection number
as detail.
Ignored on the Macintosh.
\item[{\tt settitle(title)}]
Sets the window's title string.
\item[{\tt settimer(dsecs)}]
Schedules a timer event for the window in
{\tt dsecs/10}
seconds.
\item[{\tt show(rect)}]
Tries to ensure that the given rectangle of the document is visible in
the window.
\item[{\tt textcreate(rect)}]
Creates a text-edit object in the document at the given rectangle.
Methods of text-edit objects are described below.
\end{description}

\subsubsection{Drawing Object Methods}

Drawing objects are created exclusively by the window method
{\tt begindrawing()}.
Only one drawing object can exist at any given time; the drawing object
must be deleted to finish drawing.
No drawing object may exist when
{\tt stdwin.getevent()}
is called.
Drawing objects have the following methods:
\begin{description}
\item[{\tt box(rect)}]
Draws a box around a rectangle.
\item[{\tt circle(center, radius)}]
%.br
Draws a circle with given center point and radius.
\item[{\tt elarc(center, (rh, rv), (a1, a2))}]
%.br
Draws an elliptical arc with given center point.
{\tt (rh, rv)}
gives the half sizes of the horizontal and vertical radii.
{\tt (a1, a2)}
gives the angles (in degrees) of the begin and end points.
0 degrees is at 3 o'clock, 90 degrees is at 12 o'clock.
\item[{\tt erase(rect)}]
Erases a rectangle.
\item[{\tt invert(rect)}]
Inverts a rectangle.
\item[{\tt line(p1, p2)}]
Draws a line from point
{\tt p1}
to
{\tt p2}.
\item[{\tt paint(rect)}]
Fills a rectangle.
\item[{\tt text(p, str)}]
Draws a string starting at point p (the point specifies the
top left coordinate of the string).
\item[{\tt shade(rect, percent)}]
%.br
Fills a rectangle with a shading pattern that is about
{\tt percent}
percent filled.
\item[{\tt xorline(p1, p2)}]
Draws a line in XOR mode.
\item[{\tt baseline(), lineheight(), textbreak(), textwidth()}]
%.br
These functions are similar to the corresponding functions described
above for the
{\tt stdwin}
module, but use the current font of the window instead of the (global)
default font.
\end{description}

\subsubsection{Menu Object Methods}

A menu object represents a menu.
The menu is destroyed when the menu object is deleted.
The following methods are defined:
\begin{description}
\item[{\tt additem(text, shortcut)}]
%.br
Adds a menu item with given text.
The shortcut must be a string of length 1, or omitted (to specify no
shortcut).
\item[{\tt setitem(i, text)}]
Sets the text of item number
{\tt i}.
\item[{\tt enable(i, flag)}]
Enables or disables item
{\tt i}.
\item[{\tt check(i, flag)}]
Sets or clears the
{\em check mark}
for item
{\tt i}.
\end{description}

\subsubsection{Text-edit Object Methods}

A text-edit object represents a text-edit block.
For semantics, see the STDWIN documentation for C programmers.
The following methods exist:
\begin{description}
\item[{\tt arrow(code)}]
Passes an arrow event to the text-edit block.
The
{\tt code}
must be one of
{\tt WC\_LEFT},
{\tt WC\_RIGHT},
{\tt WC\_UP}
or
{\tt WC\_DOWN}
(see module
{\tt stdwinevents}).
\item[{\tt draw(rect)}]
Passes a draw event to the text-edit block.
The rectangle specifies the redraw area.
\item[{\tt event(type, window, detail)}]
%.br
Passes an event gotten from
{\tt stdwin.getevent()}
to the text-edit block.
Returns true if the event was handled.
\item[{\tt getfocus()}]
Returns 2 integers representing the start and end positions of the
focus, usable as slice indices on the string returned by
{\tt getfocustext()}.
\item[{\tt getfocustext()}]
Returns the text in the focus.
\item[{\tt getrect()}]
Returns a rectangle giving the actual position of the text-edit block.
(The bottom coordinate may differ from the initial position because
the block automatically shrinks or grows to fit.)
\item[{\tt gettext()}]
Returns the entire text buffer.
\item[{\tt move(rect)}]
Specifies a new position for the text-edit block in the document.
\item[{\tt replace(str)}]
Replaces the focus by the given string.
The new focus is an insert point at the end of the string.
\item[{\tt setfocus(i,~j)}]
Specifies the new focus.
Out-of-bounds values are silently clipped.
\end{description}

\subsection{Built-in Module {\tt amoeba}}

This module provides some object types and operations useful for
Amoeba applications.
It is only available on systems that support Amoeba operations.
RPC errors and other Amoeba errors are reported as the exception
{\tt amoeba.error = 'amoeba.error'}.
The module
{\tt amoeba}
defines the following items:
\begin{description}
\item[{\tt name\_append(path,~cap)}]
%.br
Stores a capability in the Amoeba directory tree.
Arguments are the pathname (a string) and the capability (a capability
object as returned by
{\tt name\_lookup()}).
\item[{\tt name\_delete(path)}]
%.br
Deletes a capability from the Amoeba directory tree.
Argument is the pathname.
\item[{\tt name\_lookup(path)}]
%.br
Looks up a capability.
Argument is the pathname.
Returns a
{\em capability}
object, to which various interesting operations apply, described below.
\item[{\tt name\_replace(path,~cap)}]
%.br
Replaces a capability in the Amoeba directory tree.
Arguments are the pathname and the new capability.
(This differs from
{\tt name\_append()}
in the behavior when the pathname already exists:
{\tt name\_append()}
finds this an error while
{\tt name\_replace()}
allows it, as its name suggests.)
\item[{\tt capv}]
A table representing the capability environment at the time the
interpreter was started.
(Alas, modifying this table does not affect the capability environment
of the interpreter.)
For example,
{\tt amoeba.capv['ROOT']}
is the capability of your root directory, similar to
{\tt getcap("ROOT")}
in C.
\item[{\tt error = 'amoeba.error'}]
%.br
The exception raised when an Amoeba function returns an error.
The value accompanying this exception is a pair containing the numeric
error code and the corresponding string, as returned by the C function
{\tt err\_why()}.
\item[{\tt timeout(msecs)}]
%.br
Sets the transaction timeout, in milliseconds.
Returns the previous timeout.
Initially, the timeout is set to 2 seconds by the {\Python} interpreter.
\end{description}

\subsubsection{Capability Operations}

Capabilities are written in a convenient ASCII format, also used by the
Amoeba utilities
{\em c2a}(U)
and
{\em a2c}(U).
For example:
\begin{code}\begin{verbatim}
>>> amoeba.name_lookup('/profile/cap')
aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
>>> 
\end{verbatim}\end{code}
The following methods are defined for capability objects.
\begin{description}
\item[{\tt dir\_list()}]
Returns a list of the names of the entries in an Amoeba directory.
\item[{\tt b\_read(offset, maxsize)}]
%.br
Reads (at most)
{\tt maxsize}
bytes from a bullet file at offset
{\tt offset.}
The data is returned as a string.
EOF is reported as an empty string.
\item[{\tt b\_size()}]
Returns the size of a bullet file.
\item[{\tt dir\_append(), dir\_delete(), dir\_lookup(), dir\_replace()}]
%.br
Like the corresponding
{\tt name\_*}
functions, but with a path relative to the capability.
(For paths beginning with a slash the capability is ignored, since this
is the defined semantics for Amoeba.)
\item[{\tt std\_info()}]
Returns the standard info string of the object.
\item[{\tt tod\_gettime()}]
Returns the time (in seconds since the Epoch, in UCT, as for POSIX) from
a time server.
\item[{\tt tod\_settime(t)}]
Sets the time kept by a time server.
\end{description}

\subsection{Built-in Module {\tt audio}}

This module provides rudimentary access to the audio I/O device
{\tt /dev/audio}
on the Silicon Graphics Personal IRIS; see audio(7).
It supports the following operations:
\begin{description}
\item[{\tt setoutgain(n)}]
Sets the output gain (0-255).
\item[{\tt getoutgain()}]
Returns the output gain.
\item[{\tt setrate(n)}]
Sets the sampling rate: 1=32K/sec, 2=16K/sec, 3=8K/sec.
\item[{\tt setduration(n)}]
Sets the `sound duration' in units of 1/100 seconds.
\item[{\tt read(n)}]
Reads a chunk of
{\tt n}
sampled bytes from the audio input (line in or microphone).
The chunk is returned as a string of length n.
Each byte encodes one sample as a signed 8-bit quantity using linear
encoding.
This string can be converted to numbers using {\tt chr2num()} described
below.
\item[{\tt write(buf)}]
Writes a chunk of samples to the audio output (speaker).
\end{description}

These operations support asynchronous audio I/O:
\begin{description}
\item[{\tt start\_recording(n)}]
%.br
Starts a second thread (a process with shared memory) that begins reading
{\tt n}
bytes from the audio device.
The main thread immediately continues.
\item[{\tt wait\_recording()}]
%.br
Waits for the second thread to finish and returns the data read.
\item[{\tt stop\_recording()}]
%.br
Makes the second thread stop reading as soon as possible.
Returns the data read so far.
\item[{\tt poll\_recording()}]
%.br
Returns true if the second thread has finished reading (so
{\tt wait\_recording()} would return the data without delay).
\item[{\tt start\_playing(chunk)}, {\tt wait\_playing()},
{\tt stop\_playing()}, {\tt poll\_playing()}]
%.br
Similar but for output.
{\tt stop\_playing()}
returns a lower bound for the number of bytes actually played (not very
accurate).
\end{description}

The following operations do not affect the audio device but are
implemented in C for efficiency:
\begin{description}
\item[{\tt amplify(buf, f1, f2)}]
%.br
Amplifies a chunk of samples by a variable factor changing from
{\tt f1}/256 to {\tt f2}/256.
Negative factors are allowed.
Resulting values that are to large to fit in a byte are clipped.         
\item[{\tt reverse(buf)}]
%.br
Returns a chunk of samples backwards.
\item[{\tt add(buf1, buf2)}]
%.br
Bytewise adds two chunks of samples.
Bytes that exceed the range are clipped.
If one buffer shorter, it is assumed to be padded with zeros.
\item[{\tt chr2num(buf)}]
%.br
Converts a string of sampled bytes as returned by {\tt read()} into
a list containing the numeric values of the samples.
\item[{\tt num2chr(list)}]
%.br
Converts a list as returned by
{\tt chr2num()}
back to a buffer acceptable by
{\tt write()}.
\end{description}

\subsection{Built-in Module {\tt gl}}

This module provides access to the Silicon Graphics
{\em Graphics Library}.
It is available only on Silicon Graphics machines.

{\bf Warning:}
Some illegal calls to the GL library cause the {\Python} interpreter to dump
core.
In particular, the use of most GL calls is unsafe before the first
window is opened.

The module is too large to document here in its entirety, but the
following should help you to get started.
The parameter conventions for the C functions are translated to {\Python} as
follows:

\begin{itemize}
\item
All (short, long, unsigned) int values are represented by {\Python}
integers.
\item
All float and double values are represented by {\Python} floating point
numbers.
In most cases, {\Python} integers are also allowed.
\item
All arrays are represented by one-dimensional {\Python} lists.
In most cases, tuples are also allowed.
\item
All string and character arguments are represented by {\Python} strings,
e.g.,
{\tt winopen('Hi~There!')}
and
{\tt rotate(900,~'z')}.
\item
All (short, long, unsigned) integer arguments or return values that are
only used to specify the length of an array argument are omitted.
For example, the C call
\begin{code}\begin{verbatim}
lmdef(deftype, index, np, props)
\end{verbatim}\end{code}
is translated to {\Python} as
\begin{code}\begin{verbatim}
lmdef(deftype, index, props)
\end{verbatim}\end{code}
\item
Output arguments are omitted from the argument list; they are
transmitted as function return values instead.
If more than one value must be returned, the return value is a tuple.
If the C function has both a regular return value (that is not omitted
because of the previous rule) and an output argument, the return value
comes first in the tuple.
Examples: the C call
\begin{code}\begin{verbatim}
getmcolor(i, &red, &green, &blue)
\end{verbatim}\end{code}
is translated to {\Python} as
\begin{code}\begin{verbatim}
red, green, blue = getmcolor(i)
\end{verbatim}\end{code}
\end{itemize}

The following functions are non-standard or have special argument
conventions:
\begin{description}
\item[{\tt varray()}]
Equivalent to but faster than a number of
{\tt v3d()}
calls.
The argument is a list (or tuple) of points.
Each point must be a tuple of coordinates (x, y, z) or (x, y).
The points may be 2- or 3-dimensional but must all have the
same dimension.
Float and int values may be mixed however.
The points are always converted to 3D double precision points
by assuming z=0.0 if necessary (as indicated in the man page),
and for each point
{\tt v3d()}
is called.
\item[{\tt nvarray()}]
Equivalent to but faster than a number of
{\tt n3f}
and
{\tt v3f}
calls.
The argument is an array (list or tuple) of pairs of normals and points.
Each pair is a tuple of a point and a normal for that point.
Each point or normal must be a tuple of coordinates (x, y, z).
Three coordinates must be given.
Float and int values may be mixed.
For each pair,
{\tt n3f()}
is called for the normal, and then
{\tt v3f()}
is called for the point.
\item[{\tt vnarray()}]
Similar to 
{\tt nvarray()}
but the pairs have the point first and the normal second.
\item[{\tt nurbssurface(s\_k[], t\_k[], ctl[][], s\_ord, t\_ord, type)}]
%.br
Defines a nurbs surface.
The dimensions of
{\tt ctl[][]}
are computed as follows:
{\tt [len(s\_k)~-~s\_ord]},
{\tt [len(t\_k)~-~t\_ord]}.
\item[{\tt nurbscurve(knots, ctlpoints, order, type)}]
%.br
Defines a nurbs curve.
The length of ctlpoints is
{\tt len(knots)~-~order}.
\item[{\tt pwlcurve(points, type)}]
%.br
Defines a piecewise-linear curve.
{\tt points}
is a list of points.
{\tt type}
must be
{\tt N\_ST}.
\item[{\tt pick(n), select(n)}]
%.br
The only argument to these functions specifies the desired size of the
pick or select buffer.
\item[{\tt endpick(), endselect()}]
%.br
These functions have no arguments.
They return a list of integers representing the used part of the
pick/select buffer.
No method is provided to detect buffer overrun.
\end{description}

Here is a tiny but complete example GL program in {\Python}:
\begin{code}\begin{verbatim}
import gl, GL, time

def main():
    gl.foreground()
    gl.prefposition(500, 900, 500, 900)
    w = gl.winopen('CrissCross')
    gl.ortho2(0.0, 400.0, 0.0, 400.0)
    gl.color(GL.WHITE)
    gl.clear()
    gl.color(GL.RED)
    gl.bgnline()
    gl.v2f(0.0, 0.0)
    gl.v2f(400.0, 400.0)
    gl.endline()
    gl.bgnline()
    gl.v2f(400.0, 0.0)
    gl.v2f(0.0, 400.0)
    gl.endline()
    time.sleep(5)

main()
\end{verbatim}\end{code}

\subsection{Built-in Module {\tt pnl}}

This module provides access to the
{\em Panel Library}
built by NASA Ames (write to
{\tt panel-request@nas.nasa.gov}
to get it).
All access to it should be done through the standard module
{\tt panel},
which transparantly exports most functions from
{\tt pnl}
but redefines
{\tt pnl.dopanel()}.

{\bf Warning:}
the {\Python} interpreter will dump core if you don't create a GL window
before calling
{\tt pnl.mkpanel()}.

The module is too large to document here in its entirety.

\section{Standard Modules}

The following standard modules are defined.
They are available in one of the directories in the default module
search path (try printing
{\tt sys.path}
to find out the default search path.)

\subsection{Standard Module {\tt string}}

This module defines some constants useful for checking character
classes, some exceptions, and some useful string functions.
The constants are:
\begin{description}
\item[{\tt digits}]
The string
{\tt '0123456789'}.
\item[{\tt hexdigits}]
The string
{\tt '0123456789abcdefABCDEF'}.
\item[{\tt letters}]
The concatenation of the strings
{\tt lowercase}
and
{\tt uppercase}
described below.
\item[{\tt lowercase}]
The string
{\tt 'abcdefghijklmnopqrstuvwxyz'}.
\item[{\tt octdigits}]
The string
{\tt '01234567'}.
\item[{\tt uppercase}]
The string
{\tt 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}.
\item[{\tt whitespace}]
A string containing all characters that are considered whitespace,
i.e.,
space, tab and newline.
This definition is used by
{\tt split()}
and
{\tt strip()}.
\end{description}

The exceptions are:
\begin{description}
\item[{\tt atoi\_error = 'non-numeric argument to string.atoi'}]
%.br
Exception raised by
{\tt atoi}
when a non-numeric string argument is detected.
The exception argument is the offending string.
\item[{\tt index\_error = 'substring not found in string.index'}]
%.br
Exception raised by
{\tt index}
when
{\tt sub}
is not found.
The argument are the offending arguments to index: {\tt (s, sub)}.
\end{description}

The functions are:
\begin{description}
\item[{\tt atoi(s)}]
Converts a string to a number.
The string must consist of one or more digits, optionally preceded by a
sign ({\tt '+'} or {\tt '-'}).
\item[{\tt index(s, sub)}]
Returns the lowest index in
{\tt s}
where the substring
{\tt sub}
is found.
\item[{\tt lower(s)}]
Convert letters to lower case.
\item[{\tt split(s)}]
Returns a list of the whitespace-delimited words of the string
{\tt s}.
\item[{\tt splitfields(s, sep)}]
%.br
Returns a list containing the fields of the string
{\tt s},
using the string
{\tt sep}
as a separator.
The list will have one more items than the number of non-overlapping
occurrences of the separator in the string.
Thus,
{\tt string.splitfields(s, ' ')}
is not the same as
{\tt string.split(s)},
as the latter only returns non-empty words.
\item[{\tt strip(s)}]
Removes leading and trailing whitespace from the string
{\tt s}.
\item[{\tt swapcase(s)}]
Converts lower case letters to upper case and vice versa.
\item[{\tt upper(s)}]
Convert letters to upper case.
\item[{\tt ljust(s, width), rjust(s, width),  center(s, width)}]
%.br
These functions respectively left-justify, right-justify and center a
string in a field of given width.
They return a string that is at least
{\tt width}
characters wide, created by padding the string
{\tt s}
with spaces until the given width on the right, left or both sides.
The string is never truncated.
\end{description}

\subsection{Standard Module {\tt path}}

This module implements some useful functions on POSIX pathnames.
\begin{description}
\item[{\tt basename(p)}]
Returns the base name of pathname
{\tt p}.
This is the second half of the pair returned by
{\tt path.split(p)}.
\item[{\tt cat(p, q)}]
Performs intelligent pathname concatenation on paths
{\tt p}
and
{\tt q}:
If
{\tt q}
is an absolute path, the return value is
{\tt q}.
Otherwise, the concatenation of
{\tt p}
and
{\tt q}
is returned, with a slash ({\tt '/'}) inserted unless
{\tt p}
is empty or ends in a slash.
\item[{\tt commonprefix(list)}]
%.br
Returns the longest string that is a prefix of all strings in
{\tt list}.
If
{\tt list}
is empty, the empty string ({\tt ''}) is returned.
\item[{\tt exists(p)}]
Returns true if
{\tt p}
refers to an existing path.
\item[{\tt isdir(p)}]
Returns true if
{\tt p}
refers to an existing directory.
\item[{\tt islink(p)}]
Returns true if
{\tt p}
refers to a directory entry that is a symbolic link.
Always false if symbolic links are not supported.
\item[{\tt ismount(p)}]
Returns true if
{\tt p}
is an absolute path that occurs in the mount table as output by the
{\tt /etc/mount}
utility.
This output is read once when the function is used for the first
time.%
\footnote{
Is there a better way to check for mount points?
}
\item[{\tt split(p)}]
Returns a pair
{\tt (head,~tail)}
such that
{\tt tail}
contains no slashes and
{\tt path.cat(head, tail)}
is equal to
{\tt p}.
\item[{\tt walk(p, visit, arg)}]
%.br
Calls the function
{\tt visit}
with arguments
{\tt (arg, dirname, names)}
for each directory in the directory tree rooted at
{\tt p}
(including
{\tt p}
itself, if it is a directory).
The argument
{\tt dirname}
specifies the visited directory, the argument
{\tt names}
lists the files in the directory (gotten from
{\tt posix.listdir(dirname)}).
The
{\tt visit}
function may modify
{\tt names}
to influence the set of directories visited below
{\tt dirname},
e.g.,
to avoid visiting certain parts of the tree.
(The object referred to by
{\tt names}
must be modified in place, using
{\tt del}
or slice assignment.)
\end{description}

\subsection{Standard Module {\tt getopt}}

This module helps scripts to parse the command line arguments in
{\tt sys.argv}.
It uses the same conventions as the {\UNIX}
{\tt getopt()}
function.
It defines the function
{\tt getopt.getopt(args, options)}
and the exception
{\tt getopt.error}.

The first argument to
{\tt getopt()}
is the argument list passed to the script with its first element
chopped off (i.e.,
{\tt sys.argv[1:]}).
The second argument is the string of option letters that the
script wants to recognize, with options that require an argument
followed by a colon (i.e., the same format that {\UNIX}
{\tt getopt()}
uses).
The return value consists of two elements: the first is a list of
option-and-value pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice of the
first argument).
Each option-and-value pair returned has the option as its first element,
prefixed with a hyphen (e.g.,
{\tt '-x'}),
and the option argument as its second element, or an empty string if the
option has no argument.
The options occur in the list in the same order in which they were
found, thus allowing multiple occurrences.
Example:
\begin{code}\begin{verbatim}
>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>> 
\end{verbatim}\end{code}
The exception
{\tt getopt.error = 'getopt error'}
is raised when an unrecognized option is found in the argument list or
when an option requiring an argument is given none.
The argument to the exception is a string indicating the cause of the
error.

\subsection{Standard Module {\tt rand}}

This module implements a pseudo-random number generator similar to
{\tt rand()}
in C.
It defines the following functions:
\begin{description}
\item[{\tt rand()}]
Returns an integer random number in the range [0 ... 32768).
\item[{\tt choice(s)}]
Returns a random element from the sequence (string, tuple or list)
{\tt s.}
\item[{\tt srand(seed)}]
Initializes the random number generator with the given integral seed.
When the module is first imported, the random number is initialized with
the current time.
\end{description}

\subsection{Standard Module {\tt whrandom}}

This module implements a Wichmann-Hill pseudo-random number generator.
It defines the following functions:
\begin{description}
\item[{\tt random()}]
Returns the next random floating point number in the range [0.0 ... 1.0).
\item[{\tt seed(x, y, z)}]
Initializes the random number generator from the integers
{\tt x},
{\tt y}
and
{\tt z}.
When the module is first imported, the random number is initialized
using values derived from the current time.
\end{description}

\subsection{Standard Module {\tt stdwinevents}}

This module defines constants used by STDWIN for event types
({\tt WE\_ACTIVATE} etc.), command codes ({\tt WC\_LEFT} etc.)
and selection types ({\tt WS\_PRIMARY} etc.).
Read the file for details.
Suggested usage is
\begin{code}\begin{verbatim}
>>> from stdwinevents import *
>>> 
\end{verbatim}\end{code}

\subsection{Standard Module {\tt rect}}

This module contains useful operations on rectangles.
A rectangle is defined as in module
{\tt stdwin}:
a pair of points, where a point is a pair of integers.
For example, the rectangle
\begin{code}\begin{verbatim}
(10, 20), (90, 80)
\end{verbatim}\end{code}
is a rectangle whose left, top, right and bottom edges are 10, 20, 90
and 80, respectively.
Note that the positive vertical axis points down (as in
{\tt stdwin}).

The module defines the following objects:
\begin{description}
\item[{\tt error = 'rect.error'}]
%.br
The exception raised by functions in this module when they detect an
error.
The exception argument is a string describing the problem in more
detail.
\item[{\tt empty}]
%.br
The rectangle returned when some operations return an empty result.
This makes it possible to quickly check whether a result is empty:
\begin{code}\begin{verbatim}
>>> import rect
>>> r1 = (10, 20), (90, 80)
>>> r2 = (0, 0), (10, 20)
>>> r3 = rect.intersect(r1, r2)
>>> if r3 is rect.empty: print 'Empty intersection'
Empty intersection
>>> 
\end{verbatim}\end{code}
\item[{\tt is\_empty(r)}]
%.br
Returns true if the given rectangle is empty.
A rectangle
{\em (left,~top), (right,~bottom)}
is empty if
{\em left~$\geq$~right}
or
{\em top~$\leq$~bottom}.
\item[{\tt intersect(list)}]
%.br
Returns the intersection of all rectangles in the list argument.
It may also be called with a tuple argument or with two or more
rectangles as arguments.
Raises
{\tt rect.error}
if the list is empty.
Returns
{\tt rect.empty}
if the intersection of the rectangles is empty.
\item[{\tt union(list)}]
%.br
Returns the smallest rectangle that contains all non-empty rectangles in
the list argument.
It may also be called with a tuple argument or with two or more
rectangles as arguments.
Returns
{\tt rect.empty}
if the list is empty or all its rectangles are empty.
\item[{\tt pointinrect(point, rect)}]
%.br
Returns true if the point is inside the rectangle.
By definition, a point
{\em (h,~v)}
is inside a rectangle
{\em (left,~top),}
{\em (right,~bottom)}
if
{\em left~$\leq$~h~$<$~right}
and
{\em top~$\leq$~v~$<$~bottom}.
\item[{\tt inset(rect, (dh, dv))}]
%.br
Returns a rectangle that lies inside the
{\tt rect}
argument by
{\tt dh}
pixels horizontally
and
{\tt dv}
pixels
vertically.
If
{\tt dh}
or
{\tt dv}
is negative, the result lies outside
{\tt rect}.
\item[{\tt rect2geom(rect)}]
%.br
Converts a rectangle to geometry representation:
{\em (left,~top),}
{\em (width,~height)}.
\item[{\tt geom2rect(geom)}]
%.br
Converts a rectangle given in geometry representation back to the
standard rectangle representation
{\em (left,~top),}
{\em (right,~bottom)}.
\end{description}

\subsection{Standard Modules {\tt GL} and {\tt DEVICE}}

These modules define the constants used by the Silicon Graphics
{\em Graphics Library}
that C programmers find in the header files
{\tt <gl/gl.h>}
and
{\tt <gl/device.h>}.
Read the module files for details.

\subsection{Standard Module {\tt panel}}

This module should be used instead of the built-in module
{\tt pnl}
to interface with the
{\em Panel Library}.

The module is too large to document here in its entirety.
One interesting function:
\begin{description}
\item[{\tt defpanellist(filename)}]
%.br
Parses a panel description file containing S-expressions written by the
{\em Panel Editor}
that accompanies the Panel Library and creates the described panels.
It returns a list of panel objects.
\end{description}

{\bf Warning:}
the {\Python} interpreter will dump core if you don't create a GL window
before calling
{\tt panel.mkpanel()}
or
{\tt panel.defpanellist()}.

\subsection{Standard Module {\tt parser}}

This module defines a self-contained parser for S-expressions as output
by the Panel Editor (which is written in Scheme so it can't help writing
S-expressions).
The relevant function is
{\tt parser.parse\_file(file)}
which has a file object (not a filename!) as argument and returns a list
of parsed S-expressions.
Each S-expression is converted into a {\Python} list, with atoms converted
to {\Python} strings and sub-expressions (recursively) to {\Python} lists.
For more details, read the module file.

\subsection{P.M.}

\begin{verse}
commands

cmp?

*cache?

localtime?

calendar?

\_\_dict?
\end{verse}

\end{document}