blob: 669269e8dead8fc5c9e76b36ad53b3493d09dc8e [file] [log] [blame]
Guido van Rossum061f1821994-10-06 16:03:45 +00001NOTE -- THIS FAQ HAS NOT BEEN UPDATED TO REFLECT RELEASE 1.1 YET. FOR
21.1 RELATED PROBLEMS PLEASE WATCH THE NEWSGROUP / MAILING LIST OR
3CHECK THE FTP SITE.
4
Guido van Rossuma7925f11994-01-26 10:20:16 +00005Subject: FAQ: Python -- an object-oriented language
Guido van Rossum5333c5d1994-04-11 11:06:22 +00006Newsgroups: comp.lang.python,comp.answers,news.answers
7Followup-to: comp.lang.python
Guido van Rossuma7925f11994-01-26 10:20:16 +00008From: guido@cwi.nl (Guido van Rossum)
9Reply-to: guido@cwi.nl (Guido van Rossum)
10Approved: news-answers-request@MIT.Edu
11
12Archive-name: python-faq/part1
Guido van Rossum9351fdb1994-11-10 23:03:51 +000013Version: 1.16
14Last-modified: 11 November 1994
Guido van Rossuma7925f11994-01-26 10:20:16 +000015
16This article contains answers to Frequently Asked Questions about
17Python (an object-oriented interpreted programming language -- see
18the answer to question 1.1 for a short overview).
19
20Copyright 1993, 1994 Guido van Rossum. Unchanged electronic
21redistribution of this FAQ is allowed. Printed redistribution only
22with permission of the author. No warranties.
23
24Author's address:
25 Guido van Rossum
26 CWI, dept. CST
27 Kruislaan 413
28 P.O. Box 94079
29 1090 GB Amsterdam
30 The Netherlands
31Email: guido@cwi.nl
32
33The latest version of this FAQ is available by anonymous ftp from
Guido van Rossum7ce61c11994-06-13 15:13:56 +000034ftp.cwi.nl [192.16.191.128] in the directory /pub/python, with
Guido van Rossuma7925f11994-01-26 10:20:16 +000035filename python-FAQ. It will also be posted regularly to the
Guido van Rossum5333c5d1994-04-11 11:06:22 +000036newsgroups comp.answers and comp.lang.python.
Guido van Rossuma7925f11994-01-26 10:20:16 +000037
38Many FAQs, including this one, are available by anonymous ftp from
Guido van Rossumea2c6f71994-07-14 12:35:14 +000039rtfm.mit.edu [18.181.0.24] in the directory pub/usenet/news.answers.
Guido van Rossuma7925f11994-01-26 10:20:16 +000040The name under which a FAQ is archived appears in the Archive-name line
41at the top of the article. This FAQ is archived as python-faq/part1.
42
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
45message to mail-server@rtfm.mit.edu containing the single word help in
46the message body to receive instructions.
47
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000048Skip Montanaro <skip@automatrix.com> maintains an HTML version of this
Guido van Rossum061f1821994-10-06 16:03:45 +000049FAQ. The URL is <http://www.automatrix.com/~skip/python-faq.html>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000050
Guido van Rossuma7925f11994-01-26 10:20:16 +000051This FAQ is divided in the following chapters:
52
53 1. General information and availability
54 2. Python in the real world
55 3. Building Python
56 4. Programming in Python
57 5. Extending Python
58 6. Python's design
59 7. Using Python on non-UNIX platforms
60
61To find the start of a particular chapter, search for the chapter number
62followed by a dot and a space at the beginning of a line (e.g. to
63find chapter 4 in vi, type /^4\. /).
64
65Here's an overview of the questions per chapter:
66
67 1. General information and availability
68 1.1. Q. What is Python?
69 1.2. Q. Why is it called Python?
70 1.3. Q. How do I obtain a copy of the Python source?
71 1.4. Q. How do I get documentation on Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +000072 1.5. Q. Are there other ftp sites that mirror the Python distribution?
73 1.6. Q. Is there a newsgroup or mailing list devoted to Python?
74 1.7. Q. Is there a book on Python, or will there be one out soon?
75 1.8. Q. Are there any published articles about Python that I can quote?
76 1.9. Q. How does the Python version numbering scheme work?
77 1.10. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum7ce61c11994-06-13 15:13:56 +000078 1.11. Q. Are there copyright restrictions on the use of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +000079
80 2. Python in the real world
81 2.1. Q. How many people are using Python?
82 2.2. Q. Have any significant projects been done in Python?
83 2.3. Q. Are there any commercial projects going on using Python?
Guido van Rossum95f61a71994-01-26 17:23:37 +000084 2.4. Q. How stable is Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000085 2.5. Q. When will the next version be released?
86 2.6. Q. What new developments are expected for Python in the future?
87 2.7. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +000088
89 3. Building Python
Guido van Rossum91f60831994-02-15 15:52:27 +000090 3.1. Q. Is there a test set?
91 3.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +000092 operations, but when playing with floating point operations I cannot
93 find anything wrong with them.
Guido van Rossum9351fdb1994-11-10 23:03:51 +000094 3.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
95 3.4. Q. Link errors building Python with STDWIN 0.9.9.
96 3.5. Q. Link errors after rerunning the configure script.
97 3.6. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +000098 script (after the script name).
Guido van Rossum9351fdb1994-11-10 23:03:51 +000099 3.7. Q. When building on the SGI, make tries to run python to create
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000100 glmodule.c, but python hasn't been built or installed yet.
Guido van Rossum9351fdb1994-11-10 23:03:51 +0000101 3.8. Q. Python built with gcc for the DEC Alpha doesn't work.
102 3.9. Q. I use VPATH but some targets are built in the source directory.
103 3.10. Q. Trouble building or linking with the GNU readline library.
104 3.11. Q. Trouble building Python on Linux.
105 3.12. Q. Trouble with prototypes on Ultrix.
106 3.13. Q. Trouble with posix.listdir on NeXTSTEP 3.2.
107 3.14. Q. Other trouble building Python on platform X.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000108
109 4. Programming in Python
Guido van Rossum24349991994-02-02 14:12:45 +0000110 4.1. Q. Is there a source code level debugger with breakpoints, step,
111 etc.?
112 4.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000113 C and others in Python (e.g. through inheritance)? (Also phrased as:
114 Can I use a built-in type as base class?)
Guido van Rossum24349991994-02-02 14:12:45 +0000115 4.3. Q. Is there a curses/termcap package for Python?
116 4.4. Q. Is there an equivalent to C's onexit() in Python?
117 4.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000118 nested function seemingly can't access the local variables of the
119 outer function. What is going on? How do I pass local data to a
120 nested function?
Guido van Rossum24349991994-02-02 14:12:45 +0000121 4.6. Q. How do I iterate over a sequence in reverse order?
122 4.7. Q. My program is too slow. How do I speed it up?
123 4.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000124 again (into the same Python process), the changes don't seem to take
125 place. What is going on?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000126 4.9. Q. How do I find the current module name?
127 4.10. Q. I have a module in which I want to execute some extra code when it
128 is run as a script. How do I find out whether I am running as a
129 script?
130 4.11. Q. I try to run a program from the Demo directory but it fails with
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000131 ImportError: No module named ...; what gives?
Guido van Rossum061f1821994-10-06 16:03:45 +0000132 4.12. Q. I have successfully built Python with STDWIN but it can't
133 find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000134 4.13. Q. What GUI toolkits exist for Python?
Guido van Rossum061f1821994-10-06 16:03:45 +0000135 4.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000136 4.15. Q. Is it possible to write obfuscated one-liners in Python?
137 4.16. Q. Is there an equivalent of C's "?:" ternary operator?
138 4.17. Q. My class defines __del__ but it is not called when I delete the
139 object.
140 4.18. Q. How do I change the shell environment for programs called using
141 os.popen() or os.system()? Changing os.environ doesn't work.
142 4.19. Q. What is a class?
143 4.20. Q. What is a method?
144 4.21. Q. What is self?
145 4.22. Q. What is a unbound method?
146 4.23. Q. How do I call a method defined in a base class from a derived class
147 that overrides it?
148 4.24. Q. How do I call a method from a base class without using the name of
149 the base class?
150 4.25. Q. How can I organize my code to make it easier to change the base
151 class?
152 4.26. Q. How can I find the methods or attributes of an object?
Guido van Rossum061f1821994-10-06 16:03:45 +0000153 4.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
154 4.28. Q. How can I create a stand-alone binary from a Python script?
155 4.29. Q. Is there a special lib for writing CGI scripts in Python?
156 4.30. Q. What other WWW tools are there for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000157
158 5. Extending Python
159 5.1. Q. Can I create my own functions in C?
160 5.2. Q. Can I create my own functions in C++?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000161 5.3. Q. How can I execute arbitrary Python statements from C?
162 5.4. Q. How can I evaluate an arbitrary Python expression from C?
163 5.5. Q. How do I extract C values from a Python object?
164 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000165 5.7. Q. What happened to mktuple(), featuring in an example in the
166 Extensions manual?
167 5.8. Q. How do I call an object's method from C?
168 5.9. Q. How do I catch the output from print_error()?
169 5.10. Q. How do I access a module written in Python from C?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000170
171 6. Python's design
172 6.1. Q. Why isn't there a generic copying operation for objects in
173 Python?
174 6.2. Q. Why isn't there a generic way to implement persistent objects
175 in Python? (Persistent == automatically saved to and restored from
176 disk.)
177 6.3. Q. Why isn't there a switch or case statement in Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +0000178 6.4. Q. Why does Python use indentation for grouping of statements?
Guido van Rossum3de27361994-07-25 14:19:33 +0000179 6.5. Q. Why are Python strings immutable?
180 6.6. Q. Why don't strings have methods like index() or sort(), like
181 lists?
182 6.7. Q. Why does Python use methods for some functionality
183 (e.g. list.index()) but functions for other (e.g. len(list))?
184 6.8. Q. Why can't I derive a class from built-in types (e.g. lists or
185 files)?
186 6.9. Q. Why must 'self' be declared and used explicitly in method
187 definitions and calls?
Guido van Rossum061f1821994-10-06 16:03:45 +0000188 6.10. Q. Can't you emulate threads in the interpreter instead of
189 relying on an OS-specific thread implementation?
190 6.11. Q. Why can't lambda forms contain statements?
191 6.12. Q. Why is there no more efficient way of iterating over a dictionary
192 than first constructing the list of keys()?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000193
194 7. Using Python on non-UNIX platforms
Guido van Rossum91f60831994-02-15 15:52:27 +0000195 7.1. Q. Is there a Mac version of Python?
196 7.2. Q. Is there a DOS version of Python?
197 7.3. Q. Is there a Windows version of Python?
198 7.4. Q. Is there a Windows NT version of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000199 7.5. Q. Is there an OS/2 version of Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000200 7.6. Q. Is there a VMS version of Python?
201 7.7. Q. What about IBM mainframes, or other esoteric non-UNIX
202 platforms?
203 7.8. Q. Where are the source or Makefiles for the non-UNIX versions?
204 7.9. Q. What is the status and support for the non-UNIX versions?
205 7.10. Q. I have the PC version but it appears to be only a binary.
206 Where's the library?
207 7.11. Q. Where's the documentation for the Mac or PC version?
208 7.12. Q. The Mac (PC) version doesn't seem to have any facilities for
209 creating or editing programs apart from entering it interactively, and
210 there seems to be no way to save code that was entered interactively.
211 How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000212
213To find a particular question, search for the question number followed
214by a dot, a space, and a Q at the beginning of a line (e.g. to find
215question 4.2 in vi, type /^4\.2\. Q/).
216
217
2181. General information and availability
219=======================================
220
2211.1. Q. What is Python?
222
223A. Python is an interpreted, interactive, object-oriented programming
224language. It incorporates modules, exceptions, dynamic typing, very
225high level dynamic data types, and classes. Python combines
226remarkable power with very clear syntax. It has interfaces to many
227system calls and libraries, as well as to various window systems, and
228is extensible in C or C++. It is also usable as an extension language
229for applications that need a programmable interface. Finally, Python
230is portable: it runs on many brands of UNIX, on the Mac, and on
231MS-DOS.
232
233To find out more, the best thing to do is to start reading the
234tutorial from the documentation set (see a few questions further
235down).
236
2371.2. Q. Why is it called Python?
238
239A. Apart from being a computer wizard, I'm also a fan of "Monty
240Python's Flying Circus" (a BBC comedy series from the seventies, in
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000241the -- unlikely -- case you didn't know). It occurred to me one day
242that I needed a name that was short, unique, and slightly mysterious.
243And I happened to be reading some scripts from the series at the
244time... So then I decided to call my language Python. But Python is
245not a joke. And don't you associate it with dangerous reptiles
246either!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000247
2481.3. Q. How do I obtain a copy of the Python source?
249
250A. The latest Python source distribution is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000251anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000252/pub/python, with filename python<version>.tar.gz. (Old versions may
253have an extension of .Z, indicating use of "compress" compression.)
254It is a gzip'ed tar file containing the complete C source, LaTeX
255documentation, Python library modules, example programs, and several
256useful pieces of freely distributable software. This will compile and
Guido van Rossum3de27361994-07-25 14:19:33 +0000257run out of the box on most UNIX platforms. (See section 7 for
258non-UNIX information.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000259
2601.4. Q. How do I get documentation on Python?
261
262A. The latest Python documentation set is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000263anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000264/pub/python, with filename pythondoc-ps<version>.tar.gz. It is a
265gzip'ed tar file containing PostScript files of the reference manual,
Guido van Rossum3de27361994-07-25 14:19:33 +0000266the library manual, and the tutorial. Note that the library manual is
267the most important one of the set, as much of Python's power stems
268from the standard or built-in types, functions and modules, all of
269which are described here. PostScript for a high-level description of
270Python is in the file nluug-paper.ps.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000271
Guido van Rossumc50158e1994-05-31 09:18:50 +00002721.5. Q. Are there other ftp sites that mirror the Python distribution?
273
274A. The following sites keep mirrors of the Python distribution:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000275
276Site IP address Directory
277
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000278gatekeeper.dec.com 16.1.0.2 /pub/plan/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000279ftp.uu.net 192.48.96.9 /languages/python
280ftp.wustl.edu 128.252.135.4 /graphics/graphics/sgi-stuff/python
Guido van Rossumc50158e1994-05-31 09:18:50 +0000281ftp.funet.fi 128.214.6.100 /pub/languages/python
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000282ftp.fu-berlin.de 130.133.1.18 /unix/languages/python (*python* only)
Guido van Rossumc50158e1994-05-31 09:18:50 +0000283ftp.sunet.se 130.238.127.3 /pub/lang/python
Guido van Rossumea2c6f71994-07-14 12:35:14 +0000284unix.hensa.ac.uk 129.12.43.16 /uunet/languages/python
Guido van Rossum061f1821994-10-06 16:03:45 +0000285ftp.sterlng.com 192.124.9.3 /programming/languages/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000286
Guido van Rossum061f1821994-10-06 16:03:45 +0000287Or try archie on e.g. "python1." to locate the nearest copy of that
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000288version...
Guido van Rossuma7925f11994-01-26 10:20:16 +0000289
Guido van Rossumc50158e1994-05-31 09:18:50 +00002901.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000291
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000292A. There is a newsgroup, comp.lang.python, and a mailing list. The
293newsgroup and mailing list are gatewayed into each other -- if you can
Guido van Rossum061f1821994-10-06 16:03:45 +0000294read news it's unnecessary to subscribe to the mailing list. Send
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000295e-mail to python-list-request@cwi.nl to (un)subscribe to the mailing
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000296list. Once you're on, send e-mail tp python-list@cwi.nl to send mail
Guido van Rossum061f1821994-10-06 16:03:45 +0000297to the entire mailing list and newsgroup. Hypermail archives of
298(nearly) everything posted to the mailing list (and thus the
299newsgroup) are available -- the URL for the complete set of archives
300is <http://www.cwi.nl/~guido/hypermail/index.html>. The raw archives
301are also available by ftp from ftp.cwi.nl in /pub/python (and most
302mirrors), files mail*.gz. The uncompressed versions of these files
303can be read with the standard UNIX Mail program ("Mail -f file") or
304with nn ("nn file"). To read them using MH, you could use "inc -file
305file".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000306
Guido van Rossumc50158e1994-05-31 09:18:50 +00003071.7. Q. Is there a book on Python, or will there be one out soon?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000308
Guido van Rossum061f1821994-10-06 16:03:45 +0000309A. I am writing one. Addison-Wesley is interested. Optimistically,
310it will be published by mid-1995. Other authors are also working on
311books... (Do you guys want your name mentioned here?)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000312
Guido van Rossumc50158e1994-05-31 09:18:50 +00003131.8. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000314
315A. So far the only refereed and published article that describes
316Python in some detail is:
317
318 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
319 Servers Using the Python Programming Language", CWI Quarterly, Volume
320 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
321
322LaTeX source for this paper is available as part of the Python source
323distribution.
324
325A more recent high-level description of Python is:
326
327 Guido van Rossum, "An Introduction to Python for UNIX/C
328 Programmers", in the proceedings of the NLUUG najaarsconferentie
Guido van Rossum061f1821994-10-06 16:03:45 +0000329 1993 (dutch UNIX users group meeting November 1993).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000330
331PostScript for this paper and for the slides used for the accompanying
332presentation can be found in the ftp directory mentioned a few
333questions earlier, with filenames nluug-paper.ps and nluug-slides.ps,
334respectively.
335
Guido van Rossumc50158e1994-05-31 09:18:50 +00003361.9. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000337
338A. Python versions are numbered A.B.C. A is the major version number
339-- it is only incremented for major changes in functionality or source
340structure. B is the minor version number, incremented for less
341earth-shattering changes to a release. C is the patchlevel -- it is
342incremented for each new release. Note that in the past, patches have
343added significant changes; in fact the changeover from 0.9.9 to 1.0.0
344was the first time that either A or B changed!
345
Guido van Rossumc50158e1994-05-31 09:18:50 +00003461.10. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000347
348A. An interesting ftp site for Python users is ftp.markv.com
349(192.122.251.1); the directory pub/python contains a growing
350collection of interesting Python scripts. To submit a script for
351inclusion, place it together with a readme file (with extension
352.readme) in the publicly writable directory /incoming/python. This
353service is maintained by Lance Ellinghouse <lance@markv.com>.
354
Guido van Rossum7ce61c11994-06-13 15:13:56 +00003551.11. Q. Are there copyright restrictions on the use of Python?
356
357A. Hardly. You can do anything you want with the source, as long as
358you leave the copyrights in, display those copyrights in any
359documentation about Python that you produce, don't use the author's
360institute's name in publicity without prior written permission, and
361don't hold them responsible for anything (read the actual copyright
362for a precise legal wording).
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000363
Guido van Rossuma7925f11994-01-26 10:20:16 +0000364
3652. Python in the real world
366===========================
367
3682.1. Q. How many people are using Python?
369
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000370A. I don't know, but the maximum number of simultaneous subscriptions
371to the Python mailing list before it was gatewayed into the newsgroup
372was about 180 (several of which were local redistribution lists). I
373believe that many active Python users don't bother to subscribe to the
374list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000375is even less meaningful. I see new names on the newsgroup all the
376time and my best guess is that there are currently at least several
377thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000378
3792.2. Q. Have any significant projects been done in Python?
380
381A. Here at CWI (the home of Python), we have written a 20,000 line
382authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00003835,000 line multimedia teleconferencing tool, as well as many many
384smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000385
386The University of Virginia uses Python to control a virtual reality
387engine. Contact: Matt Conway <conway@virginia.edu>.
388
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000389If you have done a significant project in Python that you'd like to be
390included in the list above, send me email!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000391
3922.3. Q. Are there any commercial projects going on using Python?
393
394A. Several companies have revealed to me that they are planning or
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000395considering to use Python in a future product.
396
397The furthest is Sunrise Software, who already have a product out using
398Python -- they use Python for a GUI management application and an SNMP
Guido van Rossum061f1821994-10-06 16:03:45 +0000399network management application. Contact: <info@sunrise.com>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000400
Guido van Rossum061f1821994-10-06 16:03:45 +0000401Infoseek is using Python to implement their commercial WWW information
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000402retrieval service. Contact: <info@infoseek.com>.
403
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000404Michael Powers of daVinci Time & Space is "writing tons-o-python for
405interactive television entertainment." Contact: <powers@dvts.com>.
406
Guido van Rossuma7925f11994-01-26 10:20:16 +0000407Individuals at many other companies are using Python for
408internal development (witness their contributions to the Python
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000409mailing list or newsgroup).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000410
411Python has also been elected as an extension language by MADE, a
412consortium supported by the European Committee's ESPRIT program and
413consisting of Bull, CWI and some other European companies. Contact:
414Ivan Herman <ivan@cwi.nl>.
415
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000416If you'd like to be included in the list above, send me email!
417
Guido van Rossum95f61a71994-01-26 17:23:37 +00004182.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000419
Guido van Rossum3de27361994-07-25 14:19:33 +0000420A. Very stable. While the current version number would suggest it is
421in the early stages of development, in fact new, stable releases
422(numbered 0.9.x and 1.0.x) have been coming out roughly every 3 to 6
Guido van Rossum95f61a71994-01-26 17:23:37 +0000423months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000424
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00004252.5. Q. When will the next version be released?
426
427A. I am planning to release 1.1 before October 15. It will contain
428tons of changes, including (again) improved portability, especially
429better support for DOS, Windows, Windows NT an the Macintosh. A few
430modules will have been converted to the new naming scheme. A working
431signal module will be present.
432
4332.6. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000434
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000435A. A proposal is being worked out to change the semantics of operator
436overloading (__add__, __mul__ etc.) to make them more useful for
437implementing types that don't resemble numbers. Additions will be
438__call__ (to call an instance as if it were a function) and __eq__,
439_lt__ etc. (to override individual comparisons). A (new) pthreads
440interface has been submitted which will be integrated in the next
441release. The X11/Motif interface will be improved. There are ideas
442about built-in help using strings placed into function objects, and
443possibly a switch statement.
444
445There will be better ports to the Mac, DOS, Windows, Windows NT, and
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000446OS/2. The Windows ports will support dynamically loaded modules using
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000447DLLs.
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000448
449Also planned is improved support for embedding Python in other
450applications, e.g. by renaming most global symbols to have a "Py"
451prefix and providing more documentation and threading support.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000452
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00004532.7. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossum3de27361994-07-25 14:19:33 +0000454
455A. In general, no. There are already millions of lines of Python code
456around the world, so any changes in the language that invalidates more
457than a very small fraction of existing programs has to be frowned
458upon. Even if you can provide a conversion program, there still is
459the problem of updating all documentation. Providing a gradual
460upgrade path is the only way if a feature has to be changed.
461
Guido van Rossuma7925f11994-01-26 10:20:16 +0000462
4633. Building Python
464==================
465
Guido van Rossum91f60831994-02-15 15:52:27 +00004663.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000467
468A. Yes, simply do "import testall" (or "import autotest" if you aren't
469interested in the output). The standard modules whose name begins
470with "test" together comprise the test. The test set doesn't test
471*all* features of Python but it goes a long way to confirm that a new
472port is actually working. The Makefile contains an entry "make test"
473which runs the autotest module.
474
Guido van Rossum91f60831994-02-15 15:52:27 +00004753.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000476operations, but when playing with floating point operations I cannot
477find anything wrong with them.
478
479A. The test set makes occasional unwarranted assumptions about the
480semantics of C floating point operations. Until someone donates a
481better floating point test set, you will have to comment out the
482offending floating point tests and execute similar tests manually.
483
Guido van Rossum061f1821994-10-06 16:03:45 +00004843.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
Guido van Rossum24349991994-02-02 14:12:45 +0000485
Guido van Rossum061f1821994-10-06 16:03:45 +0000486A. Get STDWIN 0.9.9 from ftp://ftp.cwi.nl/pub/stdwin/stdwin0.9.9.tar.gz.
487
Guido van Rossum9351fdb1994-11-10 23:03:51 +00004883.4. Q. Link errors building Python with STDWIN 0.9.9.
Guido van Rossum061f1821994-10-06 16:03:45 +0000489
490A. Probably routines liek 'tereate', 'tenew' etc. The STDWIN 0.9.9
491distribution requires that you add TWO libraries from stdwin to the
492line for stdwin in the Setupfile. Use something like this (all on one
493line!):
494
495stdwin stdwinmodule.c -I$(STDWIN)/H $(STDWIN)/Packs/textedit/libtextedit.a $(STDWIN)/Ports/x11/libstdwin.a -lX11
Guido van Rossum24349991994-02-02 14:12:45 +0000496
Guido van Rossum9351fdb1994-11-10 23:03:51 +00004973.5. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000498
499A. It is generally necessary to run "make clean" after a configuration
500change.
501
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005023.6. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000503script (after the script name).
504
505A. You are probably linking with GNU getopt, e.g. through -liberty.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000506Don't. The reason for the complaint is that GNU getopt, unlike System
507V getopt and other getopt implementations, doesn't consider a
508non-option to be the end of the option list. A quick (and compatible)
509fix for scripts is to add "--" to the interpreter, like this:
510
511 #! /usr/local/bin/python --
512
513You can also use this interactively:
514
515 python -- script.py [options]
Guido van Rossum24349991994-02-02 14:12:45 +0000516
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005173.7. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000518glmodule.c, but python hasn't been built or installed yet.
519
520A. Comment out the line mentioning glmodule.c in Setup and build a
521python without gl first; install it or make sure it is in your $PATH,
522then edit the Setup file again to turn on the gl module, and make
523again. You don't need to do "make clean"; you do need to run "make
524Makefile" in the Modules subdirectory (or just run "make" at the
525toplevel).
526
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005273.8. Q. Python built with gcc for the DEC Alpha doesn't work.
Guido van Rossum3de27361994-07-25 14:19:33 +0000528
529People have reported problems with both gcc 2.5.8 and 2.6.0. The DEC
530OSF/1 cc compiler does not have these problems so it's probably gcc's
531fault. One person reported that the problem went away when using -g
532instead of -O so this may be an option if you insist on using gcc. If
533someone tracks it down more completely I'd like to hear about it!
534
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005353.9. Q. I use VPATH but some targets are built in the source directory.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000536
537A. On some systems (e.g. Sun), if the target already exists in the
538source directory, it is created there instead of in the build
539directory. This is usually because you have previously built without
540VPATH. Try running "make clobber" in the source directory.
541
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005423.10. Q. Trouble building or linking with the GNU readline library.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000543
544A. Consider using readline 2.0. From the Python 1.1 README:
545
546- You can use the GNU readline library to improve the interactive user
547interface: this gives you line editing and command history when
548calling python interactively. You need to configure build the GNU
549readline library before running the configure script. Its sources are
550no longer distributed with Python; you can ftp them from any GNU
551mirror site, or from its home site:
552ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz (or a higher
553version number -- using version 1.x is not recommended). Pass the
554Python configure script the option --with-readline=DIRECTORY where
555DIRECTORY is the absolute pathname of the directory where you've built
556the readline library. Some hints on building and using the readline
557library:
558
559- On SGI IRIX 5, you may have to add the following
560to rldefs.h:
561
562#ifndef sigmask
563#define sigmask(sig) (1L << ((sig)-1))
564#endif
565
566- On most systems, you will have to add #include "rldefs.h" to the
567top of several source files, and if you use the VPATH feature, you
568will have to add dependencies of the form foo.o: foo.c to the
569Makefile for several values of foo.
570
571- The readline library requires use of the termcap library. A
572known problem with this is that it contains entry points which
Guido van Rossum061f1821994-10-06 16:03:45 +0000573cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000574conflict can be solved (and will be, in the next release of
Guido van Rossum061f1821994-10-06 16:03:45 +0000575STDWIN) by adding a line saying '#define werase w_erase' to the
576stdwin.h file (in the STDWIN distribution, subdirectory H). The
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000577GL conflict has been solved in the Python configure script by a
578hack that forces use of the static version of the termcap library.
579
580- Check the newsgroup gnu.bash.bugs for specific problems with the
581readline library (I don't get this group here but I've been told
582that it is the place for readline bugs.)
583
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005843.11. Q. Trouble building Python on Linux.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000585
586A. There shouldn't be any -- I've seen several complaints but more
587reports on successful "out-of-the-box" ports on Linux. The standard
588configure script runs just fine on Linux.
589
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005903.12. Q. Trouble with prototypes on Ultrix.
Guido van Rossum72eb83c1994-10-07 11:33:28 +0000591
592A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef
593HAVE_PROTOTYPES.
594
Guido van Rossum9351fdb1994-11-10 23:03:51 +00005953.13. Q. Trouble with posix.listdir on NeXTSTEP 3.2.
596
597A. The problem seems to be that that the NeXT posix library and the
598NeXT dynamic loading library are incompatible. Mike Carlton reports
599that the following worked for him (from a clean 1.1 distribution):
600
601 1) ./configure
602 2) edited config.status and changed
603 OPT='-O'
604 to
605 OPT='-posix -O'
606 3) edited Python/import.c and commented out the section
607 #if defined(NeXT) || defined(WITH_RLD)
608 #define DYNAMIC_LINK
609 #define USE_RLD
610 #endif
611 this disables dynamic loading
612 4) make
613
6143.14. Q. Other trouble building Python on platform X.
Guido van Rossum95f61a71994-01-26 17:23:37 +0000615
616A. Please email the details to <guido@cwi.nl> and I'll look into it.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000617
618
6194. Programming in Python
620========================
621
Guido van Rossum24349991994-02-02 14:12:45 +00006224.1. Q. Is there a source code level debugger with breakpoints, step,
623etc.?
624
625A. Yes. Check out module pdb; pdb.help() prints the documentation (or
626you can read it as Lib/pdb.doc). If you use the STDWIN option,
627there's also a windowing interface, wdb. You can write your own
628debugger by using the code for pdb or wdb as an example.
629
6304.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000631C and others in Python (e.g. through inheritance)? (Also phrased as:
632Can I use a built-in type as base class?)
633
634A. No, but you can easily create a Python class which serves as a
635wrapper around a built-in object, e.g. (for dictionaries):
636
637 # A user-defined class behaving almost identical
638 # to a built-in dictionary.
639 class UserDict:
640 def __init__(self): self.data = {}
641 def __repr__(self): return repr(self.data)
642 def __cmp__(self, dict):
643 if type(dict) == type(self.data):
644 return cmp(self.data, dict)
645 else:
646 return cmp(self.data, dict.data)
647 def __len__(self): return len(self.data)
648 def __getitem__(self, key): return self.data[key]
649 def __setitem__(self, key, item): self.data[key] = item
650 def __delitem__(self, key): del self.data[key]
651 def keys(self): return self.data.keys()
652 def items(self): return self.data.items()
653 def values(self): return self.data.values()
654 def has_key(self, key): return self.data.has_key(key)
655
Guido van Rossum24349991994-02-02 14:12:45 +00006564.3. Q. Is there a curses/termcap package for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000657
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000658A. Yes -- Lance Ellinghouse has written a module that interfaces to
659System V's "ncurses". If you know a little curses and some Python,
660it's straightforward to use.
661
662You could also consider using the "alfa" (== character cell) version
663of STDWIN. (STDWIN == Standard Windows, a portable windowing system
664interface by the same author, URL: "ftp://ftp.cwi.nl/pub/stdwin".) This
665will also prepare your program for porting to windowing environments
666such as X11 or the Macintosh.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000667
Guido van Rossum24349991994-02-02 14:12:45 +00006684.4. Q. Is there an equivalent to C's onexit() in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000669
670A. Yes, if you import sys and assign a function to sys.exitfunc, it
671will be called when your program exits, is killed by an unhandled
672exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
673
Guido van Rossum24349991994-02-02 14:12:45 +00006744.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000675nested function seemingly can't access the local variables of the
676outer function. What is going on? How do I pass local data to a
677nested function?
678
679A. Python does not have arbitrarily nested scopes. When you need to
680create a function that needs to access some data which you have
681available locally, create a new class to hold the data and return a
682method of an instance of that class, e.g.:
683
684 class MultiplierClass:
685 def __init__(self, factor):
686 self.factor = factor
687 def multiplier(self, argument):
688 return argument * self.factor
689
690 def generate_multiplier(factor):
691 return MultiplierClass(factor).multiplier
692
693 twice = generate_multiplier(2)
694 print twice(10)
695 # Output: 20
696
Guido van Rossum24349991994-02-02 14:12:45 +00006974.6. Q. How do I iterate over a sequence in reverse order?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000698
699A. If it is a list, the fastest solution is
700
701 list.reverse()
702 try:
703 for x in list:
704 "do something with x"
705 finally:
706 list.reverse()
707
708This has the disadvantage that while you are in the loop, the list
709is temporarily reversed. If you don't like this, you can make a copy.
710This appears expensive but is actually faster than other solutions:
711
712 rev = list[:]
713 rev.reverse()
714 for x in rev:
715 <do something with x>
716
717If it isn't a list, a more general but slower solution is:
718
719 i = len(list)
720 while i > 0:
721 i = i-1
722 x = list[i]
723 <do something with x>
724
725A more elegant solution, is to define a class which acts as a sequence
726and yields the elements in reverse order (solution due to Steve
727Majewski):
728
729 class Rev:
730 def __init__(self, seq):
731 self.forw = seq
732 def __len__(self):
733 return len(self.forw)
734 def __getitem__(self, i):
735 return self.forw[-(i + 1)]
736
737You can now simply write:
738
739 for x in Rev(list):
740 <do something with x>
741
Guido van Rossum061f1821994-10-06 16:03:45 +0000742Unfortunately, this solution is slowest of all, due to the method
Guido van Rossuma7925f11994-01-26 10:20:16 +0000743call overhead...
744
Guido van Rossum24349991994-02-02 14:12:45 +00007454.7. Q. My program is too slow. How do I speed it up?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000746
747A. That's a tough one, in general. There are many tricks to speed up
748Python code; I would consider rewriting parts in C only as a last
749resort. One thing to notice is that function and (especially) method
750calls are rather expensive; if you have designed a purely OO interface
751with lots of tiny functions that don't do much more than get or set an
752instance variable or call another method, you may consider using a
753more direct way, e.g. directly accessing instance variables. Also see
754the standard module "profile" (described in the file
755"python/lib/profile.doc") which makes it possible to find out where
756your program is spending most of its time (if you have some patience
757-- the profiling itself can slow your program down by an order of
758magnitude).
759
Guido van Rossum24349991994-02-02 14:12:45 +00007604.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000761again (into the same Python process), the changes don't seem to take
762place. What is going on?
763
764A. For efficiency reasons, Python only reads the module file on the
765first time a module is imported (otherwise a program consisting of
766many modules, each of which imports the same basic module, would read
767the basic module over and over again). To force a changed module
768being read again, do this:
769
770 import modname
771 reload(modname)
772
773Warning: this technique is not 100% fool-proof. In particular,
774modules containing statements like
775
776 from modname import some_objects
777
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000778will continue to work with the old version of the imported objects.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000779
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00007804.9. Q. How do I find the current module name?
Guido van Rossum24349991994-02-02 14:12:45 +0000781
Guido van Rossum061f1821994-10-06 16:03:45 +0000782A. A module can find out its own module name by looking at the
Guido van Rossum24349991994-02-02 14:12:45 +0000783(predefined) global variable __name__. If this has the value
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000784'__main__' you are running as a script.
785
7864.10. Q. I have a module in which I want to execute some extra code when it
787is run as a script. How do I find out whether I am running as a
788script?
789
790A. See the previous question. E.g. if you put the following on the
791last line of your module, main() is called only when your module is
792running as a script:
Guido van Rossum24349991994-02-02 14:12:45 +0000793
794 if __name__ == '__main__': main()
795
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00007964.11. Q. I try to run a program from the Demo directory but it fails with
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000797ImportError: No module named ...; what gives?
798
Guido van Rossum061f1821994-10-06 16:03:45 +0000799A. This is probably an optional module (written in C!) which hasn't
800been configured on your system. This especially happens with modules
801like "stdwin", "gl", "Xt" or "Xm". For STDWIN and many other modules,
802see Modules/Setup.in for info on how to add these modules to your
803Python, if it is possible at all. Sometimes you will have to ftp and
804build another package first (e.g. STDWIN). Sometimes the module only
805works on specific platforms (e.g. gl only works on SGI machines).
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000806
Guido van Rossum061f1821994-10-06 16:03:45 +0000807For X-related modules (Xt and Xm) you will have to do more work: they
808are currently not part of the standard Python distribution. You will
809have to ftp the file "extensions.tar.gz" file from a Python ftp
810repository (e.g. ftp.cwi.nl) and follow the instructions there. Note:
811the X related modules are still somewhat flakey, so don't try this
812unless you alread know a bit or two about building X applications on
813your platform.
814
815See also the next question.
816
8174.12. Q. I have successfully built Python with STDWIN but it can't
818find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000819
820A. There's a subdirectory of the library directory named 'stdwin'
821which should be in the default module search path. There's a line in
822Modules/Setup(.in) that you have to enable for this purpose --
Guido van Rossum061f1821994-10-06 16:03:45 +0000823unfortunately in the latest release it's not near the other
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000824STDWIN-related lines so it's easy to miss it.
825
8264.13. Q. What GUI toolkits exist for Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000827
828A. Depending on what platform(s) you are aiming at, there are several.
829
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000830- There's a neat object-oriented interface to the Tcl/Tk widget set,
831called Tkinter. You can ftp it from ftp.cwi.nl as
832pub/python/tkinter.tar.gz. This is probably the easiest to install
833and use, and the most complete widget set.
834
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000835- The standard Python distribution comes with an interface to STDWIN,
836a platform-independent low-level windowing interface (you have to ftp
Guido van Rossum061f1821994-10-06 16:03:45 +0000837the source for STDWIN separately, e.g. from ftp.cwi.nl in pub/stdwin
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000838or gatekeeper.dec.com in pub/misc/stdwin). STDWIN runs under X11 or
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000839the Mac; a Windows port has been attempted but I can't seem to get it
840working. Note that STDWIN is really not powerful enough to implement
841a modern GUI (no widgets, etc.) and that I don't have the time to
842maintain or extend it, so you may be better off using Tkinter or the
843Motif interface, unless you require portability to the Mac (which is
844also offered by SUIT, by the way -- see below).
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000845
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000846- For SGI IRIX only, there's an interface to the complete GL (Graphics
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000847Library -- low level but very good 3D capabilities) as well as to
848FORMS (a buttons-and-sliders-etc package built on top of GL by Mark
849Overmars -- ftp'able from ftp.cs.ruu.nl in pub/SGI/FORMS).
850
851- There's an interface to X11, including the Athena and Motif widget
852sets (and a few individual widgets, like Mosaic's HTML widget and
853SGI's GL widget) in the Extensions set, which is separately ftp'able
854from ftp.cwi.nl as pub/python/extensions.tar.gz.
855
856- There's an interface to SUIT, the U of Virginia's Simple User
857Interface Toolkit; it can be ftp'ed from uvacs.cs.virginia.edu as
858pub/suit/python/SUIT_python.tar.Z. A PC binary of Python 1.0.2
859compiled with DJGPP and with SUIT support built-in has been made
860available by Antonio Costa on ftp site asterix.inescn.pt, directory
861pub/PC/python, file pyt102su.exe (a self-extracting archive).
862
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000863- There's an interface to WAFE, a Tcl interface to the X11 Motif and
864Athena widget sets. Last I heard about it it was included in the
865WAFE 1.0 prerelease, ftp'able from ftp.wu-wien.ac.at as
866pub/src/X11/wafe/wafe-1.0.tar.gz-prerelease.
867
Guido van Rossum061f1821994-10-06 16:03:45 +00008684.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000869
870A. There's an interface to SYBASE by John Redford
871<jredford@lehman.com>.
872
873There's also an interface to metalbase by Lance Ellinghouse
874<lance@markv.com>.
875
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000876Anthony Baxter <anthony.baxter@aaii.oz.au> has written an interface to
877mSQL (mini-SQL). Ftp it from ftp.cwi.nl:/pub/python/PymSQL.tar.gz.
878
8794.15. Q. Is it possible to write obfuscated one-liners in Python?
Guido van Rossumc24da7c1994-09-23 14:08:41 +0000880
881A. Yes. See the following three examples, due to Ulf Bartelt:
882
883# Primes < 1000
884print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\
885map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
886
887# First 10 Fibonacci numbers
888print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),\
889range(10))
890
891# Mandelbrot set
892print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,\
893Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\
894Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\
895i=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\
896>=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(\
89764+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\
898))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
899# \___ ___/ \___ ___/ | | |__ lines on screen
900# V V | |______ columns on screen
901# | | |__________ maximum of "iterations"
902# | |_________________ range on y axis
903# |____________________________ range on x axis
904
905Don't try this at home, kids!
906
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00009074.16. Q. Is there an equivalent of C's "?:" ternary operator?
Guido van Rossumc24da7c1994-09-23 14:08:41 +0000908
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000909A. Not directly. In many cases you can mimic a?b:c with "a and b or
910c", but there's a flaw: if b is zero (or empty, or None -- anything
911that tests false) then c will be selected instead. In many cases you
912can prove by looking at the code that this can't happen (e.g. because
913b is a constant or has a type that can never be false), but in general
914this can be a problem.
915
916Steve Majewski (or was it Tim Peters?) suggested the following
917solution: (a and [b] or [c])[0]. Because [b] is a singleton list it
918is never false, so the wrong path is never taken; then applying [0] to
919the whole thing gets the b or c that you really wanted. Ugly, but it
920gets you there in the rare cases where it is really inconvenient to
921rewrite your code using 'if'.
922
9234.17. Q. My class defines __del__ but it is not called when I delete the
924object.
925
926A. There are several possible reasons for this.
927
928- The del statement does not necessarily call __del__ -- it simply
929decrements the object's reference count, and if this reaches zero
930__del__ is called.
931
932- If your data structures contain circular links (e.g. a tree where
933each child has a parent pointer and each parent has a list of
934children) the reference counts will never go back to zero. You'll
Guido van Rossum061f1821994-10-06 16:03:45 +0000935have to define an explicit close() method which removes those
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000936pointers. Please don't ever call __del__ directly -- __del__ should
Guido van Rossum061f1821994-10-06 16:03:45 +0000937call close() and close() should make sure that it can be called more
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000938than once for the same object.
939
940- If the object has ever been a local variable (or argument, which is
941really the same thing) to a function that caught an expression in an
942except clause, chances are that a reference to the object still exists
943in that function's stack frame as contained in the stack trace.
944Normally, deleting (better: assigning None to) sys.exc_traceback will
945take care of this. If you a stack was printed for an unhandled
946exception in an interactive interpreter, delete sys.last_traceback
947instead.
948
949- There is code that deletes all objects when the interpreter exits,
950but if your Python has been configured to support threads, it is not
951called (because other threads may still be active). You can define
Guido van Rossum061f1821994-10-06 16:03:45 +0000952your own cleanup function using sys.exitfunc (see question 4.4).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000953
9544.18. Q. How do I change the shell environment for programs called using
955os.popen() or os.system()? Changing os.environ doesn't work.
956
957A. Modifying the environment passed to subshells was left out of the
958interpreter because there seemed to be no well-established portable
959way to do it.
960
961However if all you want is to pass environment variables to the
962commands run by os.system() or os.popen(), there's a simple solution:
963prefix the command string with a couple of variable assignments and
964export statements. I guess the following would be universal for popen
965(untested):
966
967import os
968from commands import mkarg # nifty routine to add shell quoting
969def epopen(cmd, mode, env = {}):
970 # env is a dictionary of environment variables
971 prefix = ''
972 for key, value in env.values():
973 prefix = prefix + '%s=%s\n' % (key, mkarg(value))
974 prefix = prefix + 'export %s\n' % key
975 return os.popen(prefix + cmd, mode)
976
9774.19. Q. What is a class?
978
979A. A class is the particular object type that is created by executing
980a class statement.
981
9824.20. Q. What is a method?
983
984A. A method is a function that you normally call as
985x.name(arguments...) for some object x. The word is used for methods
986of classes and class instances as well as for methods of built-in
987objects. The latter have a completely different implementation and
988only share the way their calls look in Python code.
989
9904.21. Q. What is self?
991
992A. Self is merely a conventional name for the first argument of a
993method -- i.e. a function defined inside a class definition. A method
994defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
995some instance x of the class in which the definition occurs;
996the called method will think it is called as meth(x, a, b, c).
997
9984.22. Q. What is a unbound method?
999
1000A. An unbound method is a method defined in a class that is not yet
1001bound to an instance. You get an unbound method if you ask for a
1002class attribute that happens to be a function. You get a bound method
1003if you ask for an instance attribute. A bound method knows which
Guido van Rossum061f1821994-10-06 16:03:45 +00001004instance it belongs to and calling it supplies the instance automatically;
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001005an unbound method only knows which class it wants for its first
1006argument (a derived class is also OK). Calling an unbound method
1007doesn't "magically" derive the first argument from the context -- you
1008have to provide it explicitly.
1009
10104.23. Q. How do I call a method defined in a base class from a derived class
1011that overrides it?
1012
1013A. If your class definition starts with "class Derived(Base): ..."
1014then you can call method meth defined in Base (or one of Base's base
1015classes) as Base.meth(self, arguments...). Here, Base.meth is an
1016unbound method (see previous question).
1017
10184.24. Q. How do I call a method from a base class without using the name of
1019the base class?
1020
1021A. DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call
1022self.__class__.__bases__[0].meth(self, arguments...) but this fails when
Guido van Rossum061f1821994-10-06 16:03:45 +00001023a doubly-derived method is derived from your class: for its instances,
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001024self.__class__.__bases__[0] is your class, not its base class -- so
1025(assuming you are doing this from within Derived.meth) you would start
1026a recursive call.
1027
10284.25. Q. How can I organize my code to make it easier to change the base
1029class?
1030
1031A. You could define an alias for the base class, assign the real base
1032class to it before your class definition, and use the alias throughout
1033your class. Then all you have to change is the value assigned to the
1034alias. Incidentally, this trick is also handy if you want to decide
1035dynamically (e.g. depending on availability of resources) which base
1036class to use. Example:
1037
1038BaseAlias = <real base class>
1039class Derived(BaseAlias):
1040 def meth(self):
1041 BaseAlias.meth(self)
1042 ...
1043
10444.26. Q. How can I find the methods or attributes of an object?
1045
1046A. This depends on the object type.
1047
1048For an instance x of a user-defined class, instance attributes are
1049found in the dictionary x.__dict__, and methods and attributes defined
1050by its class are found in x.__class__.__bases__[i].__dict__ (for i in
1051range(len(x.__class__.__bases__))). You'll have to walk the tree of
1052base classes to find *all* class methods and attributes.
1053
1054Many, but not all built-in types define a list of their method names
1055in x.__methods__, and if they have data attributes, their names may be
1056found in x.__members__. However this is only a convention.
1057
1058For more information, read the source of the standard (but
1059undocumented) module newdir.
1060
10614.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
1062
1063A. os.read() is a low-level function which takes a file descriptor (a
1064small integer). os.popen() creates a high-level file object -- the
1065same type used for sys.std{in,out,err} and returned by the builtin
1066open() function. Thus, to read n bytes from a pipe p created with
1067os.popen(), you need to use p.read(n).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001068
Guido van Rossum061f1821994-10-06 16:03:45 +000010694.28. Q. How can I create a stand-alone binary from a Python script?
1070
1071The demo script "Demo/scripts/freeze.py" does what you want. (It's
1072actually not a demo but a support tool -- there is some extra code in
1073the interpreter to accommodate it.) It requires that you have the
1074Python build tree handy, complete with all the lib*.a files.
1075
1076This works by scanning your source recursively for import statements
1077(both forms) and looking for the modules on the standard Python path
1078as well as in the source directory (for built-in modules). It then
1079"compiles" the modules written in Python to C code (array initializers
1080that can be turned into code objects using the marshal module) and
1081creates a custom-made config file that only contains those built-in
1082modules which are actually used in the program. It then compiles the
1083generated C code and links it with the rest of the Python interpreter
1084to form a self-contained binary which acts exactly like your script.
1085
1086Unfortunately, the current version is very platform-specific, because
1087each platform has its own compilation flags and libraries to link
1088with. You will probably have to edit the freeze.py file to point it
1089to the right directories and tell it about the compilation and link
1090flags for your platform. A new version will be released with Python
10911.1 -- if you want a peek write to my colleague <Jack.Jansen@cwi.nl>.
1092
10934.29. Q. Is there a special lib for writing CGI scripts in Python?
1094
1095A. There's documentation and code for a cgi.py module by Michael McLay
1096<mclay@eeel.nist.gov> available from:
1097
1098 http://www.eeel.nist.gov/python/
1099
1100(For the curious: CGI or Common Gateway Interface is the protocol
1101between HTTP servers (WWW servers) and programs/scripts they run to
1102perform queries and other tasks that require returning a dynamically
1103generated document.)
1104
11054.30. Q. What other WWW tools are there for Python?
1106
1107A. The standard library has a module urllib, which can retrieve most
1108commonly used URL types (file, ftp, http, gopher).
1109
1110The Demo2/www directory (Demo2 has to be retrieved separately from the
1111Python ftp sites) contains some (really old) code to parse HTML and to
1112display it.
1113
1114Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser
1115called Dancer. An alpha version can be FTP'ed from
1116ftp.cs.indiana.edu:/pub/smiale/dancer.tar.gz. (There are a few
1117articles about Dancer in the (hyper)mail archive.)
1118
1119
Guido van Rossuma7925f11994-01-26 10:20:16 +000011205. Extending Python
1121===================
1122
11235.1. Q. Can I create my own functions in C?
1124
1125A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +00001126variables, exceptions and even new types in C. This is explained in
1127the document "Extending and Embedding the Python Interpreter" (the
1128LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001129
11305.2. Q. Can I create my own functions in C++?
1131
1132A. Yes, using the C-compatibility features found in C++. Basically
1133you place extern "C" { ... } around the Python include files and put
1134extern "C" before each function that is going to be called by the
1135Python interpreter. Global or static C++ objects with constructors
1136are probably not a good idea.
1137
Guido van Rossum7ce61c11994-06-13 15:13:56 +000011385.3. Q. How can I execute arbitrary Python statements from C?
1139
1140A. The highest-level function to do this is run_command() which takes
1141a single string argument which is executed in the context of module
1142__main__ and returns 0 for success and -1 when an exception occurred
1143(including SyntaxError). If you want more control, use run_string();
1144see the source for run_command() in Python/pythonrun.c.
1145
11465.4. Q. How can I evaluate an arbitrary Python expression from C?
1147
1148A. Call the function run_string() from the previous question with the
1149start symbol eval_input; it then parses an expression, evaluates it
1150and returns its value. See exec_eval() in Python/bltinmodule.c.
1151
11525.5. Q. How do I extract C values from a Python object?
1153
1154A. That depends on the object's type. If it's a tuple,
1155gettuplesize(o) returns its length and gettupleitem(o, i) returns its
1156i'th item; similar for lists with getlistsize(o) and getlistitem(o,
1157i). For strings, getstringsize(o) returns its length and
1158getstringvalue(o) a pointer to its value (note that Python strings may
1159contain null bytes so strlen() is not safe). To test which type an
1160object is, first make sure it isn't NULL, and then use
1161is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
1162
11635.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
1164
1165A. You can't. Use t = newtupleobject(n) instead, and fill it with
1166objects using settupleitem(t, i, o) -- note that this "eats" a
1167reference count of o. Similar for lists with newlistobject(n) and
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001168setlistitem(l, i, o). Note that you *must* set all the tuple items to
1169some value before you pass the tuple to Python code --
1170newtupleobject(n) initializes them to NULL, which isn't a valid Python
1171value.
1172
11735.7. Q. What happened to mktuple(), featuring in an example in the
1174Extensions manual?
1175
1176A. It's a typo, I meant newtupleobject() (see previous question).
1177
11785.8. Q. How do I call an object's method from C?
1179
1180A. Here's a function (untested) that might become part of the next
1181release in some form. It uses <stdarg.h> to allow passing the
1182argument list on to vmkvalue():
1183
1184object *call_method(object *inst, char *methodname, char *format, ...)
1185{
1186 object *method;
1187 object *args;
1188 object *result;
1189 va_list va;
1190 method = getattr(inst, methodname);
1191 if (method == NULL) return NULL;
1192 va_start(va, format);
1193 args = vmkvalue(format, va);
1194 va_end(va);
1195 if (args == NULL) {
1196 DECREF(method);
1197 return NULL;
1198 }
1199 result = call_object(method, args);
1200 DECREF(method);
1201 DECREF(args);
1202 return result;
1203}
1204
1205This works for any instance that has methods -- whether built-in or
1206user-defined. You are responsible for eventually DECREF'ing the
1207return value.
1208
1209To call, e.g., a file object's "seek" method with arguments 10, 0
1210(assuming the file object pointer is "f"):
1211
1212res = call_method(f, "seek", "(OO)", 10, 0);
1213if (res == NULL) {
1214 ... an exception occurred ...
1215}
1216else {
1217 DECREF(res);
1218}
1219
1220Note that since call_object() *always* wants a tuple for the argument
1221list, to call a function without arguments, pass "()" for the format,
1222and to call a function with one argument, surround the argument in
1223parentheses, e.g. "(i)".
1224
12255.9. Q. How do I catch the output from print_error()?
1226
1227A. (Due to Mark Hammond):
1228
1229* in Python code, define an object that supports the "write()" method.
1230FWIW, there seems to be a small problem that requires the 'softspace'
Guido van Rossum061f1821994-10-06 16:03:45 +00001231attribute to be defined too (I can't remember exact details of the
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001232problem).
1233
1234* redirect sys.stdout and sys.stderr to this object.
1235
Guido van Rossum061f1821994-10-06 16:03:45 +00001236* call print_error, or just allow the standard traceback mechanism to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001237work.
1238
Guido van Rossum061f1821994-10-06 16:03:45 +00001239Then, the output will go wherever your write() method sends it.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001240
12415.10. Q. How do I access a module written in Python from C?
1242
1243A. You can get a pointer to the module object as follows:
1244
1245 module = import_module("<modulename>");
1246
1247If the module hasn't been imported yet (i.e. it is not yet present in
1248sys.modules), this initializes the module; otherwise it simply returns
1249the value of sys.modules["<modulename>"]. Note that it doesn't enter
1250the module into any namespace -- it only ensures it has been
1251initialized and is stored in sys.modules.
1252
1253You can then access the module's attributes (i.e. any name defined in
1254the module) as follows:
1255
1256 attr = getattr(module, "<attrname>");
1257
1258Calling setattr(), to assign to variables in the module, also works.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001259
Guido van Rossuma7925f11994-01-26 10:20:16 +00001260
12616. Python's design
1262==================
1263
12646.1. Q. Why isn't there a generic copying operation for objects in
1265Python?
1266
1267A. Hmm. Maybe there should be one, but it's difficult to assign a
1268useful meaning to copying of open files, sockets and windows, or
1269recursive data structures. As long as you design all your classes
1270yourself you are of course free to define a standard base class that
1271defines an overridable copying operation for all the objects you care
1272about. (One practical point: it would have to be a built-in function,
1273not a standard method name, since not all built-in object types have
1274methods; e.g. strings, integers and tuples don't.)
1275
12766.2. Q. Why isn't there a generic way to implement persistent objects
1277in Python? (Persistent == automatically saved to and restored from
1278disk.)
1279
1280A. Hmm, hmm. Basically for the same reasons as why there is no
1281generic copying operation.
1282
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001283However, since there is a real desire to have persistent operations,
1284I'm thinking of extending the marshal module to support object sharing
1285(and hence recursive objects) and to extend the list of supported
1286types considerably. For user-defined classes, hooks with __*__ names
1287will allow the class to modify the way their instances are dumped and
1288loaded. Built-in types (including those defined by new extensions)
1289may also define dump/load hooks. There are several problems still to
1290solve, e.g. how do you reliably find the class of which an object is
1291an instance at load time -- assuming the class itself is loaded from
1292some module, and not part of the dumped data. It is also necessary to
1293separate the functionality of converting a set of objects into a byte
1294stream from which they can be reloaded, from the ability to save these
1295byte streams as files and being able to reference an object by a
1296persistent global name.
1297
Guido van Rossuma7925f11994-01-26 10:20:16 +000012986.3. Q. Why isn't there a switch or case statement in Python?
1299
1300A. You can do this easily enough with a sequence of
1301if... elif... elif... else. There have been some proposals for switch
Guido van Rossum061f1821994-10-06 16:03:45 +00001302statement syntax, but there is no consensus (yet) on whether and how
Guido van Rossuma7925f11994-01-26 10:20:16 +00001303to do range tests.
1304
Guido van Rossumc50158e1994-05-31 09:18:50 +000013056.4. Q. Why does Python use indentation for grouping of statements?
1306
1307A. Basically I believe that using indentation for grouping is
1308extremely elegant and contributes a lot to the clarity of the average
1309Python program. Most people learn to love this feature after a while.
1310Some arguments for it:
1311
1312- Since there are no begin/end brackets there cannot be a disagreement
1313between grouping perceived by the parser and the human reader. I
1314remember long ago seeing a C fragment like this:
1315
1316 if (x <= y)
1317 x++;
1318 y--;
1319 z++;
1320
1321and staring a long time at it wondering why y was being decremented
1322even for x > y... (And I wasn't a C newbie then either.)
1323
1324- Since there are no begin/end brackets there can be no conflicting
1325coding styles. In C there are loads of different ways to place the
1326braces (including the choice whether to place braces around single
1327statements in certain cases, for consistency). If you're used to
1328reading (and writing) code that uses one style, you will feel at least
1329slightly uneasy when reading (or being required to write) another
1330style.
1331
1332- Many coding styles place begin/end brackets on a line by themself.
1333This makes programs considerably longer and wastes valuable screen
1334space, making it harder to get a good overview over a program.
1335Ideally, a function should fit on one basic tty screen (say, 20
1336lines). 20 lines of Python are worth a LOT more than 20 lines of C.
1337This is not solely due to the lack of begin/end brackets (the lack of
1338declarations also helps, and the powerful operations of course), but
1339it certainly helps!
1340
Guido van Rossum3de27361994-07-25 14:19:33 +000013416.5. Q. Why are Python strings immutable?
1342
1343A. There are two advantages. One is performance: knowing that a
1344string is immutable makes it easy to lay it out at construction time
1345-- fixed and unchanging storage requirements. (This is also one of
Guido van Rossum061f1821994-10-06 16:03:45 +00001346the reasons for the distinction between tuples and lists.) The
Guido van Rossum3de27361994-07-25 14:19:33 +00001347other is that strings in Python are considered as "elemental" as
1348numbers. No amount of activity will change the value 8 to anything
1349else, and in Python, no amount of activity will change the string
1350"eight" to anything else. (Adapted from Jim Roskind)
1351
13526.6. Q. Why don't strings have methods like index() or sort(), like
1353lists?
1354
1355A. Good question. Strings currently don't have methods at all
1356(likewise tuples and numbers). Long ago, it seemed unnecessary to
1357implement any of these functions in C, so a standard library module
1358"string" written in Python was created that performs string related
1359operations. Since then, the cry for performance has moved most of
1360them into the built-in module strop (this is imported by module
Guido van Rossumf8c76d01994-08-17 12:19:53 +00001361string, which is still the preferred interface, without loss of
Guido van Rossum3de27361994-07-25 14:19:33 +00001362performance except during initialization). Some of these functions
1363(e.g. index()) could easily be implemented as string methods instead,
1364but others (e.g. sort()) can't, since their interface prescribes that
1365they modify the object, while strings are immutable (see the previous
1366question).
1367
13686.7. Q. Why does Python use methods for some functionality
1369(e.g. list.index()) but functions for other (e.g. len(list))?
1370
1371A. Functions are used for those operations that are generic for a
1372group of types and which should work even for objects that don't have
1373methods at all (e.g. numbers, strings, tuples). Also, implementing
1374len(), max(), min() as a built-in function is actually less code than
1375implementing them as methods for each type. One can quibble about
1376individual cases but it's really too late to change such things
1377fundamentally now.
1378
13796.8. Q. Why can't I derive a class from built-in types (e.g. lists or
1380files)?
1381
1382A. This is caused by the relatively late addition of (user-defined)
1383classes to the language -- the implementation framework doesn't easily
1384allow it. See the answer to question 4.2 for a work-around. This
1385*may* be fixed in the (distant) future.
1386
13876.9. Q. Why must 'self' be declared and used explicitly in method
1388definitions and calls?
1389
1390A. By asking this question you reveal your C++ background. :-)
1391When I added classes, this was (again) the simplest way of
1392implementing methods without too many changes to the interpreter. I
1393borrowed the idea from Modula-3. It turns out to be very useful, for
1394a variety of reasons.
1395
1396First, it makes it more obvious that you are using a method or
1397instance attribute instead of a local variable. Reading "self.x" or
1398"self.meth()" makes it absolutely clear that an instance variable or
1399method is used even if you don't know the class definition by heart.
1400In C++, you can sort of tell by the lack of a local variable
Guido van Rossum061f1821994-10-06 16:03:45 +00001401declaration (assuming globals are rare or easily recognizable) -- but
Guido van Rossum3de27361994-07-25 14:19:33 +00001402in Python, there are no local variable declarations, so you'd have to
1403look up the class definition to be sure.
1404
1405Second, it means that no special syntax is necessary if you want to
1406explicitly reference or call the method from a particular class. In
1407C++, if you want to use a method from base class that is overridden in
1408a derived class, you have to use the :: operator -- in Python you can
1409write baseclass.methodname(self, <argument list>). This is
1410particularly useful for __init__() methods, and in general in cases
1411where a derived class method wants to extend the base class method of
1412the same name and thus has to call the base class method somehow.
1413
1414Lastly, for instance variables, it solves a syntactic problem with
1415assignment: since local variables in Python are (by definition!) those
1416variables to which a value assigned in a function body (and that
1417aren't explicitly declared global), there has to be some way to tell
1418the interpreter that an assignment was meant to assign to an instance
1419variable instead of to a local variable, and it should preferably be
1420syntactic (for efficiency reasons). C++ does this through
1421declarations, but Python doesn't have declarations and it would be a
1422pity having to introduce them just for this purpose. Using the
1423explicit "self.var" solves this nicely. Similarly, for using instance
1424variables, having to write "self.var" means that references to
1425unqualified names inside a method don't have to search the instance's
1426directories.
1427
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000014286.10. Q. Can't you emulate threads in the interpreter instead of
1429relying on an OS-specific thread implementation?
1430
1431A. Unfortunately, the interpreter pushes at least one C stack frame
1432for each Python stack frame. Also, extensions can call back into
1433Python at almost random moments. Therefore a complete threads
1434implementation requires thread support for C.
1435
Guido van Rossum061f1821994-10-06 16:03:45 +000014366.11. Q. Why can't lambda forms contain statements?
1437
1438A. Python lambda forms cannot contain statements because Python's
1439syntactic framework can't handle statements nested inside functions.
1440
1441However, in Python, this is not a serious problem. Unlike lambda
1442forms in other languages, where they add functionality, Python lambdas
1443are only a shorthand notation if you're too lazy to define a function.
1444
1445Functions are already first class objects in Python, and can be
1446declared in a local scope. Therefore the only advantage of using a
1447lambda form instead of a locally-defined function is that you'll have
1448to invent a name for the function -- but that's just a local variable
1449to which the function object (which is exactly the same type of object
1450that a lambda form yields) is assigned!
1451
14526.12. Q. Why is there no more efficient way of iterating over a dictionary
1453than first constructing the list of keys()?
1454
1455A. Have you tried it? I bet it's fast enough for your purposes! In
1456most cases such a list takes only a few percent of the space occupied
1457by the dictionary -- it needs only 4 bytes (the size of a pointer) per
1458key -- a dictionary costs 8 bytes per key plus between 30 and 70
1459percent hash table overhead, plus the space for the keys and values --
1460by necessity all keys are unique objects and a string object (the most
1461common key type) costs at least 18 bytes plus the length of the
1462string. Add to that the values contained in the dictionary, and you
1463see that 4 bytes more per item really isn't that much more memory...
1464
1465A call to dict.keys() makes one fast scan over the dictionary
1466(internally, the iteration function does exist) copying the pointers
1467to the key objects into a pre-allocated list object of the right size.
1468The iteration time isn't lost (since you'll have to iterate anyway --
1469unless in the majority of cases your loop terminates very prematurely
1470(which I doubt since you're getting the keys in random order).
1471
1472I don't expose the dictionary iteration operation to Python
1473programmers because the dictionary shouldn't be modified during the
1474entire iteration -- if it is, there's a very small chance that the
1475dictionary is reorganized because the hash table becomes too full, and
1476then the iteration may miss some items and see others twice. Exactly
1477because this only occurs rarely, it would lead to hidden bugs in
1478programs: it's easy never to have it happen during test runs if you
1479only insert or delete a few items per iteration -- but your users will
1480surely hit upon it sooner or later.
1481
Guido van Rossuma7925f11994-01-26 10:20:16 +00001482
14837. Using Python on non-UNIX platforms
1484=====================================
1485
Guido van Rossum91f60831994-02-15 15:52:27 +000014867.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001487
Guido van Rossum91f60831994-02-15 15:52:27 +00001488A. Yes. It is on most ftp sites carrying Python as python.sea.hqx --
1489this is a self-extracting archive containing the application binary as
1490well as the Lib modules.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001491
Guido van Rossum91f60831994-02-15 15:52:27 +000014927.2. Q. Is there a DOS version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001493
Guido van Rossum91f60831994-02-15 15:52:27 +00001494A. Yes. More than one, actually: 16python.exe runs in standard DOS
1495mode on 186 CPUs or higher; 32python.exe uses a DOS extender and only
1496runs on a 386 or higher CPUs. Although 16python.exe does not pass the
1497test set because test_grammar is too big for the parser, it actually
1498has about 270 kbyte of allocatable heap space, which is sufficient for
1499fairly large programs. 32python.exe is distributed as a tar file
1500containing the required DOS extended and 387 emulator. Both are on
1501most ftp sites carrying Python.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001502
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001503The file dosbuild.tar.gz on the standard ftp sites
1504(e.g. ftp.cwi.nl:/pub/python/) contains rudimentary Makefiles and
1505instructions.
1506
Guido van Rossum91f60831994-02-15 15:52:27 +000015077.3. Q. Is there a Windows version of Python?
1508
1509A. Yes. Use qwpython.exe. The only problem with it: ^C
1510unconditionally kills the entire program -- it does not raise
1511KeyboardInterrupt. You can also run 16python.exe or 32python.exe in a
1512"DOS box", but qwpython.exe appears to be slightly faster.
1513
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001514There aren't any Makefiles at this moment. Sorry.
1515
1516Using Win32s (a free NT compatibility package by Microsoft) you can
1517also use the NT version by Mark Hammond -- the Win32s package is also
1518in that directory (you'll need several MB of disk space to install
1519it). See the next question.
1520
Guido van Rossum91f60831994-02-15 15:52:27 +000015217.4. Q. Is there a Windows NT version of Python?
1522
1523A. Yes. Use ntpython.exe. This is for Intel CPUs. If you want a
1524Windows user interface, use qwpython.exe.
1525
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001526Mark Hammond <MHammond@cmutual.com.au> is building a better NT port.
1527This supports using DLLs for dynamic loading of Python modules, and
1528includes an interface to the Microsoft Foundation Classes and a Python
1529programming environment using it that's written mostly in Python. A
1530prerelease (source and binaries) can be ftp'ed from
1531ftp.cwi.nl:/pub/python/nt/ -- most mirrors will also have this. A
1532thread module is also planned but currently low on Mark's list of
1533priorities.
1534
Guido van Rossum061f1821994-10-06 16:03:45 +00001535To build Python for the Windows NT on the DEC Alpha AXP, retrieve a
1536zipfile with Makefiles for NT from the following URL:
1537"ftp://ftp.ksc.nasa.gov/pub.win3.private.proto/python-make.zip". This
1538was contributed by Sam Rushing <rushing@squirl.oau.org>.
1539
1540Note that currently there is no unified compilation environment for
1541all NT platforms -- hopefully Microsoft will fix this with the release
1542of Visual C++ 2.0.
1543
Guido van Rossum7ce61c11994-06-13 15:13:56 +000015447.5. Q. Is there an OS/2 version of Python?
1545
1546A. Yes. You can ftp it (from ftp.cwi.nl in pub/python, or from the
1547mirror sites) as pyth_os2.zip. This contains both an executable and
1548Makefiles for those fortunate enough to have a C compiler.
1549
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000015507.6. Q. Is there a VMS version of Python?
1551
1552A. I think not (yet). This question has been asked on the list
1553several times and I've never seen an answer. Maybe someone with a VMS
1554C compiler could attempt a port? Probably coming up with proper
1555Makefiles, config.h and config.c should be sufficient. If you succeed
1556(or even if you get stuck halfway), please let me know! (Info as of
155723 September 1994.)
1558
15597.7. Q. What about IBM mainframes, or other esoteric non-UNIX
1560platforms?
1561
1562A. Basically, the same story as for VMS... (Info as of 23 September
15631994.)
1564
1565For ports of Windows NT to non-Intel platforms, the normal NT port
1566should work except you may have to use a different Makefile.
1567(Unconfirmed suggestions from the Python list.)
1568
15697.8. Q. Where are the source or Makefiles for the non-UNIX versions?
1570
1571A. The standard sources can (almost) be used. See the previous
1572questions for availability of Makefiles/projects or patches. If you
1573find things in the standard sources that don't work on your particular
1574platform, please let me know and I'll integrate a solution into the
1575next release of the standard sources. If you submit a fix, please use
1576some kind of #ifdef so as to keep the source working for other
1577platforms. In particular, if the patch works around the availability
1578of a particular function of header file, you should mimic the
1579HAVE_... style used by the configure script -- you can then submit a
1580config.h file for a particular platform so there are no absolutely
1581platform-specific #ifdefs in the rest of the sources.
1582
15837.9. Q. What is the status and support for the non-UNIX versions?
1584
1585A. I don't have access to most of these platforms, so in general I am
1586dependent on material submitted by volunteers(*). However I strive to
1587integrate all changes needed to get it to compile on a particular
1588platform back into the standard sources, so porting of the next
1589version to the various non-UNIX platforms should be easy.
1590
1591(*) For the Macintosh, that volunteer is me.
1592
15937.10. Q. I have the PC version but it appears to be only a binary.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001594Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001595
1596A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +00001597"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossum3de27361994-07-25 14:19:33 +00001598you can get the file pythonlib<version>.tar.gz from most ftp sites
1599carrying Python; this is a subset of the distribution containing just
1600those file.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001601
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001602Once you have installed the library, you need to point sys.path to it.
1603Assuming the library is in C:\misc\python\lib, the following commands
1604will point your Python interpreter to it (note the doubled backslashes
1605-- you can also use single forward slashes instead):
1606
1607 >>> import sys
1608 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
1609 >>>
1610
1611For a more permanent effect, set the environment variable PYTHONPATH,
1612as follows (talking to a DOS prompt):
1613
1614 C> SET PYTHONPATH=C:\misc\python\lib
1615
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000016167.11. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001617
1618A. There isn't any. The documentation for the Unix version also
Guido van Rossum91f60831994-02-15 15:52:27 +00001619applies to the Mac and PC versions. Where applicable, differences
Guido van Rossuma7925f11994-01-26 10:20:16 +00001620are indicated in the text.
1621
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000016227.12. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +00001623creating or editing programs apart from entering it interactively, and
1624there seems to be no way to save code that was entered interactively.
1625How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001626
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001627A. Use an external editor. On the Mac, BBEdit seems to be a popular
1628no-frills text editor. I work like this: start the interpreter; edit
1629a module file using BBedit; import and test it in the interpreter;
1630edit again in BBedit; then use the built-in function reload() to
1631re-read the imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001632
1633Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
1634anyone with a pulse could certainly figure out how to do the same on
1635MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
1636Not only can you easily resave and "reload()" from Python after making
1637changes, but since WinNot auto-copies to the clipboard any text you
1638select, you can simply select the entire procedure (function) which
1639you changed in WinNot, switch to QWPython, and shift-ins to reenter
1640the changed program unit."