blob: c64969ffef05e46b2c05912a118bf164aeff79fe [file] [log] [blame]
Guido van Rossuma7925f11994-01-26 10:20:16 +00001Subject: FAQ: Python -- an object-oriented language
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002Newsgroups: comp.lang.python,comp.answers,news.answers
3Followup-to: comp.lang.python
Guido van Rossuma7925f11994-01-26 10:20:16 +00004From: guido@cwi.nl (Guido van Rossum)
5Reply-to: guido@cwi.nl (Guido van Rossum)
6Approved: news-answers-request@MIT.Edu
7
8Archive-name: python-faq/part1
Guido van Rossum3de27361994-07-25 14:19:33 +00009Version: 1.11
10Last-modified: 25 July 1994
Guido van Rossuma7925f11994-01-26 10:20:16 +000011
12This article contains answers to Frequently Asked Questions about
13Python (an object-oriented interpreted programming language -- see
14the answer to question 1.1 for a short overview).
15
16Copyright 1993, 1994 Guido van Rossum. Unchanged electronic
17redistribution of this FAQ is allowed. Printed redistribution only
18with permission of the author. No warranties.
19
20Author's address:
21 Guido van Rossum
22 CWI, dept. CST
23 Kruislaan 413
24 P.O. Box 94079
25 1090 GB Amsterdam
26 The Netherlands
27Email: guido@cwi.nl
28
29The latest version of this FAQ is available by anonymous ftp from
Guido van Rossum7ce61c11994-06-13 15:13:56 +000030ftp.cwi.nl [192.16.191.128] in the directory /pub/python, with
Guido van Rossuma7925f11994-01-26 10:20:16 +000031filename python-FAQ. It will also be posted regularly to the
Guido van Rossum5333c5d1994-04-11 11:06:22 +000032newsgroups comp.answers and comp.lang.python.
Guido van Rossuma7925f11994-01-26 10:20:16 +000033
34Many FAQs, including this one, are available by anonymous ftp from
Guido van Rossumea2c6f71994-07-14 12:35:14 +000035rtfm.mit.edu [18.181.0.24] in the directory pub/usenet/news.answers.
Guido van Rossuma7925f11994-01-26 10:20:16 +000036The name under which a FAQ is archived appears in the Archive-name line
37at the top of the article. This FAQ is archived as python-faq/part1.
38
39There's a mail server on that machine which will send you files from
40the archive by e-mail if you have no ftp access. You send a e-mail
41message to mail-server@rtfm.mit.edu containing the single word help in
42the message body to receive instructions.
43
44This FAQ is divided in the following chapters:
45
46 1. General information and availability
47 2. Python in the real world
48 3. Building Python
49 4. Programming in Python
50 5. Extending Python
51 6. Python's design
52 7. Using Python on non-UNIX platforms
53
54To find the start of a particular chapter, search for the chapter number
55followed by a dot and a space at the beginning of a line (e.g. to
56find chapter 4 in vi, type /^4\. /).
57
58Here's an overview of the questions per chapter:
59
60 1. General information and availability
61 1.1. Q. What is Python?
62 1.2. Q. Why is it called Python?
63 1.3. Q. How do I obtain a copy of the Python source?
64 1.4. Q. How do I get documentation on Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +000065 1.5. Q. Are there other ftp sites that mirror the Python distribution?
66 1.6. Q. Is there a newsgroup or mailing list devoted to Python?
67 1.7. Q. Is there a book on Python, or will there be one out soon?
68 1.8. Q. Are there any published articles about Python that I can quote?
69 1.9. Q. How does the Python version numbering scheme work?
70 1.10. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum7ce61c11994-06-13 15:13:56 +000071 1.11. Q. Are there copyright restrictions on the use of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +000072
73 2. Python in the real world
74 2.1. Q. How many people are using Python?
75 2.2. Q. Have any significant projects been done in Python?
76 2.3. Q. Are there any commercial projects going on using Python?
Guido van Rossum95f61a71994-01-26 17:23:37 +000077 2.4. Q. How stable is Python?
78 2.5. Q. What new developments are expected for Python in the future?
Guido van Rossum3de27361994-07-25 14:19:33 +000079 2.6. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +000080
81 3. Building Python
Guido van Rossum91f60831994-02-15 15:52:27 +000082 3.1. Q. Is there a test set?
83 3.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +000084 operations, but when playing with floating point operations I cannot
85 find anything wrong with them.
Guido van Rossum91f60831994-02-15 15:52:27 +000086 3.3. Q. Link errors building Python with STDWIN on SGI IRIX.
87 3.4. Q. Link errors after rerunning the configure script.
88 3.5. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +000089 script (after the script name).
Guido van Rossum91f60831994-02-15 15:52:27 +000090 3.6. Q. When building on the SGI, make tries to run python to create
Guido van Rossum5333c5d1994-04-11 11:06:22 +000091 glmodule.c, but python hasn't been built or installed yet.
Guido van Rossum3de27361994-07-25 14:19:33 +000092 3.7. Q. Python built with gcc for the DEC Alpha doesn't work.
93 3.8. Q. Other trouble building Python on platform X.
Guido van Rossuma7925f11994-01-26 10:20:16 +000094
95 4. Programming in Python
Guido van Rossum24349991994-02-02 14:12:45 +000096 4.1. Q. Is there a source code level debugger with breakpoints, step,
97 etc.?
98 4.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +000099 C and others in Python (e.g. through inheritance)? (Also phrased as:
100 Can I use a built-in type as base class?)
Guido van Rossum24349991994-02-02 14:12:45 +0000101 4.3. Q. Is there a curses/termcap package for Python?
102 4.4. Q. Is there an equivalent to C's onexit() in Python?
103 4.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000104 nested function seemingly can't access the local variables of the
105 outer function. What is going on? How do I pass local data to a
106 nested function?
Guido van Rossum24349991994-02-02 14:12:45 +0000107 4.6. Q. How do I iterate over a sequence in reverse order?
108 4.7. Q. My program is too slow. How do I speed it up?
109 4.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000110 again (into the same Python process), the changes don't seem to take
111 place. What is going on?
Guido van Rossum24349991994-02-02 14:12:45 +0000112 4.9. Q. I have a module in which I want to execute some extra code when it
113 is run as a script. How do I find out whether I am running as a
114 script?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000115 4.10. Q. I try to run a program from the Demo directory but it fails with
116 ImportError: No module named ...; what gives?
117 4.11. Q. What GUI toolkits exist for Python?
118 4.12. Q. Are there any interfaces to commercial database in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000119
120 5. Extending Python
121 5.1. Q. Can I create my own functions in C?
122 5.2. Q. Can I create my own functions in C++?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000123 5.3. Q. How can I execute arbitrary Python statements from C?
124 5.4. Q. How can I evaluate an arbitrary Python expression from C?
125 5.5. Q. How do I extract C values from a Python object?
126 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000127
128 6. Python's design
129 6.1. Q. Why isn't there a generic copying operation for objects in
130 Python?
131 6.2. Q. Why isn't there a generic way to implement persistent objects
132 in Python? (Persistent == automatically saved to and restored from
133 disk.)
134 6.3. Q. Why isn't there a switch or case statement in Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +0000135 6.4. Q. Why does Python use indentation for grouping of statements?
Guido van Rossum3de27361994-07-25 14:19:33 +0000136 6.5. Q. Why are Python strings immutable?
137 6.6. Q. Why don't strings have methods like index() or sort(), like
138 lists?
139 6.7. Q. Why does Python use methods for some functionality
140 (e.g. list.index()) but functions for other (e.g. len(list))?
141 6.8. Q. Why can't I derive a class from built-in types (e.g. lists or
142 files)?
143 6.9. Q. Why must 'self' be declared and used explicitly in method
144 definitions and calls?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000145
146 7. Using Python on non-UNIX platforms
Guido van Rossum91f60831994-02-15 15:52:27 +0000147 7.1. Q. Is there a Mac version of Python?
148 7.2. Q. Is there a DOS version of Python?
149 7.3. Q. Is there a Windows version of Python?
150 7.4. Q. Is there a Windows NT version of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000151 7.5. Q. Is there an OS/2 version of Python?
152 7.6. Q. I have the PC version but it appears to be only a binary.
153 Where's the library?
154 7.7. Q. Where's the documentation for the Mac or PC version?
155 7.8. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +0000156 creating or editing programs apart from entering it interactively, and
157 there seems to be no way to save code that was entered interactively.
158 How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000159
160To find a particular question, search for the question number followed
161by a dot, a space, and a Q at the beginning of a line (e.g. to find
162question 4.2 in vi, type /^4\.2\. Q/).
163
164
1651. General information and availability
166=======================================
167
1681.1. Q. What is Python?
169
170A. Python is an interpreted, interactive, object-oriented programming
171language. It incorporates modules, exceptions, dynamic typing, very
172high level dynamic data types, and classes. Python combines
173remarkable power with very clear syntax. It has interfaces to many
174system calls and libraries, as well as to various window systems, and
175is extensible in C or C++. It is also usable as an extension language
176for applications that need a programmable interface. Finally, Python
177is portable: it runs on many brands of UNIX, on the Mac, and on
178MS-DOS.
179
180To find out more, the best thing to do is to start reading the
181tutorial from the documentation set (see a few questions further
182down).
183
1841.2. Q. Why is it called Python?
185
186A. Apart from being a computer wizard, I'm also a fan of "Monty
187Python's Flying Circus" (a BBC comedy series from the seventies, in
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000188the -- unlikely -- case you didn't know). It occurred to me one day
189that I needed a name that was short, unique, and slightly mysterious.
190And I happened to be reading some scripts from the series at the
191time... So then I decided to call my language Python. But Python is
192not a joke. And don't you associate it with dangerous reptiles
193either!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000194
1951.3. Q. How do I obtain a copy of the Python source?
196
197A. The latest Python source distribution is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000198anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000199/pub/python, with filename python<version>.tar.gz. (Old versions may
200have an extension of .Z, indicating use of "compress" compression.)
201It is a gzip'ed tar file containing the complete C source, LaTeX
202documentation, Python library modules, example programs, and several
203useful pieces of freely distributable software. This will compile and
Guido van Rossum3de27361994-07-25 14:19:33 +0000204run out of the box on most UNIX platforms. (See section 7 for
205non-UNIX information.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000206
2071.4. Q. How do I get documentation on Python?
208
209A. The latest Python documentation set is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000210anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000211/pub/python, with filename pythondoc-ps<version>.tar.gz. It is a
212gzip'ed tar file containing PostScript files of the reference manual,
Guido van Rossum3de27361994-07-25 14:19:33 +0000213the library manual, and the tutorial. Note that the library manual is
214the most important one of the set, as much of Python's power stems
215from the standard or built-in types, functions and modules, all of
216which are described here. PostScript for a high-level description of
217Python is in the file nluug-paper.ps.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000218
Guido van Rossumc50158e1994-05-31 09:18:50 +00002191.5. Q. Are there other ftp sites that mirror the Python distribution?
220
221A. The following sites keep mirrors of the Python distribution:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000222
223Site IP address Directory
224
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000225gatekeeper.dec.com 16.1.0.2 /pub/plan/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000226ftp.uu.net 192.48.96.9 /languages/python
227ftp.wustl.edu 128.252.135.4 /graphics/graphics/sgi-stuff/python
Guido van Rossumc50158e1994-05-31 09:18:50 +0000228ftp.funet.fi 128.214.6.100 /pub/languages/python
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000229ftp.fu-berlin.de 130.133.4.50 /pub/unix/languages/python (*python* only)
Guido van Rossumc50158e1994-05-31 09:18:50 +0000230ftp.sunet.se 130.238.127.3 /pub/lang/python
Guido van Rossumea2c6f71994-07-14 12:35:14 +0000231unix.hensa.ac.uk 129.12.43.16 /uunet/languages/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000232
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000233Or try archie on e.g. python1.0 to locate the nearest copy of that
234version...
Guido van Rossuma7925f11994-01-26 10:20:16 +0000235
Guido van Rossumc50158e1994-05-31 09:18:50 +00002361.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000237
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000238A. There is a newsgroup, comp.lang.python, and a mailing list. The
239newsgroup and mailing list are gatewayed into each other -- if you can
240read news it is not necessary to subscribe to the mailing list. Send
241e-mail to python-list-request@cwi.nl to (un)subscribe to the mailing
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000242list. Once you're on, send e-mail tp python-list@cwi.nl to send mail
243to the entire mailing list and newsgroup.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000244
Guido van Rossumc50158e1994-05-31 09:18:50 +00002451.7. Q. Is there a book on Python, or will there be one out soon?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000246
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000247A. Unfortunately, not yet. Mark Lutz and I are planning to write one,
248but we are still a in very preliminary stage. If you would like to
249beat us at it and get rich from book royalties, go ahead!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000250
Guido van Rossumc50158e1994-05-31 09:18:50 +00002511.8. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000252
253A. So far the only refereed and published article that describes
254Python in some detail is:
255
256 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
257 Servers Using the Python Programming Language", CWI Quarterly, Volume
258 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
259
260LaTeX source for this paper is available as part of the Python source
261distribution.
262
263A more recent high-level description of Python is:
264
265 Guido van Rossum, "An Introduction to Python for UNIX/C
266 Programmers", in the proceedings of the NLUUG najaarsconferentie
267 1993 (dutch UNIX users group meeting november 1993).
268
269PostScript for this paper and for the slides used for the accompanying
270presentation can be found in the ftp directory mentioned a few
271questions earlier, with filenames nluug-paper.ps and nluug-slides.ps,
272respectively.
273
Guido van Rossumc50158e1994-05-31 09:18:50 +00002741.9. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000275
276A. Python versions are numbered A.B.C. A is the major version number
277-- it is only incremented for major changes in functionality or source
278structure. B is the minor version number, incremented for less
279earth-shattering changes to a release. C is the patchlevel -- it is
280incremented for each new release. Note that in the past, patches have
281added significant changes; in fact the changeover from 0.9.9 to 1.0.0
282was the first time that either A or B changed!
283
Guido van Rossumc50158e1994-05-31 09:18:50 +00002841.10. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000285
286A. An interesting ftp site for Python users is ftp.markv.com
287(192.122.251.1); the directory pub/python contains a growing
288collection of interesting Python scripts. To submit a script for
289inclusion, place it together with a readme file (with extension
290.readme) in the publicly writable directory /incoming/python. This
291service is maintained by Lance Ellinghouse <lance@markv.com>.
292
Guido van Rossum7ce61c11994-06-13 15:13:56 +00002931.11. Q. Are there copyright restrictions on the use of Python?
294
295A. Hardly. You can do anything you want with the source, as long as
296you leave the copyrights in, display those copyrights in any
297documentation about Python that you produce, don't use the author's
298institute's name in publicity without prior written permission, and
299don't hold them responsible for anything (read the actual copyright
300for a precise legal wording).
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000301
Guido van Rossuma7925f11994-01-26 10:20:16 +0000302
3032. Python in the real world
304===========================
305
3062.1. Q. How many people are using Python?
307
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000308A. I don't know, but the maximum number of simultaneous subscriptions
309to the Python mailing list before it was gatewayed into the newsgroup
310was about 180 (several of which were local redistribution lists). I
311believe that many active Python users don't bother to subscribe to the
312list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000313is even less meaningful. I see new names on the newsgroup all the
314time and my best guess is that there are currently at least several
315thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000316
3172.2. Q. Have any significant projects been done in Python?
318
319A. Here at CWI (the home of Python), we have written a 20,000 line
320authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00003215,000 line multimedia teleconferencing tool, as well as many many
322smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000323
324The University of Virginia uses Python to control a virtual reality
325engine. Contact: Matt Conway <conway@virginia.edu>.
326
327See also the next question.
328
3292.3. Q. Are there any commercial projects going on using Python?
330
331A. Several companies have revealed to me that they are planning or
332considering to use Python in a future product. The furthest is
333Sunrise Software, who already have a product out using Python -- they
334use Python for a GUI management application and an SNMP network
335manangement application. Contact: <info@sunrise.com>.
336
337Individuals at many other companies are using Python for
338internal development (witness their contributions to the Python
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000339mailing list or newsgroup).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000340
341Python has also been elected as an extension language by MADE, a
342consortium supported by the European Committee's ESPRIT program and
343consisting of Bull, CWI and some other European companies. Contact:
344Ivan Herman <ivan@cwi.nl>.
345
Guido van Rossum95f61a71994-01-26 17:23:37 +00003462.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000347
Guido van Rossum3de27361994-07-25 14:19:33 +0000348A. Very stable. While the current version number would suggest it is
349in the early stages of development, in fact new, stable releases
350(numbered 0.9.x and 1.0.x) have been coming out roughly every 3 to 6
Guido van Rossum95f61a71994-01-26 17:23:37 +0000351months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000352
Guido van Rossum95f61a71994-01-26 17:23:37 +00003532.5. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000354
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000355A. A proposal is being worked out to change the semantics of operator
356overloading (__add__, __mul__ etc.) to make them more useful for
357implementing types that don't resemble numbers. Additions will be
358__call__ (to call an instance as if it were a function) and __eq__,
359_lt__ etc. (to override individual comparisons). A (new) pthreads
360interface has been submitted which will be integrated in the next
361release. The X11/Motif interface will be improved. There are ideas
362about built-in help using strings placed into function objects, and
363possibly a switch statement.
364
365There will be better ports to the Mac, DOS, Windows, Windows NT, and
366OS/2. The Windows ports will support dynalically loaded modules using
367DLLs. The Mac port may also support dynamic loading of modules.
368There may be a Windows version of STDWIN.
369
370Also planned is improved support for embedding Python in other
371applications, e.g. by renaming most global symbols to have a "Py"
372prefix and providing more documentation and threading support.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000373
Guido van Rossum3de27361994-07-25 14:19:33 +00003742.6. Q. Is it reasonable to propose incompatible changes to Python?
375
376A. In general, no. There are already millions of lines of Python code
377around the world, so any changes in the language that invalidates more
378than a very small fraction of existing programs has to be frowned
379upon. Even if you can provide a conversion program, there still is
380the problem of updating all documentation. Providing a gradual
381upgrade path is the only way if a feature has to be changed.
382
Guido van Rossuma7925f11994-01-26 10:20:16 +0000383
3843. Building Python
385==================
386
Guido van Rossum91f60831994-02-15 15:52:27 +00003873.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000388
389A. Yes, simply do "import testall" (or "import autotest" if you aren't
390interested in the output). The standard modules whose name begins
391with "test" together comprise the test. The test set doesn't test
392*all* features of Python but it goes a long way to confirm that a new
393port is actually working. The Makefile contains an entry "make test"
394which runs the autotest module.
395
Guido van Rossum91f60831994-02-15 15:52:27 +00003963.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000397operations, but when playing with floating point operations I cannot
398find anything wrong with them.
399
400A. The test set makes occasional unwarranted assumptions about the
401semantics of C floating point operations. Until someone donates a
402better floating point test set, you will have to comment out the
403offending floating point tests and execute similar tests manually.
404
Guido van Rossum91f60831994-02-15 15:52:27 +00004053.3. Q. Link errors building Python with STDWIN on SGI IRIX.
Guido van Rossum24349991994-02-02 14:12:45 +0000406
407A. Rebuild STDWIN, specifying "CC=cc -cckr" in the Makefile.
408
Guido van Rossum91f60831994-02-15 15:52:27 +00004093.4. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000410
411A. It is generally necessary to run "make clean" after a configuration
412change.
413
Guido van Rossum91f60831994-02-15 15:52:27 +00004143.5. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000415script (after the script name).
416
417A. You are probably linking with GNU getopt, e.g. through -liberty.
418Don't. (If you are using this because you link with -lreadline, use
419the readline distributed with Python instead.)
420
Guido van Rossum91f60831994-02-15 15:52:27 +00004213.6. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000422glmodule.c, but python hasn't been built or installed yet.
423
424A. Comment out the line mentioning glmodule.c in Setup and build a
425python without gl first; install it or make sure it is in your $PATH,
426then edit the Setup file again to turn on the gl module, and make
427again. You don't need to do "make clean"; you do need to run "make
428Makefile" in the Modules subdirectory (or just run "make" at the
429toplevel).
430
Guido van Rossum3de27361994-07-25 14:19:33 +00004313.7. Q. Python built with gcc for the DEC Alpha doesn't work.
432
433People have reported problems with both gcc 2.5.8 and 2.6.0. The DEC
434OSF/1 cc compiler does not have these problems so it's probably gcc's
435fault. One person reported that the problem went away when using -g
436instead of -O so this may be an option if you insist on using gcc. If
437someone tracks it down more completely I'd like to hear about it!
438
4393.8. Q. Other trouble building Python on platform X.
Guido van Rossum95f61a71994-01-26 17:23:37 +0000440
441A. Please email the details to <guido@cwi.nl> and I'll look into it.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000442
443
4444. Programming in Python
445========================
446
Guido van Rossum24349991994-02-02 14:12:45 +00004474.1. Q. Is there a source code level debugger with breakpoints, step,
448etc.?
449
450A. Yes. Check out module pdb; pdb.help() prints the documentation (or
451you can read it as Lib/pdb.doc). If you use the STDWIN option,
452there's also a windowing interface, wdb. You can write your own
453debugger by using the code for pdb or wdb as an example.
454
4554.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000456C and others in Python (e.g. through inheritance)? (Also phrased as:
457Can I use a built-in type as base class?)
458
459A. No, but you can easily create a Python class which serves as a
460wrapper around a built-in object, e.g. (for dictionaries):
461
462 # A user-defined class behaving almost identical
463 # to a built-in dictionary.
464 class UserDict:
465 def __init__(self): self.data = {}
466 def __repr__(self): return repr(self.data)
467 def __cmp__(self, dict):
468 if type(dict) == type(self.data):
469 return cmp(self.data, dict)
470 else:
471 return cmp(self.data, dict.data)
472 def __len__(self): return len(self.data)
473 def __getitem__(self, key): return self.data[key]
474 def __setitem__(self, key, item): self.data[key] = item
475 def __delitem__(self, key): del self.data[key]
476 def keys(self): return self.data.keys()
477 def items(self): return self.data.items()
478 def values(self): return self.data.values()
479 def has_key(self, key): return self.data.has_key(key)
480
Guido van Rossum24349991994-02-02 14:12:45 +00004814.3. Q. Is there a curses/termcap package for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000482
483A. No, but you can use the "alfa" (== character cell) version of
484STDWIN. (STDWIN == Standard Windows, a portable windowing system
Guido van Rossum91f60831994-02-15 15:52:27 +0000485interface by the same author, URL: ftp://ftp.cwi.nl/pub/stdwin.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000486This will also prepare your program for porting to windowing
487environments such as X11 or the Macintosh.
488
Guido van Rossum24349991994-02-02 14:12:45 +00004894.4. Q. Is there an equivalent to C's onexit() in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000490
491A. Yes, if you import sys and assign a function to sys.exitfunc, it
492will be called when your program exits, is killed by an unhandled
493exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
494
Guido van Rossum24349991994-02-02 14:12:45 +00004954.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000496nested function seemingly can't access the local variables of the
497outer function. What is going on? How do I pass local data to a
498nested function?
499
500A. Python does not have arbitrarily nested scopes. When you need to
501create a function that needs to access some data which you have
502available locally, create a new class to hold the data and return a
503method of an instance of that class, e.g.:
504
505 class MultiplierClass:
506 def __init__(self, factor):
507 self.factor = factor
508 def multiplier(self, argument):
509 return argument * self.factor
510
511 def generate_multiplier(factor):
512 return MultiplierClass(factor).multiplier
513
514 twice = generate_multiplier(2)
515 print twice(10)
516 # Output: 20
517
Guido van Rossum24349991994-02-02 14:12:45 +00005184.6. Q. How do I iterate over a sequence in reverse order?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000519
520A. If it is a list, the fastest solution is
521
522 list.reverse()
523 try:
524 for x in list:
525 "do something with x"
526 finally:
527 list.reverse()
528
529This has the disadvantage that while you are in the loop, the list
530is temporarily reversed. If you don't like this, you can make a copy.
531This appears expensive but is actually faster than other solutions:
532
533 rev = list[:]
534 rev.reverse()
535 for x in rev:
536 <do something with x>
537
538If it isn't a list, a more general but slower solution is:
539
540 i = len(list)
541 while i > 0:
542 i = i-1
543 x = list[i]
544 <do something with x>
545
546A more elegant solution, is to define a class which acts as a sequence
547and yields the elements in reverse order (solution due to Steve
548Majewski):
549
550 class Rev:
551 def __init__(self, seq):
552 self.forw = seq
553 def __len__(self):
554 return len(self.forw)
555 def __getitem__(self, i):
556 return self.forw[-(i + 1)]
557
558You can now simply write:
559
560 for x in Rev(list):
561 <do something with x>
562
563Unfortunately, this solution is slowest of all, due the the method
564call overhead...
565
Guido van Rossum24349991994-02-02 14:12:45 +00005664.7. Q. My program is too slow. How do I speed it up?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000567
568A. That's a tough one, in general. There are many tricks to speed up
569Python code; I would consider rewriting parts in C only as a last
570resort. One thing to notice is that function and (especially) method
571calls are rather expensive; if you have designed a purely OO interface
572with lots of tiny functions that don't do much more than get or set an
573instance variable or call another method, you may consider using a
574more direct way, e.g. directly accessing instance variables. Also see
575the standard module "profile" (described in the file
576"python/lib/profile.doc") which makes it possible to find out where
577your program is spending most of its time (if you have some patience
578-- the profiling itself can slow your program down by an order of
579magnitude).
580
Guido van Rossum24349991994-02-02 14:12:45 +00005814.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000582again (into the same Python process), the changes don't seem to take
583place. What is going on?
584
585A. For efficiency reasons, Python only reads the module file on the
586first time a module is imported (otherwise a program consisting of
587many modules, each of which imports the same basic module, would read
588the basic module over and over again). To force a changed module
589being read again, do this:
590
591 import modname
592 reload(modname)
593
594Warning: this technique is not 100% fool-proof. In particular,
595modules containing statements like
596
597 from modname import some_objects
598
599will continue to work with the old version of the objects imported
600thus.
601
Guido van Rossum24349991994-02-02 14:12:45 +00006024.9. Q. I have a module in which I want to execute some extra code when it
603is run as a script. How do I find out whether I am running as a
604script?
605
606A. A module can find out its own module name by alooking at the
607(predefined) global variable __name__. If this has the value
608'__main__' you are running as a script. E.g. if you put the following
609on the last line of your module, main() is called only when your
610module is running as a script:
611
612 if __name__ == '__main__': main()
613
Guido van Rossum7ce61c11994-06-13 15:13:56 +00006144.10. Q. I try to run a program from the Demo directory but it fails with
615ImportError: No module named ...; what gives?
616
617A. This is probably an optional module which hasn't been configured on
618your system. This especially happens with modules like "stdwin",
619"gl", "Xt" or "Xm". For stdwin and many other modules, see
620Modules/Setup.in for info on how to add these modules to your Python,
621if it is possible at all. Sometimes you will have to ftp and build
622another package first (e.g. stdwin). Sometimes the module only works
623on specific platforms (e.g. gl only works on SGI machines). For
624X-related modules (Xt and Xm) you will have to do more work: they are
625currently not part of the standard Python distribution. You will have
626to ftp the file "extensions.tar.gz" file from a Python ftp repository
627(e.g. ftp.cwi.nl) and follow the instructions there. Note: the X
628related modules are still somewhat flakey, so don't try this unless
629you know a bit or two about building X applications on your platform.
630
6314.11. Q. What GUI toolkits exist for Python?
632
633A. Depending on what platform(s) you are aiming at, there are several.
634
635- The standard Python distribution comes with an interface to STDWIN,
636a platform-independent low-level windowing interface (you have to ftp
637the source for stdwin separately, e.g. from ftp.cwi.nl in pub/stdwin
638or gatekeeper.dec.com in pub/misc/stdwin). STDWIN runs under X11 or
639the Mac; a Windows port is about to be released.
640
641- For SGI only, there's an interface to the complete GL (Graphics
642Library -- low level but very good 3D capabilities) as well as to
643FORMS (a buttons-and-sliders-etc package built on top of GL by Mark
644Overmars -- ftp'able from ftp.cs.ruu.nl in pub/SGI/FORMS).
645
646- There's an interface to X11, including the Athena and Motif widget
647sets (and a few individual widgets, like Mosaic's HTML widget and
648SGI's GL widget) in the Extensions set, which is separately ftp'able
649from ftp.cwi.nl as pub/python/extensions.tar.gz.
650
651- There's an interface to SUIT, the U of Virginia's Simple User
652Interface Toolkit; it can be ftp'ed from uvacs.cs.virginia.edu as
653pub/suit/python/SUIT_python.tar.Z. A PC binary of Python 1.0.2
654compiled with DJGPP and with SUIT support built-in has been made
655available by Antonio Costa on ftp site asterix.inescn.pt, directory
656pub/PC/python, file pyt102su.exe (a self-extracting archive).
657
658- There's a neat interface to the Tcl/Tk widget set; ftp it from
659ftp.cwi.nl as pub/python/tkinter.tar.gz.
660
661- There's an interface to WAFE, a Tcl interface to the X11 Motif and
662Athena widget sets. Last I heard about it it was included in the
663WAFE 1.0 prerelease, ftp'able from ftp.wu-wien.ac.at as
664pub/src/X11/wafe/wafe-1.0.tar.gz-prerelease.
665
6664.12. Q. Are there any interfaces to commercial database in Python?
667
668A. There's an interface to SYBASE by John Redford
669<jredford@lehman.com>.
670
671There's also an interface to metalbase by Lance Ellinghouse
672<lance@markv.com>.
673
Guido van Rossuma7925f11994-01-26 10:20:16 +0000674
6755. Extending Python
676===================
677
6785.1. Q. Can I create my own functions in C?
679
680A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +0000681variables, exceptions and even new types in C. This is explained in
682the document "Extending and Embedding the Python Interpreter" (the
683LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000684
6855.2. Q. Can I create my own functions in C++?
686
687A. Yes, using the C-compatibility features found in C++. Basically
688you place extern "C" { ... } around the Python include files and put
689extern "C" before each function that is going to be called by the
690Python interpreter. Global or static C++ objects with constructors
691are probably not a good idea.
692
Guido van Rossum7ce61c11994-06-13 15:13:56 +00006935.3. Q. How can I execute arbitrary Python statements from C?
694
695A. The highest-level function to do this is run_command() which takes
696a single string argument which is executed in the context of module
697__main__ and returns 0 for success and -1 when an exception occurred
698(including SyntaxError). If you want more control, use run_string();
699see the source for run_command() in Python/pythonrun.c.
700
7015.4. Q. How can I evaluate an arbitrary Python expression from C?
702
703A. Call the function run_string() from the previous question with the
704start symbol eval_input; it then parses an expression, evaluates it
705and returns its value. See exec_eval() in Python/bltinmodule.c.
706
7075.5. Q. How do I extract C values from a Python object?
708
709A. That depends on the object's type. If it's a tuple,
710gettuplesize(o) returns its length and gettupleitem(o, i) returns its
711i'th item; similar for lists with getlistsize(o) and getlistitem(o,
712i). For strings, getstringsize(o) returns its length and
713getstringvalue(o) a pointer to its value (note that Python strings may
714contain null bytes so strlen() is not safe). To test which type an
715object is, first make sure it isn't NULL, and then use
716is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
717
7185.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
719
720A. You can't. Use t = newtupleobject(n) instead, and fill it with
721objects using settupleitem(t, i, o) -- note that this "eats" a
722reference count of o. Similar for lists with newlistobject(n) and
723setlistitem(l, i, o).
724
Guido van Rossuma7925f11994-01-26 10:20:16 +0000725
7266. Python's design
727==================
728
7296.1. Q. Why isn't there a generic copying operation for objects in
730Python?
731
732A. Hmm. Maybe there should be one, but it's difficult to assign a
733useful meaning to copying of open files, sockets and windows, or
734recursive data structures. As long as you design all your classes
735yourself you are of course free to define a standard base class that
736defines an overridable copying operation for all the objects you care
737about. (One practical point: it would have to be a built-in function,
738not a standard method name, since not all built-in object types have
739methods; e.g. strings, integers and tuples don't.)
740
7416.2. Q. Why isn't there a generic way to implement persistent objects
742in Python? (Persistent == automatically saved to and restored from
743disk.)
744
745A. Hmm, hmm. Basically for the same reasons as why there is no
746generic copying operation.
747
7486.3. Q. Why isn't there a switch or case statement in Python?
749
750A. You can do this easily enough with a sequence of
751if... elif... elif... else. There have been some proposals for switch
752statement syntax, but there is no concensus (yet) on whether and how
753to do range tests.
754
Guido van Rossumc50158e1994-05-31 09:18:50 +00007556.4. Q. Why does Python use indentation for grouping of statements?
756
757A. Basically I believe that using indentation for grouping is
758extremely elegant and contributes a lot to the clarity of the average
759Python program. Most people learn to love this feature after a while.
760Some arguments for it:
761
762- Since there are no begin/end brackets there cannot be a disagreement
763between grouping perceived by the parser and the human reader. I
764remember long ago seeing a C fragment like this:
765
766 if (x <= y)
767 x++;
768 y--;
769 z++;
770
771and staring a long time at it wondering why y was being decremented
772even for x > y... (And I wasn't a C newbie then either.)
773
774- Since there are no begin/end brackets there can be no conflicting
775coding styles. In C there are loads of different ways to place the
776braces (including the choice whether to place braces around single
777statements in certain cases, for consistency). If you're used to
778reading (and writing) code that uses one style, you will feel at least
779slightly uneasy when reading (or being required to write) another
780style.
781
782- Many coding styles place begin/end brackets on a line by themself.
783This makes programs considerably longer and wastes valuable screen
784space, making it harder to get a good overview over a program.
785Ideally, a function should fit on one basic tty screen (say, 20
786lines). 20 lines of Python are worth a LOT more than 20 lines of C.
787This is not solely due to the lack of begin/end brackets (the lack of
788declarations also helps, and the powerful operations of course), but
789it certainly helps!
790
Guido van Rossum3de27361994-07-25 14:19:33 +00007916.5. Q. Why are Python strings immutable?
792
793A. There are two advantages. One is performance: knowing that a
794string is immutable makes it easy to lay it out at construction time
795-- fixed and unchanging storage requirements. (This is also one of
796the reasons for the the distinction between tuples and lists.) The
797other is that strings in Python are considered as "elemental" as
798numbers. No amount of activity will change the value 8 to anything
799else, and in Python, no amount of activity will change the string
800"eight" to anything else. (Adapted from Jim Roskind)
801
8026.6. Q. Why don't strings have methods like index() or sort(), like
803lists?
804
805A. Good question. Strings currently don't have methods at all
806(likewise tuples and numbers). Long ago, it seemed unnecessary to
807implement any of these functions in C, so a standard library module
808"string" written in Python was created that performs string related
809operations. Since then, the cry for performance has moved most of
810them into the built-in module strop (this is imported by module
811string, which is still the perferred interface, without loss of
812performance except during initialization). Some of these functions
813(e.g. index()) could easily be implemented as string methods instead,
814but others (e.g. sort()) can't, since their interface prescribes that
815they modify the object, while strings are immutable (see the previous
816question).
817
8186.7. Q. Why does Python use methods for some functionality
819(e.g. list.index()) but functions for other (e.g. len(list))?
820
821A. Functions are used for those operations that are generic for a
822group of types and which should work even for objects that don't have
823methods at all (e.g. numbers, strings, tuples). Also, implementing
824len(), max(), min() as a built-in function is actually less code than
825implementing them as methods for each type. One can quibble about
826individual cases but it's really too late to change such things
827fundamentally now.
828
8296.8. Q. Why can't I derive a class from built-in types (e.g. lists or
830files)?
831
832A. This is caused by the relatively late addition of (user-defined)
833classes to the language -- the implementation framework doesn't easily
834allow it. See the answer to question 4.2 for a work-around. This
835*may* be fixed in the (distant) future.
836
8376.9. Q. Why must 'self' be declared and used explicitly in method
838definitions and calls?
839
840A. By asking this question you reveal your C++ background. :-)
841When I added classes, this was (again) the simplest way of
842implementing methods without too many changes to the interpreter. I
843borrowed the idea from Modula-3. It turns out to be very useful, for
844a variety of reasons.
845
846First, it makes it more obvious that you are using a method or
847instance attribute instead of a local variable. Reading "self.x" or
848"self.meth()" makes it absolutely clear that an instance variable or
849method is used even if you don't know the class definition by heart.
850In C++, you can sort of tell by the lack of a local variable
851declaration (assuming globals are rare or reasily recognizable) -- but
852in Python, there are no local variable declarations, so you'd have to
853look up the class definition to be sure.
854
855Second, it means that no special syntax is necessary if you want to
856explicitly reference or call the method from a particular class. In
857C++, if you want to use a method from base class that is overridden in
858a derived class, you have to use the :: operator -- in Python you can
859write baseclass.methodname(self, <argument list>). This is
860particularly useful for __init__() methods, and in general in cases
861where a derived class method wants to extend the base class method of
862the same name and thus has to call the base class method somehow.
863
864Lastly, for instance variables, it solves a syntactic problem with
865assignment: since local variables in Python are (by definition!) those
866variables to which a value assigned in a function body (and that
867aren't explicitly declared global), there has to be some way to tell
868the interpreter that an assignment was meant to assign to an instance
869variable instead of to a local variable, and it should preferably be
870syntactic (for efficiency reasons). C++ does this through
871declarations, but Python doesn't have declarations and it would be a
872pity having to introduce them just for this purpose. Using the
873explicit "self.var" solves this nicely. Similarly, for using instance
874variables, having to write "self.var" means that references to
875unqualified names inside a method don't have to search the instance's
876directories.
877
Guido van Rossuma7925f11994-01-26 10:20:16 +0000878
8797. Using Python on non-UNIX platforms
880=====================================
881
Guido van Rossum91f60831994-02-15 15:52:27 +00008827.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000883
Guido van Rossum91f60831994-02-15 15:52:27 +0000884A. Yes. It is on most ftp sites carrying Python as python.sea.hqx --
885this is a self-extracting archive containing the application binary as
886well as the Lib modules.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000887
Guido van Rossum91f60831994-02-15 15:52:27 +00008887.2. Q. Is there a DOS version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000889
Guido van Rossum91f60831994-02-15 15:52:27 +0000890A. Yes. More than one, actually: 16python.exe runs in standard DOS
891mode on 186 CPUs or higher; 32python.exe uses a DOS extender and only
892runs on a 386 or higher CPUs. Although 16python.exe does not pass the
893test set because test_grammar is too big for the parser, it actually
894has about 270 kbyte of allocatable heap space, which is sufficient for
895fairly large programs. 32python.exe is distributed as a tar file
896containing the required DOS extended and 387 emulator. Both are on
897most ftp sites carrying Python.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000898
Guido van Rossum91f60831994-02-15 15:52:27 +00008997.3. Q. Is there a Windows version of Python?
900
901A. Yes. Use qwpython.exe. The only problem with it: ^C
902unconditionally kills the entire program -- it does not raise
903KeyboardInterrupt. You can also run 16python.exe or 32python.exe in a
904"DOS box", but qwpython.exe appears to be slightly faster.
905
9067.4. Q. Is there a Windows NT version of Python?
907
908A. Yes. Use ntpython.exe. This is for Intel CPUs. If you want a
909Windows user interface, use qwpython.exe.
910
Guido van Rossum7ce61c11994-06-13 15:13:56 +00009117.5. Q. Is there an OS/2 version of Python?
912
913A. Yes. You can ftp it (from ftp.cwi.nl in pub/python, or from the
914mirror sites) as pyth_os2.zip. This contains both an executable and
915Makefiles for those fortunate enough to have a C compiler.
916
9177.6. Q. I have the PC version but it appears to be only a binary.
918Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000919
920A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +0000921"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossum3de27361994-07-25 14:19:33 +0000922you can get the file pythonlib<version>.tar.gz from most ftp sites
923carrying Python; this is a subset of the distribution containing just
924those file.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000925
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000926Once you have installed the library, you need to point sys.path to it.
927Assuming the library is in C:\misc\python\lib, the following commands
928will point your Python interpreter to it (note the doubled backslashes
929-- you can also use single forward slashes instead):
930
931 >>> import sys
932 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
933 >>>
934
935For a more permanent effect, set the environment variable PYTHONPATH,
936as follows (talking to a DOS prompt):
937
938 C> SET PYTHONPATH=C:\misc\python\lib
939
Guido van Rossum7ce61c11994-06-13 15:13:56 +00009407.7. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000941
942A. There isn't any. The documentation for the Unix version also
Guido van Rossum91f60831994-02-15 15:52:27 +0000943applies to the Mac and PC versions. Where applicable, differences
Guido van Rossuma7925f11994-01-26 10:20:16 +0000944are indicated in the text.
945
Guido van Rossum7ce61c11994-06-13 15:13:56 +00009467.8. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +0000947creating or editing programs apart from entering it interactively, and
948there seems to be no way to save code that was entered interactively.
949How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000950
Guido van Rossum91f60831994-02-15 15:52:27 +0000951A. Use an external editor. On the Mac, I am quite happy with the Desk
952Accessory called Sigma Edit; this doesn't require Multifinder or
953System 7. I work like this: start the interpreter; edit a module file
954using Sigma Edit; import and test it in the interpreter; edit again in
955Sigma Edit; then use the built-in function reload() to re-read the
956imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000957
958Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
959anyone with a pulse could certainly figure out how to do the same on
960MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
961Not only can you easily resave and "reload()" from Python after making
962changes, but since WinNot auto-copies to the clipboard any text you
963select, you can simply select the entire procedure (function) which
964you changed in WinNot, switch to QWPython, and shift-ins to reenter
965the changed program unit."