blob: b008e7072f08a1e4e1bf1c7f01fdf1f145549654 [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 Rossum061f1821994-10-06 16:03:45 +000013Version: 1.15
14Last-modified: 6 October 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 Rossum91f60831994-02-15 15:52:27 +000094 3.3. Q. Link errors building Python with STDWIN on SGI IRIX.
95 3.4. Q. Link errors after rerunning the configure script.
96 3.5. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +000097 script (after the script name).
Guido van Rossum91f60831994-02-15 15:52:27 +000098 3.6. Q. When building on the SGI, make tries to run python to create
Guido van Rossum5333c5d1994-04-11 11:06:22 +000099 glmodule.c, but python hasn't been built or installed yet.
Guido van Rossum3de27361994-07-25 14:19:33 +0000100 3.7. Q. Python built with gcc for the DEC Alpha doesn't work.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000101 3.8. Q. I use VPATH but some targets are built in the source directory.
102 3.9. Q. Trouble building or linking with the GNU readline library.
103 3.10. Q. Trouble building Python on Linux.
104 3.11. Q. Other trouble building Python on platform X.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000105
106 4. Programming in Python
Guido van Rossum24349991994-02-02 14:12:45 +0000107 4.1. Q. Is there a source code level debugger with breakpoints, step,
108 etc.?
109 4.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000110 C and others in Python (e.g. through inheritance)? (Also phrased as:
111 Can I use a built-in type as base class?)
Guido van Rossum24349991994-02-02 14:12:45 +0000112 4.3. Q. Is there a curses/termcap package for Python?
113 4.4. Q. Is there an equivalent to C's onexit() in Python?
114 4.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000115 nested function seemingly can't access the local variables of the
116 outer function. What is going on? How do I pass local data to a
117 nested function?
Guido van Rossum24349991994-02-02 14:12:45 +0000118 4.6. Q. How do I iterate over a sequence in reverse order?
119 4.7. Q. My program is too slow. How do I speed it up?
120 4.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000121 again (into the same Python process), the changes don't seem to take
122 place. What is going on?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000123 4.9. Q. How do I find the current module name?
124 4.10. Q. I have a module in which I want to execute some extra code when it
125 is run as a script. How do I find out whether I am running as a
126 script?
127 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 +0000128 ImportError: No module named ...; what gives?
Guido van Rossum061f1821994-10-06 16:03:45 +0000129 4.12. Q. I have successfully built Python with STDWIN but it can't
130 find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000131 4.13. Q. What GUI toolkits exist for Python?
Guido van Rossum061f1821994-10-06 16:03:45 +0000132 4.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000133 4.15. Q. Is it possible to write obfuscated one-liners in Python?
134 4.16. Q. Is there an equivalent of C's "?:" ternary operator?
135 4.17. Q. My class defines __del__ but it is not called when I delete the
136 object.
137 4.18. Q. How do I change the shell environment for programs called using
138 os.popen() or os.system()? Changing os.environ doesn't work.
139 4.19. Q. What is a class?
140 4.20. Q. What is a method?
141 4.21. Q. What is self?
142 4.22. Q. What is a unbound method?
143 4.23. Q. How do I call a method defined in a base class from a derived class
144 that overrides it?
145 4.24. Q. How do I call a method from a base class without using the name of
146 the base class?
147 4.25. Q. How can I organize my code to make it easier to change the base
148 class?
149 4.26. Q. How can I find the methods or attributes of an object?
Guido van Rossum061f1821994-10-06 16:03:45 +0000150 4.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
151 4.28. Q. How can I create a stand-alone binary from a Python script?
152 4.29. Q. Is there a special lib for writing CGI scripts in Python?
153 4.30. Q. What other WWW tools are there for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000154
155 5. Extending Python
156 5.1. Q. Can I create my own functions in C?
157 5.2. Q. Can I create my own functions in C++?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000158 5.3. Q. How can I execute arbitrary Python statements from C?
159 5.4. Q. How can I evaluate an arbitrary Python expression from C?
160 5.5. Q. How do I extract C values from a Python object?
161 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000162 5.7. Q. What happened to mktuple(), featuring in an example in the
163 Extensions manual?
164 5.8. Q. How do I call an object's method from C?
165 5.9. Q. How do I catch the output from print_error()?
166 5.10. Q. How do I access a module written in Python from C?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000167
168 6. Python's design
169 6.1. Q. Why isn't there a generic copying operation for objects in
170 Python?
171 6.2. Q. Why isn't there a generic way to implement persistent objects
172 in Python? (Persistent == automatically saved to and restored from
173 disk.)
174 6.3. Q. Why isn't there a switch or case statement in Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +0000175 6.4. Q. Why does Python use indentation for grouping of statements?
Guido van Rossum3de27361994-07-25 14:19:33 +0000176 6.5. Q. Why are Python strings immutable?
177 6.6. Q. Why don't strings have methods like index() or sort(), like
178 lists?
179 6.7. Q. Why does Python use methods for some functionality
180 (e.g. list.index()) but functions for other (e.g. len(list))?
181 6.8. Q. Why can't I derive a class from built-in types (e.g. lists or
182 files)?
183 6.9. Q. Why must 'self' be declared and used explicitly in method
184 definitions and calls?
Guido van Rossum061f1821994-10-06 16:03:45 +0000185 6.10. Q. Can't you emulate threads in the interpreter instead of
186 relying on an OS-specific thread implementation?
187 6.11. Q. Why can't lambda forms contain statements?
188 6.12. Q. Why is there no more efficient way of iterating over a dictionary
189 than first constructing the list of keys()?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000190
191 7. Using Python on non-UNIX platforms
Guido van Rossum91f60831994-02-15 15:52:27 +0000192 7.1. Q. Is there a Mac version of Python?
193 7.2. Q. Is there a DOS version of Python?
194 7.3. Q. Is there a Windows version of Python?
195 7.4. Q. Is there a Windows NT version of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000196 7.5. Q. Is there an OS/2 version of Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000197 7.6. Q. Is there a VMS version of Python?
198 7.7. Q. What about IBM mainframes, or other esoteric non-UNIX
199 platforms?
200 7.8. Q. Where are the source or Makefiles for the non-UNIX versions?
201 7.9. Q. What is the status and support for the non-UNIX versions?
202 7.10. Q. I have the PC version but it appears to be only a binary.
203 Where's the library?
204 7.11. Q. Where's the documentation for the Mac or PC version?
205 7.12. Q. The Mac (PC) version doesn't seem to have any facilities for
206 creating or editing programs apart from entering it interactively, and
207 there seems to be no way to save code that was entered interactively.
208 How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000209
210To find a particular question, search for the question number followed
211by a dot, a space, and a Q at the beginning of a line (e.g. to find
212question 4.2 in vi, type /^4\.2\. Q/).
213
214
2151. General information and availability
216=======================================
217
2181.1. Q. What is Python?
219
220A. Python is an interpreted, interactive, object-oriented programming
221language. It incorporates modules, exceptions, dynamic typing, very
222high level dynamic data types, and classes. Python combines
223remarkable power with very clear syntax. It has interfaces to many
224system calls and libraries, as well as to various window systems, and
225is extensible in C or C++. It is also usable as an extension language
226for applications that need a programmable interface. Finally, Python
227is portable: it runs on many brands of UNIX, on the Mac, and on
228MS-DOS.
229
230To find out more, the best thing to do is to start reading the
231tutorial from the documentation set (see a few questions further
232down).
233
2341.2. Q. Why is it called Python?
235
236A. Apart from being a computer wizard, I'm also a fan of "Monty
237Python's Flying Circus" (a BBC comedy series from the seventies, in
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000238the -- unlikely -- case you didn't know). It occurred to me one day
239that I needed a name that was short, unique, and slightly mysterious.
240And I happened to be reading some scripts from the series at the
241time... So then I decided to call my language Python. But Python is
242not a joke. And don't you associate it with dangerous reptiles
243either!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000244
2451.3. Q. How do I obtain a copy of the Python source?
246
247A. The latest Python source distribution is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000248anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000249/pub/python, with filename python<version>.tar.gz. (Old versions may
250have an extension of .Z, indicating use of "compress" compression.)
251It is a gzip'ed tar file containing the complete C source, LaTeX
252documentation, Python library modules, example programs, and several
253useful pieces of freely distributable software. This will compile and
Guido van Rossum3de27361994-07-25 14:19:33 +0000254run out of the box on most UNIX platforms. (See section 7 for
255non-UNIX information.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000256
2571.4. Q. How do I get documentation on Python?
258
259A. The latest Python documentation set is always available by
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000260anonymous ftp from ftp.cwi.nl [192.16.191.128] in the directory
Guido van Rossum44b4cb11994-05-04 13:28:51 +0000261/pub/python, with filename pythondoc-ps<version>.tar.gz. It is a
262gzip'ed tar file containing PostScript files of the reference manual,
Guido van Rossum3de27361994-07-25 14:19:33 +0000263the library manual, and the tutorial. Note that the library manual is
264the most important one of the set, as much of Python's power stems
265from the standard or built-in types, functions and modules, all of
266which are described here. PostScript for a high-level description of
267Python is in the file nluug-paper.ps.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000268
Guido van Rossumc50158e1994-05-31 09:18:50 +00002691.5. Q. Are there other ftp sites that mirror the Python distribution?
270
271A. The following sites keep mirrors of the Python distribution:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000272
273Site IP address Directory
274
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000275gatekeeper.dec.com 16.1.0.2 /pub/plan/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000276ftp.uu.net 192.48.96.9 /languages/python
277ftp.wustl.edu 128.252.135.4 /graphics/graphics/sgi-stuff/python
Guido van Rossumc50158e1994-05-31 09:18:50 +0000278ftp.funet.fi 128.214.6.100 /pub/languages/python
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000279ftp.fu-berlin.de 130.133.1.18 /unix/languages/python (*python* only)
Guido van Rossumc50158e1994-05-31 09:18:50 +0000280ftp.sunet.se 130.238.127.3 /pub/lang/python
Guido van Rossumea2c6f71994-07-14 12:35:14 +0000281unix.hensa.ac.uk 129.12.43.16 /uunet/languages/python
Guido van Rossum061f1821994-10-06 16:03:45 +0000282ftp.sterlng.com 192.124.9.3 /programming/languages/python
Guido van Rossuma7925f11994-01-26 10:20:16 +0000283
Guido van Rossum061f1821994-10-06 16:03:45 +0000284Or try archie on e.g. "python1." to locate the nearest copy of that
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000285version...
Guido van Rossuma7925f11994-01-26 10:20:16 +0000286
Guido van Rossumc50158e1994-05-31 09:18:50 +00002871.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000288
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000289A. There is a newsgroup, comp.lang.python, and a mailing list. The
290newsgroup and mailing list are gatewayed into each other -- if you can
Guido van Rossum061f1821994-10-06 16:03:45 +0000291read news it's unnecessary to subscribe to the mailing list. Send
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000292e-mail to python-list-request@cwi.nl to (un)subscribe to the mailing
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000293list. Once you're on, send e-mail tp python-list@cwi.nl to send mail
Guido van Rossum061f1821994-10-06 16:03:45 +0000294to the entire mailing list and newsgroup. Hypermail archives of
295(nearly) everything posted to the mailing list (and thus the
296newsgroup) are available -- the URL for the complete set of archives
297is <http://www.cwi.nl/~guido/hypermail/index.html>. The raw archives
298are also available by ftp from ftp.cwi.nl in /pub/python (and most
299mirrors), files mail*.gz. The uncompressed versions of these files
300can be read with the standard UNIX Mail program ("Mail -f file") or
301with nn ("nn file"). To read them using MH, you could use "inc -file
302file".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000303
Guido van Rossumc50158e1994-05-31 09:18:50 +00003041.7. Q. Is there a book on Python, or will there be one out soon?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000305
Guido van Rossum061f1821994-10-06 16:03:45 +0000306A. I am writing one. Addison-Wesley is interested. Optimistically,
307it will be published by mid-1995. Other authors are also working on
308books... (Do you guys want your name mentioned here?)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000309
Guido van Rossumc50158e1994-05-31 09:18:50 +00003101.8. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000311
312A. So far the only refereed and published article that describes
313Python in some detail is:
314
315 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
316 Servers Using the Python Programming Language", CWI Quarterly, Volume
317 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
318
319LaTeX source for this paper is available as part of the Python source
320distribution.
321
322A more recent high-level description of Python is:
323
324 Guido van Rossum, "An Introduction to Python for UNIX/C
325 Programmers", in the proceedings of the NLUUG najaarsconferentie
Guido van Rossum061f1821994-10-06 16:03:45 +0000326 1993 (dutch UNIX users group meeting November 1993).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000327
328PostScript for this paper and for the slides used for the accompanying
329presentation can be found in the ftp directory mentioned a few
330questions earlier, with filenames nluug-paper.ps and nluug-slides.ps,
331respectively.
332
Guido van Rossumc50158e1994-05-31 09:18:50 +00003331.9. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000334
335A. Python versions are numbered A.B.C. A is the major version number
336-- it is only incremented for major changes in functionality or source
337structure. B is the minor version number, incremented for less
338earth-shattering changes to a release. C is the patchlevel -- it is
339incremented for each new release. Note that in the past, patches have
340added significant changes; in fact the changeover from 0.9.9 to 1.0.0
341was the first time that either A or B changed!
342
Guido van Rossumc50158e1994-05-31 09:18:50 +00003431.10. Q. Are there other ftp sites that carry Python related material?
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000344
345A. An interesting ftp site for Python users is ftp.markv.com
346(192.122.251.1); the directory pub/python contains a growing
347collection of interesting Python scripts. To submit a script for
348inclusion, place it together with a readme file (with extension
349.readme) in the publicly writable directory /incoming/python. This
350service is maintained by Lance Ellinghouse <lance@markv.com>.
351
Guido van Rossum7ce61c11994-06-13 15:13:56 +00003521.11. Q. Are there copyright restrictions on the use of Python?
353
354A. Hardly. You can do anything you want with the source, as long as
355you leave the copyrights in, display those copyrights in any
356documentation about Python that you produce, don't use the author's
357institute's name in publicity without prior written permission, and
358don't hold them responsible for anything (read the actual copyright
359for a precise legal wording).
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000360
Guido van Rossuma7925f11994-01-26 10:20:16 +0000361
3622. Python in the real world
363===========================
364
3652.1. Q. How many people are using Python?
366
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000367A. I don't know, but the maximum number of simultaneous subscriptions
368to the Python mailing list before it was gatewayed into the newsgroup
369was about 180 (several of which were local redistribution lists). I
370believe that many active Python users don't bother to subscribe to the
371list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000372is even less meaningful. I see new names on the newsgroup all the
373time and my best guess is that there are currently at least several
374thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000375
3762.2. Q. Have any significant projects been done in Python?
377
378A. Here at CWI (the home of Python), we have written a 20,000 line
379authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00003805,000 line multimedia teleconferencing tool, as well as many many
381smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000382
383The University of Virginia uses Python to control a virtual reality
384engine. Contact: Matt Conway <conway@virginia.edu>.
385
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000386If you have done a significant project in Python that you'd like to be
387included in the list above, send me email!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000388
3892.3. Q. Are there any commercial projects going on using Python?
390
391A. Several companies have revealed to me that they are planning or
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000392considering to use Python in a future product.
393
394The furthest is Sunrise Software, who already have a product out using
395Python -- they use Python for a GUI management application and an SNMP
Guido van Rossum061f1821994-10-06 16:03:45 +0000396network management application. Contact: <info@sunrise.com>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000397
Guido van Rossum061f1821994-10-06 16:03:45 +0000398Infoseek is using Python to implement their commercial WWW information
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000399retrieval service. Contact: <info@infoseek.com>.
400
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000401Michael Powers of daVinci Time & Space is "writing tons-o-python for
402interactive television entertainment." Contact: <powers@dvts.com>.
403
Guido van Rossuma7925f11994-01-26 10:20:16 +0000404Individuals at many other companies are using Python for
405internal development (witness their contributions to the Python
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000406mailing list or newsgroup).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000407
408Python has also been elected as an extension language by MADE, a
409consortium supported by the European Committee's ESPRIT program and
410consisting of Bull, CWI and some other European companies. Contact:
411Ivan Herman <ivan@cwi.nl>.
412
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000413If you'd like to be included in the list above, send me email!
414
Guido van Rossum95f61a71994-01-26 17:23:37 +00004152.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000416
Guido van Rossum3de27361994-07-25 14:19:33 +0000417A. Very stable. While the current version number would suggest it is
418in the early stages of development, in fact new, stable releases
419(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 +0000420months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000421
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00004222.5. Q. When will the next version be released?
423
424A. I am planning to release 1.1 before October 15. It will contain
425tons of changes, including (again) improved portability, especially
426better support for DOS, Windows, Windows NT an the Macintosh. A few
427modules will have been converted to the new naming scheme. A working
428signal module will be present.
429
4302.6. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000431
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000432A. A proposal is being worked out to change the semantics of operator
433overloading (__add__, __mul__ etc.) to make them more useful for
434implementing types that don't resemble numbers. Additions will be
435__call__ (to call an instance as if it were a function) and __eq__,
436_lt__ etc. (to override individual comparisons). A (new) pthreads
437interface has been submitted which will be integrated in the next
438release. The X11/Motif interface will be improved. There are ideas
439about built-in help using strings placed into function objects, and
440possibly a switch statement.
441
442There will be better ports to the Mac, DOS, Windows, Windows NT, and
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000443OS/2. The Windows ports will support dynamically loaded modules using
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000444DLLs.
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000445
446Also planned is improved support for embedding Python in other
447applications, e.g. by renaming most global symbols to have a "Py"
448prefix and providing more documentation and threading support.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000449
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00004502.7. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossum3de27361994-07-25 14:19:33 +0000451
452A. In general, no. There are already millions of lines of Python code
453around the world, so any changes in the language that invalidates more
454than a very small fraction of existing programs has to be frowned
455upon. Even if you can provide a conversion program, there still is
456the problem of updating all documentation. Providing a gradual
457upgrade path is the only way if a feature has to be changed.
458
Guido van Rossuma7925f11994-01-26 10:20:16 +0000459
4603. Building Python
461==================
462
Guido van Rossum91f60831994-02-15 15:52:27 +00004633.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000464
465A. Yes, simply do "import testall" (or "import autotest" if you aren't
466interested in the output). The standard modules whose name begins
467with "test" together comprise the test. The test set doesn't test
468*all* features of Python but it goes a long way to confirm that a new
469port is actually working. The Makefile contains an entry "make test"
470which runs the autotest module.
471
Guido van Rossum91f60831994-02-15 15:52:27 +00004723.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000473operations, but when playing with floating point operations I cannot
474find anything wrong with them.
475
476A. The test set makes occasional unwarranted assumptions about the
477semantics of C floating point operations. Until someone donates a
478better floating point test set, you will have to comment out the
479offending floating point tests and execute similar tests manually.
480
Guido van Rossum061f1821994-10-06 16:03:45 +00004813.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
Guido van Rossum24349991994-02-02 14:12:45 +0000482
Guido van Rossum061f1821994-10-06 16:03:45 +0000483A. Get STDWIN 0.9.9 from ftp://ftp.cwi.nl/pub/stdwin/stdwin0.9.9.tar.gz.
484
485Q. Link errors building Python with STDWIN 0.9.9.
486
487A. Probably routines liek 'tereate', 'tenew' etc. The STDWIN 0.9.9
488distribution requires that you add TWO libraries from stdwin to the
489line for stdwin in the Setupfile. Use something like this (all on one
490line!):
491
492stdwin stdwinmodule.c -I$(STDWIN)/H $(STDWIN)/Packs/textedit/libtextedit.a $(STDWIN)/Ports/x11/libstdwin.a -lX11
Guido van Rossum24349991994-02-02 14:12:45 +0000493
Guido van Rossum91f60831994-02-15 15:52:27 +00004943.4. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000495
496A. It is generally necessary to run "make clean" after a configuration
497change.
498
Guido van Rossum91f60831994-02-15 15:52:27 +00004993.5. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000500script (after the script name).
501
502A. You are probably linking with GNU getopt, e.g. through -liberty.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000503Don't. The reason for the complaint is that GNU getopt, unlike System
504V getopt and other getopt implementations, doesn't consider a
505non-option to be the end of the option list. A quick (and compatible)
506fix for scripts is to add "--" to the interpreter, like this:
507
508 #! /usr/local/bin/python --
509
510You can also use this interactively:
511
512 python -- script.py [options]
Guido van Rossum24349991994-02-02 14:12:45 +0000513
Guido van Rossum91f60831994-02-15 15:52:27 +00005143.6. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000515glmodule.c, but python hasn't been built or installed yet.
516
517A. Comment out the line mentioning glmodule.c in Setup and build a
518python without gl first; install it or make sure it is in your $PATH,
519then edit the Setup file again to turn on the gl module, and make
520again. You don't need to do "make clean"; you do need to run "make
521Makefile" in the Modules subdirectory (or just run "make" at the
522toplevel).
523
Guido van Rossum3de27361994-07-25 14:19:33 +00005243.7. Q. Python built with gcc for the DEC Alpha doesn't work.
525
526People have reported problems with both gcc 2.5.8 and 2.6.0. The DEC
527OSF/1 cc compiler does not have these problems so it's probably gcc's
528fault. One person reported that the problem went away when using -g
529instead of -O so this may be an option if you insist on using gcc. If
530someone tracks it down more completely I'd like to hear about it!
531
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00005323.8. Q. I use VPATH but some targets are built in the source directory.
533
534A. On some systems (e.g. Sun), if the target already exists in the
535source directory, it is created there instead of in the build
536directory. This is usually because you have previously built without
537VPATH. Try running "make clobber" in the source directory.
538
5393.9. Q. Trouble building or linking with the GNU readline library.
540
541A. Consider using readline 2.0. From the Python 1.1 README:
542
543- You can use the GNU readline library to improve the interactive user
544interface: this gives you line editing and command history when
545calling python interactively. You need to configure build the GNU
546readline library before running the configure script. Its sources are
547no longer distributed with Python; you can ftp them from any GNU
548mirror site, or from its home site:
549ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz (or a higher
550version number -- using version 1.x is not recommended). Pass the
551Python configure script the option --with-readline=DIRECTORY where
552DIRECTORY is the absolute pathname of the directory where you've built
553the readline library. Some hints on building and using the readline
554library:
555
556- On SGI IRIX 5, you may have to add the following
557to rldefs.h:
558
559#ifndef sigmask
560#define sigmask(sig) (1L << ((sig)-1))
561#endif
562
563- On most systems, you will have to add #include "rldefs.h" to the
564top of several source files, and if you use the VPATH feature, you
565will have to add dependencies of the form foo.o: foo.c to the
566Makefile for several values of foo.
567
568- The readline library requires use of the termcap library. A
569known problem with this is that it contains entry points which
Guido van Rossum061f1821994-10-06 16:03:45 +0000570cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000571conflict can be solved (and will be, in the next release of
Guido van Rossum061f1821994-10-06 16:03:45 +0000572STDWIN) by adding a line saying '#define werase w_erase' to the
573stdwin.h file (in the STDWIN distribution, subdirectory H). The
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000574GL conflict has been solved in the Python configure script by a
575hack that forces use of the static version of the termcap library.
576
577- Check the newsgroup gnu.bash.bugs for specific problems with the
578readline library (I don't get this group here but I've been told
579that it is the place for readline bugs.)
580
5813.10. Q. Trouble building Python on Linux.
582
583A. There shouldn't be any -- I've seen several complaints but more
584reports on successful "out-of-the-box" ports on Linux. The standard
585configure script runs just fine on Linux.
586
Guido van Rossum72eb83c1994-10-07 11:33:28 +0000587Q. Trouble with prototypes on Ultrix.
588
589A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef
590HAVE_PROTOTYPES.
591
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00005923.11. Q. Other trouble building Python on platform X.
Guido van Rossum95f61a71994-01-26 17:23:37 +0000593
594A. Please email the details to <guido@cwi.nl> and I'll look into it.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000595
596
5974. Programming in Python
598========================
599
Guido van Rossum24349991994-02-02 14:12:45 +00006004.1. Q. Is there a source code level debugger with breakpoints, step,
601etc.?
602
603A. Yes. Check out module pdb; pdb.help() prints the documentation (or
604you can read it as Lib/pdb.doc). If you use the STDWIN option,
605there's also a windowing interface, wdb. You can write your own
606debugger by using the code for pdb or wdb as an example.
607
6084.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000609C and others in Python (e.g. through inheritance)? (Also phrased as:
610Can I use a built-in type as base class?)
611
612A. No, but you can easily create a Python class which serves as a
613wrapper around a built-in object, e.g. (for dictionaries):
614
615 # A user-defined class behaving almost identical
616 # to a built-in dictionary.
617 class UserDict:
618 def __init__(self): self.data = {}
619 def __repr__(self): return repr(self.data)
620 def __cmp__(self, dict):
621 if type(dict) == type(self.data):
622 return cmp(self.data, dict)
623 else:
624 return cmp(self.data, dict.data)
625 def __len__(self): return len(self.data)
626 def __getitem__(self, key): return self.data[key]
627 def __setitem__(self, key, item): self.data[key] = item
628 def __delitem__(self, key): del self.data[key]
629 def keys(self): return self.data.keys()
630 def items(self): return self.data.items()
631 def values(self): return self.data.values()
632 def has_key(self, key): return self.data.has_key(key)
633
Guido van Rossum24349991994-02-02 14:12:45 +00006344.3. Q. Is there a curses/termcap package for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000635
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000636A. Yes -- Lance Ellinghouse has written a module that interfaces to
637System V's "ncurses". If you know a little curses and some Python,
638it's straightforward to use.
639
640You could also consider using the "alfa" (== character cell) version
641of STDWIN. (STDWIN == Standard Windows, a portable windowing system
642interface by the same author, URL: "ftp://ftp.cwi.nl/pub/stdwin".) This
643will also prepare your program for porting to windowing environments
644such as X11 or the Macintosh.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000645
Guido van Rossum24349991994-02-02 14:12:45 +00006464.4. Q. Is there an equivalent to C's onexit() in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000647
648A. Yes, if you import sys and assign a function to sys.exitfunc, it
649will be called when your program exits, is killed by an unhandled
650exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
651
Guido van Rossum24349991994-02-02 14:12:45 +00006524.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000653nested function seemingly can't access the local variables of the
654outer function. What is going on? How do I pass local data to a
655nested function?
656
657A. Python does not have arbitrarily nested scopes. When you need to
658create a function that needs to access some data which you have
659available locally, create a new class to hold the data and return a
660method of an instance of that class, e.g.:
661
662 class MultiplierClass:
663 def __init__(self, factor):
664 self.factor = factor
665 def multiplier(self, argument):
666 return argument * self.factor
667
668 def generate_multiplier(factor):
669 return MultiplierClass(factor).multiplier
670
671 twice = generate_multiplier(2)
672 print twice(10)
673 # Output: 20
674
Guido van Rossum24349991994-02-02 14:12:45 +00006754.6. Q. How do I iterate over a sequence in reverse order?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000676
677A. If it is a list, the fastest solution is
678
679 list.reverse()
680 try:
681 for x in list:
682 "do something with x"
683 finally:
684 list.reverse()
685
686This has the disadvantage that while you are in the loop, the list
687is temporarily reversed. If you don't like this, you can make a copy.
688This appears expensive but is actually faster than other solutions:
689
690 rev = list[:]
691 rev.reverse()
692 for x in rev:
693 <do something with x>
694
695If it isn't a list, a more general but slower solution is:
696
697 i = len(list)
698 while i > 0:
699 i = i-1
700 x = list[i]
701 <do something with x>
702
703A more elegant solution, is to define a class which acts as a sequence
704and yields the elements in reverse order (solution due to Steve
705Majewski):
706
707 class Rev:
708 def __init__(self, seq):
709 self.forw = seq
710 def __len__(self):
711 return len(self.forw)
712 def __getitem__(self, i):
713 return self.forw[-(i + 1)]
714
715You can now simply write:
716
717 for x in Rev(list):
718 <do something with x>
719
Guido van Rossum061f1821994-10-06 16:03:45 +0000720Unfortunately, this solution is slowest of all, due to the method
Guido van Rossuma7925f11994-01-26 10:20:16 +0000721call overhead...
722
Guido van Rossum24349991994-02-02 14:12:45 +00007234.7. Q. My program is too slow. How do I speed it up?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000724
725A. That's a tough one, in general. There are many tricks to speed up
726Python code; I would consider rewriting parts in C only as a last
727resort. One thing to notice is that function and (especially) method
728calls are rather expensive; if you have designed a purely OO interface
729with lots of tiny functions that don't do much more than get or set an
730instance variable or call another method, you may consider using a
731more direct way, e.g. directly accessing instance variables. Also see
732the standard module "profile" (described in the file
733"python/lib/profile.doc") which makes it possible to find out where
734your program is spending most of its time (if you have some patience
735-- the profiling itself can slow your program down by an order of
736magnitude).
737
Guido van Rossum24349991994-02-02 14:12:45 +00007384.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000739again (into the same Python process), the changes don't seem to take
740place. What is going on?
741
742A. For efficiency reasons, Python only reads the module file on the
743first time a module is imported (otherwise a program consisting of
744many modules, each of which imports the same basic module, would read
745the basic module over and over again). To force a changed module
746being read again, do this:
747
748 import modname
749 reload(modname)
750
751Warning: this technique is not 100% fool-proof. In particular,
752modules containing statements like
753
754 from modname import some_objects
755
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000756will continue to work with the old version of the imported objects.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000757
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00007584.9. Q. How do I find the current module name?
Guido van Rossum24349991994-02-02 14:12:45 +0000759
Guido van Rossum061f1821994-10-06 16:03:45 +0000760A. A module can find out its own module name by looking at the
Guido van Rossum24349991994-02-02 14:12:45 +0000761(predefined) global variable __name__. If this has the value
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000762'__main__' you are running as a script.
763
7644.10. Q. I have a module in which I want to execute some extra code when it
765is run as a script. How do I find out whether I am running as a
766script?
767
768A. See the previous question. E.g. if you put the following on the
769last line of your module, main() is called only when your module is
770running as a script:
Guido van Rossum24349991994-02-02 14:12:45 +0000771
772 if __name__ == '__main__': main()
773
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00007744.11. Q. I try to run a program from the Demo directory but it fails with
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000775ImportError: No module named ...; what gives?
776
Guido van Rossum061f1821994-10-06 16:03:45 +0000777A. This is probably an optional module (written in C!) which hasn't
778been configured on your system. This especially happens with modules
779like "stdwin", "gl", "Xt" or "Xm". For STDWIN and many other modules,
780see Modules/Setup.in for info on how to add these modules to your
781Python, if it is possible at all. Sometimes you will have to ftp and
782build another package first (e.g. STDWIN). Sometimes the module only
783works on specific platforms (e.g. gl only works on SGI machines).
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000784
Guido van Rossum061f1821994-10-06 16:03:45 +0000785For X-related modules (Xt and Xm) you will have to do more work: they
786are currently not part of the standard Python distribution. You will
787have to ftp the file "extensions.tar.gz" file from a Python ftp
788repository (e.g. ftp.cwi.nl) and follow the instructions there. Note:
789the X related modules are still somewhat flakey, so don't try this
790unless you alread know a bit or two about building X applications on
791your platform.
792
793See also the next question.
794
7954.12. Q. I have successfully built Python with STDWIN but it can't
796find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000797
798A. There's a subdirectory of the library directory named 'stdwin'
799which should be in the default module search path. There's a line in
800Modules/Setup(.in) that you have to enable for this purpose --
Guido van Rossum061f1821994-10-06 16:03:45 +0000801unfortunately in the latest release it's not near the other
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000802STDWIN-related lines so it's easy to miss it.
803
8044.13. Q. What GUI toolkits exist for Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000805
806A. Depending on what platform(s) you are aiming at, there are several.
807
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000808- There's a neat object-oriented interface to the Tcl/Tk widget set,
809called Tkinter. You can ftp it from ftp.cwi.nl as
810pub/python/tkinter.tar.gz. This is probably the easiest to install
811and use, and the most complete widget set.
812
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000813- The standard Python distribution comes with an interface to STDWIN,
814a platform-independent low-level windowing interface (you have to ftp
Guido van Rossum061f1821994-10-06 16:03:45 +0000815the source for STDWIN separately, e.g. from ftp.cwi.nl in pub/stdwin
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000816or gatekeeper.dec.com in pub/misc/stdwin). STDWIN runs under X11 or
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000817the Mac; a Windows port has been attempted but I can't seem to get it
818working. Note that STDWIN is really not powerful enough to implement
819a modern GUI (no widgets, etc.) and that I don't have the time to
820maintain or extend it, so you may be better off using Tkinter or the
821Motif interface, unless you require portability to the Mac (which is
822also offered by SUIT, by the way -- see below).
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000823
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000824- For SGI IRIX only, there's an interface to the complete GL (Graphics
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000825Library -- low level but very good 3D capabilities) as well as to
826FORMS (a buttons-and-sliders-etc package built on top of GL by Mark
827Overmars -- ftp'able from ftp.cs.ruu.nl in pub/SGI/FORMS).
828
829- There's an interface to X11, including the Athena and Motif widget
830sets (and a few individual widgets, like Mosaic's HTML widget and
831SGI's GL widget) in the Extensions set, which is separately ftp'able
832from ftp.cwi.nl as pub/python/extensions.tar.gz.
833
834- There's an interface to SUIT, the U of Virginia's Simple User
835Interface Toolkit; it can be ftp'ed from uvacs.cs.virginia.edu as
836pub/suit/python/SUIT_python.tar.Z. A PC binary of Python 1.0.2
837compiled with DJGPP and with SUIT support built-in has been made
838available by Antonio Costa on ftp site asterix.inescn.pt, directory
839pub/PC/python, file pyt102su.exe (a self-extracting archive).
840
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000841- There's an interface to WAFE, a Tcl interface to the X11 Motif and
842Athena widget sets. Last I heard about it it was included in the
843WAFE 1.0 prerelease, ftp'able from ftp.wu-wien.ac.at as
844pub/src/X11/wafe/wafe-1.0.tar.gz-prerelease.
845
Guido van Rossum061f1821994-10-06 16:03:45 +00008464.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000847
848A. There's an interface to SYBASE by John Redford
849<jredford@lehman.com>.
850
851There's also an interface to metalbase by Lance Ellinghouse
852<lance@markv.com>.
853
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000854Anthony Baxter <anthony.baxter@aaii.oz.au> has written an interface to
855mSQL (mini-SQL). Ftp it from ftp.cwi.nl:/pub/python/PymSQL.tar.gz.
856
8574.15. Q. Is it possible to write obfuscated one-liners in Python?
Guido van Rossumc24da7c1994-09-23 14:08:41 +0000858
859A. Yes. See the following three examples, due to Ulf Bartelt:
860
861# Primes < 1000
862print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\
863map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
864
865# First 10 Fibonacci numbers
866print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),\
867range(10))
868
869# Mandelbrot set
870print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,\
871Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\
872Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\
873i=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\
874>=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(\
87564+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\
876))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
877# \___ ___/ \___ ___/ | | |__ lines on screen
878# V V | |______ columns on screen
879# | | |__________ maximum of "iterations"
880# | |_________________ range on y axis
881# |____________________________ range on x axis
882
883Don't try this at home, kids!
884
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00008854.16. Q. Is there an equivalent of C's "?:" ternary operator?
Guido van Rossumc24da7c1994-09-23 14:08:41 +0000886
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000887A. Not directly. In many cases you can mimic a?b:c with "a and b or
888c", but there's a flaw: if b is zero (or empty, or None -- anything
889that tests false) then c will be selected instead. In many cases you
890can prove by looking at the code that this can't happen (e.g. because
891b is a constant or has a type that can never be false), but in general
892this can be a problem.
893
894Steve Majewski (or was it Tim Peters?) suggested the following
895solution: (a and [b] or [c])[0]. Because [b] is a singleton list it
896is never false, so the wrong path is never taken; then applying [0] to
897the whole thing gets the b or c that you really wanted. Ugly, but it
898gets you there in the rare cases where it is really inconvenient to
899rewrite your code using 'if'.
900
9014.17. Q. My class defines __del__ but it is not called when I delete the
902object.
903
904A. There are several possible reasons for this.
905
906- The del statement does not necessarily call __del__ -- it simply
907decrements the object's reference count, and if this reaches zero
908__del__ is called.
909
910- If your data structures contain circular links (e.g. a tree where
911each child has a parent pointer and each parent has a list of
912children) the reference counts will never go back to zero. You'll
Guido van Rossum061f1821994-10-06 16:03:45 +0000913have to define an explicit close() method which removes those
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000914pointers. Please don't ever call __del__ directly -- __del__ should
Guido van Rossum061f1821994-10-06 16:03:45 +0000915call close() and close() should make sure that it can be called more
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000916than once for the same object.
917
918- If the object has ever been a local variable (or argument, which is
919really the same thing) to a function that caught an expression in an
920except clause, chances are that a reference to the object still exists
921in that function's stack frame as contained in the stack trace.
922Normally, deleting (better: assigning None to) sys.exc_traceback will
923take care of this. If you a stack was printed for an unhandled
924exception in an interactive interpreter, delete sys.last_traceback
925instead.
926
927- There is code that deletes all objects when the interpreter exits,
928but if your Python has been configured to support threads, it is not
929called (because other threads may still be active). You can define
Guido van Rossum061f1821994-10-06 16:03:45 +0000930your own cleanup function using sys.exitfunc (see question 4.4).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000931
9324.18. Q. How do I change the shell environment for programs called using
933os.popen() or os.system()? Changing os.environ doesn't work.
934
935A. Modifying the environment passed to subshells was left out of the
936interpreter because there seemed to be no well-established portable
937way to do it.
938
939However if all you want is to pass environment variables to the
940commands run by os.system() or os.popen(), there's a simple solution:
941prefix the command string with a couple of variable assignments and
942export statements. I guess the following would be universal for popen
943(untested):
944
945import os
946from commands import mkarg # nifty routine to add shell quoting
947def epopen(cmd, mode, env = {}):
948 # env is a dictionary of environment variables
949 prefix = ''
950 for key, value in env.values():
951 prefix = prefix + '%s=%s\n' % (key, mkarg(value))
952 prefix = prefix + 'export %s\n' % key
953 return os.popen(prefix + cmd, mode)
954
9554.19. Q. What is a class?
956
957A. A class is the particular object type that is created by executing
958a class statement.
959
9604.20. Q. What is a method?
961
962A. A method is a function that you normally call as
963x.name(arguments...) for some object x. The word is used for methods
964of classes and class instances as well as for methods of built-in
965objects. The latter have a completely different implementation and
966only share the way their calls look in Python code.
967
9684.21. Q. What is self?
969
970A. Self is merely a conventional name for the first argument of a
971method -- i.e. a function defined inside a class definition. A method
972defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
973some instance x of the class in which the definition occurs;
974the called method will think it is called as meth(x, a, b, c).
975
9764.22. Q. What is a unbound method?
977
978A. An unbound method is a method defined in a class that is not yet
979bound to an instance. You get an unbound method if you ask for a
980class attribute that happens to be a function. You get a bound method
981if you ask for an instance attribute. A bound method knows which
Guido van Rossum061f1821994-10-06 16:03:45 +0000982instance it belongs to and calling it supplies the instance automatically;
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000983an unbound method only knows which class it wants for its first
984argument (a derived class is also OK). Calling an unbound method
985doesn't "magically" derive the first argument from the context -- you
986have to provide it explicitly.
987
9884.23. Q. How do I call a method defined in a base class from a derived class
989that overrides it?
990
991A. If your class definition starts with "class Derived(Base): ..."
992then you can call method meth defined in Base (or one of Base's base
993classes) as Base.meth(self, arguments...). Here, Base.meth is an
994unbound method (see previous question).
995
9964.24. Q. How do I call a method from a base class without using the name of
997the base class?
998
999A. DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call
1000self.__class__.__bases__[0].meth(self, arguments...) but this fails when
Guido van Rossum061f1821994-10-06 16:03:45 +00001001a doubly-derived method is derived from your class: for its instances,
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001002self.__class__.__bases__[0] is your class, not its base class -- so
1003(assuming you are doing this from within Derived.meth) you would start
1004a recursive call.
1005
10064.25. Q. How can I organize my code to make it easier to change the base
1007class?
1008
1009A. You could define an alias for the base class, assign the real base
1010class to it before your class definition, and use the alias throughout
1011your class. Then all you have to change is the value assigned to the
1012alias. Incidentally, this trick is also handy if you want to decide
1013dynamically (e.g. depending on availability of resources) which base
1014class to use. Example:
1015
1016BaseAlias = <real base class>
1017class Derived(BaseAlias):
1018 def meth(self):
1019 BaseAlias.meth(self)
1020 ...
1021
10224.26. Q. How can I find the methods or attributes of an object?
1023
1024A. This depends on the object type.
1025
1026For an instance x of a user-defined class, instance attributes are
1027found in the dictionary x.__dict__, and methods and attributes defined
1028by its class are found in x.__class__.__bases__[i].__dict__ (for i in
1029range(len(x.__class__.__bases__))). You'll have to walk the tree of
1030base classes to find *all* class methods and attributes.
1031
1032Many, but not all built-in types define a list of their method names
1033in x.__methods__, and if they have data attributes, their names may be
1034found in x.__members__. However this is only a convention.
1035
1036For more information, read the source of the standard (but
1037undocumented) module newdir.
1038
10394.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
1040
1041A. os.read() is a low-level function which takes a file descriptor (a
1042small integer). os.popen() creates a high-level file object -- the
1043same type used for sys.std{in,out,err} and returned by the builtin
1044open() function. Thus, to read n bytes from a pipe p created with
1045os.popen(), you need to use p.read(n).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001046
Guido van Rossum061f1821994-10-06 16:03:45 +000010474.28. Q. How can I create a stand-alone binary from a Python script?
1048
1049The demo script "Demo/scripts/freeze.py" does what you want. (It's
1050actually not a demo but a support tool -- there is some extra code in
1051the interpreter to accommodate it.) It requires that you have the
1052Python build tree handy, complete with all the lib*.a files.
1053
1054This works by scanning your source recursively for import statements
1055(both forms) and looking for the modules on the standard Python path
1056as well as in the source directory (for built-in modules). It then
1057"compiles" the modules written in Python to C code (array initializers
1058that can be turned into code objects using the marshal module) and
1059creates a custom-made config file that only contains those built-in
1060modules which are actually used in the program. It then compiles the
1061generated C code and links it with the rest of the Python interpreter
1062to form a self-contained binary which acts exactly like your script.
1063
1064Unfortunately, the current version is very platform-specific, because
1065each platform has its own compilation flags and libraries to link
1066with. You will probably have to edit the freeze.py file to point it
1067to the right directories and tell it about the compilation and link
1068flags for your platform. A new version will be released with Python
10691.1 -- if you want a peek write to my colleague <Jack.Jansen@cwi.nl>.
1070
10714.29. Q. Is there a special lib for writing CGI scripts in Python?
1072
1073A. There's documentation and code for a cgi.py module by Michael McLay
1074<mclay@eeel.nist.gov> available from:
1075
1076 http://www.eeel.nist.gov/python/
1077
1078(For the curious: CGI or Common Gateway Interface is the protocol
1079between HTTP servers (WWW servers) and programs/scripts they run to
1080perform queries and other tasks that require returning a dynamically
1081generated document.)
1082
10834.30. Q. What other WWW tools are there for Python?
1084
1085A. The standard library has a module urllib, which can retrieve most
1086commonly used URL types (file, ftp, http, gopher).
1087
1088The Demo2/www directory (Demo2 has to be retrieved separately from the
1089Python ftp sites) contains some (really old) code to parse HTML and to
1090display it.
1091
1092Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser
1093called Dancer. An alpha version can be FTP'ed from
1094ftp.cs.indiana.edu:/pub/smiale/dancer.tar.gz. (There are a few
1095articles about Dancer in the (hyper)mail archive.)
1096
1097
Guido van Rossuma7925f11994-01-26 10:20:16 +000010985. Extending Python
1099===================
1100
11015.1. Q. Can I create my own functions in C?
1102
1103A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +00001104variables, exceptions and even new types in C. This is explained in
1105the document "Extending and Embedding the Python Interpreter" (the
1106LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001107
11085.2. Q. Can I create my own functions in C++?
1109
1110A. Yes, using the C-compatibility features found in C++. Basically
1111you place extern "C" { ... } around the Python include files and put
1112extern "C" before each function that is going to be called by the
1113Python interpreter. Global or static C++ objects with constructors
1114are probably not a good idea.
1115
Guido van Rossum7ce61c11994-06-13 15:13:56 +000011165.3. Q. How can I execute arbitrary Python statements from C?
1117
1118A. The highest-level function to do this is run_command() which takes
1119a single string argument which is executed in the context of module
1120__main__ and returns 0 for success and -1 when an exception occurred
1121(including SyntaxError). If you want more control, use run_string();
1122see the source for run_command() in Python/pythonrun.c.
1123
11245.4. Q. How can I evaluate an arbitrary Python expression from C?
1125
1126A. Call the function run_string() from the previous question with the
1127start symbol eval_input; it then parses an expression, evaluates it
1128and returns its value. See exec_eval() in Python/bltinmodule.c.
1129
11305.5. Q. How do I extract C values from a Python object?
1131
1132A. That depends on the object's type. If it's a tuple,
1133gettuplesize(o) returns its length and gettupleitem(o, i) returns its
1134i'th item; similar for lists with getlistsize(o) and getlistitem(o,
1135i). For strings, getstringsize(o) returns its length and
1136getstringvalue(o) a pointer to its value (note that Python strings may
1137contain null bytes so strlen() is not safe). To test which type an
1138object is, first make sure it isn't NULL, and then use
1139is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
1140
11415.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
1142
1143A. You can't. Use t = newtupleobject(n) instead, and fill it with
1144objects using settupleitem(t, i, o) -- note that this "eats" a
1145reference count of o. Similar for lists with newlistobject(n) and
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001146setlistitem(l, i, o). Note that you *must* set all the tuple items to
1147some value before you pass the tuple to Python code --
1148newtupleobject(n) initializes them to NULL, which isn't a valid Python
1149value.
1150
11515.7. Q. What happened to mktuple(), featuring in an example in the
1152Extensions manual?
1153
1154A. It's a typo, I meant newtupleobject() (see previous question).
1155
11565.8. Q. How do I call an object's method from C?
1157
1158A. Here's a function (untested) that might become part of the next
1159release in some form. It uses <stdarg.h> to allow passing the
1160argument list on to vmkvalue():
1161
1162object *call_method(object *inst, char *methodname, char *format, ...)
1163{
1164 object *method;
1165 object *args;
1166 object *result;
1167 va_list va;
1168 method = getattr(inst, methodname);
1169 if (method == NULL) return NULL;
1170 va_start(va, format);
1171 args = vmkvalue(format, va);
1172 va_end(va);
1173 if (args == NULL) {
1174 DECREF(method);
1175 return NULL;
1176 }
1177 result = call_object(method, args);
1178 DECREF(method);
1179 DECREF(args);
1180 return result;
1181}
1182
1183This works for any instance that has methods -- whether built-in or
1184user-defined. You are responsible for eventually DECREF'ing the
1185return value.
1186
1187To call, e.g., a file object's "seek" method with arguments 10, 0
1188(assuming the file object pointer is "f"):
1189
1190res = call_method(f, "seek", "(OO)", 10, 0);
1191if (res == NULL) {
1192 ... an exception occurred ...
1193}
1194else {
1195 DECREF(res);
1196}
1197
1198Note that since call_object() *always* wants a tuple for the argument
1199list, to call a function without arguments, pass "()" for the format,
1200and to call a function with one argument, surround the argument in
1201parentheses, e.g. "(i)".
1202
12035.9. Q. How do I catch the output from print_error()?
1204
1205A. (Due to Mark Hammond):
1206
1207* in Python code, define an object that supports the "write()" method.
1208FWIW, there seems to be a small problem that requires the 'softspace'
Guido van Rossum061f1821994-10-06 16:03:45 +00001209attribute to be defined too (I can't remember exact details of the
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001210problem).
1211
1212* redirect sys.stdout and sys.stderr to this object.
1213
Guido van Rossum061f1821994-10-06 16:03:45 +00001214* call print_error, or just allow the standard traceback mechanism to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001215work.
1216
Guido van Rossum061f1821994-10-06 16:03:45 +00001217Then, the output will go wherever your write() method sends it.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001218
12195.10. Q. How do I access a module written in Python from C?
1220
1221A. You can get a pointer to the module object as follows:
1222
1223 module = import_module("<modulename>");
1224
1225If the module hasn't been imported yet (i.e. it is not yet present in
1226sys.modules), this initializes the module; otherwise it simply returns
1227the value of sys.modules["<modulename>"]. Note that it doesn't enter
1228the module into any namespace -- it only ensures it has been
1229initialized and is stored in sys.modules.
1230
1231You can then access the module's attributes (i.e. any name defined in
1232the module) as follows:
1233
1234 attr = getattr(module, "<attrname>");
1235
1236Calling setattr(), to assign to variables in the module, also works.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001237
Guido van Rossuma7925f11994-01-26 10:20:16 +00001238
12396. Python's design
1240==================
1241
12426.1. Q. Why isn't there a generic copying operation for objects in
1243Python?
1244
1245A. Hmm. Maybe there should be one, but it's difficult to assign a
1246useful meaning to copying of open files, sockets and windows, or
1247recursive data structures. As long as you design all your classes
1248yourself you are of course free to define a standard base class that
1249defines an overridable copying operation for all the objects you care
1250about. (One practical point: it would have to be a built-in function,
1251not a standard method name, since not all built-in object types have
1252methods; e.g. strings, integers and tuples don't.)
1253
12546.2. Q. Why isn't there a generic way to implement persistent objects
1255in Python? (Persistent == automatically saved to and restored from
1256disk.)
1257
1258A. Hmm, hmm. Basically for the same reasons as why there is no
1259generic copying operation.
1260
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001261However, since there is a real desire to have persistent operations,
1262I'm thinking of extending the marshal module to support object sharing
1263(and hence recursive objects) and to extend the list of supported
1264types considerably. For user-defined classes, hooks with __*__ names
1265will allow the class to modify the way their instances are dumped and
1266loaded. Built-in types (including those defined by new extensions)
1267may also define dump/load hooks. There are several problems still to
1268solve, e.g. how do you reliably find the class of which an object is
1269an instance at load time -- assuming the class itself is loaded from
1270some module, and not part of the dumped data. It is also necessary to
1271separate the functionality of converting a set of objects into a byte
1272stream from which they can be reloaded, from the ability to save these
1273byte streams as files and being able to reference an object by a
1274persistent global name.
1275
Guido van Rossuma7925f11994-01-26 10:20:16 +000012766.3. Q. Why isn't there a switch or case statement in Python?
1277
1278A. You can do this easily enough with a sequence of
1279if... elif... elif... else. There have been some proposals for switch
Guido van Rossum061f1821994-10-06 16:03:45 +00001280statement syntax, but there is no consensus (yet) on whether and how
Guido van Rossuma7925f11994-01-26 10:20:16 +00001281to do range tests.
1282
Guido van Rossumc50158e1994-05-31 09:18:50 +000012836.4. Q. Why does Python use indentation for grouping of statements?
1284
1285A. Basically I believe that using indentation for grouping is
1286extremely elegant and contributes a lot to the clarity of the average
1287Python program. Most people learn to love this feature after a while.
1288Some arguments for it:
1289
1290- Since there are no begin/end brackets there cannot be a disagreement
1291between grouping perceived by the parser and the human reader. I
1292remember long ago seeing a C fragment like this:
1293
1294 if (x <= y)
1295 x++;
1296 y--;
1297 z++;
1298
1299and staring a long time at it wondering why y was being decremented
1300even for x > y... (And I wasn't a C newbie then either.)
1301
1302- Since there are no begin/end brackets there can be no conflicting
1303coding styles. In C there are loads of different ways to place the
1304braces (including the choice whether to place braces around single
1305statements in certain cases, for consistency). If you're used to
1306reading (and writing) code that uses one style, you will feel at least
1307slightly uneasy when reading (or being required to write) another
1308style.
1309
1310- Many coding styles place begin/end brackets on a line by themself.
1311This makes programs considerably longer and wastes valuable screen
1312space, making it harder to get a good overview over a program.
1313Ideally, a function should fit on one basic tty screen (say, 20
1314lines). 20 lines of Python are worth a LOT more than 20 lines of C.
1315This is not solely due to the lack of begin/end brackets (the lack of
1316declarations also helps, and the powerful operations of course), but
1317it certainly helps!
1318
Guido van Rossum3de27361994-07-25 14:19:33 +000013196.5. Q. Why are Python strings immutable?
1320
1321A. There are two advantages. One is performance: knowing that a
1322string is immutable makes it easy to lay it out at construction time
1323-- fixed and unchanging storage requirements. (This is also one of
Guido van Rossum061f1821994-10-06 16:03:45 +00001324the reasons for the distinction between tuples and lists.) The
Guido van Rossum3de27361994-07-25 14:19:33 +00001325other is that strings in Python are considered as "elemental" as
1326numbers. No amount of activity will change the value 8 to anything
1327else, and in Python, no amount of activity will change the string
1328"eight" to anything else. (Adapted from Jim Roskind)
1329
13306.6. Q. Why don't strings have methods like index() or sort(), like
1331lists?
1332
1333A. Good question. Strings currently don't have methods at all
1334(likewise tuples and numbers). Long ago, it seemed unnecessary to
1335implement any of these functions in C, so a standard library module
1336"string" written in Python was created that performs string related
1337operations. Since then, the cry for performance has moved most of
1338them into the built-in module strop (this is imported by module
Guido van Rossumf8c76d01994-08-17 12:19:53 +00001339string, which is still the preferred interface, without loss of
Guido van Rossum3de27361994-07-25 14:19:33 +00001340performance except during initialization). Some of these functions
1341(e.g. index()) could easily be implemented as string methods instead,
1342but others (e.g. sort()) can't, since their interface prescribes that
1343they modify the object, while strings are immutable (see the previous
1344question).
1345
13466.7. Q. Why does Python use methods for some functionality
1347(e.g. list.index()) but functions for other (e.g. len(list))?
1348
1349A. Functions are used for those operations that are generic for a
1350group of types and which should work even for objects that don't have
1351methods at all (e.g. numbers, strings, tuples). Also, implementing
1352len(), max(), min() as a built-in function is actually less code than
1353implementing them as methods for each type. One can quibble about
1354individual cases but it's really too late to change such things
1355fundamentally now.
1356
13576.8. Q. Why can't I derive a class from built-in types (e.g. lists or
1358files)?
1359
1360A. This is caused by the relatively late addition of (user-defined)
1361classes to the language -- the implementation framework doesn't easily
1362allow it. See the answer to question 4.2 for a work-around. This
1363*may* be fixed in the (distant) future.
1364
13656.9. Q. Why must 'self' be declared and used explicitly in method
1366definitions and calls?
1367
1368A. By asking this question you reveal your C++ background. :-)
1369When I added classes, this was (again) the simplest way of
1370implementing methods without too many changes to the interpreter. I
1371borrowed the idea from Modula-3. It turns out to be very useful, for
1372a variety of reasons.
1373
1374First, it makes it more obvious that you are using a method or
1375instance attribute instead of a local variable. Reading "self.x" or
1376"self.meth()" makes it absolutely clear that an instance variable or
1377method is used even if you don't know the class definition by heart.
1378In C++, you can sort of tell by the lack of a local variable
Guido van Rossum061f1821994-10-06 16:03:45 +00001379declaration (assuming globals are rare or easily recognizable) -- but
Guido van Rossum3de27361994-07-25 14:19:33 +00001380in Python, there are no local variable declarations, so you'd have to
1381look up the class definition to be sure.
1382
1383Second, it means that no special syntax is necessary if you want to
1384explicitly reference or call the method from a particular class. In
1385C++, if you want to use a method from base class that is overridden in
1386a derived class, you have to use the :: operator -- in Python you can
1387write baseclass.methodname(self, <argument list>). This is
1388particularly useful for __init__() methods, and in general in cases
1389where a derived class method wants to extend the base class method of
1390the same name and thus has to call the base class method somehow.
1391
1392Lastly, for instance variables, it solves a syntactic problem with
1393assignment: since local variables in Python are (by definition!) those
1394variables to which a value assigned in a function body (and that
1395aren't explicitly declared global), there has to be some way to tell
1396the interpreter that an assignment was meant to assign to an instance
1397variable instead of to a local variable, and it should preferably be
1398syntactic (for efficiency reasons). C++ does this through
1399declarations, but Python doesn't have declarations and it would be a
1400pity having to introduce them just for this purpose. Using the
1401explicit "self.var" solves this nicely. Similarly, for using instance
1402variables, having to write "self.var" means that references to
1403unqualified names inside a method don't have to search the instance's
1404directories.
1405
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000014066.10. Q. Can't you emulate threads in the interpreter instead of
1407relying on an OS-specific thread implementation?
1408
1409A. Unfortunately, the interpreter pushes at least one C stack frame
1410for each Python stack frame. Also, extensions can call back into
1411Python at almost random moments. Therefore a complete threads
1412implementation requires thread support for C.
1413
Guido van Rossum061f1821994-10-06 16:03:45 +000014146.11. Q. Why can't lambda forms contain statements?
1415
1416A. Python lambda forms cannot contain statements because Python's
1417syntactic framework can't handle statements nested inside functions.
1418
1419However, in Python, this is not a serious problem. Unlike lambda
1420forms in other languages, where they add functionality, Python lambdas
1421are only a shorthand notation if you're too lazy to define a function.
1422
1423Functions are already first class objects in Python, and can be
1424declared in a local scope. Therefore the only advantage of using a
1425lambda form instead of a locally-defined function is that you'll have
1426to invent a name for the function -- but that's just a local variable
1427to which the function object (which is exactly the same type of object
1428that a lambda form yields) is assigned!
1429
14306.12. Q. Why is there no more efficient way of iterating over a dictionary
1431than first constructing the list of keys()?
1432
1433A. Have you tried it? I bet it's fast enough for your purposes! In
1434most cases such a list takes only a few percent of the space occupied
1435by the dictionary -- it needs only 4 bytes (the size of a pointer) per
1436key -- a dictionary costs 8 bytes per key plus between 30 and 70
1437percent hash table overhead, plus the space for the keys and values --
1438by necessity all keys are unique objects and a string object (the most
1439common key type) costs at least 18 bytes plus the length of the
1440string. Add to that the values contained in the dictionary, and you
1441see that 4 bytes more per item really isn't that much more memory...
1442
1443A call to dict.keys() makes one fast scan over the dictionary
1444(internally, the iteration function does exist) copying the pointers
1445to the key objects into a pre-allocated list object of the right size.
1446The iteration time isn't lost (since you'll have to iterate anyway --
1447unless in the majority of cases your loop terminates very prematurely
1448(which I doubt since you're getting the keys in random order).
1449
1450I don't expose the dictionary iteration operation to Python
1451programmers because the dictionary shouldn't be modified during the
1452entire iteration -- if it is, there's a very small chance that the
1453dictionary is reorganized because the hash table becomes too full, and
1454then the iteration may miss some items and see others twice. Exactly
1455because this only occurs rarely, it would lead to hidden bugs in
1456programs: it's easy never to have it happen during test runs if you
1457only insert or delete a few items per iteration -- but your users will
1458surely hit upon it sooner or later.
1459
Guido van Rossuma7925f11994-01-26 10:20:16 +00001460
14617. Using Python on non-UNIX platforms
1462=====================================
1463
Guido van Rossum91f60831994-02-15 15:52:27 +000014647.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001465
Guido van Rossum91f60831994-02-15 15:52:27 +00001466A. Yes. It is on most ftp sites carrying Python as python.sea.hqx --
1467this is a self-extracting archive containing the application binary as
1468well as the Lib modules.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001469
Guido van Rossum91f60831994-02-15 15:52:27 +000014707.2. Q. Is there a DOS version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001471
Guido van Rossum91f60831994-02-15 15:52:27 +00001472A. Yes. More than one, actually: 16python.exe runs in standard DOS
1473mode on 186 CPUs or higher; 32python.exe uses a DOS extender and only
1474runs on a 386 or higher CPUs. Although 16python.exe does not pass the
1475test set because test_grammar is too big for the parser, it actually
1476has about 270 kbyte of allocatable heap space, which is sufficient for
1477fairly large programs. 32python.exe is distributed as a tar file
1478containing the required DOS extended and 387 emulator. Both are on
1479most ftp sites carrying Python.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001480
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001481The file dosbuild.tar.gz on the standard ftp sites
1482(e.g. ftp.cwi.nl:/pub/python/) contains rudimentary Makefiles and
1483instructions.
1484
Guido van Rossum91f60831994-02-15 15:52:27 +000014857.3. Q. Is there a Windows version of Python?
1486
1487A. Yes. Use qwpython.exe. The only problem with it: ^C
1488unconditionally kills the entire program -- it does not raise
1489KeyboardInterrupt. You can also run 16python.exe or 32python.exe in a
1490"DOS box", but qwpython.exe appears to be slightly faster.
1491
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001492There aren't any Makefiles at this moment. Sorry.
1493
1494Using Win32s (a free NT compatibility package by Microsoft) you can
1495also use the NT version by Mark Hammond -- the Win32s package is also
1496in that directory (you'll need several MB of disk space to install
1497it). See the next question.
1498
Guido van Rossum91f60831994-02-15 15:52:27 +000014997.4. Q. Is there a Windows NT version of Python?
1500
1501A. Yes. Use ntpython.exe. This is for Intel CPUs. If you want a
1502Windows user interface, use qwpython.exe.
1503
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001504Mark Hammond <MHammond@cmutual.com.au> is building a better NT port.
1505This supports using DLLs for dynamic loading of Python modules, and
1506includes an interface to the Microsoft Foundation Classes and a Python
1507programming environment using it that's written mostly in Python. A
1508prerelease (source and binaries) can be ftp'ed from
1509ftp.cwi.nl:/pub/python/nt/ -- most mirrors will also have this. A
1510thread module is also planned but currently low on Mark's list of
1511priorities.
1512
Guido van Rossum061f1821994-10-06 16:03:45 +00001513To build Python for the Windows NT on the DEC Alpha AXP, retrieve a
1514zipfile with Makefiles for NT from the following URL:
1515"ftp://ftp.ksc.nasa.gov/pub.win3.private.proto/python-make.zip". This
1516was contributed by Sam Rushing <rushing@squirl.oau.org>.
1517
1518Note that currently there is no unified compilation environment for
1519all NT platforms -- hopefully Microsoft will fix this with the release
1520of Visual C++ 2.0.
1521
Guido van Rossum7ce61c11994-06-13 15:13:56 +000015227.5. Q. Is there an OS/2 version of Python?
1523
1524A. Yes. You can ftp it (from ftp.cwi.nl in pub/python, or from the
1525mirror sites) as pyth_os2.zip. This contains both an executable and
1526Makefiles for those fortunate enough to have a C compiler.
1527
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000015287.6. Q. Is there a VMS version of Python?
1529
1530A. I think not (yet). This question has been asked on the list
1531several times and I've never seen an answer. Maybe someone with a VMS
1532C compiler could attempt a port? Probably coming up with proper
1533Makefiles, config.h and config.c should be sufficient. If you succeed
1534(or even if you get stuck halfway), please let me know! (Info as of
153523 September 1994.)
1536
15377.7. Q. What about IBM mainframes, or other esoteric non-UNIX
1538platforms?
1539
1540A. Basically, the same story as for VMS... (Info as of 23 September
15411994.)
1542
1543For ports of Windows NT to non-Intel platforms, the normal NT port
1544should work except you may have to use a different Makefile.
1545(Unconfirmed suggestions from the Python list.)
1546
15477.8. Q. Where are the source or Makefiles for the non-UNIX versions?
1548
1549A. The standard sources can (almost) be used. See the previous
1550questions for availability of Makefiles/projects or patches. If you
1551find things in the standard sources that don't work on your particular
1552platform, please let me know and I'll integrate a solution into the
1553next release of the standard sources. If you submit a fix, please use
1554some kind of #ifdef so as to keep the source working for other
1555platforms. In particular, if the patch works around the availability
1556of a particular function of header file, you should mimic the
1557HAVE_... style used by the configure script -- you can then submit a
1558config.h file for a particular platform so there are no absolutely
1559platform-specific #ifdefs in the rest of the sources.
1560
15617.9. Q. What is the status and support for the non-UNIX versions?
1562
1563A. I don't have access to most of these platforms, so in general I am
1564dependent on material submitted by volunteers(*). However I strive to
1565integrate all changes needed to get it to compile on a particular
1566platform back into the standard sources, so porting of the next
1567version to the various non-UNIX platforms should be easy.
1568
1569(*) For the Macintosh, that volunteer is me.
1570
15717.10. Q. I have the PC version but it appears to be only a binary.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001572Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001573
1574A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +00001575"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossum3de27361994-07-25 14:19:33 +00001576you can get the file pythonlib<version>.tar.gz from most ftp sites
1577carrying Python; this is a subset of the distribution containing just
1578those file.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001579
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001580Once you have installed the library, you need to point sys.path to it.
1581Assuming the library is in C:\misc\python\lib, the following commands
1582will point your Python interpreter to it (note the doubled backslashes
1583-- you can also use single forward slashes instead):
1584
1585 >>> import sys
1586 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
1587 >>>
1588
1589For a more permanent effect, set the environment variable PYTHONPATH,
1590as follows (talking to a DOS prompt):
1591
1592 C> SET PYTHONPATH=C:\misc\python\lib
1593
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000015947.11. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001595
1596A. There isn't any. The documentation for the Unix version also
Guido van Rossum91f60831994-02-15 15:52:27 +00001597applies to the Mac and PC versions. Where applicable, differences
Guido van Rossuma7925f11994-01-26 10:20:16 +00001598are indicated in the text.
1599
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000016007.12. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +00001601creating or editing programs apart from entering it interactively, and
1602there seems to be no way to save code that was entered interactively.
1603How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001604
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001605A. Use an external editor. On the Mac, BBEdit seems to be a popular
1606no-frills text editor. I work like this: start the interpreter; edit
1607a module file using BBedit; import and test it in the interpreter;
1608edit again in BBedit; then use the built-in function reload() to
1609re-read the imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +00001610
1611Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
1612anyone with a pulse could certainly figure out how to do the same on
1613MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
1614Not only can you easily resave and "reload()" from Python after making
1615changes, but since WinNot auto-copies to the clipboard any text you
1616select, you can simply select the entire procedure (function) which
1617you changed in WinNot, switch to QWPython, and shift-ins to reenter
1618the changed program unit."