blob: a385863ffc2df156705f109149ea48fd48da89a7 [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 Rossum7ce61c11994-06-13 15:13:56 +00009Version: 1.9
10Last-modified: 8 June 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
35rtfm.mit.edu [18.70.0.209] in the directory pub/usenet/news.answers.
36The 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 Rossuma7925f11994-01-26 10:20:16 +000079
80 3. Building Python
Guido van Rossum91f60831994-02-15 15:52:27 +000081 3.1. Q. Is there a test set?
82 3.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +000083 operations, but when playing with floating point operations I cannot
84 find anything wrong with them.
Guido van Rossum91f60831994-02-15 15:52:27 +000085 3.3. Q. Link errors building Python with STDWIN on SGI IRIX.
86 3.4. Q. Link errors after rerunning the configure script.
87 3.5. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +000088 script (after the script name).
Guido van Rossum91f60831994-02-15 15:52:27 +000089 3.6. Q. When building on the SGI, make tries to run python to create
Guido van Rossum5333c5d1994-04-11 11:06:22 +000090 glmodule.c, but python hasn't been built or installed yet.
Guido van Rossum44b4cb11994-05-04 13:28:51 +000091 3.7. Q. Other trouble building Python 1.0.2 on platform X.
Guido van Rossuma7925f11994-01-26 10:20:16 +000092
93 4. Programming in Python
Guido van Rossum24349991994-02-02 14:12:45 +000094 4.1. Q. Is there a source code level debugger with breakpoints, step,
95 etc.?
96 4.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +000097 C and others in Python (e.g. through inheritance)? (Also phrased as:
98 Can I use a built-in type as base class?)
Guido van Rossum24349991994-02-02 14:12:45 +000099 4.3. Q. Is there a curses/termcap package for Python?
100 4.4. Q. Is there an equivalent to C's onexit() in Python?
101 4.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000102 nested function seemingly can't access the local variables of the
103 outer function. What is going on? How do I pass local data to a
104 nested function?
Guido van Rossum24349991994-02-02 14:12:45 +0000105 4.6. Q. How do I iterate over a sequence in reverse order?
106 4.7. Q. My program is too slow. How do I speed it up?
107 4.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000108 again (into the same Python process), the changes don't seem to take
109 place. What is going on?
Guido van Rossum24349991994-02-02 14:12:45 +0000110 4.9. Q. I have a module in which I want to execute some extra code when it
111 is run as a script. How do I find out whether I am running as a
112 script?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000113 4.10. Q. I try to run a program from the Demo directory but it fails with
114 ImportError: No module named ...; what gives?
115 4.11. Q. What GUI toolkits exist for Python?
116 4.12. Q. Are there any interfaces to commercial database in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000117
118 5. Extending Python
119 5.1. Q. Can I create my own functions in C?
120 5.2. Q. Can I create my own functions in C++?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000121 5.3. Q. How can I execute arbitrary Python statements from C?
122 5.4. Q. How can I evaluate an arbitrary Python expression from C?
123 5.5. Q. How do I extract C values from a Python object?
124 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000125
126 6. Python's design
127 6.1. Q. Why isn't there a generic copying operation for objects in
128 Python?
129 6.2. Q. Why isn't there a generic way to implement persistent objects
130 in Python? (Persistent == automatically saved to and restored from
131 disk.)
132 6.3. Q. Why isn't there a switch or case statement in Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +0000133 6.4. Q. Why does Python use indentation for grouping of statements?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000134
135 7. Using Python on non-UNIX platforms
Guido van Rossum91f60831994-02-15 15:52:27 +0000136 7.1. Q. Is there a Mac version of Python?
137 7.2. Q. Is there a DOS version of Python?
138 7.3. Q. Is there a Windows version of Python?
139 7.4. Q. Is there a Windows NT version of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000140 7.5. Q. Is there an OS/2 version of Python?
141 7.6. Q. I have the PC version but it appears to be only a binary.
142 Where's the library?
143 7.7. Q. Where's the documentation for the Mac or PC version?
144 7.8. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +0000145 creating or editing programs apart from entering it interactively, and
146 there seems to be no way to save code that was entered interactively.
147 How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000148
149To find a particular question, search for the question number followed
150by a dot, a space, and a Q at the beginning of a line (e.g. to find
151question 4.2 in vi, type /^4\.2\. Q/).
152
153
1541. General information and availability
155=======================================
156
1571.1. Q. What is Python?
158
159A. Python is an interpreted, interactive, object-oriented programming
160language. It incorporates modules, exceptions, dynamic typing, very
161high level dynamic data types, and classes. Python combines
162remarkable power with very clear syntax. It has interfaces to many
163system calls and libraries, as well as to various window systems, and
164is extensible in C or C++. It is also usable as an extension language
165for applications that need a programmable interface. Finally, Python
166is portable: it runs on many brands of UNIX, on the Mac, and on
167MS-DOS.
168
169To find out more, the best thing to do is to start reading the
170tutorial from the documentation set (see a few questions further
171down).
172
1731.2. Q. Why is it called Python?
174
175A. Apart from being a computer wizard, I'm also a fan of "Monty
176Python's Flying Circus" (a BBC comedy series from the seventies, in
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000177the -- unlikely -- case you didn't know). It occurred to me one day
178that I needed a name that was short, unique, and slightly mysterious.
179And I happened to be reading some scripts from the series at the
180time... So then I decided to call my language Python. But Python is
181not a joke. And don't you associate it with dangerous reptiles
182either!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000183
1841.3. Q. How do I obtain a copy of the Python source?
185
186A. The latest Python source distribution is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000187anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000188/pub/python, with filename python<version>.tar.gz. (Old versions may
189have an extension of .Z, indicating use of "compress" compression.)
190It is a gzip'ed tar file containing the complete C source, LaTeX
191documentation, Python library modules, example programs, and several
192useful pieces of freely distributable software. This will compile and
193run out of the box on most UNIX platforms. At the time of writing,
194<version> is 1.0.2. (See section 7 for non-UNIX information.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000195
1961.4. Q. How do I get documentation on Python?
197
198A. The latest Python documentation set is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000199anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000200/pub/python, with filename pythondoc-ps<version>.tar.gz. It is a
201gzip'ed tar file containing PostScript files of the reference manual,
202the library manual, and the tutorial. At the time of writing
203<version> is 1.0.2. Note that the library manual is the most
204important one of the set, as much of Python's power stems from the
205standard or built-in types, functions and modules, all of which are
206described here. PostScript for a high-level description of Python is
207in the file nluug-paper.ps.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000208
Guido van Rossumc50158e1994-05-31 09:18:50 +00002091.5. Q. Are there other ftp sites that mirror the Python distribution?
210
211A. The following sites keep mirrors of the Python distribution:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000212
213Site IP address Directory
214
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000215gatekeeper.dec.com 16.1.0.2 /pub/plan/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000216ftp.uu.net 192.48.96.9 /languages/python
217ftp.wustl.edu 128.252.135.4 /graphics/graphics/sgi-stuff/python
Guido van Rossumc50158e1994-05-31 09:18:50 +0000218ftp.funet.fi 128.214.6.100 /pub/languages/python
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000219ftp.fu-berlin.de 130.133.4.50 /pub/unix/languages/python (*python* only)
Guido van Rossumc50158e1994-05-31 09:18:50 +0000220ftp.sunet.se 130.238.127.3 /pub/lang/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000221
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000222Or try archie on e.g. python1.0 to locate the nearest copy of that
223version...
Guido van Rossuma7925f11994-01-26 10:20:16 +0000224
Guido van Rossumc50158e1994-05-31 09:18:50 +00002251.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000226
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000227A. There is a newsgroup, comp.lang.python, and a mailing list. The
228newsgroup and mailing list are gatewayed into each other -- if you can
229read news it is not necessary to subscribe to the mailing list. Send
230e-mail to python-list-request@cwi.nl to (un)subscribe to the mailing
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000231list. Once you're on, send e-mail tp python-list@cwi.nl to send mail
232to the entire mailing list and newsgroup.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000233
Guido van Rossumc50158e1994-05-31 09:18:50 +00002341.7. Q. Is there a book on Python, or will there be one out soon?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000235
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000236A. Unfortunately, not yet. Mark Lutz and I are planning to write one,
237but we are still a in very preliminary stage. If you would like to
238beat us at it and get rich from book royalties, go ahead!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000239
Guido van Rossumc50158e1994-05-31 09:18:50 +00002401.8. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000241
242A. So far the only refereed and published article that describes
243Python in some detail is:
244
245 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
246 Servers Using the Python Programming Language", CWI Quarterly, Volume
247 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
248
249LaTeX source for this paper is available as part of the Python source
250distribution.
251
252A more recent high-level description of Python is:
253
254 Guido van Rossum, "An Introduction to Python for UNIX/C
255 Programmers", in the proceedings of the NLUUG najaarsconferentie
256 1993 (dutch UNIX users group meeting november 1993).
257
258PostScript for this paper and for the slides used for the accompanying
259presentation can be found in the ftp directory mentioned a few
260questions earlier, with filenames nluug-paper.ps and nluug-slides.ps,
261respectively.
262
Guido van Rossumc50158e1994-05-31 09:18:50 +00002631.9. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000264
265A. Python versions are numbered A.B.C. A is the major version number
266-- it is only incremented for major changes in functionality or source
267structure. B is the minor version number, incremented for less
268earth-shattering changes to a release. C is the patchlevel -- it is
269incremented for each new release. Note that in the past, patches have
270added significant changes; in fact the changeover from 0.9.9 to 1.0.0
271was the first time that either A or B changed!
272
Guido van Rossumc50158e1994-05-31 09:18:50 +00002731.10. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000274
275A. An interesting ftp site for Python users is ftp.markv.com
276(192.122.251.1); the directory pub/python contains a growing
277collection of interesting Python scripts. To submit a script for
278inclusion, place it together with a readme file (with extension
279.readme) in the publicly writable directory /incoming/python. This
280service is maintained by Lance Ellinghouse <lance@markv.com>.
281
Guido van Rossum7ce61c11994-06-13 15:13:56 +00002821.11. Q. Are there copyright restrictions on the use of Python?
283
284A. Hardly. You can do anything you want with the source, as long as
285you leave the copyrights in, display those copyrights in any
286documentation about Python that you produce, don't use the author's
287institute's name in publicity without prior written permission, and
288don't hold them responsible for anything (read the actual copyright
289for a precise legal wording).
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000290
Guido van Rossuma7925f11994-01-26 10:20:16 +0000291
2922. Python in the real world
293===========================
294
2952.1. Q. How many people are using Python?
296
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000297A. I don't know, but the maximum number of simultaneous subscriptions
298to the Python mailing list before it was gatewayed into the newsgroup
299was about 180 (several of which were local redistribution lists). I
300believe that many active Python users don't bother to subscribe to the
301list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000302is even less meaningful. I see new names on the newsgroup all the
303time and my best guess is that there are currently at least several
304thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000305
3062.2. Q. Have any significant projects been done in Python?
307
308A. Here at CWI (the home of Python), we have written a 20,000 line
309authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00003105,000 line multimedia teleconferencing tool, as well as many many
311smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000312
313The University of Virginia uses Python to control a virtual reality
314engine. Contact: Matt Conway <conway@virginia.edu>.
315
316See also the next question.
317
3182.3. Q. Are there any commercial projects going on using Python?
319
320A. Several companies have revealed to me that they are planning or
321considering to use Python in a future product. The furthest is
322Sunrise Software, who already have a product out using Python -- they
323use Python for a GUI management application and an SNMP network
324manangement application. Contact: <info@sunrise.com>.
325
326Individuals at many other companies are using Python for
327internal development (witness their contributions to the Python
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000328mailing list or newsgroup).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000329
330Python has also been elected as an extension language by MADE, a
331consortium supported by the European Committee's ESPRIT program and
332consisting of Bull, CWI and some other European companies. Contact:
333Ivan Herman <ivan@cwi.nl>.
334
Guido van Rossum95f61a71994-01-26 17:23:37 +00003352.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000336
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000337A. Very stable. While the current version number (1.0.2) would
Guido van Rossuma7925f11994-01-26 10:20:16 +0000338suggest it is in the early stages of development, in fact new, stable
Guido van Rossum95f61a71994-01-26 17:23:37 +0000339releases (numbered 0.9.x) have been coming out roughly every 3 to 6
340months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000341
Guido van Rossum95f61a71994-01-26 17:23:37 +00003422.5. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000343
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000344A. A proposal is being worked out to change the semantics of operator
345overloading (__add__, __mul__ etc.) to make them more useful for
346implementing types that don't resemble numbers. Additions will be
347__call__ (to call an instance as if it were a function) and __eq__,
348_lt__ etc. (to override individual comparisons). A (new) pthreads
349interface has been submitted which will be integrated in the next
350release. The X11/Motif interface will be improved. There are ideas
351about built-in help using strings placed into function objects, and
352possibly a switch statement.
353
354There will be better ports to the Mac, DOS, Windows, Windows NT, and
355OS/2. The Windows ports will support dynalically loaded modules using
356DLLs. The Mac port may also support dynamic loading of modules.
357There may be a Windows version of STDWIN.
358
359Also planned is improved support for embedding Python in other
360applications, e.g. by renaming most global symbols to have a "Py"
361prefix and providing more documentation and threading support.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000362
363
3643. Building Python
365==================
366
Guido van Rossum91f60831994-02-15 15:52:27 +00003673.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000368
369A. Yes, simply do "import testall" (or "import autotest" if you aren't
370interested in the output). The standard modules whose name begins
371with "test" together comprise the test. The test set doesn't test
372*all* features of Python but it goes a long way to confirm that a new
373port is actually working. The Makefile contains an entry "make test"
374which runs the autotest module.
375
Guido van Rossum91f60831994-02-15 15:52:27 +00003763.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000377operations, but when playing with floating point operations I cannot
378find anything wrong with them.
379
380A. The test set makes occasional unwarranted assumptions about the
381semantics of C floating point operations. Until someone donates a
382better floating point test set, you will have to comment out the
383offending floating point tests and execute similar tests manually.
384
Guido van Rossum91f60831994-02-15 15:52:27 +00003853.3. Q. Link errors building Python with STDWIN on SGI IRIX.
Guido van Rossum24349991994-02-02 14:12:45 +0000386
387A. Rebuild STDWIN, specifying "CC=cc -cckr" in the Makefile.
388
Guido van Rossum91f60831994-02-15 15:52:27 +00003893.4. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000390
391A. It is generally necessary to run "make clean" after a configuration
392change.
393
Guido van Rossum91f60831994-02-15 15:52:27 +00003943.5. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000395script (after the script name).
396
397A. You are probably linking with GNU getopt, e.g. through -liberty.
398Don't. (If you are using this because you link with -lreadline, use
399the readline distributed with Python instead.)
400
Guido van Rossum91f60831994-02-15 15:52:27 +00004013.6. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000402glmodule.c, but python hasn't been built or installed yet.
403
404A. Comment out the line mentioning glmodule.c in Setup and build a
405python without gl first; install it or make sure it is in your $PATH,
406then edit the Setup file again to turn on the gl module, and make
407again. You don't need to do "make clean"; you do need to run "make
408Makefile" in the Modules subdirectory (or just run "make" at the
409toplevel).
410
Guido van Rossum44b4cb11994-05-04 13:28:51 +00004113.7. Q. Other trouble building Python 1.0.2 on platform X.
Guido van Rossum95f61a71994-01-26 17:23:37 +0000412
413A. Please email the details to <guido@cwi.nl> and I'll look into it.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000414
415
4164. Programming in Python
417========================
418
Guido van Rossum24349991994-02-02 14:12:45 +00004194.1. Q. Is there a source code level debugger with breakpoints, step,
420etc.?
421
422A. Yes. Check out module pdb; pdb.help() prints the documentation (or
423you can read it as Lib/pdb.doc). If you use the STDWIN option,
424there's also a windowing interface, wdb. You can write your own
425debugger by using the code for pdb or wdb as an example.
426
4274.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000428C and others in Python (e.g. through inheritance)? (Also phrased as:
429Can I use a built-in type as base class?)
430
431A. No, but you can easily create a Python class which serves as a
432wrapper around a built-in object, e.g. (for dictionaries):
433
434 # A user-defined class behaving almost identical
435 # to a built-in dictionary.
436 class UserDict:
437 def __init__(self): self.data = {}
438 def __repr__(self): return repr(self.data)
439 def __cmp__(self, dict):
440 if type(dict) == type(self.data):
441 return cmp(self.data, dict)
442 else:
443 return cmp(self.data, dict.data)
444 def __len__(self): return len(self.data)
445 def __getitem__(self, key): return self.data[key]
446 def __setitem__(self, key, item): self.data[key] = item
447 def __delitem__(self, key): del self.data[key]
448 def keys(self): return self.data.keys()
449 def items(self): return self.data.items()
450 def values(self): return self.data.values()
451 def has_key(self, key): return self.data.has_key(key)
452
Guido van Rossum24349991994-02-02 14:12:45 +00004534.3. Q. Is there a curses/termcap package for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000454
455A. No, but you can use the "alfa" (== character cell) version of
456STDWIN. (STDWIN == Standard Windows, a portable windowing system
Guido van Rossum91f60831994-02-15 15:52:27 +0000457interface by the same author, URL: ftp://ftp.cwi.nl/pub/stdwin.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000458This will also prepare your program for porting to windowing
459environments such as X11 or the Macintosh.
460
Guido van Rossum24349991994-02-02 14:12:45 +00004614.4. Q. Is there an equivalent to C's onexit() in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000462
463A. Yes, if you import sys and assign a function to sys.exitfunc, it
464will be called when your program exits, is killed by an unhandled
465exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
466
Guido van Rossum24349991994-02-02 14:12:45 +00004674.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000468nested function seemingly can't access the local variables of the
469outer function. What is going on? How do I pass local data to a
470nested function?
471
472A. Python does not have arbitrarily nested scopes. When you need to
473create a function that needs to access some data which you have
474available locally, create a new class to hold the data and return a
475method of an instance of that class, e.g.:
476
477 class MultiplierClass:
478 def __init__(self, factor):
479 self.factor = factor
480 def multiplier(self, argument):
481 return argument * self.factor
482
483 def generate_multiplier(factor):
484 return MultiplierClass(factor).multiplier
485
486 twice = generate_multiplier(2)
487 print twice(10)
488 # Output: 20
489
Guido van Rossum24349991994-02-02 14:12:45 +00004904.6. Q. How do I iterate over a sequence in reverse order?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000491
492A. If it is a list, the fastest solution is
493
494 list.reverse()
495 try:
496 for x in list:
497 "do something with x"
498 finally:
499 list.reverse()
500
501This has the disadvantage that while you are in the loop, the list
502is temporarily reversed. If you don't like this, you can make a copy.
503This appears expensive but is actually faster than other solutions:
504
505 rev = list[:]
506 rev.reverse()
507 for x in rev:
508 <do something with x>
509
510If it isn't a list, a more general but slower solution is:
511
512 i = len(list)
513 while i > 0:
514 i = i-1
515 x = list[i]
516 <do something with x>
517
518A more elegant solution, is to define a class which acts as a sequence
519and yields the elements in reverse order (solution due to Steve
520Majewski):
521
522 class Rev:
523 def __init__(self, seq):
524 self.forw = seq
525 def __len__(self):
526 return len(self.forw)
527 def __getitem__(self, i):
528 return self.forw[-(i + 1)]
529
530You can now simply write:
531
532 for x in Rev(list):
533 <do something with x>
534
535Unfortunately, this solution is slowest of all, due the the method
536call overhead...
537
Guido van Rossum24349991994-02-02 14:12:45 +00005384.7. Q. My program is too slow. How do I speed it up?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000539
540A. That's a tough one, in general. There are many tricks to speed up
541Python code; I would consider rewriting parts in C only as a last
542resort. One thing to notice is that function and (especially) method
543calls are rather expensive; if you have designed a purely OO interface
544with lots of tiny functions that don't do much more than get or set an
545instance variable or call another method, you may consider using a
546more direct way, e.g. directly accessing instance variables. Also see
547the standard module "profile" (described in the file
548"python/lib/profile.doc") which makes it possible to find out where
549your program is spending most of its time (if you have some patience
550-- the profiling itself can slow your program down by an order of
551magnitude).
552
Guido van Rossum24349991994-02-02 14:12:45 +00005534.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000554again (into the same Python process), the changes don't seem to take
555place. What is going on?
556
557A. For efficiency reasons, Python only reads the module file on the
558first time a module is imported (otherwise a program consisting of
559many modules, each of which imports the same basic module, would read
560the basic module over and over again). To force a changed module
561being read again, do this:
562
563 import modname
564 reload(modname)
565
566Warning: this technique is not 100% fool-proof. In particular,
567modules containing statements like
568
569 from modname import some_objects
570
571will continue to work with the old version of the objects imported
572thus.
573
Guido van Rossum24349991994-02-02 14:12:45 +00005744.9. Q. I have a module in which I want to execute some extra code when it
575is run as a script. How do I find out whether I am running as a
576script?
577
578A. A module can find out its own module name by alooking at the
579(predefined) global variable __name__. If this has the value
580'__main__' you are running as a script. E.g. if you put the following
581on the last line of your module, main() is called only when your
582module is running as a script:
583
584 if __name__ == '__main__': main()
585
Guido van Rossum7ce61c11994-06-13 15:13:56 +00005864.10. Q. I try to run a program from the Demo directory but it fails with
587ImportError: No module named ...; what gives?
588
589A. This is probably an optional module which hasn't been configured on
590your system. This especially happens with modules like "stdwin",
591"gl", "Xt" or "Xm". For stdwin and many other modules, see
592Modules/Setup.in for info on how to add these modules to your Python,
593if it is possible at all. Sometimes you will have to ftp and build
594another package first (e.g. stdwin). Sometimes the module only works
595on specific platforms (e.g. gl only works on SGI machines). For
596X-related modules (Xt and Xm) you will have to do more work: they are
597currently not part of the standard Python distribution. You will have
598to ftp the file "extensions.tar.gz" file from a Python ftp repository
599(e.g. ftp.cwi.nl) and follow the instructions there. Note: the X
600related modules are still somewhat flakey, so don't try this unless
601you know a bit or two about building X applications on your platform.
602
6034.11. Q. What GUI toolkits exist for Python?
604
605A. Depending on what platform(s) you are aiming at, there are several.
606
607- The standard Python distribution comes with an interface to STDWIN,
608a platform-independent low-level windowing interface (you have to ftp
609the source for stdwin separately, e.g. from ftp.cwi.nl in pub/stdwin
610or gatekeeper.dec.com in pub/misc/stdwin). STDWIN runs under X11 or
611the Mac; a Windows port is about to be released.
612
613- For SGI only, there's an interface to the complete GL (Graphics
614Library -- low level but very good 3D capabilities) as well as to
615FORMS (a buttons-and-sliders-etc package built on top of GL by Mark
616Overmars -- ftp'able from ftp.cs.ruu.nl in pub/SGI/FORMS).
617
618- There's an interface to X11, including the Athena and Motif widget
619sets (and a few individual widgets, like Mosaic's HTML widget and
620SGI's GL widget) in the Extensions set, which is separately ftp'able
621from ftp.cwi.nl as pub/python/extensions.tar.gz.
622
623- There's an interface to SUIT, the U of Virginia's Simple User
624Interface Toolkit; it can be ftp'ed from uvacs.cs.virginia.edu as
625pub/suit/python/SUIT_python.tar.Z. A PC binary of Python 1.0.2
626compiled with DJGPP and with SUIT support built-in has been made
627available by Antonio Costa on ftp site asterix.inescn.pt, directory
628pub/PC/python, file pyt102su.exe (a self-extracting archive).
629
630- There's a neat interface to the Tcl/Tk widget set; ftp it from
631ftp.cwi.nl as pub/python/tkinter.tar.gz.
632
633- There's an interface to WAFE, a Tcl interface to the X11 Motif and
634Athena widget sets. Last I heard about it it was included in the
635WAFE 1.0 prerelease, ftp'able from ftp.wu-wien.ac.at as
636pub/src/X11/wafe/wafe-1.0.tar.gz-prerelease.
637
6384.12. Q. Are there any interfaces to commercial database in Python?
639
640A. There's an interface to SYBASE by John Redford
641<jredford@lehman.com>.
642
643There's also an interface to metalbase by Lance Ellinghouse
644<lance@markv.com>.
645
Guido van Rossuma7925f11994-01-26 10:20:16 +0000646
6475. Extending Python
648===================
649
6505.1. Q. Can I create my own functions in C?
651
652A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +0000653variables, exceptions and even new types in C. This is explained in
654the document "Extending and Embedding the Python Interpreter" (the
655LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000656
6575.2. Q. Can I create my own functions in C++?
658
659A. Yes, using the C-compatibility features found in C++. Basically
660you place extern "C" { ... } around the Python include files and put
661extern "C" before each function that is going to be called by the
662Python interpreter. Global or static C++ objects with constructors
663are probably not a good idea.
664
Guido van Rossum7ce61c11994-06-13 15:13:56 +00006655.3. Q. How can I execute arbitrary Python statements from C?
666
667A. The highest-level function to do this is run_command() which takes
668a single string argument which is executed in the context of module
669__main__ and returns 0 for success and -1 when an exception occurred
670(including SyntaxError). If you want more control, use run_string();
671see the source for run_command() in Python/pythonrun.c.
672
6735.4. Q. How can I evaluate an arbitrary Python expression from C?
674
675A. Call the function run_string() from the previous question with the
676start symbol eval_input; it then parses an expression, evaluates it
677and returns its value. See exec_eval() in Python/bltinmodule.c.
678
6795.5. Q. How do I extract C values from a Python object?
680
681A. That depends on the object's type. If it's a tuple,
682gettuplesize(o) returns its length and gettupleitem(o, i) returns its
683i'th item; similar for lists with getlistsize(o) and getlistitem(o,
684i). For strings, getstringsize(o) returns its length and
685getstringvalue(o) a pointer to its value (note that Python strings may
686contain null bytes so strlen() is not safe). To test which type an
687object is, first make sure it isn't NULL, and then use
688is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
689
6905.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
691
692A. You can't. Use t = newtupleobject(n) instead, and fill it with
693objects using settupleitem(t, i, o) -- note that this "eats" a
694reference count of o. Similar for lists with newlistobject(n) and
695setlistitem(l, i, o).
696
Guido van Rossuma7925f11994-01-26 10:20:16 +0000697
6986. Python's design
699==================
700
7016.1. Q. Why isn't there a generic copying operation for objects in
702Python?
703
704A. Hmm. Maybe there should be one, but it's difficult to assign a
705useful meaning to copying of open files, sockets and windows, or
706recursive data structures. As long as you design all your classes
707yourself you are of course free to define a standard base class that
708defines an overridable copying operation for all the objects you care
709about. (One practical point: it would have to be a built-in function,
710not a standard method name, since not all built-in object types have
711methods; e.g. strings, integers and tuples don't.)
712
7136.2. Q. Why isn't there a generic way to implement persistent objects
714in Python? (Persistent == automatically saved to and restored from
715disk.)
716
717A. Hmm, hmm. Basically for the same reasons as why there is no
718generic copying operation.
719
7206.3. Q. Why isn't there a switch or case statement in Python?
721
722A. You can do this easily enough with a sequence of
723if... elif... elif... else. There have been some proposals for switch
724statement syntax, but there is no concensus (yet) on whether and how
725to do range tests.
726
Guido van Rossumc50158e1994-05-31 09:18:50 +00007276.4. Q. Why does Python use indentation for grouping of statements?
728
729A. Basically I believe that using indentation for grouping is
730extremely elegant and contributes a lot to the clarity of the average
731Python program. Most people learn to love this feature after a while.
732Some arguments for it:
733
734- Since there are no begin/end brackets there cannot be a disagreement
735between grouping perceived by the parser and the human reader. I
736remember long ago seeing a C fragment like this:
737
738 if (x <= y)
739 x++;
740 y--;
741 z++;
742
743and staring a long time at it wondering why y was being decremented
744even for x > y... (And I wasn't a C newbie then either.)
745
746- Since there are no begin/end brackets there can be no conflicting
747coding styles. In C there are loads of different ways to place the
748braces (including the choice whether to place braces around single
749statements in certain cases, for consistency). If you're used to
750reading (and writing) code that uses one style, you will feel at least
751slightly uneasy when reading (or being required to write) another
752style.
753
754- Many coding styles place begin/end brackets on a line by themself.
755This makes programs considerably longer and wastes valuable screen
756space, making it harder to get a good overview over a program.
757Ideally, a function should fit on one basic tty screen (say, 20
758lines). 20 lines of Python are worth a LOT more than 20 lines of C.
759This is not solely due to the lack of begin/end brackets (the lack of
760declarations also helps, and the powerful operations of course), but
761it certainly helps!
762
Guido van Rossuma7925f11994-01-26 10:20:16 +0000763
7647. Using Python on non-UNIX platforms
765=====================================
766
Guido van Rossum91f60831994-02-15 15:52:27 +00007677.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000768
Guido van Rossum91f60831994-02-15 15:52:27 +0000769A. Yes. It is on most ftp sites carrying Python as python.sea.hqx --
770this is a self-extracting archive containing the application binary as
771well as the Lib modules.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000772
Guido van Rossum91f60831994-02-15 15:52:27 +00007737.2. Q. Is there a DOS version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000774
Guido van Rossum91f60831994-02-15 15:52:27 +0000775A. Yes. More than one, actually: 16python.exe runs in standard DOS
776mode on 186 CPUs or higher; 32python.exe uses a DOS extender and only
777runs on a 386 or higher CPUs. Although 16python.exe does not pass the
778test set because test_grammar is too big for the parser, it actually
779has about 270 kbyte of allocatable heap space, which is sufficient for
780fairly large programs. 32python.exe is distributed as a tar file
781containing the required DOS extended and 387 emulator. Both are on
782most ftp sites carrying Python.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000783
Guido van Rossum91f60831994-02-15 15:52:27 +00007847.3. Q. Is there a Windows version of Python?
785
786A. Yes. Use qwpython.exe. The only problem with it: ^C
787unconditionally kills the entire program -- it does not raise
788KeyboardInterrupt. You can also run 16python.exe or 32python.exe in a
789"DOS box", but qwpython.exe appears to be slightly faster.
790
7917.4. Q. Is there a Windows NT version of Python?
792
793A. Yes. Use ntpython.exe. This is for Intel CPUs. If you want a
794Windows user interface, use qwpython.exe.
795
Guido van Rossum7ce61c11994-06-13 15:13:56 +00007967.5. Q. Is there an OS/2 version of Python?
797
798A. Yes. You can ftp it (from ftp.cwi.nl in pub/python, or from the
799mirror sites) as pyth_os2.zip. This contains both an executable and
800Makefiles for those fortunate enough to have a C compiler.
801
8027.6. Q. I have the PC version but it appears to be only a binary.
803Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000804
805A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +0000806"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000807you can get the file pythonlib1.0.2.tar.gz from most ftp sites carrying
Guido van Rossum91f60831994-02-15 15:52:27 +0000808Python; this is a subset of the distribution containing just those
809file.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000810
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000811Once you have installed the library, you need to point sys.path to it.
812Assuming the library is in C:\misc\python\lib, the following commands
813will point your Python interpreter to it (note the doubled backslashes
814-- you can also use single forward slashes instead):
815
816 >>> import sys
817 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
818 >>>
819
820For a more permanent effect, set the environment variable PYTHONPATH,
821as follows (talking to a DOS prompt):
822
823 C> SET PYTHONPATH=C:\misc\python\lib
824
Guido van Rossum7ce61c11994-06-13 15:13:56 +00008257.7. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000826
827A. There isn't any. The documentation for the Unix version also
Guido van Rossum91f60831994-02-15 15:52:27 +0000828applies to the Mac and PC versions. Where applicable, differences
Guido van Rossuma7925f11994-01-26 10:20:16 +0000829are indicated in the text.
830
Guido van Rossum7ce61c11994-06-13 15:13:56 +00008317.8. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +0000832creating or editing programs apart from entering it interactively, and
833there seems to be no way to save code that was entered interactively.
834How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000835
Guido van Rossum91f60831994-02-15 15:52:27 +0000836A. Use an external editor. On the Mac, I am quite happy with the Desk
837Accessory called Sigma Edit; this doesn't require Multifinder or
838System 7. I work like this: start the interpreter; edit a module file
839using Sigma Edit; import and test it in the interpreter; edit again in
840Sigma Edit; then use the built-in function reload() to re-read the
841imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000842
843Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
844anyone with a pulse could certainly figure out how to do the same on
845MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
846Not only can you easily resave and "reload()" from Python after making
847changes, but since WinNot auto-copies to the clipboard any text you
848select, you can simply select the entire procedure (function) which
849you changed in WinNot, switch to QWPython, and shift-ins to reenter
850the changed program unit."