blob: d6bdbb5c757d43b3c57931523eec152b5fd310a1 [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 Rossumac3f2121995-04-10 11:53:42 +00006Expires: Mon, 1 May 1995 00:00:00 GMT
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00007Supersedes: <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 Rossumac3f2121995-04-10 11:53:42 +000012Version: 1.22
13Last-modified: 10 April 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 Rossumac3f2121995-04-10 11:53:42 +0000161 4.32. Q. How do I call a function if I have the arguments in a tuple?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000162
163 5. Extending Python
164 5.1. Q. Can I create my own functions in C?
165 5.2. Q. Can I create my own functions in C++?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000166 5.3. Q. How can I execute arbitrary Python statements from C?
167 5.4. Q. How can I evaluate an arbitrary Python expression from C?
168 5.5. Q. How do I extract C values from a Python object?
169 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
Guido van Rossum796b2591995-01-20 23:05:52 +0000170 5.7. Q. What happened to mktuple(), featured in an example in the
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000171 Extensions manual?
172 5.8. Q. How do I call an object's method from C?
173 5.9. Q. How do I catch the output from print_error()?
174 5.10. Q. How do I access a module written in Python from C?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000175
176 6. Python's design
177 6.1. Q. Why isn't there a generic copying operation for objects in
178 Python?
179 6.2. Q. Why isn't there a generic way to implement persistent objects
180 in Python? (Persistent == automatically saved to and restored from
181 disk.)
182 6.3. Q. Why isn't there a switch or case statement in Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +0000183 6.4. Q. Why does Python use indentation for grouping of statements?
Guido van Rossum3de27361994-07-25 14:19:33 +0000184 6.5. Q. Why are Python strings immutable?
185 6.6. Q. Why don't strings have methods like index() or sort(), like
186 lists?
187 6.7. Q. Why does Python use methods for some functionality
188 (e.g. list.index()) but functions for other (e.g. len(list))?
189 6.8. Q. Why can't I derive a class from built-in types (e.g. lists or
190 files)?
191 6.9. Q. Why must 'self' be declared and used explicitly in method
192 definitions and calls?
Guido van Rossum061f1821994-10-06 16:03:45 +0000193 6.10. Q. Can't you emulate threads in the interpreter instead of
194 relying on an OS-specific thread implementation?
195 6.11. Q. Why can't lambda forms contain statements?
196 6.12. Q. Why is there no more efficient way of iterating over a dictionary
197 than first constructing the list of keys()?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000198
199 7. Using Python on non-UNIX platforms
Guido van Rossum91f60831994-02-15 15:52:27 +0000200 7.1. Q. Is there a Mac version of Python?
201 7.2. Q. Is there a DOS version of Python?
202 7.3. Q. Is there a Windows version of Python?
203 7.4. Q. Is there a Windows NT version of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000204 7.5. Q. Is there an OS/2 version of Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000205 7.6. Q. Is there a VMS version of Python?
206 7.7. Q. What about IBM mainframes, or other esoteric non-UNIX
207 platforms?
208 7.8. Q. Where are the source or Makefiles for the non-UNIX versions?
209 7.9. Q. What is the status and support for the non-UNIX versions?
210 7.10. Q. I have the PC version but it appears to be only a binary.
211 Where's the library?
212 7.11. Q. Where's the documentation for the Mac or PC version?
213 7.12. Q. The Mac (PC) version doesn't seem to have any facilities for
214 creating or editing programs apart from entering it interactively, and
215 there seems to be no way to save code that was entered interactively.
216 How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000217
218To find a particular question, search for the question number followed
219by a dot, a space, and a Q at the beginning of a line (e.g. to find
220question 4.2 in vi, type /^4\.2\. Q/).
221
222
2231. General information and availability
224=======================================
225
2261.1. Q. What is Python?
227
228A. Python is an interpreted, interactive, object-oriented programming
229language. It incorporates modules, exceptions, dynamic typing, very
230high level dynamic data types, and classes. Python combines
231remarkable power with very clear syntax. It has interfaces to many
232system calls and libraries, as well as to various window systems, and
233is extensible in C or C++. It is also usable as an extension language
234for applications that need a programmable interface. Finally, Python
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000235is portable: it runs on many brands of UNIX, on the Mac, and on PCs
236under MS-DOS, Windows, Windows NT, and OS/2.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000237
238To find out more, the best thing to do is to start reading the
239tutorial from the documentation set (see a few questions further
240down).
241
2421.2. Q. Why is it called Python?
243
Guido van Rossum796b2591995-01-20 23:05:52 +0000244A. Apart from being a computer scientist, I'm also a fan of "Monty
Guido van Rossuma7925f11994-01-26 10:20:16 +0000245Python's Flying Circus" (a BBC comedy series from the seventies, in
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000246the -- unlikely -- case you didn't know). It occurred to me one day
247that I needed a name that was short, unique, and slightly mysterious.
248And I happened to be reading some scripts from the series at the
249time... So then I decided to call my language Python. But Python is
250not a joke. And don't you associate it with dangerous reptiles
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000251either! (If you need an icon, use an image of the 16-ton weight from
252the TV series or of a can of SPAM :-)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000253
2541.3. Q. How do I obtain a copy of the Python source?
255
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000256A. The latest complete Python source distribution is always available
257by anonymous ftp, e.g.
258<URL:ftp://ftp.cwi.nl/pub/python/python1.1.tar.gz>. It is a gzipped
259tar file containing the complete C source, LaTeX documentation, Python
260library modules, example programs, and several useful pieces of freely
261distributable software. This will compile and run out of the box on
262most UNIX platforms. (See section 7 for non-UNIX information.)
263
264Occasionally a set of patches is issued which has to be applied using
265the patch program. These patches are placed in the same directory,
266e.g. <URL:ftp://ftp.cwi.nl/pub/python/patch1.1.1>.
267
268An index of said ftp directory can be found in the file INDEX. An
269HTML version of the index can be found in the file index.html,
270<URL:ftp://ftp.cwi.nl/pub/python/index.html>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000271
2721.4. Q. How do I get documentation on Python?
273
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000274A. The LaTeX source for the documentation is part of the source
275distribution. If you don't have LaTeX, the latest Python
276documentation set is always available by anonymous ftp, e.g.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000277<URL:ftp://ftp.cwi.nl/pub/python/pythondoc-ps1.1.tar.gz>. It is a
278gzipped tar file containing PostScript files of the reference manual,
Guido van Rossum3de27361994-07-25 14:19:33 +0000279the library manual, and the tutorial. Note that the library manual is
280the most important one of the set, as much of Python's power stems
281from the standard or built-in types, functions and modules, all of
282which are described here. PostScript for a high-level description of
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000283Python is in the file nluug-paper.ps (a separate file on the ftp
284site).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000285
Guido van Rossumc50158e1994-05-31 09:18:50 +00002861.5. Q. Are there other ftp sites that mirror the Python distribution?
287
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000288A. The following anonymous ftp sites keep mirrors of the Python
289distribution:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000290
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000291 <URL:ftp://gatekeeper.dec.com/pub/plan/python/>
292 <URL:ftp://ftp.uu.net/languages/python/>
293 <URL:ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/>
294 <URL:ftp://ftp.funet.fi/pub/languages/python/>
295 <URL:ftp://ftp.sunet.se/pub/lang/python/>
296 <URL:ftp://unix.hensa.ac.uk/uunet/languages/python/>
297 <URL:ftp://ftp.sterlng.com/programming/languages/python/>
298 <URL:ftp://ftp.ibp.fr/pub/python/>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000299
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000300Or try archie on the string "python".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000301
Guido van Rossumc50158e1994-05-31 09:18:50 +00003021.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000303
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000304A. There is a newsgroup, comp.lang.python <URL:news:comp.lang.python>,
305and a mailing list. The newsgroup and mailing list are gatewayed into
306each other -- if you can read news it's unnecessary to subscribe to
307the mailing list. Send e-mail to <python-list-request@cwi.nl> to
Guido van Rossum796b2591995-01-20 23:05:52 +0000308(un)subscribe to the mailing list. Hypermail archives of
Guido van Rossum061f1821994-10-06 16:03:45 +0000309(nearly) everything posted to the mailing list (and thus the
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000310newsgroup) are available on our WWW server,
311<URL:http://www.cwi.nl/~guido/hypermail/index.html>. The raw archives
312are also available by ftp, e.g.
313<URL:ftp://ftp.cwi.nl/pub/python/mailinglist.gz>. The uncompressed
314versions of these files can be read with the standard UNIX Mail
315program ("Mail -f file") or with nn ("nn file"). To read them using
316MH, you could use "inc -file file".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000317
Guido van Rossuma6c707c1995-01-02 17:32:28 +00003181.7. Q. Is there a WWW page devoted to Python?
319
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000320A. Yes, <URL:http://www.cwi.nl/~guido/Python.html> is the official
321Python home page. Michael McLay at NIST maintains a Python page at
322<URL:http://www.eeel.nist.gov/python/>. And finally the emerging
323Python Software Association has a preliminary web server at
324<URL:http://www.cminds.com/python/> (eventually to be moved to
325somewhere under python.org).
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000326
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003271.8. Q. Is the Python documentation available on the WWW?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000328
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000329A. Yes, see <URL:http://www.cwi.nl/~guido/Python.html> (Python's home
330page). It contains pointers to hypertext versions of the whole
331documentation set (as hypertext, not just PostScript).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000332
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000333If you wish to browse this collection of HTML files on your own
334machine, it is available bundled up by anonymous ftp,
335e.g. <URL:ftp://ftp.cwi.nl/pub/python/python-html.tar.gz>. (This
336requires some manual patch-up for the references to images,
337unfortunately.)
338
339An Emacs-INFO set containing the library manual is also available by
340ftp, e.g. <URL:ftp://ftp.cwi.nl/pub/python/python-lin-info.tar.gz>.
341
3421.9. Q. Is there a book on Python, or will there be one out soon?
343
344A. I am writing one. Publishers are interested. Optimistically, it
345will be ready for the press by mid-1995. Mark Lutz is working on one
346too -- more details as they emerge.
347
3481.10. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000349
350A. So far the only refereed and published article that describes
351Python in some detail is:
352
353 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
354 Servers Using the Python Programming Language", CWI Quarterly, Volume
355 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
356
357LaTeX source for this paper is available as part of the Python source
358distribution.
359
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003601.11. Q. Are there short introductory papers or talks on Python?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000361
362A. A recent high-level description of Python is:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000363
364 Guido van Rossum, "An Introduction to Python for UNIX/C
365 Programmers", in the proceedings of the NLUUG najaarsconferentie
Guido van Rossum061f1821994-10-06 16:03:45 +0000366 1993 (dutch UNIX users group meeting November 1993).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000367
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000368PostScript for this paper and for the slides used for the accompanying
369presentation is available by ftp as
370<URL:ftp://ftp.cwi.nl/pub/python/nluug-paper.ps> and
371<URL:ftp://ftp.cwi.nl/pub/python/nluug-slides.ps>, respectively.
372
373Slides for a talk on Python that I gave at the Usenix Symposium on
374Very High Level Languages in Santa Fe, NM, USA in October 1995 are
375available as <URL:ftp://ftp.cwi.nl/pub/python/vhll-slides.ps>.
376
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003771.12. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000378
379A. Python versions are numbered A.B.C. A is the major version number
380-- it is only incremented for major changes in functionality or source
381structure. B is the minor version number, incremented for less
382earth-shattering changes to a release. C is the patchlevel -- it is
383incremented for each new release. Note that in the past, patches have
384added significant changes; in fact the changeover from 0.9.9 to 1.0.0
385was the first time that either A or B changed!
386
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000387Beta versions have an additional suffix of "-beta-N" for some small
388number N. Note that (for instance) all versions labeled 1.2-beta-N
389*precede* the actual release of 1.2.
390
3911.13. Q. How do I get a beta test version of Python?
392
393A. Write me. I might like you :-) Seriously, anybody who has
394previously used and installed Python can become a beta tester, but I
395expect feedback, so you have to write me first before I divulge the
396secret location of the latest beta release.
397
3981.14. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000399
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000400A. An interesting ftp site for Python users is ftp.markv.com; the
401directory pub/python contains a growing collection of interesting
402Python scripts <URL:ftp://ftp.markv.com/pub/python/>. To submit a
403script for inclusion, place it together with a readme file (with
404extension .readme) in the publicly writable directory
405/incoming/python. This service is maintained by Lance Ellinghaus
406<lance@markv.com>. (I've heard complaints about this service not
407being very responsive -- try at your own risk.)
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000408
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00004091.15. Q. Are there copyright restrictions on the use of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000410
411A. Hardly. You can do anything you want with the source, as long as
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000412you leave the copyrights in, and display those copyrights in any
413documentation about Python that you produce. Also, don't use the
414author's institute's name in publicity without prior written
415permission, and don't hold them responsible for anything (read the
416actual copyright for a precise legal wording).
417
418In particular, if you honor the copyright rules, it's OK to use Python
419for commercial use, to sell copies of Python in source or binary form,
420or to sell products that enhance Python or incorporate Python (or part
421of it) in some form. I would still like to know about all commercial
422use of Python!
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000423
Guido van Rossuma7925f11994-01-26 10:20:16 +0000424
4252. Python in the real world
426===========================
427
4282.1. Q. How many people are using Python?
429
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000430A. I don't know, but the maximum number of simultaneous subscriptions
431to the Python mailing list before it was gatewayed into the newsgroup
432was about 180 (several of which were local redistribution lists). I
433believe that many active Python users don't bother to subscribe to the
434list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000435is even less meaningful. I see new names on the newsgroup all the
436time and my best guess is that there are currently at least several
437thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000438
4392.2. Q. Have any significant projects been done in Python?
440
441A. Here at CWI (the home of Python), we have written a 20,000 line
442authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00004435,000 line multimedia teleconferencing tool, as well as many many
444smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000445
446The University of Virginia uses Python to control a virtual reality
447engine. Contact: Matt Conway <conway@virginia.edu>.
448
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000449The ILU project at Xerox PARC can generate Python glue for ILU
450interfaces. See <URL:ftp://ftp.parc.xerox.com/pub/ilu/ilu.html>.
451
Guido van Rossumac3f2121995-04-10 11:53:42 +0000452The University of California, Irvine uses a student administration
453system called TELE-Vision written entirely in Python. Contact: Ray
454Price <rlprice@uci.edu>.
455
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000456If you have done a significant project in Python that you'd like to be
457included in the list above, send me email!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000458
4592.3. Q. Are there any commercial projects going on using Python?
460
461A. Several companies have revealed to me that they are planning or
Guido van Rossum796b2591995-01-20 23:05:52 +0000462considering use of Python in a future product.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000463
Guido van Rossumac3f2121995-04-10 11:53:42 +0000464Sunrise Software, have a product out using Python -- they use Python
465for a GUI management application and an SNMP network management
466application. Contact: <info@sunrise.com>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000467
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000468Infoseek uses Python to implement their commercial WWW information
469retrieval service <URL:http://www.infoseek.com/>. Contact:
470<info@infoseek.com>.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000471
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000472Michael Powers of daVinci Time & Space is "writing tons-o-python for
473interactive television entertainment." Contact: <powers@dvts.com>.
474
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000475Paul Everitt of Connecting Minds is planning a Lotus Notes gateway.
476Contact: <Paul.Everitt@cminds.com>. Or see their WWW server
477<URL:http://www.cminds.com/>.
478
Guido van Rossumac3f2121995-04-10 11:53:42 +0000479KaPRE in Boulder, CO is using Python for on-site customization of C++
480applications, rapid-prototyping/development,
481language-based-components, and possibly more. This is pretty solid:
482Python's being shipped with their tool-set now, to beta sites.
483Contact: <lutz@KaPRE.COM> (Mark Lutz).
484
485Individuals at many other companies are using Python for internal
486development or for as yet unannounced products (witness their
487contributions to the Python mailing list or newsgroup).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000488
489Python has also been elected as an extension language by MADE, a
490consortium supported by the European Committee's ESPRIT program and
491consisting of Bull, CWI and some other European companies. Contact:
492Ivan Herman <ivan@cwi.nl>.
493
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000494If you'd like to be included in the list above, send me email!
495
Guido van Rossum95f61a71994-01-26 17:23:37 +00004962.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000497
Guido van Rossum3de27361994-07-25 14:19:33 +0000498A. Very stable. While the current version number would suggest it is
499in the early stages of development, in fact new, stable releases
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000500(numbered 0.9.x through 1.1.x) have been coming out roughly every 3 to
5016 months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000502
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00005032.5. Q. When will the next version be released?
504
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000505A. I am planning to release 1.2 in February or early March 1995. It
506will contain hooks into the implementation of the import command, a
507(still limited) form of persistent objects, and the usual complement
508of bug fixes (including many fixed memory leaks and thread problems).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000509
5102.6. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000511
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000512A. There will be better ports to the Mac, DOS, Windows, Windows NT, and
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000513OS/2. The Windows ports will support dynamically loaded modules using
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000514DLLs.
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000515
516Also planned is improved support for embedding Python in other
517applications, e.g. by renaming most global symbols to have a "Py"
518prefix and providing more documentation and threading support.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000519
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000520Some proposals were discussed at the recent Python workshop:
521
522 - persistent objects
523
524 - safe execution of untrusted Python code
525
526 - extensions to the import statement for managing packages
527 (groups of related modules)
528
529 - automatic generation of C/C++ interface glue
530
531 - interfaces to OMG IDL (== Interface Definition Language by
532 the Object Management Group)
533
534 - a portable GUI API (Graphical User Interface Application
535 Programmers Interface)
536
537 - module customization tools
538
539 - standardized documentation strings on module, class and
540 function objects
541
542 - the formation of a Python Steering Committee
543
544 - another Python Workshop
545
546For more info, have a look at the WWW page for the last Python
547Workshop <URL:http://www.eeel.nist.gov/python/workshop11-94/>.
548
549
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00005502.7. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossum3de27361994-07-25 14:19:33 +0000551
552A. In general, no. There are already millions of lines of Python code
553around the world, so any changes in the language that invalidates more
554than a very small fraction of existing programs has to be frowned
555upon. Even if you can provide a conversion program, there still is
556the problem of updating all documentation. Providing a gradual
557upgrade path is the only way if a feature has to be changed.
558
Guido van Rossuma7925f11994-01-26 10:20:16 +0000559
5603. Building Python
561==================
562
Guido van Rossum91f60831994-02-15 15:52:27 +00005633.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000564
565A. Yes, simply do "import testall" (or "import autotest" if you aren't
566interested in the output). The standard modules whose name begins
567with "test" together comprise the test. The test set doesn't test
568*all* features of Python but it goes a long way to confirm that a new
569port is actually working. The Makefile contains an entry "make test"
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000570which runs the autotest module. NOTE: if "make test" fails, run the
571tests manually ("import testall") to see what goes wrong before
572reporting the error.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000573
Guido van Rossum91f60831994-02-15 15:52:27 +00005743.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000575operations, but when playing with floating point operations I cannot
576find anything wrong with them.
577
578A. The test set makes occasional unwarranted assumptions about the
579semantics of C floating point operations. Until someone donates a
580better floating point test set, you will have to comment out the
581offending floating point tests and execute similar tests manually.
582
Guido van Rossum061f1821994-10-06 16:03:45 +00005833.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
Guido van Rossum24349991994-02-02 14:12:45 +0000584
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000585A. 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 +0000586
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005873.4. Q. Link errors building Python with STDWIN 0.9.9.
Guido van Rossum061f1821994-10-06 16:03:45 +0000588
Guido van Rossum796b2591995-01-20 23:05:52 +0000589A. The linker probably complains that it can't find routines like
590'tecreate', 'tenew' etc. The STDWIN 0.9.9 distribution requires that
591you add TWO libraries from stdwin to the line for stdwin in the
592Setupfile. Use something like this (all on one line!):
Guido van Rossum061f1821994-10-06 16:03:45 +0000593
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000594 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 +0000595
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005963.5. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000597
598A. It is generally necessary to run "make clean" after a configuration
599change.
600
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006013.6. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000602script (after the script name).
603
604A. You are probably linking with GNU getopt, e.g. through -liberty.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000605Don't. The reason for the complaint is that GNU getopt, unlike System
606V getopt and other getopt implementations, doesn't consider a
607non-option to be the end of the option list. A quick (and compatible)
608fix for scripts is to add "--" to the interpreter, like this:
609
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000610 #! /usr/local/bin/python --
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000611
612You can also use this interactively:
613
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000614 python -- script.py [options]
615
616Note that a working getopt implementation is provided in the Python
617distribution (in Python/getopt.c) but not automatically used.
Guido van Rossum24349991994-02-02 14:12:45 +0000618
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006193.7. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000620glmodule.c, but python hasn't been built or installed yet.
621
622A. Comment out the line mentioning glmodule.c in Setup and build a
623python without gl first; install it or make sure it is in your $PATH,
624then edit the Setup file again to turn on the gl module, and make
625again. You don't need to do "make clean"; you do need to run "make
626Makefile" in the Modules subdirectory (or just run "make" at the
627toplevel).
628
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006293.8. Q. Python built with gcc for the DEC Alpha doesn't work.
Guido van Rossum3de27361994-07-25 14:19:33 +0000630
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000631People have reported problems with gcc 2.5.8 up to 2.6.3. The DEC
632OSF/1 cc compiler does not have these problems so it's likely a gcc
633bug. The latest news is that (at least in the 1.2 beta release) the
634problem still exists but only when you use -O, and only affects the
635code generated from Python/marshal.c. A fix is to change "long i, n;"
636into "int i, n;" in w_object().
Guido van Rossum3de27361994-07-25 14:19:33 +0000637
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006383.9. Q. I use VPATH but some targets are built in the source directory.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000639
640A. On some systems (e.g. Sun), if the target already exists in the
641source directory, it is created there instead of in the build
642directory. This is usually because you have previously built without
643VPATH. Try running "make clobber" in the source directory.
644
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006453.10. Q. Trouble building or linking with the GNU readline library.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000646
Guido van Rossumac3f2121995-04-10 11:53:42 +0000647A. Consider using readline 2.0. Some hints:
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000648
649- You can use the GNU readline library to improve the interactive user
650interface: this gives you line editing and command history when
Guido van Rossum796b2591995-01-20 23:05:52 +0000651calling python interactively. You need to configure and build the GNU
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000652readline library before running the configure script. Its sources are
653no longer distributed with Python; you can ftp them from any GNU
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000654mirror site, or from its home site
655<URL:ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz> (or a
656higher version number -- using version 1.x is not recommended). Pass
657the Python configure script the option --with-readline=DIRECTORY where
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000658DIRECTORY is the absolute pathname of the directory where you've built
659the readline library. Some hints on building and using the readline
660library:
661
662- On SGI IRIX 5, you may have to add the following
663to rldefs.h:
664
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000665 #ifndef sigmask
666 #define sigmask(sig) (1L << ((sig)-1))
667 #endif
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000668
669- On most systems, you will have to add #include "rldefs.h" to the
670top of several source files, and if you use the VPATH feature, you
671will have to add dependencies of the form foo.o: foo.c to the
672Makefile for several values of foo.
673
674- The readline library requires use of the termcap library. A
675known problem with this is that it contains entry points which
Guido van Rossum061f1821994-10-06 16:03:45 +0000676cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000677conflict can be solved (and will be, in the next release of
Guido van Rossum061f1821994-10-06 16:03:45 +0000678STDWIN) by adding a line saying '#define werase w_erase' to the
679stdwin.h file (in the STDWIN distribution, subdirectory H). The
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000680GL conflict has been solved in the Python configure script by a
681hack that forces use of the static version of the termcap library.
682
Guido van Rossumac3f2121995-04-10 11:53:42 +0000683- Check the newsgroup gnu.bash.bug <URL:news:gnu.bash.bug> for
684specific problems with the readline library (I don't read this group
685but I've been told that it is the place for readline bugs).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000686
Guido van Rossum9351fdb1994-11-10 23:03:51 +00006873.11. Q. Trouble building Python on Linux.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000688
Guido van Rossumac3f2121995-04-10 11:53:42 +0000689A. If you're building Python 1.2, Slackware 2.2 has a buggy bash
690(version 1.14.3) which breaks a sed script that is used to build
691Modules/Makefile. Replace /bin/sh with /bin/ash in both makesetup and
692Makefile.pre.in.
693
694In 1.1 and 1.1.1, there's a bug in the reference counting logic of
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000695ternary pow() which is only tripped by very picky mallocs, like the
696GNU malloc on Linux. This has been fixed in 1.2. To continue the
Guido van Rossumac3f2121995-04-10 11:53:42 +0000697tests in 1.1(.1), just disable the tests of pow() with three arguments
698from Lib/test/test_b2.py.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000699
Guido van Rossumac3f2121995-04-10 11:53:42 +0000700Apart from this, Python builds and runs fine on most Linux versions
701(if you run into trouble on an old Linux version, consider upgrading).
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 Rossumac3f2121995-04-10 11:53:42 +0000710A. (This is fixed in 1.2.) You need to pass "-posix" to the C
711compiler, especially in the link phase -- it uses the correct version
712of the C library. The easiest way is perhaps to do "make OPT=-posix".
713You also need to remove this NeXT-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 Rossumac3f2121995-04-10 11:53:42 +000013814.32. Q. How do I call a function if I have the arguments in a tuple?
1382
1383A. Use the built-in function apply(). For instance,
1384
1385 func(1, 2, 3)
1386
1387is equivalent to
1388
1389 args = (1, 2, 3)
1390 apply(func, args)
1391
1392Note that func(args) is not the same -- it calls func() with exactly
1393one argument, the tuple args, instead of three arguments, the integers
13941, 2 and 3.
1395
Guido van Rossum061f1821994-10-06 16:03:45 +00001396
Guido van Rossuma7925f11994-01-26 10:20:16 +000013975. Extending Python
1398===================
1399
14005.1. Q. Can I create my own functions in C?
1401
1402A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +00001403variables, exceptions and even new types in C. This is explained in
1404the document "Extending and Embedding the Python Interpreter" (the
1405LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001406
14075.2. Q. Can I create my own functions in C++?
1408
1409A. Yes, using the C-compatibility features found in C++. Basically
1410you place extern "C" { ... } around the Python include files and put
1411extern "C" before each function that is going to be called by the
1412Python interpreter. Global or static C++ objects with constructors
1413are probably not a good idea.
1414
Guido van Rossum7ce61c11994-06-13 15:13:56 +000014155.3. Q. How can I execute arbitrary Python statements from C?
1416
1417A. The highest-level function to do this is run_command() which takes
1418a single string argument which is executed in the context of module
1419__main__ and returns 0 for success and -1 when an exception occurred
1420(including SyntaxError). If you want more control, use run_string();
1421see the source for run_command() in Python/pythonrun.c.
1422
14235.4. Q. How can I evaluate an arbitrary Python expression from C?
1424
1425A. Call the function run_string() from the previous question with the
1426start symbol eval_input; it then parses an expression, evaluates it
1427and returns its value. See exec_eval() in Python/bltinmodule.c.
1428
14295.5. Q. How do I extract C values from a Python object?
1430
1431A. That depends on the object's type. If it's a tuple,
1432gettuplesize(o) returns its length and gettupleitem(o, i) returns its
1433i'th item; similar for lists with getlistsize(o) and getlistitem(o,
1434i). For strings, getstringsize(o) returns its length and
1435getstringvalue(o) a pointer to its value (note that Python strings may
1436contain null bytes so strlen() is not safe). To test which type an
1437object is, first make sure it isn't NULL, and then use
1438is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
1439
14405.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
1441
1442A. You can't. Use t = newtupleobject(n) instead, and fill it with
1443objects using settupleitem(t, i, o) -- note that this "eats" a
1444reference count of o. Similar for lists with newlistobject(n) and
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001445setlistitem(l, i, o). Note that you *must* set all the tuple items to
1446some value before you pass the tuple to Python code --
1447newtupleobject(n) initializes them to NULL, which isn't a valid Python
1448value.
1449
Guido van Rossum796b2591995-01-20 23:05:52 +000014505.7. Q. What happened to mktuple(), featured in an example in the
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001451Extensions manual?
1452
1453A. It's a typo, I meant newtupleobject() (see previous question).
1454
14555.8. Q. How do I call an object's method from C?
1456
1457A. Here's a function (untested) that might become part of the next
1458release in some form. It uses <stdarg.h> to allow passing the
1459argument list on to vmkvalue():
1460
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001461 object *call_method(object *inst, char *methodname, char *format, ...)
1462 {
1463 object *method;
1464 object *args;
1465 object *result;
1466 va_list va;
1467 method = getattr(inst, methodname);
1468 if (method == NULL) return NULL;
1469 va_start(va, format);
1470 args = vmkvalue(format, va);
1471 va_end(va);
1472 if (args == NULL) {
1473 DECREF(method);
1474 return NULL;
1475 }
1476 result = call_object(method, args);
1477 DECREF(method);
1478 DECREF(args);
1479 return result;
1480 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001481
1482This works for any instance that has methods -- whether built-in or
1483user-defined. You are responsible for eventually DECREF'ing the
1484return value.
1485
1486To call, e.g., a file object's "seek" method with arguments 10, 0
1487(assuming the file object pointer is "f"):
1488
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001489 res = call_method(f, "seek", "(OO)", 10, 0);
1490 if (res == NULL) {
1491 ... an exception occurred ...
1492 }
1493 else {
1494 DECREF(res);
1495 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001496
1497Note that since call_object() *always* wants a tuple for the argument
1498list, to call a function without arguments, pass "()" for the format,
1499and to call a function with one argument, surround the argument in
1500parentheses, e.g. "(i)".
1501
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001502(This function and a companion will be available in 1.2 under the
1503names PyEval_CallFunction and PyEval_CallMethod.)
1504
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000015055.9. Q. How do I catch the output from print_error()?
1506
1507A. (Due to Mark Hammond):
1508
1509* in Python code, define an object that supports the "write()" method.
1510FWIW, there seems to be a small problem that requires the 'softspace'
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001511attribute to be defined too (fixed in 1.2).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001512
1513* redirect sys.stdout and sys.stderr to this object.
1514
Guido van Rossum061f1821994-10-06 16:03:45 +00001515* call print_error, or just allow the standard traceback mechanism to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001516work.
1517
Guido van Rossum061f1821994-10-06 16:03:45 +00001518Then, the output will go wherever your write() method sends it.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001519
15205.10. Q. How do I access a module written in Python from C?
1521
1522A. You can get a pointer to the module object as follows:
1523
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001524 module = import_module("<modulename>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001525
1526If the module hasn't been imported yet (i.e. it is not yet present in
1527sys.modules), this initializes the module; otherwise it simply returns
1528the value of sys.modules["<modulename>"]. Note that it doesn't enter
1529the module into any namespace -- it only ensures it has been
1530initialized and is stored in sys.modules.
1531
1532You can then access the module's attributes (i.e. any name defined in
1533the module) as follows:
1534
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001535 attr = getattr(module, "<attrname>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001536
1537Calling setattr(), to assign to variables in the module, also works.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001538
Guido van Rossuma7925f11994-01-26 10:20:16 +00001539
15406. Python's design
1541==================
1542
15436.1. Q. Why isn't there a generic copying operation for objects in
1544Python?
1545
1546A. Hmm. Maybe there should be one, but it's difficult to assign a
1547useful meaning to copying of open files, sockets and windows, or
1548recursive data structures. As long as you design all your classes
1549yourself you are of course free to define a standard base class that
1550defines an overridable copying operation for all the objects you care
1551about. (One practical point: it would have to be a built-in function,
1552not a standard method name, since not all built-in object types have
1553methods; e.g. strings, integers and tuples don't.)
1554
15556.2. Q. Why isn't there a generic way to implement persistent objects
1556in Python? (Persistent == automatically saved to and restored from
1557disk.)
1558
1559A. Hmm, hmm. Basically for the same reasons as why there is no
1560generic copying operation.
1561
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001562A partial solution will appear in release 1.2. This will also provide
1563a partial solution to the problem of a generic copying operation.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001564(Partial because it still won't cope with open files etc.; however it
1565does handle user-defined classes!)
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001566
Guido van Rossuma7925f11994-01-26 10:20:16 +000015676.3. Q. Why isn't there a switch or case statement in Python?
1568
1569A. You can do this easily enough with a sequence of
1570if... elif... elif... else. There have been some proposals for switch
Guido van Rossum061f1821994-10-06 16:03:45 +00001571statement syntax, but there is no consensus (yet) on whether and how
Guido van Rossuma7925f11994-01-26 10:20:16 +00001572to do range tests.
1573
Guido van Rossumc50158e1994-05-31 09:18:50 +000015746.4. Q. Why does Python use indentation for grouping of statements?
1575
1576A. Basically I believe that using indentation for grouping is
1577extremely elegant and contributes a lot to the clarity of the average
1578Python program. Most people learn to love this feature after a while.
1579Some arguments for it:
1580
1581- Since there are no begin/end brackets there cannot be a disagreement
1582between grouping perceived by the parser and the human reader. I
1583remember long ago seeing a C fragment like this:
1584
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001585 if (x <= y)
1586 x++;
1587 y--;
1588 z++;
Guido van Rossumc50158e1994-05-31 09:18:50 +00001589
1590and staring a long time at it wondering why y was being decremented
1591even for x > y... (And I wasn't a C newbie then either.)
1592
1593- Since there are no begin/end brackets there can be no conflicting
1594coding styles. In C there are loads of different ways to place the
1595braces (including the choice whether to place braces around single
1596statements in certain cases, for consistency). If you're used to
1597reading (and writing) code that uses one style, you will feel at least
1598slightly uneasy when reading (or being required to write) another
1599style.
1600
1601- Many coding styles place begin/end brackets on a line by themself.
1602This makes programs considerably longer and wastes valuable screen
1603space, making it harder to get a good overview over a program.
1604Ideally, a function should fit on one basic tty screen (say, 20
1605lines). 20 lines of Python are worth a LOT more than 20 lines of C.
1606This is not solely due to the lack of begin/end brackets (the lack of
1607declarations also helps, and the powerful operations of course), but
1608it certainly helps!
1609
Guido van Rossum3de27361994-07-25 14:19:33 +000016106.5. Q. Why are Python strings immutable?
1611
1612A. There are two advantages. One is performance: knowing that a
1613string is immutable makes it easy to lay it out at construction time
1614-- fixed and unchanging storage requirements. (This is also one of
Guido van Rossum061f1821994-10-06 16:03:45 +00001615the reasons for the distinction between tuples and lists.) The
Guido van Rossum3de27361994-07-25 14:19:33 +00001616other is that strings in Python are considered as "elemental" as
1617numbers. No amount of activity will change the value 8 to anything
1618else, and in Python, no amount of activity will change the string
1619"eight" to anything else. (Adapted from Jim Roskind)
1620
16216.6. Q. Why don't strings have methods like index() or sort(), like
1622lists?
1623
1624A. Good question. Strings currently don't have methods at all
1625(likewise tuples and numbers). Long ago, it seemed unnecessary to
1626implement any of these functions in C, so a standard library module
1627"string" written in Python was created that performs string related
1628operations. Since then, the cry for performance has moved most of
1629them into the built-in module strop (this is imported by module
Guido van Rossumf8c76d01994-08-17 12:19:53 +00001630string, which is still the preferred interface, without loss of
Guido van Rossum3de27361994-07-25 14:19:33 +00001631performance except during initialization). Some of these functions
1632(e.g. index()) could easily be implemented as string methods instead,
1633but others (e.g. sort()) can't, since their interface prescribes that
1634they modify the object, while strings are immutable (see the previous
1635question).
1636
16376.7. Q. Why does Python use methods for some functionality
1638(e.g. list.index()) but functions for other (e.g. len(list))?
1639
1640A. Functions are used for those operations that are generic for a
1641group of types and which should work even for objects that don't have
1642methods at all (e.g. numbers, strings, tuples). Also, implementing
1643len(), max(), min() as a built-in function is actually less code than
1644implementing them as methods for each type. One can quibble about
1645individual cases but it's really too late to change such things
1646fundamentally now.
1647
16486.8. Q. Why can't I derive a class from built-in types (e.g. lists or
1649files)?
1650
1651A. This is caused by the relatively late addition of (user-defined)
1652classes to the language -- the implementation framework doesn't easily
1653allow it. See the answer to question 4.2 for a work-around. This
1654*may* be fixed in the (distant) future.
1655
16566.9. Q. Why must 'self' be declared and used explicitly in method
1657definitions and calls?
1658
1659A. By asking this question you reveal your C++ background. :-)
1660When I added classes, this was (again) the simplest way of
1661implementing methods without too many changes to the interpreter. I
1662borrowed the idea from Modula-3. It turns out to be very useful, for
1663a variety of reasons.
1664
1665First, it makes it more obvious that you are using a method or
1666instance attribute instead of a local variable. Reading "self.x" or
1667"self.meth()" makes it absolutely clear that an instance variable or
1668method is used even if you don't know the class definition by heart.
1669In C++, you can sort of tell by the lack of a local variable
Guido van Rossum061f1821994-10-06 16:03:45 +00001670declaration (assuming globals are rare or easily recognizable) -- but
Guido van Rossum3de27361994-07-25 14:19:33 +00001671in Python, there are no local variable declarations, so you'd have to
1672look up the class definition to be sure.
1673
1674Second, it means that no special syntax is necessary if you want to
1675explicitly reference or call the method from a particular class. In
1676C++, if you want to use a method from base class that is overridden in
1677a derived class, you have to use the :: operator -- in Python you can
1678write baseclass.methodname(self, <argument list>). This is
1679particularly useful for __init__() methods, and in general in cases
1680where a derived class method wants to extend the base class method of
1681the same name and thus has to call the base class method somehow.
1682
1683Lastly, for instance variables, it solves a syntactic problem with
1684assignment: since local variables in Python are (by definition!) those
1685variables to which a value assigned in a function body (and that
1686aren't explicitly declared global), there has to be some way to tell
1687the interpreter that an assignment was meant to assign to an instance
1688variable instead of to a local variable, and it should preferably be
1689syntactic (for efficiency reasons). C++ does this through
1690declarations, but Python doesn't have declarations and it would be a
1691pity having to introduce them just for this purpose. Using the
1692explicit "self.var" solves this nicely. Similarly, for using instance
1693variables, having to write "self.var" means that references to
1694unqualified names inside a method don't have to search the instance's
1695directories.
1696
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000016976.10. Q. Can't you emulate threads in the interpreter instead of
1698relying on an OS-specific thread implementation?
1699
1700A. Unfortunately, the interpreter pushes at least one C stack frame
1701for each Python stack frame. Also, extensions can call back into
1702Python at almost random moments. Therefore a complete threads
1703implementation requires thread support for C.
1704
Guido van Rossum061f1821994-10-06 16:03:45 +000017056.11. Q. Why can't lambda forms contain statements?
1706
1707A. Python lambda forms cannot contain statements because Python's
Guido van Rossum796b2591995-01-20 23:05:52 +00001708syntactic framework can't handle statements nested inside expressions.
Guido van Rossum061f1821994-10-06 16:03:45 +00001709
1710However, in Python, this is not a serious problem. Unlike lambda
1711forms in other languages, where they add functionality, Python lambdas
1712are only a shorthand notation if you're too lazy to define a function.
1713
1714Functions are already first class objects in Python, and can be
1715declared in a local scope. Therefore the only advantage of using a
1716lambda form instead of a locally-defined function is that you'll have
1717to invent a name for the function -- but that's just a local variable
1718to which the function object (which is exactly the same type of object
1719that a lambda form yields) is assigned!
1720
17216.12. Q. Why is there no more efficient way of iterating over a dictionary
1722than first constructing the list of keys()?
1723
1724A. Have you tried it? I bet it's fast enough for your purposes! In
1725most cases such a list takes only a few percent of the space occupied
1726by the dictionary -- it needs only 4 bytes (the size of a pointer) per
1727key -- a dictionary costs 8 bytes per key plus between 30 and 70
1728percent hash table overhead, plus the space for the keys and values --
1729by necessity all keys are unique objects and a string object (the most
1730common key type) costs at least 18 bytes plus the length of the
1731string. Add to that the values contained in the dictionary, and you
1732see that 4 bytes more per item really isn't that much more memory...
1733
1734A call to dict.keys() makes one fast scan over the dictionary
1735(internally, the iteration function does exist) copying the pointers
1736to the key objects into a pre-allocated list object of the right size.
1737The iteration time isn't lost (since you'll have to iterate anyway --
1738unless in the majority of cases your loop terminates very prematurely
1739(which I doubt since you're getting the keys in random order).
1740
1741I don't expose the dictionary iteration operation to Python
1742programmers because the dictionary shouldn't be modified during the
1743entire iteration -- if it is, there's a very small chance that the
1744dictionary is reorganized because the hash table becomes too full, and
1745then the iteration may miss some items and see others twice. Exactly
1746because this only occurs rarely, it would lead to hidden bugs in
1747programs: it's easy never to have it happen during test runs if you
1748only insert or delete a few items per iteration -- but your users will
1749surely hit upon it sooner or later.
1750
Guido van Rossuma7925f11994-01-26 10:20:16 +00001751
17527. Using Python on non-UNIX platforms
1753=====================================
1754
Guido van Rossum91f60831994-02-15 15:52:27 +000017557.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001756
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001757A. Yes. It is on most ftp sites carrying Python as python.sea.hqx,
1758e.g. <URL:ftp://ftp.cwi.nl/pub/python/python_1.1.sea.hqx> -- this is a
1759self-extracting archive containing the application binary as well as
1760the Lib modules.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001761
Guido van Rossum91f60831994-02-15 15:52:27 +000017627.2. Q. Is there a DOS version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001763
Guido van Rossum91f60831994-02-15 15:52:27 +00001764A. Yes. More than one, actually: 16python.exe runs in standard DOS
1765mode on 186 CPUs or higher; 32python.exe uses a DOS extender and only
1766runs on a 386 or higher CPUs. Although 16python.exe does not pass the
1767test set because test_grammar is too big for the parser, it actually
1768has about 270 kbyte of allocatable heap space, which is sufficient for
1769fairly large programs. 32python.exe is distributed as a tar file
1770containing the required DOS extended and 387 emulator. Both are on
1771most ftp sites carrying Python.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001772
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001773The file dosbuild.tar.gz on the standard ftp sites contains
1774rudimentary Makefiles and instructions
1775<URL:ftp://ftp.cwi.nl/pub/python/dosbuild.tar.gz>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001776
Guido van Rossum91f60831994-02-15 15:52:27 +000017777.3. Q. Is there a Windows version of Python?
1778
1779A. Yes. Use qwpython.exe. The only problem with it: ^C
1780unconditionally kills the entire program -- it does not raise
1781KeyboardInterrupt. You can also run 16python.exe or 32python.exe in a
1782"DOS box", but qwpython.exe appears to be slightly faster.
1783
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001784There aren't any Makefiles at this moment. Sorry.
1785
1786Using Win32s (a free NT compatibility package by Microsoft) you can
1787also use the NT version by Mark Hammond -- the Win32s package is also
1788in that directory (you'll need several MB of disk space to install
1789it). See the next question.
1790
Guido van Rossum91f60831994-02-15 15:52:27 +000017917.4. Q. Is there a Windows NT version of Python?
1792
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001793A. Yes. Mark Hammond <MHammond@cmutual.com.au> has built a full NT
1794port. This supports using DLLs for dynamic loading of Python modules,
1795and includes an interface to the Microsoft Foundation Classes and a
1796Python programming environment using it that's written mostly in
1797Python. See <URL:ftp://ftp.cwi.nl/pub/python/nt/> -- most mirrors
1798will also have this.
Guido van Rossum91f60831994-02-15 15:52:27 +00001799
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001800Sam Rushing <rushing@squirl.oau.org> once announced he knows how to
1801build Python for the Windows NT on the DEC Alpha AXP.
Guido van Rossum061f1821994-10-06 16:03:45 +00001802
1803Note that currently there is no unified compilation environment for
1804all NT platforms -- hopefully Microsoft will fix this with the release
1805of Visual C++ 2.0.
1806
Guido van Rossum7ce61c11994-06-13 15:13:56 +000018077.5. Q. Is there an OS/2 version of Python?
1808
Guido van Rossumac3f2121995-04-10 11:53:42 +00001809A. Yes. You can ftp an old version from the usual places as
1810pyth_os2.zip, e.g. <URL:ftp://ftp.cwi.nl/pub/python/pyth_os2.zip>.
1811This contains both an executable and Makefiles for those fortunate
1812enough to have a C compiler. A newer port is in progress -- Chris
1813Vale <cvale@netcom.com> is doing the work, using Borland C, based on
1814Mark Hammond's NT port.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001815
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000018167.6. Q. Is there a VMS version of Python?
1817
1818A. I think not (yet). This question has been asked on the list
1819several times and I've never seen an answer. Maybe someone with a VMS
1820C compiler could attempt a port? Probably coming up with proper
1821Makefiles, config.h and config.c should be sufficient. If you succeed
1822(or even if you get stuck halfway), please let me know! (Info as of
182323 September 1994.)
1824
18257.7. Q. What about IBM mainframes, or other esoteric non-UNIX
1826platforms?
1827
1828A. Basically, the same story as for VMS... (Info as of 23 September
18291994.)
1830
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000018317.8. Q. Where are the source or Makefiles for the non-UNIX versions?
1832
1833A. The standard sources can (almost) be used. See the previous
1834questions for availability of Makefiles/projects or patches. If you
1835find things in the standard sources that don't work on your particular
1836platform, please let me know and I'll integrate a solution into the
1837next release of the standard sources. If you submit a fix, please use
1838some kind of #ifdef so as to keep the source working for other
1839platforms. In particular, if the patch works around the availability
1840of a particular function of header file, you should mimic the
1841HAVE_... style used by the configure script -- you can then submit a
1842config.h file for a particular platform so there are no absolutely
1843platform-specific #ifdefs in the rest of the sources.
1844
18457.9. Q. What is the status and support for the non-UNIX versions?
1846
1847A. I don't have access to most of these platforms, so in general I am
1848dependent on material submitted by volunteers(*). However I strive to
1849integrate all changes needed to get it to compile on a particular
1850platform back into the standard sources, so porting of the next
1851version to the various non-UNIX platforms should be easy.
1852
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001853(*) For the Macintosh, that volunteer is me, with help from Jack
1854Jansen <jack@cwi.nl>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001855
18567.10. Q. I have the PC version but it appears to be only a binary.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001857Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001858
1859A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +00001860"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossum3de27361994-07-25 14:19:33 +00001861you can get the file pythonlib<version>.tar.gz from most ftp sites
1862carrying Python; this is a subset of the distribution containing just
Guido van Rossum796b2591995-01-20 23:05:52 +00001863those files, e.g.
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001864<URL:ftp://ftp.cwi.nl/pub/python/pythonlib1.1.tar.gz>.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001865
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001866Once you have installed the library, you need to point sys.path to it.
1867Assuming the library is in C:\misc\python\lib, the following commands
1868will point your Python interpreter to it (note the doubled backslashes
1869-- you can also use single forward slashes instead):
1870
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001871 >>> import sys
1872 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
1873 >>>
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001874
1875For a more permanent effect, set the environment variable PYTHONPATH,
1876as follows (talking to a DOS prompt):
1877
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001878 C> SET PYTHONPATH=C:\misc\python\lib
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001879
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000018807.11. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001881
1882A. There isn't any. The documentation for the Unix version also
Guido van Rossum91f60831994-02-15 15:52:27 +00001883applies to the Mac and PC versions. Where applicable, differences
Guido van Rossuma7925f11994-01-26 10:20:16 +00001884are indicated in the text.
1885
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000018867.12. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +00001887creating or editing programs apart from entering it interactively, and
1888there seems to be no way to save code that was entered interactively.
1889How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001890
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001891A. Use an external editor. On the Mac, BBEdit seems to be a popular
1892no-frills text editor. I work like this: start the interpreter; edit
1893a module file using BBedit; import and test it in the interpreter;
1894edit again in BBedit; then use the built-in function reload() to
1895re-read the imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001896
1897Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
1898anyone with a pulse could certainly figure out how to do the same on
1899MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
1900Not only can you easily resave and "reload()" from Python after making
1901changes, but since WinNot auto-copies to the clipboard any text you
1902select, you can simply select the entire procedure (function) which
1903you changed in WinNot, switch to QWPython, and shift-ins to reenter
1904the changed program unit."