blob: 89f34462f9741325c73c37e6c878669fcbdbef0e [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)
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00006Expires: Sat, 1 Apr 1995 00:00:00 GMT
7Supersedes: <D1sGoJ.Mps@cwi.nl>
Guido van Rossuma7925f11994-01-26 10:20:16 +00008Approved: news-answers-request@MIT.Edu
9
10Archive-name: python-faq/part1
Guido van Rossum07779351995-02-07 16:59:56 +000011Submitted-by: Guido van Rossum <guido@cwi.nl>
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +000012Version: 1.20++
13Last-modified: 16 Februari 1995
Guido van Rossuma7925f11994-01-26 10:20:16 +000014
15This article contains answers to Frequently Asked Questions about
16Python (an object-oriented interpreted programming language -- see
17the answer to question 1.1 for a short overview).
18
Guido van Rossuma6c707c1995-01-02 17:32:28 +000019Copyright 1993-1995 Guido van Rossum. Unchanged electronic
Guido van Rossuma7925f11994-01-26 10:20:16 +000020redistribution of this FAQ is allowed. Printed redistribution only
21with permission of the author. No warranties.
22
23Author's address:
Guido van Rossuma6c707c1995-01-02 17:32:28 +000024 Guido van Rossum
25 CWI, dept. CST
26 Kruislaan 413
27 P.O. Box 94079
28 1090 GB Amsterdam
29 The Netherlands
Guido van Rossum796b2591995-01-20 23:05:52 +000030Email: <guido@cwi.nl>
Guido van Rossuma7925f11994-01-26 10:20:16 +000031
32The latest version of this FAQ is available by anonymous ftp from
Guido van Rossuma6c707c1995-01-02 17:32:28 +000033<URL:ftp://ftp.cwi.nl/pub/python/python-FAQ>. It will also be posted
34regularly to the newsgroups comp.answers <URL:news:comp.answers> and
35comp.lang.python <URL:news:comp.lang.python>.
Guido van Rossuma7925f11994-01-26 10:20:16 +000036
Guido van Rossuma6c707c1995-01-02 17:32:28 +000037Many FAQs, including this one, are available by anonymous ftp
38<URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/>. The name under
39which a FAQ is archived appears in the Archive-name line at the top of
40the article. This FAQ is archived as python-faq/part1
41<URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/python-faq/part1>.
Guido van Rossuma7925f11994-01-26 10:20:16 +000042
43There's a mail server on that machine which will send you files from
44the archive by e-mail if you have no ftp access. You send a e-mail
Guido van Rossuma6c707c1995-01-02 17:32:28 +000045message to <mail-server@rtfm.mit.edu> containing the single word help
46in the message body to receive instructions.
Guido van Rossuma7925f11994-01-26 10:20:16 +000047
48This FAQ is divided in the following chapters:
49
50 1. General information and availability
51 2. Python in the real world
52 3. Building Python
53 4. Programming in Python
54 5. Extending Python
55 6. Python's design
56 7. Using Python on non-UNIX platforms
57
58To find the start of a particular chapter, search for the chapter number
59followed by a dot and a space at the beginning of a line (e.g. to
60find chapter 4 in vi, type /^4\. /).
61
62Here's an overview of the questions per chapter:
63
64 1. General information and availability
65 1.1. Q. What is Python?
66 1.2. Q. Why is it called Python?
67 1.3. Q. How do I obtain a copy of the Python source?
68 1.4. Q. How do I get documentation on Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +000069 1.5. Q. Are there other ftp sites that mirror the Python distribution?
70 1.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma6c707c1995-01-02 17:32:28 +000071 1.7. Q. Is there a WWW page devoted to Python?
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +000072 1.8. Q. Is the Python documentation available on the WWW?
73 1.9. Q. Is there a book on Python, or will there be one out soon?
74 1.10. Q. Are there any published articles about Python that I can quote?
75 1.11. Q. Are there short introductory papers or talks on Python?
76 1.12. Q. How does the Python version numbering scheme work?
77 1.13. Q. How do I get a beta test version of Python?
78 1.14. Q. Are there other ftp sites that carry Python related material?
79 1.15. Q. Are there copyright restrictions on the use of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +000080
81 2. Python in the real world
82 2.1. Q. How many people are using Python?
83 2.2. Q. Have any significant projects been done in Python?
84 2.3. Q. Are there any commercial projects going on using Python?
Guido van Rossum95f61a71994-01-26 17:23:37 +000085 2.4. Q. How stable is Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000086 2.5. Q. When will the next version be released?
87 2.6. Q. What new developments are expected for Python in the future?
88 2.7. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +000089
90 3. Building Python
Guido van Rossum91f60831994-02-15 15:52:27 +000091 3.1. Q. Is there a test set?
92 3.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +000093 operations, but when playing with floating point operations I cannot
94 find anything wrong with them.
Guido van Rossum9351fdb1994-11-10 23:03:51 +000095 3.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
96 3.4. Q. Link errors building Python with STDWIN 0.9.9.
97 3.5. Q. Link errors after rerunning the configure script.
98 3.6. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +000099 script (after the script name).
Guido van Rossum9351fdb1994-11-10 23:03:51 +0000100 3.7. Q. When building on the SGI, make tries to run python to create
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000101 glmodule.c, but python hasn't been built or installed yet.
Guido van Rossum9351fdb1994-11-10 23:03:51 +0000102 3.8. Q. Python built with gcc for the DEC Alpha doesn't work.
103 3.9. Q. I use VPATH but some targets are built in the source directory.
104 3.10. Q. Trouble building or linking with the GNU readline library.
105 3.11. Q. Trouble building Python on Linux.
106 3.12. Q. Trouble with prototypes on Ultrix.
107 3.13. Q. Trouble with posix.listdir on NeXTSTEP 3.2.
108 3.14. Q. Other trouble building Python on platform X.
Guido van Rossum07779351995-02-07 16:59:56 +0000109 3.15. Q. How to configure dynamic loading on Lixux.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000110
111 4. Programming in Python
Guido van Rossum24349991994-02-02 14:12:45 +0000112 4.1. Q. Is there a source code level debugger with breakpoints, step,
113 etc.?
114 4.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000115 C and others in Python (e.g. through inheritance)? (Also phrased as:
116 Can I use a built-in type as base class?)
Guido van Rossum24349991994-02-02 14:12:45 +0000117 4.3. Q. Is there a curses/termcap package for Python?
118 4.4. Q. Is there an equivalent to C's onexit() in Python?
119 4.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000120 nested function seemingly can't access the local variables of the
121 outer function. What is going on? How do I pass local data to a
122 nested function?
Guido van Rossum24349991994-02-02 14:12:45 +0000123 4.6. Q. How do I iterate over a sequence in reverse order?
124 4.7. Q. My program is too slow. How do I speed it up?
125 4.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000126 again (into the same Python process), the changes don't seem to take
127 place. What is going on?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000128 4.9. Q. How do I find the current module name?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000129 4.10. Q. I have a module in which I want to execute some extra code
130 when it is run as a script. How do I find out whether I am running as
131 a script?
132 4.11. Q. I try to run a program from the Demo directory but it fails
133 with ImportError: No module named ...; what gives?
Guido van Rossum061f1821994-10-06 16:03:45 +0000134 4.12. Q. I have successfully built Python with STDWIN but it can't
135 find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000136 4.13. Q. What GUI toolkits exist for Python?
Guido van Rossum061f1821994-10-06 16:03:45 +0000137 4.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000138 4.15. Q. Is it possible to write obfuscated one-liners in Python?
139 4.16. Q. Is there an equivalent of C's "?:" ternary operator?
140 4.17. Q. My class defines __del__ but it is not called when I delete the
141 object.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000142 4.18. Q. How do I change the shell environment for programs called
143 using os.popen() or os.system()? Changing os.environ doesn't work.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000144 4.19. Q. What is a class?
145 4.20. Q. What is a method?
146 4.21. Q. What is self?
147 4.22. Q. What is a unbound method?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000148 4.23. Q. How do I call a method defined in a base class from a derived
149 class that overrides it?
150 4.24. Q. How do I call a method from a base class without using the
151 name of the base class?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000152 4.25. Q. How can I organize my code to make it easier to change the base
153 class?
154 4.26. Q. How can I find the methods or attributes of an object?
Guido van Rossum061f1821994-10-06 16:03:45 +0000155 4.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
156 4.28. Q. How can I create a stand-alone binary from a Python script?
157 4.29. Q. Is there a special lib for writing CGI scripts in Python?
158 4.30. Q. What other WWW tools are there for Python?
Guido van Rossum796b2591995-01-20 23:05:52 +0000159 4.31. Q. How do I run a subprocess with pipes connected to both input
160 and output?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000161
162 5. Extending Python
163 5.1. Q. Can I create my own functions in C?
164 5.2. Q. Can I create my own functions in C++?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000165 5.3. Q. How can I execute arbitrary Python statements from C?
166 5.4. Q. How can I evaluate an arbitrary Python expression from C?
167 5.5. Q. How do I extract C values from a Python object?
168 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
Guido van Rossum796b2591995-01-20 23:05:52 +0000169 5.7. Q. What happened to mktuple(), featured in an example in the
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000170 Extensions manual?
171 5.8. Q. How do I call an object's method from C?
172 5.9. Q. How do I catch the output from print_error()?
173 5.10. Q. How do I access a module written in Python from C?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000174
175 6. Python's design
176 6.1. Q. Why isn't there a generic copying operation for objects in
177 Python?
178 6.2. Q. Why isn't there a generic way to implement persistent objects
179 in Python? (Persistent == automatically saved to and restored from
180 disk.)
181 6.3. Q. Why isn't there a switch or case statement in Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +0000182 6.4. Q. Why does Python use indentation for grouping of statements?
Guido van Rossum3de27361994-07-25 14:19:33 +0000183 6.5. Q. Why are Python strings immutable?
184 6.6. Q. Why don't strings have methods like index() or sort(), like
185 lists?
186 6.7. Q. Why does Python use methods for some functionality
187 (e.g. list.index()) but functions for other (e.g. len(list))?
188 6.8. Q. Why can't I derive a class from built-in types (e.g. lists or
189 files)?
190 6.9. Q. Why must 'self' be declared and used explicitly in method
191 definitions and calls?
Guido van Rossum061f1821994-10-06 16:03:45 +0000192 6.10. Q. Can't you emulate threads in the interpreter instead of
193 relying on an OS-specific thread implementation?
194 6.11. Q. Why can't lambda forms contain statements?
195 6.12. Q. Why is there no more efficient way of iterating over a dictionary
196 than first constructing the list of keys()?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000197
198 7. Using Python on non-UNIX platforms
Guido van Rossum91f60831994-02-15 15:52:27 +0000199 7.1. Q. Is there a Mac version of Python?
200 7.2. Q. Is there a DOS version of Python?
201 7.3. Q. Is there a Windows version of Python?
202 7.4. Q. Is there a Windows NT version of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000203 7.5. Q. Is there an OS/2 version of Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000204 7.6. Q. Is there a VMS version of Python?
205 7.7. Q. What about IBM mainframes, or other esoteric non-UNIX
206 platforms?
207 7.8. Q. Where are the source or Makefiles for the non-UNIX versions?
208 7.9. Q. What is the status and support for the non-UNIX versions?
209 7.10. Q. I have the PC version but it appears to be only a binary.
210 Where's the library?
211 7.11. Q. Where's the documentation for the Mac or PC version?
212 7.12. Q. The Mac (PC) version doesn't seem to have any facilities for
213 creating or editing programs apart from entering it interactively, and
214 there seems to be no way to save code that was entered interactively.
215 How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000216
217To find a particular question, search for the question number followed
218by a dot, a space, and a Q at the beginning of a line (e.g. to find
219question 4.2 in vi, type /^4\.2\. Q/).
220
221
2221. General information and availability
223=======================================
224
2251.1. Q. What is Python?
226
227A. Python is an interpreted, interactive, object-oriented programming
228language. It incorporates modules, exceptions, dynamic typing, very
229high level dynamic data types, and classes. Python combines
230remarkable power with very clear syntax. It has interfaces to many
231system calls and libraries, as well as to various window systems, and
232is extensible in C or C++. It is also usable as an extension language
233for applications that need a programmable interface. Finally, Python
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000234is portable: it runs on many brands of UNIX, on the Mac, and on PCs
235under MS-DOS, Windows, Windows NT, and OS/2.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000236
237To find out more, the best thing to do is to start reading the
238tutorial from the documentation set (see a few questions further
239down).
240
2411.2. Q. Why is it called Python?
242
Guido van Rossum796b2591995-01-20 23:05:52 +0000243A. Apart from being a computer scientist, I'm also a fan of "Monty
Guido van Rossuma7925f11994-01-26 10:20:16 +0000244Python's Flying Circus" (a BBC comedy series from the seventies, in
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000245the -- unlikely -- case you didn't know). It occurred to me one day
246that I needed a name that was short, unique, and slightly mysterious.
247And I happened to be reading some scripts from the series at the
248time... So then I decided to call my language Python. But Python is
249not a joke. And don't you associate it with dangerous reptiles
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000250either! (If you need an icon, use an image of the 16-ton weight from
251the TV series or of a can of SPAM :-)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000252
2531.3. Q. How do I obtain a copy of the Python source?
254
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000255A. The latest complete Python source distribution is always available
256by anonymous ftp, e.g.
257<URL:ftp://ftp.cwi.nl/pub/python/python1.1.tar.gz>. It is a gzipped
258tar file containing the complete C source, LaTeX documentation, Python
259library modules, example programs, and several useful pieces of freely
260distributable software. This will compile and run out of the box on
261most UNIX platforms. (See section 7 for non-UNIX information.)
262
263Occasionally a set of patches is issued which has to be applied using
264the patch program. These patches are placed in the same directory,
265e.g. <URL:ftp://ftp.cwi.nl/pub/python/patch1.1.1>.
266
267An index of said ftp directory can be found in the file INDEX. An
268HTML version of the index can be found in the file index.html,
269<URL:ftp://ftp.cwi.nl/pub/python/index.html>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000270
2711.4. Q. How do I get documentation on Python?
272
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000273A. The LaTeX source for the documentation is part of the source
274distribution. If you don't have LaTeX, the latest Python
275documentation set is always available by anonymous ftp, e.g.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000276<URL:ftp://ftp.cwi.nl/pub/python/pythondoc-ps1.1.tar.gz>. It is a
277gzipped tar file containing PostScript files of the reference manual,
Guido van Rossum3de27361994-07-25 14:19:33 +0000278the library manual, and the tutorial. Note that the library manual is
279the most important one of the set, as much of Python's power stems
280from the standard or built-in types, functions and modules, all of
281which are described here. PostScript for a high-level description of
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000282Python is in the file nluug-paper.ps (a separate file on the ftp
283site).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000284
Guido van Rossumc50158e1994-05-31 09:18:50 +00002851.5. Q. Are there other ftp sites that mirror the Python distribution?
286
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000287A. The following anonymous ftp sites keep mirrors of the Python
288distribution:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000289
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000290 <URL:ftp://gatekeeper.dec.com/pub/plan/python/>
291 <URL:ftp://ftp.uu.net/languages/python/>
292 <URL:ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/>
293 <URL:ftp://ftp.funet.fi/pub/languages/python/>
294 <URL:ftp://ftp.sunet.se/pub/lang/python/>
295 <URL:ftp://unix.hensa.ac.uk/uunet/languages/python/>
296 <URL:ftp://ftp.sterlng.com/programming/languages/python/>
297 <URL:ftp://ftp.ibp.fr/pub/python/>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000298
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000299Or try archie on the string "python".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000300
Guido van Rossumc50158e1994-05-31 09:18:50 +00003011.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000302
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000303A. There is a newsgroup, comp.lang.python <URL:news:comp.lang.python>,
304and a mailing list. The newsgroup and mailing list are gatewayed into
305each other -- if you can read news it's unnecessary to subscribe to
306the mailing list. Send e-mail to <python-list-request@cwi.nl> to
Guido van Rossum796b2591995-01-20 23:05:52 +0000307(un)subscribe to the mailing list. Hypermail archives of
Guido van Rossum061f1821994-10-06 16:03:45 +0000308(nearly) everything posted to the mailing list (and thus the
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000309newsgroup) are available on our WWW server,
310<URL:http://www.cwi.nl/~guido/hypermail/index.html>. The raw archives
311are also available by ftp, e.g.
312<URL:ftp://ftp.cwi.nl/pub/python/mailinglist.gz>. The uncompressed
313versions of these files can be read with the standard UNIX Mail
314program ("Mail -f file") or with nn ("nn file"). To read them using
315MH, you could use "inc -file file".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000316
Guido van Rossuma6c707c1995-01-02 17:32:28 +00003171.7. Q. Is there a WWW page devoted to Python?
318
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000319A. Yes, <URL:http://www.cwi.nl/~guido/Python.html> is the official
320Python home page. Michael McLay at NIST maintains a Python page at
321<URL:http://www.eeel.nist.gov/python/>. And finally the emerging
322Python Software Association has a preliminary web server at
323<URL:http://www.cminds.com/python/> (eventually to be moved to
324somewhere under python.org).
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000325
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003261.8. Q. Is the Python documentation available on the WWW?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000327
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000328A. Yes, see <URL:http://www.cwi.nl/~guido/Python.html> (Python's home
329page). It contains pointers to hypertext versions of the whole
330documentation set (as hypertext, not just PostScript).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000331
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000332If you wish to browse this collection of HTML files on your own
333machine, it is available bundled up by anonymous ftp,
334e.g. <URL:ftp://ftp.cwi.nl/pub/python/python-html.tar.gz>. (This
335requires some manual patch-up for the references to images,
336unfortunately.)
337
338An Emacs-INFO set containing the library manual is also available by
339ftp, e.g. <URL:ftp://ftp.cwi.nl/pub/python/python-lin-info.tar.gz>.
340
3411.9. Q. Is there a book on Python, or will there be one out soon?
342
343A. I am writing one. Publishers are interested. Optimistically, it
344will be ready for the press by mid-1995. Mark Lutz is working on one
345too -- more details as they emerge.
346
3471.10. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000348
349A. So far the only refereed and published article that describes
350Python in some detail is:
351
352 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
353 Servers Using the Python Programming Language", CWI Quarterly, Volume
354 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
355
356LaTeX source for this paper is available as part of the Python source
357distribution.
358
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003591.11. Q. Are there short introductory papers or talks on Python?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000360
361A. A recent high-level description of Python is:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000362
363 Guido van Rossum, "An Introduction to Python for UNIX/C
364 Programmers", in the proceedings of the NLUUG najaarsconferentie
Guido van Rossum061f1821994-10-06 16:03:45 +0000365 1993 (dutch UNIX users group meeting November 1993).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000366
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000367PostScript for this paper and for the slides used for the accompanying
368presentation is available by ftp as
369<URL:ftp://ftp.cwi.nl/pub/python/nluug-paper.ps> and
370<URL:ftp://ftp.cwi.nl/pub/python/nluug-slides.ps>, respectively.
371
372Slides for a talk on Python that I gave at the Usenix Symposium on
373Very High Level Languages in Santa Fe, NM, USA in October 1995 are
374available as <URL:ftp://ftp.cwi.nl/pub/python/vhll-slides.ps>.
375
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003761.12. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000377
378A. Python versions are numbered A.B.C. A is the major version number
379-- it is only incremented for major changes in functionality or source
380structure. B is the minor version number, incremented for less
381earth-shattering changes to a release. C is the patchlevel -- it is
382incremented for each new release. Note that in the past, patches have
383added significant changes; in fact the changeover from 0.9.9 to 1.0.0
384was the first time that either A or B changed!
385
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000386Beta versions have an additional suffix of "-beta-N" for some small
387number N. Note that (for instance) all versions labeled 1.2-beta-N
388*precede* the actual release of 1.2.
389
3901.13. Q. How do I get a beta test version of Python?
391
392A. Write me. I might like you :-) Seriously, anybody who has
393previously used and installed Python can become a beta tester, but I
394expect feedback, so you have to write me first before I divulge the
395secret location of the latest beta release.
396
3971.14. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000398
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000399A. An interesting ftp site for Python users is ftp.markv.com; the
400directory pub/python contains a growing collection of interesting
401Python scripts <URL:ftp://ftp.markv.com/pub/python/>. To submit a
402script for inclusion, place it together with a readme file (with
403extension .readme) in the publicly writable directory
404/incoming/python. This service is maintained by Lance Ellinghaus
405<lance@markv.com>. (I've heard complaints about this service not
406being very responsive -- try at your own risk.)
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000407
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00004081.15. Q. Are there copyright restrictions on the use of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000409
410A. Hardly. You can do anything you want with the source, as long as
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000411you leave the copyrights in, and display those copyrights in any
412documentation about Python that you produce. Also, don't use the
413author's institute's name in publicity without prior written
414permission, and don't hold them responsible for anything (read the
415actual copyright for a precise legal wording).
416
417In particular, if you honor the copyright rules, it's OK to use Python
418for commercial use, to sell copies of Python in source or binary form,
419or to sell products that enhance Python or incorporate Python (or part
420of it) in some form. I would still like to know about all commercial
421use of Python!
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000422
Guido van Rossuma7925f11994-01-26 10:20:16 +0000423
4242. Python in the real world
425===========================
426
4272.1. Q. How many people are using Python?
428
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000429A. I don't know, but the maximum number of simultaneous subscriptions
430to the Python mailing list before it was gatewayed into the newsgroup
431was about 180 (several of which were local redistribution lists). I
432believe that many active Python users don't bother to subscribe to the
433list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000434is even less meaningful. I see new names on the newsgroup all the
435time and my best guess is that there are currently at least several
436thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000437
4382.2. Q. Have any significant projects been done in Python?
439
440A. Here at CWI (the home of Python), we have written a 20,000 line
441authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00004425,000 line multimedia teleconferencing tool, as well as many many
443smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000444
445The University of Virginia uses Python to control a virtual reality
446engine. Contact: Matt Conway <conway@virginia.edu>.
447
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000448The ILU project at Xerox PARC can generate Python glue for ILU
449interfaces. See <URL:ftp://ftp.parc.xerox.com/pub/ilu/ilu.html>.
450
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000451If you have done a significant project in Python that you'd like to be
452included in the list above, send me email!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000453
4542.3. Q. Are there any commercial projects going on using Python?
455
456A. Several companies have revealed to me that they are planning or
Guido van Rossum796b2591995-01-20 23:05:52 +0000457considering use of Python in a future product.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000458
459The furthest is Sunrise Software, who already have a product out using
460Python -- they use Python for a GUI management application and an SNMP
Guido van Rossum061f1821994-10-06 16:03:45 +0000461network management application. Contact: <info@sunrise.com>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000462
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000463Infoseek uses Python to implement their commercial WWW information
464retrieval service <URL:http://www.infoseek.com/>. Contact:
465<info@infoseek.com>.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000466
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000467Michael Powers of daVinci Time & Space is "writing tons-o-python for
468interactive television entertainment." Contact: <powers@dvts.com>.
469
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000470Paul Everitt of Connecting Minds is planning a Lotus Notes gateway.
471Contact: <Paul.Everitt@cminds.com>. Or see their WWW server
472<URL:http://www.cminds.com/>.
473
Guido van Rossuma7925f11994-01-26 10:20:16 +0000474Individuals at many other companies are using Python for
475internal development (witness their contributions to the Python
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000476mailing list or newsgroup).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000477
478Python has also been elected as an extension language by MADE, a
479consortium supported by the European Committee's ESPRIT program and
480consisting of Bull, CWI and some other European companies. Contact:
481Ivan Herman <ivan@cwi.nl>.
482
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000483If you'd like to be included in the list above, send me email!
484
Guido van Rossum95f61a71994-01-26 17:23:37 +00004852.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000486
Guido van Rossum3de27361994-07-25 14:19:33 +0000487A. Very stable. While the current version number would suggest it is
488in the early stages of development, in fact new, stable releases
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000489(numbered 0.9.x through 1.1.x) have been coming out roughly every 3 to
4906 months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000491
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00004922.5. Q. When will the next version be released?
493
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000494A. I am planning to release 1.2 in February or early March 1995. It
495will contain hooks into the implementation of the import command, a
496(still limited) form of persistent objects, and the usual complement
497of bug fixes (including many fixed memory leaks and thread problems).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000498
4992.6. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000500
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000501A. There will be better ports to the Mac, DOS, Windows, Windows NT, and
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000502OS/2. The Windows ports will support dynamically loaded modules using
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000503DLLs.
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000504
505Also planned is improved support for embedding Python in other
506applications, e.g. by renaming most global symbols to have a "Py"
507prefix and providing more documentation and threading support.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000508
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000509Some proposals were discussed at the recent Python workshop:
510
511 - persistent objects
512
513 - safe execution of untrusted Python code
514
515 - extensions to the import statement for managing packages
516 (groups of related modules)
517
518 - automatic generation of C/C++ interface glue
519
520 - interfaces to OMG IDL (== Interface Definition Language by
521 the Object Management Group)
522
523 - a portable GUI API (Graphical User Interface Application
524 Programmers Interface)
525
526 - module customization tools
527
528 - standardized documentation strings on module, class and
529 function objects
530
531 - the formation of a Python Steering Committee
532
533 - another Python Workshop
534
535For more info, have a look at the WWW page for the last Python
536Workshop <URL:http://www.eeel.nist.gov/python/workshop11-94/>.
537
538
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00005392.7. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossum3de27361994-07-25 14:19:33 +0000540
541A. In general, no. There are already millions of lines of Python code
542around the world, so any changes in the language that invalidates more
543than a very small fraction of existing programs has to be frowned
544upon. Even if you can provide a conversion program, there still is
545the problem of updating all documentation. Providing a gradual
546upgrade path is the only way if a feature has to be changed.
547
Guido van Rossuma7925f11994-01-26 10:20:16 +0000548
5493. Building Python
550==================
551
Guido van Rossum91f60831994-02-15 15:52:27 +00005523.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000553
554A. Yes, simply do "import testall" (or "import autotest" if you aren't
555interested in the output). The standard modules whose name begins
556with "test" together comprise the test. The test set doesn't test
557*all* features of Python but it goes a long way to confirm that a new
558port is actually working. The Makefile contains an entry "make test"
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000559which runs the autotest module. NOTE: if "make test" fails, run the
560tests manually ("import testall") to see what goes wrong before
561reporting the error.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000562
Guido van Rossum91f60831994-02-15 15:52:27 +00005633.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000564operations, but when playing with floating point operations I cannot
565find anything wrong with them.
566
567A. The test set makes occasional unwarranted assumptions about the
568semantics of C floating point operations. Until someone donates a
569better floating point test set, you will have to comment out the
570offending floating point tests and execute similar tests manually.
571
Guido van Rossum061f1821994-10-06 16:03:45 +00005723.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
Guido van Rossum24349991994-02-02 14:12:45 +0000573
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000574A. Get STDWIN 0.9.9 <URL:ftp://ftp.cwi.nl/pub/stdwin/stdwin0.9.9.tar.gz>.
Guido van Rossum061f1821994-10-06 16:03:45 +0000575
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005763.4. Q. Link errors building Python with STDWIN 0.9.9.
Guido van Rossum061f1821994-10-06 16:03:45 +0000577
Guido van Rossum796b2591995-01-20 23:05:52 +0000578A. The linker probably complains that it can't find routines like
579'tecreate', 'tenew' etc. The STDWIN 0.9.9 distribution requires that
580you add TWO libraries from stdwin to the line for stdwin in the
581Setupfile. Use something like this (all on one line!):
Guido van Rossum061f1821994-10-06 16:03:45 +0000582
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000583 stdwin stdwinmodule.c -I$(STDWIN)/H $(STDWIN)/Packs/textedit/libtextedit.a $(STDWIN)/Ports/x11/libstdwin.a -lX11
Guido van Rossum24349991994-02-02 14:12:45 +0000584
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005853.5. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000586
587A. It is generally necessary to run "make clean" after a configuration
588change.
589
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005903.6. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000591script (after the script name).
592
593A. You are probably linking with GNU getopt, e.g. through -liberty.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000594Don't. The reason for the complaint is that GNU getopt, unlike System
595V getopt and other getopt implementations, doesn't consider a
596non-option to be the end of the option list. A quick (and compatible)
597fix for scripts is to add "--" to the interpreter, like this:
598
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000599 #! /usr/local/bin/python --
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000600
601You can also use this interactively:
602
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000603 python -- script.py [options]
604
605Note that a working getopt implementation is provided in the Python
606distribution (in Python/getopt.c) but not automatically used.
Guido van Rossum24349991994-02-02 14:12:45 +0000607
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006083.7. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000609glmodule.c, but python hasn't been built or installed yet.
610
611A. Comment out the line mentioning glmodule.c in Setup and build a
612python without gl first; install it or make sure it is in your $PATH,
613then edit the Setup file again to turn on the gl module, and make
614again. You don't need to do "make clean"; you do need to run "make
615Makefile" in the Modules subdirectory (or just run "make" at the
616toplevel).
617
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006183.8. Q. Python built with gcc for the DEC Alpha doesn't work.
Guido van Rossum3de27361994-07-25 14:19:33 +0000619
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000620People have reported problems with gcc 2.5.8 up to 2.6.3. The DEC
621OSF/1 cc compiler does not have these problems so it's likely a gcc
622bug. The latest news is that (at least in the 1.2 beta release) the
623problem still exists but only when you use -O, and only affects the
624code generated from Python/marshal.c. A fix is to change "long i, n;"
625into "int i, n;" in w_object().
Guido van Rossum3de27361994-07-25 14:19:33 +0000626
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006273.9. Q. I use VPATH but some targets are built in the source directory.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000628
629A. On some systems (e.g. Sun), if the target already exists in the
630source directory, it is created there instead of in the build
631directory. This is usually because you have previously built without
632VPATH. Try running "make clobber" in the source directory.
633
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006343.10. Q. Trouble building or linking with the GNU readline library.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000635
636A. Consider using readline 2.0. From the Python 1.1 README:
637
638- You can use the GNU readline library to improve the interactive user
639interface: this gives you line editing and command history when
Guido van Rossum796b2591995-01-20 23:05:52 +0000640calling python interactively. You need to configure and build the GNU
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000641readline library before running the configure script. Its sources are
642no longer distributed with Python; you can ftp them from any GNU
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000643mirror site, or from its home site
644<URL:ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz> (or a
645higher version number -- using version 1.x is not recommended). Pass
646the Python configure script the option --with-readline=DIRECTORY where
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000647DIRECTORY is the absolute pathname of the directory where you've built
648the readline library. Some hints on building and using the readline
649library:
650
651- On SGI IRIX 5, you may have to add the following
652to rldefs.h:
653
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000654 #ifndef sigmask
655 #define sigmask(sig) (1L << ((sig)-1))
656 #endif
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000657
658- On most systems, you will have to add #include "rldefs.h" to the
659top of several source files, and if you use the VPATH feature, you
660will have to add dependencies of the form foo.o: foo.c to the
661Makefile for several values of foo.
662
663- The readline library requires use of the termcap library. A
664known problem with this is that it contains entry points which
Guido van Rossum061f1821994-10-06 16:03:45 +0000665cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000666conflict can be solved (and will be, in the next release of
Guido van Rossum061f1821994-10-06 16:03:45 +0000667STDWIN) by adding a line saying '#define werase w_erase' to the
668stdwin.h file (in the STDWIN distribution, subdirectory H). The
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000669GL conflict has been solved in the Python configure script by a
670hack that forces use of the static version of the termcap library.
671
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000672- Check the newsgroup gnu.bash.bugs <URL:news:gnu.bash.bugs> for
673specific problems with the readline library (I don't get this group
674here but I've been told that it is the place for readline bugs.)
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000675
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006763.11. Q. Trouble building Python on Linux.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000677
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000678A. In 1.1 and 1.1.1, there's a bug in the reference counting logic of
679ternary pow() which is only tripped by very picky mallocs, like the
680GNU malloc on Linux. This has been fixed in 1.2. To continue the
681tests, just disable the tests of pow() with three arguments from
682Lib/test/test_b2.py.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000683
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000684Apart from this, Python builds and runs fine on most Linux versions.
685Bennet Todd has this to say on the subject:
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000686
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000687 It seems to work for some people but not for others.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000688
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000689 This might depend on which Linux release you're using. Older Linux
690 releases had (understandably) fewer gracious hack to improve Unix
691 compatibility; really old Linux was Posix 1003.1 compatible, without
692 nearly as much Unix compatibility as one might have wished. Current
693 releases of Linux build most current free software, either BSD or
694 System V, with little or no trouble.
695
696 Besides that, there are quite a few different releases currently,
697 including MCC, Slackware, SLS, and Debian, and probably more. The
698 differences between their compilation environments are far smaller
699 than they used to be, but they're still updated with different
700 frequencies. It's likely that the current Slackware works fine, as
701 it currently seems to be the most popular. But that's just a guess.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000702
Guido van Rossum9351fdb1994-11-10 23:03:51 +00007033.12. Q. Trouble with prototypes on Ultrix.
Guido van Rossum72eb83c1994-10-07 11:33:28 +0000704
705A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef
706HAVE_PROTOTYPES.
707
Guido van Rossum9351fdb1994-11-10 23:03:51 +00007083.13. Q. Trouble with posix.listdir on NeXTSTEP 3.2.
709
Guido van Rossum07779351995-02-07 16:59:56 +0000710A. You need to pass "-posix" to the C compiler, especially in the link
711phase -- it uses the correct version of the C library. The easiest
712way is perhaps to do "make OPT=-posix". You also need to remove this
Guido van Rossum796b2591995-01-20 23:05:52 +0000713NeXT-specific section from import.c:
Guido van Rossum9351fdb1994-11-10 23:03:51 +0000714
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000715 #if defined(NeXT) || defined(WITH_RLD)
716 #define DYNAMIC_LINK
717 #define USE_RLD
718 #endif
Guido van Rossum9351fdb1994-11-10 23:03:51 +0000719
7203.14. Q. Other trouble building Python on platform X.
Guido van Rossum95f61a71994-01-26 17:23:37 +0000721
Guido van Rossum796b2591995-01-20 23:05:52 +0000722A. Please email the details to <guido@cwi.nl> and I'll look into it.
723Please provide as many details as possible. In particular, if you
724don't tell me what type of computer and what operating system (and
725version) you are using it will be difficult for me to figure out what
726is the matter. If you get a specific error message, please email it
727to me too.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000728
Guido van Rossum07779351995-02-07 16:59:56 +00007293.15. Q. How to configure dynamic loading on Lixux.
730
731A. (Thanks to Andrew Kuchling):
732
733Linux requires that you use the GNU DLD library. The stages of using
734dynamic libraries on Linux are:
735
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00007361) Get dld 3.2.5 from a Linux site. Be careful here; the most recent
737GNU version is 3.2.3, and doesn't support Linux; be sure to get it
738from a Linux mirror, not a GNU mirror (3.2.4 should also work).
739Compile it and install the library libdld.a somewhere; I used
740/usr/local/lib.
741
742Suitable URLs for the dld distribution are currently:
743<URL:ftp://sunsite.unc.edu/pub/Linux/libs/dld-3.2.5.src.tar.gz> and
744<URL:ftp://tsx-11.mit.edu/pub/linux/sources/libs/dld-3.2.5.src.tar.gz>.
745There's also a binary distribution of it:
746<URL:ftp://sunsite.unc.edu/pub/Linux/libs/dld-3.2.5.bin.tar.gz>.
Guido van Rossum07779351995-02-07 16:59:56 +0000747
7482) Get Jack Jansen's DL library; its location is given in the
749_Extending Python_ manual as ftp://ftp.cwi.nl/pub/dynload/. Compile
750it and install libdl.a wherever you put libdld.a.
751
7523) Run Python's configure script, giving it the --with-dl-dld option,
753which requires a parameter giving the directory where you put the
754libraries.
755
7564) Recompile Python.
757
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000758Note that once ELF is common in the Linux world, it will be much
759easier (probably within a year) -- the standard SVR4-style dlopen()
760interface is then available. This has already proved to work
761perfectly using a beta version of the ELF-capable GCC for Linux.
Guido van Rossum07779351995-02-07 16:59:56 +0000762
Guido van Rossuma7925f11994-01-26 10:20:16 +0000763
7644. Programming in Python
765========================
766
Guido van Rossum24349991994-02-02 14:12:45 +00007674.1. Q. Is there a source code level debugger with breakpoints, step,
768etc.?
769
770A. Yes. Check out module pdb; pdb.help() prints the documentation (or
771you can read it as Lib/pdb.doc). If you use the STDWIN option,
772there's also a windowing interface, wdb. You can write your own
773debugger by using the code for pdb or wdb as an example.
774
7754.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000776C and others in Python (e.g. through inheritance)? (Also phrased as:
777Can I use a built-in type as base class?)
778
779A. No, but you can easily create a Python class which serves as a
780wrapper around a built-in object, e.g. (for dictionaries):
781
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000782 # A user-defined class behaving almost identical
783 # to a built-in dictionary.
784 class UserDict:
785 def __init__(self): self.data = {}
786 def __repr__(self): return repr(self.data)
787 def __cmp__(self, dict):
788 if type(dict) == type(self.data):
789 return cmp(self.data, dict)
790 else:
791 return cmp(self.data, dict.data)
792 def __len__(self): return len(self.data)
793 def __getitem__(self, key): return self.data[key]
794 def __setitem__(self, key, item): self.data[key] = item
795 def __delitem__(self, key): del self.data[key]
796 def keys(self): return self.data.keys()
797 def items(self): return self.data.items()
798 def values(self): return self.data.values()
799 def has_key(self, key): return self.data.has_key(key)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000800
Guido van Rossum24349991994-02-02 14:12:45 +00008014.3. Q. Is there a curses/termcap package for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000802
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000803A. Yes -- Lance Ellinghaus has written a module that interfaces to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000804System V's "ncurses". If you know a little curses and some Python,
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000805it's straightforward to use. It is part of the standard Python
806distribution, but not configured by default -- you must enable it by
807editing Modules/Setup. It requires a System V curses implementation.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000808
809You could also consider using the "alfa" (== character cell) version
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000810of STDWIN. (Standard Window System Interface, a portable windowing
811system interface by myself <URL:ftp://ftp.cwi.nl/pub/stdwin/>.) This
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000812will also prepare your program for porting to windowing environments
813such as X11 or the Macintosh.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000814
Guido van Rossum24349991994-02-02 14:12:45 +00008154.4. Q. Is there an equivalent to C's onexit() in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000816
817A. Yes, if you import sys and assign a function to sys.exitfunc, it
818will be called when your program exits, is killed by an unhandled
819exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
820
Guido van Rossum24349991994-02-02 14:12:45 +00008214.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000822nested function seemingly can't access the local variables of the
823outer function. What is going on? How do I pass local data to a
824nested function?
825
826A. Python does not have arbitrarily nested scopes. When you need to
827create a function that needs to access some data which you have
828available locally, create a new class to hold the data and return a
829method of an instance of that class, e.g.:
830
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000831 class MultiplierClass:
832 def __init__(self, factor):
833 self.factor = factor
834 def multiplier(self, argument):
835 return argument * self.factor
Guido van Rossuma7925f11994-01-26 10:20:16 +0000836
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000837 def generate_multiplier(factor):
838 return MultiplierClass(factor).multiplier
Guido van Rossuma7925f11994-01-26 10:20:16 +0000839
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000840 twice = generate_multiplier(2)
841 print twice(10)
842 # Output: 20
843
844An alternative solution uses default arguments, e.g.:
845
846 def generate_multiplier(factor):
847 def multiplier(arg, fact = factor):
848 return arg*fact
849 return multiplier
850
851 twice = generate_multiplier(2)
852 print twice(10)
853 # Output: 20
Guido van Rossuma7925f11994-01-26 10:20:16 +0000854
Guido van Rossum24349991994-02-02 14:12:45 +00008554.6. Q. How do I iterate over a sequence in reverse order?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000856
857A. If it is a list, the fastest solution is
858
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000859 list.reverse()
860 try:
861 for x in list:
862 "do something with x"
863 finally:
864 list.reverse()
Guido van Rossuma7925f11994-01-26 10:20:16 +0000865
866This has the disadvantage that while you are in the loop, the list
867is temporarily reversed. If you don't like this, you can make a copy.
868This appears expensive but is actually faster than other solutions:
869
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000870 rev = list[:]
871 rev.reverse()
872 for x in rev:
873 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000874
875If it isn't a list, a more general but slower solution is:
876
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000877 i = len(list)
878 while i > 0:
879 i = i-1
880 x = list[i]
881 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000882
883A more elegant solution, is to define a class which acts as a sequence
884and yields the elements in reverse order (solution due to Steve
885Majewski):
886
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000887 class Rev:
888 def __init__(self, seq):
889 self.forw = seq
890 def __len__(self):
891 return len(self.forw)
892 def __getitem__(self, i):
893 return self.forw[-(i + 1)]
Guido van Rossuma7925f11994-01-26 10:20:16 +0000894
895You can now simply write:
896
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000897 for x in Rev(list):
898 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000899
Guido van Rossum061f1821994-10-06 16:03:45 +0000900Unfortunately, this solution is slowest of all, due to the method
Guido van Rossuma7925f11994-01-26 10:20:16 +0000901call overhead...
902
Guido van Rossum24349991994-02-02 14:12:45 +00009034.7. Q. My program is too slow. How do I speed it up?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000904
905A. That's a tough one, in general. There are many tricks to speed up
906Python code; I would consider rewriting parts in C only as a last
907resort. One thing to notice is that function and (especially) method
908calls are rather expensive; if you have designed a purely OO interface
909with lots of tiny functions that don't do much more than get or set an
910instance variable or call another method, you may consider using a
911more direct way, e.g. directly accessing instance variables. Also see
912the standard module "profile" (described in the file
913"python/lib/profile.doc") which makes it possible to find out where
914your program is spending most of its time (if you have some patience
915-- the profiling itself can slow your program down by an order of
916magnitude).
917
Guido van Rossum24349991994-02-02 14:12:45 +00009184.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000919again (into the same Python process), the changes don't seem to take
920place. What is going on?
921
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000922A. For reasons of efficiency as well as consistency, Python only reads
Guido van Rossum796b2591995-01-20 23:05:52 +0000923the module file on the first time a module is imported. (Otherwise a
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000924program consisting of many modules, each of which imports the same
Guido van Rossum796b2591995-01-20 23:05:52 +0000925basic module, would read the basic module over and over again.) To
926force rereading of a changed module, do this:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000927
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000928 import modname
929 reload(modname)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000930
931Warning: this technique is not 100% fool-proof. In particular,
932modules containing statements like
933
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000934 from modname import some_objects
Guido van Rossuma7925f11994-01-26 10:20:16 +0000935
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000936will continue to work with the old version of the imported objects.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000937
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00009384.9. Q. How do I find the current module name?
Guido van Rossum24349991994-02-02 14:12:45 +0000939
Guido van Rossum061f1821994-10-06 16:03:45 +0000940A. A module can find out its own module name by looking at the
Guido van Rossum24349991994-02-02 14:12:45 +0000941(predefined) global variable __name__. If this has the value
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000942'__main__' you are running as a script.
943
Guido van Rossuma6c707c1995-01-02 17:32:28 +00009444.10. Q. I have a module in which I want to execute some extra code
945when it is run as a script. How do I find out whether I am running as
946a script?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000947
948A. See the previous question. E.g. if you put the following on the
949last line of your module, main() is called only when your module is
950running as a script:
Guido van Rossum24349991994-02-02 14:12:45 +0000951
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000952 if __name__ == '__main__': main()
Guido van Rossum24349991994-02-02 14:12:45 +0000953
Guido van Rossuma6c707c1995-01-02 17:32:28 +00009544.11. Q. I try to run a program from the Demo directory but it fails
955with ImportError: No module named ...; what gives?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000956
Guido van Rossum061f1821994-10-06 16:03:45 +0000957A. This is probably an optional module (written in C!) which hasn't
958been configured on your system. This especially happens with modules
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000959like "Tkinter", "stdwin", "gl", "Xt" or "Xm". For Tkinter, STDWIN and
960many other modules, see Modules/Setup.in for info on how to add these
961modules to your Python, if it is possible at all. Sometimes you will
962have to ftp and build another package first (e.g. STDWIN). Sometimes
963the module only works on specific platforms (e.g. gl only works on SGI
964machines).
965
966NOTE: if the complaint is about "Tkinter" (upper case T) and you have
967already configured module "tkinter" (lower case t), the solution is
968*not* to rename tkinter to Tkinter or vice versa. There is probably
Guido van Rossum796b2591995-01-20 23:05:52 +0000969something wrong with your module search path. Check out the value of
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000970sys.path.
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000971
Guido van Rossum061f1821994-10-06 16:03:45 +0000972For X-related modules (Xt and Xm) you will have to do more work: they
973are currently not part of the standard Python distribution. You will
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000974have to ftp the Extensions tar file, e.g.
975<URL:ftp://ftp.cwi.nl/pub/python/extensions.tar.gz> and follow the
976instructions there. Note: the X related modules are still somewhat
977flakey, so don't try this unless you alread know a bit or two about
978building X applications on your platform.
Guido van Rossum061f1821994-10-06 16:03:45 +0000979
980See also the next question.
981
9824.12. Q. I have successfully built Python with STDWIN but it can't
983find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000984
985A. There's a subdirectory of the library directory named 'stdwin'
986which should be in the default module search path. There's a line in
987Modules/Setup(.in) that you have to enable for this purpose --
Guido van Rossum061f1821994-10-06 16:03:45 +0000988unfortunately in the latest release it's not near the other
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000989STDWIN-related lines so it's easy to miss it.
990
9914.13. Q. What GUI toolkits exist for Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000992
993A. Depending on what platform(s) you are aiming at, there are several.
994
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000995- There's a neat object-oriented interface to the Tcl/Tk widget set,
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000996called Tkinter. As of python 1.1, it is part of the standard Python
997distribution -- all you need to do is enable it in Modules/Setup
998(provided you have already installed Tk and Tcl). This is probably
999the easiest to install and use, and the most complete widget set. It
1000is also very likely that in the future the standard Python GUI API
1001will be based on or at least look very much like the Tkinter
1002interface. For more info about Tk, including pointers to the source,
1003see John Ousterhout's home page
Guido van Rossum796b2591995-01-20 23:05:52 +00001004<URL:http://playground.sun.com/~ouster/>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001005
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001006- The standard Python distribution comes with an interface to STDWIN,
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001007a platform-independent low-level windowing interface. You have to ftp
1008the source for STDWIN separately,
1009e.g. <URL:ftp://ftp.cwi.nl/pub/stdwin/> or gatekeeper.dec.com in
1010pub/misc/stdwin <URL:ftp://gatekeeper.dec.com/pub/misc/stdwin/>.
1011STDWIN runs under X11 or the Mac; a Windows port has been attempted
1012but I can't seem to get it working. Note that STDWIN is really not
1013powerful enough to implement a modern GUI (no widgets, etc.) and that
1014I don't have the time to maintain or extend it, so you may be better
1015off using Tkinter or the Motif interface, unless you require
1016portability to the Mac (which is also offered by SUIT, by the way --
1017see below).
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001018
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001019- For SGI IRIX only, there's an interface to the complete GL (Graphics
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001020Library -- low level but very good 3D capabilities) as well as to
1021FORMS (a buttons-and-sliders-etc package built on top of GL by Mark
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001022Overmars -- ftp'able from <URL:ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/>).
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001023
1024- There's an interface to X11, including the Athena and Motif widget
1025sets (and a few individual widgets, like Mosaic's HTML widget and
1026SGI's GL widget) in the Extensions set, which is separately ftp'able
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001027<URL:ftp://ftp.cwi.nl/pub/python/extensions.tar.gz>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001028
1029- There's an interface to SUIT, the U of Virginia's Simple User
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001030Interface Toolkit; it can be ftp'ed from
1031<URL:ftp://uvacs.cs.virginia.edu/pub/suit/python/SUIT_python.tar.Z>.
1032A PC binary of Python 1.0.2 compiled with DJGPP and with SUIT support
1033built-in has been made available by Antonio Costa
1034<URL:ftp://asterix.inescn.pt/pub/PC/python/pyt102su.exe> (a
1035self-extracting archive). Note that the UVa people themselves have
1036expressed doubts about SUIT, and are planning to build a Python GUI
1037API based upon Tk (though not necessarily on Tkinter); see
1038<URL:http://server.cs.virginia.edu/~tnb2d/IT/IT.html>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001039
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001040- There's an interface to WAFE, a Tcl interface to the X11 Motif and
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001041Athena widget sets. Last I heard about it it was included in the WAFE
10421.0 prerelease
1043<URL:ftp://ftp.wu-wien.ac.at/pub/src/X11/wafe/wafe-1.0.tar.gz-prerelease>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001044
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001045- There's an interface to wxWindows. wxWindows is a portable GUI
1046class library written in C++. It supports XView, Motif, MS-Windows as
1047targets. There is some support for Macs and CURSES as well. wxWindows
1048preserves the look and feel of the underlying graphics toolkit. See
1049the wxPython WWW page at
1050<URL:http://www.aiai.ed.ac.uk/~jacs/wx/wxpython/wxpython.html>.
1051
1052- Python has been mentioned on the "Futurism" subpage of the Fresco
1053home page <URL:http://www.faslab.com/fresco/HomePage.html>. "Pesto"
1054is a Python interface to the CORBA dynamic invocation interface, and
1055thus Fresco. A Pesto prototype is running and is currently being
1056packaged up for inclusion in the Fresco snapshot.
1057
Guido van Rossum061f1821994-10-06 16:03:45 +000010584.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001059
1060A. There's an interface to SYBASE by John Redford
1061<jredford@lehman.com>.
1062
Guido van Rossum796b2591995-01-20 23:05:52 +00001063There's an interface to metalbase by Lance Ellinghaus
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001064<lance@markv.com>; it is part of the separate Extensions distribution
1065<URL:ftp://ftp.cwi.nl/pub/python/extensions.tar.gz>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001066
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001067Anthony Baxter <anthony.baxter@aaii.oz.au> has written an interface to
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001068mSQL (mini-SQL). <URL:ftp://ftp.cwi.nl/pub/python/PymSQL.tar.gz>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001069
Guido van Rossum796b2591995-01-20 23:05:52 +00001070Tom Culliton <culliton@clark.net> has written an Oracle module. Write
Guido van Rossum07779351995-02-07 16:59:56 +00001071him to get a copy of the latest version.
Guido van Rossum796b2591995-01-20 23:05:52 +00001072
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000010734.15. Q. Is it possible to write obfuscated one-liners in Python?
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001074
1075A. Yes. See the following three examples, due to Ulf Bartelt:
1076
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001077 # Primes < 1000
1078 print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
1079 map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001080
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001081 # First 10 Fibonacci numbers
1082 print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
1083 range(10))
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001084
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001085 # Mandelbrot set
1086 print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
1087 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
1088 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
1089 i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
1090 >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
1091 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
1092 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
1093 # \___ ___/ \___ ___/ | | |__ lines on screen
1094 # V V | |______ columns on screen
1095 # | | |__________ maximum of "iterations"
1096 # | |_________________ range on y axis
1097 # |____________________________ range on x axis
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001098
1099Don't try this at home, kids!
1100
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000011014.16. Q. Is there an equivalent of C's "?:" ternary operator?
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001102
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001103A. Not directly. In many cases you can mimic a?b:c with "a and b or
1104c", but there's a flaw: if b is zero (or empty, or None -- anything
1105that tests false) then c will be selected instead. In many cases you
1106can prove by looking at the code that this can't happen (e.g. because
1107b is a constant or has a type that can never be false), but in general
1108this can be a problem.
1109
1110Steve Majewski (or was it Tim Peters?) suggested the following
1111solution: (a and [b] or [c])[0]. Because [b] is a singleton list it
1112is never false, so the wrong path is never taken; then applying [0] to
1113the whole thing gets the b or c that you really wanted. Ugly, but it
1114gets you there in the rare cases where it is really inconvenient to
1115rewrite your code using 'if'.
1116
11174.17. Q. My class defines __del__ but it is not called when I delete the
1118object.
1119
1120A. There are several possible reasons for this.
1121
1122- The del statement does not necessarily call __del__ -- it simply
1123decrements the object's reference count, and if this reaches zero
1124__del__ is called.
1125
1126- If your data structures contain circular links (e.g. a tree where
1127each child has a parent pointer and each parent has a list of
1128children) the reference counts will never go back to zero. You'll
Guido van Rossum061f1821994-10-06 16:03:45 +00001129have to define an explicit close() method which removes those
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001130pointers. Please don't ever call __del__ directly -- __del__ should
Guido van Rossum061f1821994-10-06 16:03:45 +00001131call close() and close() should make sure that it can be called more
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001132than once for the same object.
1133
1134- If the object has ever been a local variable (or argument, which is
1135really the same thing) to a function that caught an expression in an
1136except clause, chances are that a reference to the object still exists
1137in that function's stack frame as contained in the stack trace.
1138Normally, deleting (better: assigning None to) sys.exc_traceback will
1139take care of this. If you a stack was printed for an unhandled
1140exception in an interactive interpreter, delete sys.last_traceback
1141instead.
1142
1143- There is code that deletes all objects when the interpreter exits,
1144but if your Python has been configured to support threads, it is not
1145called (because other threads may still be active). You can define
Guido van Rossum061f1821994-10-06 16:03:45 +00001146your own cleanup function using sys.exitfunc (see question 4.4).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001147
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001148- Finally, there are some obscure bugs if your __del__ method does
1149complicated things such as updating dictionaries or lists or
1150references globals. I hope to have fixed these in release 1.2.
1151
11524.18. Q. How do I change the shell environment for programs called
1153using os.popen() or os.system()? Changing os.environ doesn't work.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001154
1155A. Modifying the environment passed to subshells was left out of the
1156interpreter because there seemed to be no well-established portable
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001157way to do it (in particular, some systems, have putenv(), others have
1158setenv(), and some have none at all).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001159
1160However if all you want is to pass environment variables to the
1161commands run by os.system() or os.popen(), there's a simple solution:
1162prefix the command string with a couple of variable assignments and
Guido van Rossum796b2591995-01-20 23:05:52 +00001163export statements. The following would be universal for popen:
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001164
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001165 import os
1166 from commands import mkarg # nifty routine to add shell quoting
1167 def epopen(cmd, mode, env = {}):
1168 # env is a dictionary of environment variables
1169 prefix = ''
Guido van Rossum796b2591995-01-20 23:05:52 +00001170 for key, value in env.items():
1171 prefix = prefix + '%s=%s\n' % (key, mkarg(value)[1:])
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001172 prefix = prefix + 'export %s\n' % key
1173 return os.popen(prefix + cmd, mode)
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001174
11754.19. Q. What is a class?
1176
1177A. A class is the particular object type that is created by executing
Guido van Rossum796b2591995-01-20 23:05:52 +00001178a class statement. Class objects are used as templates, to create
1179class instance objects, which embody both the data structure and
1180program routines specific to a datatype.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001181
11824.20. Q. What is a method?
1183
1184A. A method is a function that you normally call as
Guido van Rossum796b2591995-01-20 23:05:52 +00001185x.name(arguments...) for some object x. The term is used for methods
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001186of classes and class instances as well as for methods of built-in
Guido van Rossum796b2591995-01-20 23:05:52 +00001187objects. (The latter have a completely different implementation and
1188only share the way their calls look in Python code.) Methods of
1189classes (and class instances) are defined as functions inside the
1190class definition.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001191
11924.21. Q. What is self?
1193
1194A. Self is merely a conventional name for the first argument of a
1195method -- i.e. a function defined inside a class definition. A method
1196defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
1197some instance x of the class in which the definition occurs;
1198the called method will think it is called as meth(x, a, b, c).
1199
12004.22. Q. What is a unbound method?
1201
1202A. An unbound method is a method defined in a class that is not yet
1203bound to an instance. You get an unbound method if you ask for a
1204class attribute that happens to be a function. You get a bound method
1205if you ask for an instance attribute. A bound method knows which
Guido van Rossum061f1821994-10-06 16:03:45 +00001206instance it belongs to and calling it supplies the instance automatically;
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001207an unbound method only knows which class it wants for its first
1208argument (a derived class is also OK). Calling an unbound method
1209doesn't "magically" derive the first argument from the context -- you
1210have to provide it explicitly.
1211
Guido van Rossuma6c707c1995-01-02 17:32:28 +000012124.23. Q. How do I call a method defined in a base class from a derived
1213class that overrides it?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001214
1215A. If your class definition starts with "class Derived(Base): ..."
1216then you can call method meth defined in Base (or one of Base's base
1217classes) as Base.meth(self, arguments...). Here, Base.meth is an
1218unbound method (see previous question).
1219
Guido van Rossuma6c707c1995-01-02 17:32:28 +000012204.24. Q. How do I call a method from a base class without using the
1221name of the base class?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001222
1223A. DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call
1224self.__class__.__bases__[0].meth(self, arguments...) but this fails when
Guido van Rossum061f1821994-10-06 16:03:45 +00001225a doubly-derived method is derived from your class: for its instances,
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001226self.__class__.__bases__[0] is your class, not its base class -- so
1227(assuming you are doing this from within Derived.meth) you would start
1228a recursive call.
1229
12304.25. Q. How can I organize my code to make it easier to change the base
1231class?
1232
1233A. You could define an alias for the base class, assign the real base
1234class to it before your class definition, and use the alias throughout
1235your class. Then all you have to change is the value assigned to the
1236alias. Incidentally, this trick is also handy if you want to decide
1237dynamically (e.g. depending on availability of resources) which base
1238class to use. Example:
1239
1240BaseAlias = <real base class>
1241class Derived(BaseAlias):
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001242 def meth(self):
1243 BaseAlias.meth(self)
1244 ...
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001245
12464.26. Q. How can I find the methods or attributes of an object?
1247
1248A. This depends on the object type.
1249
1250For an instance x of a user-defined class, instance attributes are
1251found in the dictionary x.__dict__, and methods and attributes defined
1252by its class are found in x.__class__.__bases__[i].__dict__ (for i in
1253range(len(x.__class__.__bases__))). You'll have to walk the tree of
1254base classes to find *all* class methods and attributes.
1255
1256Many, but not all built-in types define a list of their method names
1257in x.__methods__, and if they have data attributes, their names may be
1258found in x.__members__. However this is only a convention.
1259
1260For more information, read the source of the standard (but
1261undocumented) module newdir.
1262
12634.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
1264
1265A. os.read() is a low-level function which takes a file descriptor (a
1266small integer). os.popen() creates a high-level file object -- the
1267same type used for sys.std{in,out,err} and returned by the builtin
1268open() function. Thus, to read n bytes from a pipe p created with
1269os.popen(), you need to use p.read(n).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001270
Guido van Rossum061f1821994-10-06 16:03:45 +000012714.28. Q. How can I create a stand-alone binary from a Python script?
1272
1273The demo script "Demo/scripts/freeze.py" does what you want. (It's
1274actually not a demo but a support tool -- there is some extra code in
1275the interpreter to accommodate it.) It requires that you have the
1276Python build tree handy, complete with all the lib*.a files.
1277
1278This works by scanning your source recursively for import statements
1279(both forms) and looking for the modules on the standard Python path
1280as well as in the source directory (for built-in modules). It then
1281"compiles" the modules written in Python to C code (array initializers
1282that can be turned into code objects using the marshal module) and
1283creates a custom-made config file that only contains those built-in
1284modules which are actually used in the program. It then compiles the
1285generated C code and links it with the rest of the Python interpreter
1286to form a self-contained binary which acts exactly like your script.
1287
Guido van Rossum061f1821994-10-06 16:03:45 +000012884.29. Q. Is there a special lib for writing CGI scripts in Python?
1289
1290A. There's documentation and code for a cgi.py module by Michael McLay
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001291<mclay@eeel.nist.gov> available from
1292<URL:http://www.eeel.nist.gov/python/>
Guido van Rossum061f1821994-10-06 16:03:45 +00001293
1294(For the curious: CGI or Common Gateway Interface is the protocol
1295between HTTP servers (WWW servers) and programs/scripts they run to
1296perform queries and other tasks that require returning a dynamically
1297generated document.)
1298
12994.30. Q. What other WWW tools are there for Python?
1300
1301A. The standard library has a module urllib, which can retrieve most
1302commonly used URL types (file, ftp, http, gopher).
1303
1304The Demo2/www directory (Demo2 has to be retrieved separately from the
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001305Python ftp sites <URL:ftp://ftp.cwi.nl/pub/python/demo2.tar.gz>)
1306contains some (really old) code to parse HTML and to display it.
Guido van Rossum061f1821994-10-06 16:03:45 +00001307
1308Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser
1309called Dancer. An alpha version can be FTP'ed from
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001310<URL:ftp://ftp.cs.indiana.edu/pub/smiale/dancer.tar.gz>. (There are a
1311few articles about Dancer in the (hyper)mail archive
1312<URL:http://www.cwi.nl/~guido/hypermail/python-1994q3/index.html>.)
Guido van Rossum061f1821994-10-06 16:03:45 +00001313
Guido van Rossum796b2591995-01-20 23:05:52 +000013144.31. Q. How do I run a subprocess with pipes connected to both input
1315and output?
1316
1317A. This is really a UNIX question. Also, in general, it is unwise to
1318do so, because you can easily cause a deadlock where the parent
1319process is blocked waiting for output from the child, while the child
1320is blocked waiting for input from the child. This can be caused
1321because the parent expects the child to output more text than it does,
1322or it can be caused by data being stuck in stdio buffers due to lack
1323of flushing. The Python parent can of course explicitly flush the data
1324it sends to the child before it reads any output, but if the child is
1325a naive C program it can easily have been written to never explicitly
1326flush its output, even if it is interactive, since flushing is
1327normally automatic.
1328
1329In many cases, all you really need is to run some data through a
1330command and get the result back. Unless the data is infinite in size,
1331the easiest (and often the most efficient!) way to do this is to write
1332it to a temporary file and run the command with that temporary file as
1333input. The standard module tempfile exports a function mktemp() which
1334generates unique temporary file names.
1335
1336If after reading all of the above you still want to connect two pipes
1337to a subprocess's standard input and output, here's a simple solution,
1338due to Jack Jansen:
1339
1340 import os
1341 import sys
1342 import string
1343
1344 MAXFD = 100 # Max number of file descriptors in this system
1345
1346 def popen2(cmd):
1347 cmd = string.split(cmd)
1348 p2cread, p2cwrite = os.pipe()
1349 c2pread, c2pwrite = os.pipe()
1350 pid = os.fork()
1351 if pid == 0:
1352 # Child
1353 os.close(0)
1354 os.close(1)
1355 if os.dup(p2cread) <> 0:
1356 sys.stderr.write('popen2: bad read dup\n')
1357 if os.dup(c2pwrite) <> 1:
1358 sys.stderr.write('popen2: bad write dup\n')
1359 for i in range(3, MAXFD):
1360 try:
1361 os.close(i)
1362 except:
1363 pass
1364 try:
1365 os.execv(cmd[0], cmd)
1366 finally:
1367 os._exit(1)
1368 os.close(p2cread)
1369 tochild = os.fdopen(p2cwrite, 'w')
1370 os.close(c2pwrite)
1371 fromchild = os.fdopen(c2pread, 'r')
1372 return fromchild, tochild
1373
1374Note that many interactive programs (e.g. vi) don't work well with
1375pipes substituted for standard input and output. You will have to use
1376pseudo ttys ("ptys") instead of pipes. There is some undocumented
1377code to use these in the library module pty.py -- I'm afraid you're on
1378your own here. What's *really* needed is a Python interface to Don
1379Libes' expect library -- any takers?
1380
Guido van Rossum061f1821994-10-06 16:03:45 +00001381
Guido van Rossuma7925f11994-01-26 10:20:16 +000013825. Extending Python
1383===================
1384
13855.1. Q. Can I create my own functions in C?
1386
1387A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +00001388variables, exceptions and even new types in C. This is explained in
1389the document "Extending and Embedding the Python Interpreter" (the
1390LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001391
13925.2. Q. Can I create my own functions in C++?
1393
1394A. Yes, using the C-compatibility features found in C++. Basically
1395you place extern "C" { ... } around the Python include files and put
1396extern "C" before each function that is going to be called by the
1397Python interpreter. Global or static C++ objects with constructors
1398are probably not a good idea.
1399
Guido van Rossum7ce61c11994-06-13 15:13:56 +000014005.3. Q. How can I execute arbitrary Python statements from C?
1401
1402A. The highest-level function to do this is run_command() which takes
1403a single string argument which is executed in the context of module
1404__main__ and returns 0 for success and -1 when an exception occurred
1405(including SyntaxError). If you want more control, use run_string();
1406see the source for run_command() in Python/pythonrun.c.
1407
14085.4. Q. How can I evaluate an arbitrary Python expression from C?
1409
1410A. Call the function run_string() from the previous question with the
1411start symbol eval_input; it then parses an expression, evaluates it
1412and returns its value. See exec_eval() in Python/bltinmodule.c.
1413
14145.5. Q. How do I extract C values from a Python object?
1415
1416A. That depends on the object's type. If it's a tuple,
1417gettuplesize(o) returns its length and gettupleitem(o, i) returns its
1418i'th item; similar for lists with getlistsize(o) and getlistitem(o,
1419i). For strings, getstringsize(o) returns its length and
1420getstringvalue(o) a pointer to its value (note that Python strings may
1421contain null bytes so strlen() is not safe). To test which type an
1422object is, first make sure it isn't NULL, and then use
1423is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
1424
14255.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
1426
1427A. You can't. Use t = newtupleobject(n) instead, and fill it with
1428objects using settupleitem(t, i, o) -- note that this "eats" a
1429reference count of o. Similar for lists with newlistobject(n) and
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001430setlistitem(l, i, o). Note that you *must* set all the tuple items to
1431some value before you pass the tuple to Python code --
1432newtupleobject(n) initializes them to NULL, which isn't a valid Python
1433value.
1434
Guido van Rossum796b2591995-01-20 23:05:52 +000014355.7. Q. What happened to mktuple(), featured in an example in the
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001436Extensions manual?
1437
1438A. It's a typo, I meant newtupleobject() (see previous question).
1439
14405.8. Q. How do I call an object's method from C?
1441
1442A. Here's a function (untested) that might become part of the next
1443release in some form. It uses <stdarg.h> to allow passing the
1444argument list on to vmkvalue():
1445
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001446 object *call_method(object *inst, char *methodname, char *format, ...)
1447 {
1448 object *method;
1449 object *args;
1450 object *result;
1451 va_list va;
1452 method = getattr(inst, methodname);
1453 if (method == NULL) return NULL;
1454 va_start(va, format);
1455 args = vmkvalue(format, va);
1456 va_end(va);
1457 if (args == NULL) {
1458 DECREF(method);
1459 return NULL;
1460 }
1461 result = call_object(method, args);
1462 DECREF(method);
1463 DECREF(args);
1464 return result;
1465 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001466
1467This works for any instance that has methods -- whether built-in or
1468user-defined. You are responsible for eventually DECREF'ing the
1469return value.
1470
1471To call, e.g., a file object's "seek" method with arguments 10, 0
1472(assuming the file object pointer is "f"):
1473
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001474 res = call_method(f, "seek", "(OO)", 10, 0);
1475 if (res == NULL) {
1476 ... an exception occurred ...
1477 }
1478 else {
1479 DECREF(res);
1480 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001481
1482Note that since call_object() *always* wants a tuple for the argument
1483list, to call a function without arguments, pass "()" for the format,
1484and to call a function with one argument, surround the argument in
1485parentheses, e.g. "(i)".
1486
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001487(This function and a companion will be available in 1.2 under the
1488names PyEval_CallFunction and PyEval_CallMethod.)
1489
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000014905.9. Q. How do I catch the output from print_error()?
1491
1492A. (Due to Mark Hammond):
1493
1494* in Python code, define an object that supports the "write()" method.
1495FWIW, there seems to be a small problem that requires the 'softspace'
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001496attribute to be defined too (fixed in 1.2).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001497
1498* redirect sys.stdout and sys.stderr to this object.
1499
Guido van Rossum061f1821994-10-06 16:03:45 +00001500* call print_error, or just allow the standard traceback mechanism to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001501work.
1502
Guido van Rossum061f1821994-10-06 16:03:45 +00001503Then, the output will go wherever your write() method sends it.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001504
15055.10. Q. How do I access a module written in Python from C?
1506
1507A. You can get a pointer to the module object as follows:
1508
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001509 module = import_module("<modulename>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001510
1511If the module hasn't been imported yet (i.e. it is not yet present in
1512sys.modules), this initializes the module; otherwise it simply returns
1513the value of sys.modules["<modulename>"]. Note that it doesn't enter
1514the module into any namespace -- it only ensures it has been
1515initialized and is stored in sys.modules.
1516
1517You can then access the module's attributes (i.e. any name defined in
1518the module) as follows:
1519
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001520 attr = getattr(module, "<attrname>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001521
1522Calling setattr(), to assign to variables in the module, also works.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001523
Guido van Rossuma7925f11994-01-26 10:20:16 +00001524
15256. Python's design
1526==================
1527
15286.1. Q. Why isn't there a generic copying operation for objects in
1529Python?
1530
1531A. Hmm. Maybe there should be one, but it's difficult to assign a
1532useful meaning to copying of open files, sockets and windows, or
1533recursive data structures. As long as you design all your classes
1534yourself you are of course free to define a standard base class that
1535defines an overridable copying operation for all the objects you care
1536about. (One practical point: it would have to be a built-in function,
1537not a standard method name, since not all built-in object types have
1538methods; e.g. strings, integers and tuples don't.)
1539
15406.2. Q. Why isn't there a generic way to implement persistent objects
1541in Python? (Persistent == automatically saved to and restored from
1542disk.)
1543
1544A. Hmm, hmm. Basically for the same reasons as why there is no
1545generic copying operation.
1546
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001547A partial solution will appear in release 1.2. This will also provide
1548a partial solution to the problem of a generic copying operation.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001549(Partial because it still won't cope with open files etc.; however it
1550does handle user-defined classes!)
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001551
Guido van Rossuma7925f11994-01-26 10:20:16 +000015526.3. Q. Why isn't there a switch or case statement in Python?
1553
1554A. You can do this easily enough with a sequence of
1555if... elif... elif... else. There have been some proposals for switch
Guido van Rossum061f1821994-10-06 16:03:45 +00001556statement syntax, but there is no consensus (yet) on whether and how
Guido van Rossuma7925f11994-01-26 10:20:16 +00001557to do range tests.
1558
Guido van Rossumc50158e1994-05-31 09:18:50 +000015596.4. Q. Why does Python use indentation for grouping of statements?
1560
1561A. Basically I believe that using indentation for grouping is
1562extremely elegant and contributes a lot to the clarity of the average
1563Python program. Most people learn to love this feature after a while.
1564Some arguments for it:
1565
1566- Since there are no begin/end brackets there cannot be a disagreement
1567between grouping perceived by the parser and the human reader. I
1568remember long ago seeing a C fragment like this:
1569
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001570 if (x <= y)
1571 x++;
1572 y--;
1573 z++;
Guido van Rossumc50158e1994-05-31 09:18:50 +00001574
1575and staring a long time at it wondering why y was being decremented
1576even for x > y... (And I wasn't a C newbie then either.)
1577
1578- Since there are no begin/end brackets there can be no conflicting
1579coding styles. In C there are loads of different ways to place the
1580braces (including the choice whether to place braces around single
1581statements in certain cases, for consistency). If you're used to
1582reading (and writing) code that uses one style, you will feel at least
1583slightly uneasy when reading (or being required to write) another
1584style.
1585
1586- Many coding styles place begin/end brackets on a line by themself.
1587This makes programs considerably longer and wastes valuable screen
1588space, making it harder to get a good overview over a program.
1589Ideally, a function should fit on one basic tty screen (say, 20
1590lines). 20 lines of Python are worth a LOT more than 20 lines of C.
1591This is not solely due to the lack of begin/end brackets (the lack of
1592declarations also helps, and the powerful operations of course), but
1593it certainly helps!
1594
Guido van Rossum3de27361994-07-25 14:19:33 +000015956.5. Q. Why are Python strings immutable?
1596
1597A. There are two advantages. One is performance: knowing that a
1598string is immutable makes it easy to lay it out at construction time
1599-- fixed and unchanging storage requirements. (This is also one of
Guido van Rossum061f1821994-10-06 16:03:45 +00001600the reasons for the distinction between tuples and lists.) The
Guido van Rossum3de27361994-07-25 14:19:33 +00001601other is that strings in Python are considered as "elemental" as
1602numbers. No amount of activity will change the value 8 to anything
1603else, and in Python, no amount of activity will change the string
1604"eight" to anything else. (Adapted from Jim Roskind)
1605
16066.6. Q. Why don't strings have methods like index() or sort(), like
1607lists?
1608
1609A. Good question. Strings currently don't have methods at all
1610(likewise tuples and numbers). Long ago, it seemed unnecessary to
1611implement any of these functions in C, so a standard library module
1612"string" written in Python was created that performs string related
1613operations. Since then, the cry for performance has moved most of
1614them into the built-in module strop (this is imported by module
Guido van Rossumf8c76d01994-08-17 12:19:53 +00001615string, which is still the preferred interface, without loss of
Guido van Rossum3de27361994-07-25 14:19:33 +00001616performance except during initialization). Some of these functions
1617(e.g. index()) could easily be implemented as string methods instead,
1618but others (e.g. sort()) can't, since their interface prescribes that
1619they modify the object, while strings are immutable (see the previous
1620question).
1621
16226.7. Q. Why does Python use methods for some functionality
1623(e.g. list.index()) but functions for other (e.g. len(list))?
1624
1625A. Functions are used for those operations that are generic for a
1626group of types and which should work even for objects that don't have
1627methods at all (e.g. numbers, strings, tuples). Also, implementing
1628len(), max(), min() as a built-in function is actually less code than
1629implementing them as methods for each type. One can quibble about
1630individual cases but it's really too late to change such things
1631fundamentally now.
1632
16336.8. Q. Why can't I derive a class from built-in types (e.g. lists or
1634files)?
1635
1636A. This is caused by the relatively late addition of (user-defined)
1637classes to the language -- the implementation framework doesn't easily
1638allow it. See the answer to question 4.2 for a work-around. This
1639*may* be fixed in the (distant) future.
1640
16416.9. Q. Why must 'self' be declared and used explicitly in method
1642definitions and calls?
1643
1644A. By asking this question you reveal your C++ background. :-)
1645When I added classes, this was (again) the simplest way of
1646implementing methods without too many changes to the interpreter. I
1647borrowed the idea from Modula-3. It turns out to be very useful, for
1648a variety of reasons.
1649
1650First, it makes it more obvious that you are using a method or
1651instance attribute instead of a local variable. Reading "self.x" or
1652"self.meth()" makes it absolutely clear that an instance variable or
1653method is used even if you don't know the class definition by heart.
1654In C++, you can sort of tell by the lack of a local variable
Guido van Rossum061f1821994-10-06 16:03:45 +00001655declaration (assuming globals are rare or easily recognizable) -- but
Guido van Rossum3de27361994-07-25 14:19:33 +00001656in Python, there are no local variable declarations, so you'd have to
1657look up the class definition to be sure.
1658
1659Second, it means that no special syntax is necessary if you want to
1660explicitly reference or call the method from a particular class. In
1661C++, if you want to use a method from base class that is overridden in
1662a derived class, you have to use the :: operator -- in Python you can
1663write baseclass.methodname(self, <argument list>). This is
1664particularly useful for __init__() methods, and in general in cases
1665where a derived class method wants to extend the base class method of
1666the same name and thus has to call the base class method somehow.
1667
1668Lastly, for instance variables, it solves a syntactic problem with
1669assignment: since local variables in Python are (by definition!) those
1670variables to which a value assigned in a function body (and that
1671aren't explicitly declared global), there has to be some way to tell
1672the interpreter that an assignment was meant to assign to an instance
1673variable instead of to a local variable, and it should preferably be
1674syntactic (for efficiency reasons). C++ does this through
1675declarations, but Python doesn't have declarations and it would be a
1676pity having to introduce them just for this purpose. Using the
1677explicit "self.var" solves this nicely. Similarly, for using instance
1678variables, having to write "self.var" means that references to
1679unqualified names inside a method don't have to search the instance's
1680directories.
1681
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000016826.10. Q. Can't you emulate threads in the interpreter instead of
1683relying on an OS-specific thread implementation?
1684
1685A. Unfortunately, the interpreter pushes at least one C stack frame
1686for each Python stack frame. Also, extensions can call back into
1687Python at almost random moments. Therefore a complete threads
1688implementation requires thread support for C.
1689
Guido van Rossum061f1821994-10-06 16:03:45 +000016906.11. Q. Why can't lambda forms contain statements?
1691
1692A. Python lambda forms cannot contain statements because Python's
Guido van Rossum796b2591995-01-20 23:05:52 +00001693syntactic framework can't handle statements nested inside expressions.
Guido van Rossum061f1821994-10-06 16:03:45 +00001694
1695However, in Python, this is not a serious problem. Unlike lambda
1696forms in other languages, where they add functionality, Python lambdas
1697are only a shorthand notation if you're too lazy to define a function.
1698
1699Functions are already first class objects in Python, and can be
1700declared in a local scope. Therefore the only advantage of using a
1701lambda form instead of a locally-defined function is that you'll have
1702to invent a name for the function -- but that's just a local variable
1703to which the function object (which is exactly the same type of object
1704that a lambda form yields) is assigned!
1705
17066.12. Q. Why is there no more efficient way of iterating over a dictionary
1707than first constructing the list of keys()?
1708
1709A. Have you tried it? I bet it's fast enough for your purposes! In
1710most cases such a list takes only a few percent of the space occupied
1711by the dictionary -- it needs only 4 bytes (the size of a pointer) per
1712key -- a dictionary costs 8 bytes per key plus between 30 and 70
1713percent hash table overhead, plus the space for the keys and values --
1714by necessity all keys are unique objects and a string object (the most
1715common key type) costs at least 18 bytes plus the length of the
1716string. Add to that the values contained in the dictionary, and you
1717see that 4 bytes more per item really isn't that much more memory...
1718
1719A call to dict.keys() makes one fast scan over the dictionary
1720(internally, the iteration function does exist) copying the pointers
1721to the key objects into a pre-allocated list object of the right size.
1722The iteration time isn't lost (since you'll have to iterate anyway --
1723unless in the majority of cases your loop terminates very prematurely
1724(which I doubt since you're getting the keys in random order).
1725
1726I don't expose the dictionary iteration operation to Python
1727programmers because the dictionary shouldn't be modified during the
1728entire iteration -- if it is, there's a very small chance that the
1729dictionary is reorganized because the hash table becomes too full, and
1730then the iteration may miss some items and see others twice. Exactly
1731because this only occurs rarely, it would lead to hidden bugs in
1732programs: it's easy never to have it happen during test runs if you
1733only insert or delete a few items per iteration -- but your users will
1734surely hit upon it sooner or later.
1735
Guido van Rossuma7925f11994-01-26 10:20:16 +00001736
17377. Using Python on non-UNIX platforms
1738=====================================
1739
Guido van Rossum91f60831994-02-15 15:52:27 +000017407.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001741
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001742A. Yes. It is on most ftp sites carrying Python as python.sea.hqx,
1743e.g. <URL:ftp://ftp.cwi.nl/pub/python/python_1.1.sea.hqx> -- this is a
1744self-extracting archive containing the application binary as well as
1745the Lib modules.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001746
Guido van Rossum91f60831994-02-15 15:52:27 +000017477.2. Q. Is there a DOS version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001748
Guido van Rossum91f60831994-02-15 15:52:27 +00001749A. Yes. More than one, actually: 16python.exe runs in standard DOS
1750mode on 186 CPUs or higher; 32python.exe uses a DOS extender and only
1751runs on a 386 or higher CPUs. Although 16python.exe does not pass the
1752test set because test_grammar is too big for the parser, it actually
1753has about 270 kbyte of allocatable heap space, which is sufficient for
1754fairly large programs. 32python.exe is distributed as a tar file
1755containing the required DOS extended and 387 emulator. Both are on
1756most ftp sites carrying Python.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001757
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001758The file dosbuild.tar.gz on the standard ftp sites contains
1759rudimentary Makefiles and instructions
1760<URL:ftp://ftp.cwi.nl/pub/python/dosbuild.tar.gz>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001761
Guido van Rossum91f60831994-02-15 15:52:27 +000017627.3. Q. Is there a Windows version of Python?
1763
1764A. Yes. Use qwpython.exe. The only problem with it: ^C
1765unconditionally kills the entire program -- it does not raise
1766KeyboardInterrupt. You can also run 16python.exe or 32python.exe in a
1767"DOS box", but qwpython.exe appears to be slightly faster.
1768
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001769There aren't any Makefiles at this moment. Sorry.
1770
1771Using Win32s (a free NT compatibility package by Microsoft) you can
1772also use the NT version by Mark Hammond -- the Win32s package is also
1773in that directory (you'll need several MB of disk space to install
1774it). See the next question.
1775
Guido van Rossum91f60831994-02-15 15:52:27 +000017767.4. Q. Is there a Windows NT version of Python?
1777
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001778A. Yes. Mark Hammond <MHammond@cmutual.com.au> has built a full NT
1779port. This supports using DLLs for dynamic loading of Python modules,
1780and includes an interface to the Microsoft Foundation Classes and a
1781Python programming environment using it that's written mostly in
1782Python. See <URL:ftp://ftp.cwi.nl/pub/python/nt/> -- most mirrors
1783will also have this.
Guido van Rossum91f60831994-02-15 15:52:27 +00001784
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001785Sam Rushing <rushing@squirl.oau.org> once announced he knows how to
1786build Python for the Windows NT on the DEC Alpha AXP.
Guido van Rossum061f1821994-10-06 16:03:45 +00001787
1788Note that currently there is no unified compilation environment for
1789all NT platforms -- hopefully Microsoft will fix this with the release
1790of Visual C++ 2.0.
1791
Guido van Rossum7ce61c11994-06-13 15:13:56 +000017927.5. Q. Is there an OS/2 version of Python?
1793
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001794A. Yes. You can ftp it from the usual places as pyth_os2.zip, e.g.
1795<URL:ftp://ftp.cwi.nl/pub/python/pyth_os2.zip>. This contains both an
1796executable and Makefiles for those fortunate enough to have a C
1797compiler.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001798
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000017997.6. Q. Is there a VMS version of Python?
1800
1801A. I think not (yet). This question has been asked on the list
1802several times and I've never seen an answer. Maybe someone with a VMS
1803C compiler could attempt a port? Probably coming up with proper
1804Makefiles, config.h and config.c should be sufficient. If you succeed
1805(or even if you get stuck halfway), please let me know! (Info as of
180623 September 1994.)
1807
18087.7. Q. What about IBM mainframes, or other esoteric non-UNIX
1809platforms?
1810
1811A. Basically, the same story as for VMS... (Info as of 23 September
18121994.)
1813
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000018147.8. Q. Where are the source or Makefiles for the non-UNIX versions?
1815
1816A. The standard sources can (almost) be used. See the previous
1817questions for availability of Makefiles/projects or patches. If you
1818find things in the standard sources that don't work on your particular
1819platform, please let me know and I'll integrate a solution into the
1820next release of the standard sources. If you submit a fix, please use
1821some kind of #ifdef so as to keep the source working for other
1822platforms. In particular, if the patch works around the availability
1823of a particular function of header file, you should mimic the
1824HAVE_... style used by the configure script -- you can then submit a
1825config.h file for a particular platform so there are no absolutely
1826platform-specific #ifdefs in the rest of the sources.
1827
18287.9. Q. What is the status and support for the non-UNIX versions?
1829
1830A. I don't have access to most of these platforms, so in general I am
1831dependent on material submitted by volunteers(*). However I strive to
1832integrate all changes needed to get it to compile on a particular
1833platform back into the standard sources, so porting of the next
1834version to the various non-UNIX platforms should be easy.
1835
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001836(*) For the Macintosh, that volunteer is me, with help from Jack
1837Jansen <jack@cwi.nl>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001838
18397.10. Q. I have the PC version but it appears to be only a binary.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001840Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001841
1842A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +00001843"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossum3de27361994-07-25 14:19:33 +00001844you can get the file pythonlib<version>.tar.gz from most ftp sites
1845carrying Python; this is a subset of the distribution containing just
Guido van Rossum796b2591995-01-20 23:05:52 +00001846those files, e.g.
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001847<URL:ftp://ftp.cwi.nl/pub/python/pythonlib1.1.tar.gz>.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001848
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001849Once you have installed the library, you need to point sys.path to it.
1850Assuming the library is in C:\misc\python\lib, the following commands
1851will point your Python interpreter to it (note the doubled backslashes
1852-- you can also use single forward slashes instead):
1853
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001854 >>> import sys
1855 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
1856 >>>
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001857
1858For a more permanent effect, set the environment variable PYTHONPATH,
1859as follows (talking to a DOS prompt):
1860
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001861 C> SET PYTHONPATH=C:\misc\python\lib
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001862
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000018637.11. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001864
1865A. There isn't any. The documentation for the Unix version also
Guido van Rossum91f60831994-02-15 15:52:27 +00001866applies to the Mac and PC versions. Where applicable, differences
Guido van Rossuma7925f11994-01-26 10:20:16 +00001867are indicated in the text.
1868
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000018697.12. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +00001870creating or editing programs apart from entering it interactively, and
1871there seems to be no way to save code that was entered interactively.
1872How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001873
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001874A. Use an external editor. On the Mac, BBEdit seems to be a popular
1875no-frills text editor. I work like this: start the interpreter; edit
1876a module file using BBedit; import and test it in the interpreter;
1877edit again in BBedit; then use the built-in function reload() to
1878re-read the imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001879
1880Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
1881anyone with a pulse could certainly figure out how to do the same on
1882MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
1883Not only can you easily resave and "reload()" from Python after making
1884changes, but since WinNot auto-copies to the clipboard any text you
1885select, you can simply select the entire procedure (function) which
1886you changed in WinNot, switch to QWPython, and shift-ins to reenter
1887the changed program unit."