blob: 7a94fda9571f8ed8c2add665aa9b6c0e8b921657 [file] [log] [blame]
Guido van Rossuma7925f11994-01-26 10:20:16 +00001Subject: FAQ: Python -- an object-oriented language
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002Newsgroups: comp.lang.python,comp.answers,news.answers
3Followup-to: comp.lang.python
Guido van Rossum81300541996-09-06 16:37:56 +00004From: guido@cnri.reston.va.us (Guido van Rossum)
Guido van Rossum7be34a81995-05-31 15:17:12 +00005Reply-to: guido@cnri.reston.va.us (Guido van Rossum)
Guido van Rossumc458e941996-09-11 15:43:13 +00006Expires: Sun, 1 Dec 1996 00:00:00 GMT
7Supersedes: <DxJ3t1.CJv@cwi.nl>
Guido van Rossuma7925f11994-01-26 10:20:16 +00008Approved: news-answers-request@MIT.Edu
9
10Archive-name: python-faq/part1
Guido van Rossum81300541996-09-06 16:37:56 +000011Submitted-by: Guido van Rossum <guido@cnri.reston.va.us>
Guido van Rossumc458e941996-09-11 15:43:13 +000012Version: $Revision$
Guido van Rossum9c5dc291996-10-13 15:48:56 +000013Last-modified: $Date$
Guido van Rossuma7925f11994-01-26 10:20:16 +000014
15This article contains answers to Frequently Asked Questions about
16Python (an object-oriented interpreted programming language -- see
17the answer to question 1.1 for a short overview).
18
Guido van Rossumc458e941996-09-11 15:43:13 +000019Copyright 1993-1996 Guido van Rossum. Unchanged electronic
Guido van Rossuma7925f11994-01-26 10:20:16 +000020redistribution of this FAQ is allowed. Printed redistribution only
21with permission of the author. No warranties.
22
23Author's address:
Guido van Rossume7d92d51995-10-11 18:06:54 +000024 Guido van Rossum
25 C.N.R.I.
26 1895 Preston White Drive
Guido van Rossum81300541996-09-06 16:37:56 +000027 Reston, VA 20191
Guido van Rossume7d92d51995-10-11 18:06:54 +000028 U.S.A.
Guido van Rossum81300541996-09-06 16:37:56 +000029Email: <guido@python.org>, <guido@cnri.reston.va.us>
Guido van Rossuma7925f11994-01-26 10:20:16 +000030
31The latest version of this FAQ is available by anonymous ftp from
Guido van Rossumca318ec1996-06-26 19:50:09 +000032<URL:ftp://ftp.python.org/pub/python/doc/FAQ>. It will also be posted
Guido van Rossuma6c707c1995-01-02 17:32:28 +000033regularly to the newsgroups comp.answers <URL:news:comp.answers> and
34comp.lang.python <URL:news:comp.lang.python>.
Guido van Rossuma7925f11994-01-26 10:20:16 +000035
Guido van Rossuma6c707c1995-01-02 17:32:28 +000036Many FAQs, including this one, are available by anonymous ftp
37<URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/>. The name under
38which a FAQ is archived appears in the Archive-name line at the top of
39the article. This FAQ is archived as python-faq/part1
40<URL:ftp://rtfm.mit.edu/pub/usenet/news.answers/python-faq/part1>.
Guido van Rossuma7925f11994-01-26 10:20:16 +000041
42There's a mail server on that machine which will send you files from
43the archive by e-mail if you have no ftp access. You send a e-mail
Guido van Rossuma6c707c1995-01-02 17:32:28 +000044message to <mail-server@rtfm.mit.edu> containing the single word help
45in the message body to receive instructions.
Guido van Rossuma7925f11994-01-26 10:20:16 +000046
47This FAQ is divided in the following chapters:
48
49 1. General information and availability
50 2. Python in the real world
Guido van Rossumb0a2ce51995-08-28 19:41:35 +000051 3. Building Python and Other Known Bugs
Guido van Rossuma7925f11994-01-26 10:20:16 +000052 4. Programming in Python
53 5. Extending Python
54 6. Python's design
55 7. Using Python on non-UNIX platforms
56
57To find the start of a particular chapter, search for the chapter number
58followed by a dot and a space at the beginning of a line (e.g. to
59find chapter 4 in vi, type /^4\. /).
60
61Here's an overview of the questions per chapter:
62
63 1. General information and availability
64 1.1. Q. What is Python?
65 1.2. Q. Why is it called Python?
66 1.3. Q. How do I obtain a copy of the Python source?
67 1.4. Q. How do I get documentation on Python?
Guido van Rossumc50158e1994-05-31 09:18:50 +000068 1.5. Q. Are there other ftp sites that mirror the Python distribution?
69 1.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma6c707c1995-01-02 17:32:28 +000070 1.7. Q. Is there a WWW page devoted to Python?
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +000071 1.8. Q. Is the Python documentation available on the WWW?
72 1.9. Q. Is there a book on Python, or will there be one out soon?
73 1.10. Q. Are there any published articles about Python that I can quote?
74 1.11. Q. Are there short introductory papers or talks on Python?
75 1.12. Q. How does the Python version numbering scheme work?
76 1.13. Q. How do I get a beta test version of Python?
Guido van Rossum05151e01995-09-28 13:24:46 +000077 1.14. Q. Are there copyright restrictions on the use of Python?
78 1.15. Q. Why was Python created in the first place?
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 Rossum8727df41996-09-09 15:16:39 +000085 2.5. Q. What new developments are expected for Python in the future?
86 2.6. Q. Is it reasonable to propose incompatible changes to Python?
87 2.7. Q. What is the future of Python?
88 2.8. Q. What is the PSA, anyway?
89 2.9. Q. How do I join the PSA?
90 2.10. Q. What are the benefits of joining the PSA?
Guido van Rossuma7925f11994-01-26 10:20:16 +000091
Guido van Rossumb0a2ce51995-08-28 19:41:35 +000092 3. Building Python and Other Known Bugs
Guido van Rossum91f60831994-02-15 15:52:27 +000093 3.1. Q. Is there a test set?
94 3.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +000095 operations, but when playing with floating point operations I cannot
96 find anything wrong with them.
Guido van Rossum7be34a81995-05-31 15:17:12 +000097 3.3. Q. Link errors after rerunning the configure script.
98 3.4. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +000099 script (after the script name).
Guido van Rossum7be34a81995-05-31 15:17:12 +0000100 3.5. Q. When building on the SGI, make tries to run python to create
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000101 glmodule.c, but python hasn't been built or installed yet.
Guido van Rossum8727df41996-09-09 15:16:39 +0000102 3.6. Q. I use VPATH but some targets are built in the source directory.
103 3.7. Q. Trouble building or linking with the GNU readline library.
104 3.8. Q. Trouble with socket I/O on older Linux 1.x versions.
105 3.9. Q. Trouble with prototypes on Ultrix.
Guido van Rossum8a913021996-10-08 17:18:30 +0000106 3.10. Q. Other trouble building Python on platform X.
107 3.11. Q. How to configure dynamic loading on Linux.
Guido van Rossum9c5dc291996-10-13 15:48:56 +0000108 3.12. Q: I can't get shared modules to work on Linux 2.0 (Slackware96)?
Guido van Rossumcaa83c41996-11-13 15:06:24 +0000109 3.13. Q: Trouble when making modules shared on Linux.
110 3.14. Q. How to use threads on Linux.
111 3.15. Q. Errors when linking with a shared library containing C++ code.
112 3.16. Q. I built with tkintermodule.c enabled but get "Tkinter not found".
113 3.17. Q. I built with Tk 4.0 but Tkinter complains about the Tk version.
114 3.18. Q. Link errors for Tcl/Tk symbols when linking with Tcl/Tk.
115 3.19. Q. I configured and built Python for Tcl/Tk but "import Tkinter"
Guido van Rossum8727df41996-09-09 15:16:39 +0000116 fails.
Guido van Rossumcaa83c41996-11-13 15:06:24 +0000117 3.20. Q. Tk doesn't work right on DEC Alpha.
118 3.21. Q. Several common system calls are missing from the posix module.
119 3.22. Q. ImportError: No module named string, on MS Windows.
120 3.23. Q. Core dump on SGI when using the gl module.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000121
122 4. Programming in Python
Guido van Rossum24349991994-02-02 14:12:45 +0000123 4.1. Q. Is there a source code level debugger with breakpoints, step,
124 etc.?
125 4.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000126 C and others in Python (e.g. through inheritance)? (Also phrased as:
127 Can I use a built-in type as base class?)
Guido van Rossum24349991994-02-02 14:12:45 +0000128 4.3. Q. Is there a curses/termcap package for Python?
129 4.4. Q. Is there an equivalent to C's onexit() in Python?
130 4.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000131 nested function seemingly can't access the local variables of the
132 outer function. What is going on? How do I pass local data to a
133 nested function?
Guido van Rossum24349991994-02-02 14:12:45 +0000134 4.6. Q. How do I iterate over a sequence in reverse order?
135 4.7. Q. My program is too slow. How do I speed it up?
136 4.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +0000137 again (into the same Python process), the changes don't seem to take
138 place. What is going on?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000139 4.9. Q. How do I find the current module name?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000140 4.10. Q. I have a module in which I want to execute some extra code
141 when it is run as a script. How do I find out whether I am running as
142 a script?
143 4.11. Q. I try to run a program from the Demo directory but it fails
144 with ImportError: No module named ...; what gives?
Guido van Rossum061f1821994-10-06 16:03:45 +0000145 4.12. Q. I have successfully built Python with STDWIN but it can't
146 find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000147 4.13. Q. What GUI toolkits exist for Python?
Guido van Rossum061f1821994-10-06 16:03:45 +0000148 4.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000149 4.15. Q. Is it possible to write obfuscated one-liners in Python?
150 4.16. Q. Is there an equivalent of C's "?:" ternary operator?
151 4.17. Q. My class defines __del__ but it is not called when I delete the
152 object.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000153 4.18. Q. How do I change the shell environment for programs called
154 using os.popen() or os.system()? Changing os.environ doesn't work.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000155 4.19. Q. What is a class?
156 4.20. Q. What is a method?
157 4.21. Q. What is self?
158 4.22. Q. What is a unbound method?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000159 4.23. Q. How do I call a method defined in a base class from a derived
160 class that overrides it?
161 4.24. Q. How do I call a method from a base class without using the
162 name of the base class?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000163 4.25. Q. How can I organize my code to make it easier to change the base
164 class?
165 4.26. Q. How can I find the methods or attributes of an object?
Guido van Rossum061f1821994-10-06 16:03:45 +0000166 4.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
167 4.28. Q. How can I create a stand-alone binary from a Python script?
Guido van Rossum7be34a81995-05-31 15:17:12 +0000168 4.29. Q. What WWW tools are there for Python?
169 4.30. Q. How do I run a subprocess with pipes connected to both input
Guido van Rossum796b2591995-01-20 23:05:52 +0000170 and output?
Guido van Rossum7be34a81995-05-31 15:17:12 +0000171 4.31. Q. How do I call a function if I have the arguments in a tuple?
172 4.32. Q. How do I enable font-lock-mode for Python in Emacs?
173 4.33. Q. Is there an inverse to the format operator (a la C's scanf())?
Guido van Rossumca318ec1996-06-26 19:50:09 +0000174 4.34. Q. Can I have Tk events handled while waiting for I/O?
175 4.35. Q. How do I write a function with output parameters (call by reference)?
Guido van Rossum0d20cfa1996-07-30 18:53:05 +0000176 4.36. Q. Please explain the rules for local and global variables in Python.
177 4.37. Q. How can I have modules that mutually import each other?
Guido van Rossum8727df41996-09-09 15:16:39 +0000178 4.38. Q. How do I copy an object in Python?
179 4.39. Q. How to implement persistent objects in Python? (Persistent ==
180 automatically saved to and restored from disk.)
Guido van Rossuma4e41a81996-10-22 03:00:43 +0000181 4.40. Q. I try to use __spam and I get an error about _SomeClassName__spam.
Guido van Rossumc59120b1996-11-14 14:10:11 +0000182 4.41. Q. How do I delete a file? And other file questions.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000183
184 5. Extending Python
185 5.1. Q. Can I create my own functions in C?
186 5.2. Q. Can I create my own functions in C++?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000187 5.3. Q. How can I execute arbitrary Python statements from C?
188 5.4. Q. How can I evaluate an arbitrary Python expression from C?
189 5.5. Q. How do I extract C values from a Python object?
190 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
Guido van Rossum8727df41996-09-09 15:16:39 +0000191 5.7. Q. How do I call an object's method from C?
192 5.8. Q. How do I catch the output from print_error()?
193 5.9. Q. How do I access a module written in Python from C?
194 5.10. Q. How do I interface to C++ objects from Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000195
196 6. Python's design
Guido van Rossum8727df41996-09-09 15:16:39 +0000197 6.1. Q. Why isn't there a switch or case statement in Python?
198 6.2. Q. Why does Python use indentation for grouping of statements?
199 6.3. Q. Why are Python strings immutable?
200 6.4. Q. Why don't strings have methods like index() or sort(), like
Guido van Rossum3de27361994-07-25 14:19:33 +0000201 lists?
Guido van Rossum8727df41996-09-09 15:16:39 +0000202 6.5. Q. Why does Python use methods for some functionality
Guido van Rossum3de27361994-07-25 14:19:33 +0000203 (e.g. list.index()) but functions for other (e.g. len(list))?
Guido van Rossum8727df41996-09-09 15:16:39 +0000204 6.6. Q. Why can't I derive a class from built-in types (e.g. lists or
Guido van Rossum3de27361994-07-25 14:19:33 +0000205 files)?
Guido van Rossum8727df41996-09-09 15:16:39 +0000206 6.7. Q. Why must 'self' be declared and used explicitly in method
Guido van Rossum3de27361994-07-25 14:19:33 +0000207 definitions and calls?
Guido van Rossum8727df41996-09-09 15:16:39 +0000208 6.8. Q. Can't you emulate threads in the interpreter instead of
209 relying on an OS-specific thread implementation?
210 6.9. Q. Why can't lambda forms contain statements?
211 6.10. Q. Why don't lambdas have access to variables defined in the
212 containing scope?
213 6.11. Q. Why can't recursive functions be defined inside other functions?
Guido van Rossum061f1821994-10-06 16:03:45 +0000214 6.12. Q. Why is there no more efficient way of iterating over a dictionary
215 than first constructing the list of keys()?
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000216 6.13. Q. Can Python be compiled to machine code, C or some other language?
Guido van Rossum05151e01995-09-28 13:24:46 +0000217 6.14. Q. Why doesn't Python use proper garbage collection?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000218
219 7. Using Python on non-UNIX platforms
Guido van Rossum91f60831994-02-15 15:52:27 +0000220 7.1. Q. Is there a Mac version of Python?
Guido van Rossumc458e941996-09-11 15:43:13 +0000221 7.2. Q. Are there DOS and Windows versions of Python?
222 7.3. Q. Is there an OS/2 version of Python?
223 7.4. Q. Is there a VMS version of Python?
224 7.5. Q. What about IBM mainframes, or other non-UNIX platforms?
225 7.6. Q. Where are the source or Makefiles for the non-UNIX versions?
226 7.7. Q. What is the status and support for the non-UNIX versions?
227 7.8. Q. I have a PC version but it appears to be only a binary.
228 Where's the library?
229 7.9. Q. Where's the documentation for the Mac or PC version?
230 7.10. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000231 creating or editing programs apart from entering it interactively, and
232 there seems to be no way to save code that was entered interactively.
233 How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000234
235To find a particular question, search for the question number followed
236by a dot, a space, and a Q at the beginning of a line (e.g. to find
237question 4.2 in vi, type /^4\.2\. Q/).
238
239
2401. General information and availability
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000241 =======================================
Guido van Rossuma7925f11994-01-26 10:20:16 +0000242
2431.1. Q. What is Python?
244
245A. Python is an interpreted, interactive, object-oriented programming
246language. It incorporates modules, exceptions, dynamic typing, very
247high level dynamic data types, and classes. Python combines
248remarkable power with very clear syntax. It has interfaces to many
249system calls and libraries, as well as to various window systems, and
250is extensible in C or C++. It is also usable as an extension language
251for applications that need a programmable interface. Finally, Python
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000252is portable: it runs on many brands of UNIX, on the Mac, and on PCs
253under MS-DOS, Windows, Windows NT, and OS/2.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000254
255To find out more, the best thing to do is to start reading the
256tutorial from the documentation set (see a few questions further
257down).
258
2591.2. Q. Why is it called Python?
260
Guido van Rossum796b2591995-01-20 23:05:52 +0000261A. Apart from being a computer scientist, I'm also a fan of "Monty
Guido van Rossuma7925f11994-01-26 10:20:16 +0000262Python's Flying Circus" (a BBC comedy series from the seventies, in
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000263the -- unlikely -- case you didn't know). It occurred to me one day
264that I needed a name that was short, unique, and slightly mysterious.
265And I happened to be reading some scripts from the series at the
266time... So then I decided to call my language Python. But Python is
267not a joke. And don't you associate it with dangerous reptiles
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000268either! (If you need an icon, use an image of the 16-ton weight from
269the TV series or of a can of SPAM :-)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000270
2711.3. Q. How do I obtain a copy of the Python source?
272
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000273A. The latest complete Python source distribution is always available
274by anonymous ftp, e.g.
Guido van Rossum8727df41996-09-09 15:16:39 +0000275<URL:ftp://ftp.python.org/pub/python/src/python1.3.tar.gz>. It is a
Guido van Rossume530c581995-04-10 12:32:16 +0000276gzipped tar file containing the complete C source, LaTeX
277documentation, Python library modules, example programs, and several
278useful pieces of freely distributable software. This will compile and
279run out of the box on most UNIX platforms. (See section 7 for
280non-UNIX information.)
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000281
Guido van Rossum8727df41996-09-09 15:16:39 +0000282Sometimes beta versions of a newer release are available; check the
283subdirectory "beta" of the above-mentioned URL (i.e.
284<URL:ftp://ftp.python.org/pub/python/src/beta/>). (At the time of
285writing, beta3 for Python 1.4 is available there, and should be
286checked before reporting problems with version 1.3.)
287
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000288Occasionally a set of patches is issued which has to be applied using
289the patch program. These patches are placed in the same directory,
Guido van Rossum7be34a81995-05-31 15:17:12 +0000290e.g. <URL:ftp://ftp.python.org/pub/python/src/patch1.1.1>. (At the time
Guido van Rossum8727df41996-09-09 15:16:39 +0000291of writing, no patches exist.)
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000292
293An index of said ftp directory can be found in the file INDEX. An
294HTML version of the index can be found in the file index.html,
Guido van Rossum7be34a81995-05-31 15:17:12 +0000295<URL:ftp://ftp.python.org/pub/python/index.html>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000296
2971.4. Q. How do I get documentation on Python?
298
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000299A. The LaTeX source for the documentation is part of the source
300distribution. If you don't have LaTeX, the latest Python
301documentation set is always available by anonymous ftp, e.g.
Guido van Rossum7be34a81995-05-31 15:17:12 +0000302<URL:ftp://ftp.python.org/pub/python/doc/postscript.tar.gz>. It is a
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000303gzipped tar file containing PostScript files of the reference manual,
Guido van Rossum3de27361994-07-25 14:19:33 +0000304the library manual, and the tutorial. Note that the library manual is
305the most important one of the set, as much of Python's power stems
306from the standard or built-in types, functions and modules, all of
307which are described here. PostScript for a high-level description of
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000308Python is in the file nluug-paper.ps (a separate file on the ftp
309site).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000310
Guido van Rossumc50158e1994-05-31 09:18:50 +00003111.5. Q. Are there other ftp sites that mirror the Python distribution?
312
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000313A. The following anonymous ftp sites keep mirrors of the Python
314distribution:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000315
Guido van Rossume7d92d51995-10-11 18:06:54 +0000316USA:
317
318 <URL:ftp://ftp.python.org/pub/python/>
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000319 <URL:ftp://gatekeeper.dec.com/pub/plan/python/>
Guido van Rossume7d92d51995-10-11 18:06:54 +0000320 <URL:ftp://ftp.uu.net/languages/python/>
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000321 <URL:ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/>
Guido van Rossume7d92d51995-10-11 18:06:54 +0000322 <URL:ftp://ftp.sterling.com/programming/languages/python/>
323 <URL:ftp://uiarchive.cso.uiuc.edu/pub/lang/python/>
324 <URL:ftp://ftp.pht.com/mirrors/python/python/>
Guido van Rossum7b6f3431997-02-25 23:08:03 +0000325 <URL:ftp://ftp.cdrom.com/pub/python/>
Guido van Rossume7d92d51995-10-11 18:06:54 +0000326
327Europe:
328
329 <URL:ftp://ftp.cwi.nl/pub/python/>
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000330 <URL:ftp://ftp.funet.fi/pub/languages/python/>
331 <URL:ftp://ftp.sunet.se/pub/lang/python/>
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000332 <URL:ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/>
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000333 <URL:ftp://ftp.ibp.fr/pub/python/>
Guido van Rossum79413791996-12-05 22:01:11 +0000334 <URL:ftp://sunsite.cnlab-switch.ch/mirror/python/>
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000335 <URL:ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000336
Guido van Rossume7d92d51995-10-11 18:06:54 +0000337Australia:
338
339 <URL:ftp://ftp.dstc.edu.au/pub/python/>
340
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000341Or try archie on the string "python".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000342
Guido van Rossumc50158e1994-05-31 09:18:50 +00003431.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000344
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000345A. There is a newsgroup, comp.lang.python <URL:news:comp.lang.python>,
346and a mailing list. The newsgroup and mailing list are gatewayed into
347each other -- if you can read news it's unnecessary to subscribe to
348the mailing list. Send e-mail to <python-list-request@cwi.nl> to
Guido van Rossume530c581995-04-10 12:32:16 +0000349(un)subscribe to the mailing list. Hypermail archives of (nearly)
350everything posted to the mailing list (and thus the newsgroup) are
351available on our WWW server,
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000352<URL:http://www.cwi.nl/~guido/hypermail/index.html>. The raw archives
353are also available by ftp, e.g.
Guido van Rossum7be34a81995-05-31 15:17:12 +0000354<URL:ftp://ftp.python.org/pub/python/mail/mailinglist.gz>. The
Guido van Rossume530c581995-04-10 12:32:16 +0000355uncompressed versions of these files can be read with the standard
356UNIX Mail program ("Mail -f file") or with nn ("nn file"). To read
Guido van Rossumbf8e7d51995-08-28 03:09:13 +0000357them using MH, you could use "inc -file file". (The archival service
358has stopped archiving new articles around the end of April 1995. I
359hope to revive it on the PSA server www.python.org sometime in the
360future.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000361
Guido van Rossuma6c707c1995-01-02 17:32:28 +00003621.7. Q. Is there a WWW page devoted to Python?
363
Guido van Rossum7be34a81995-05-31 15:17:12 +0000364A. Yes, <URL:http://www.python.org/> is the official Python home page.
365At the time of writing, this page is not yet completely operational;
366you may have a look at the old Python home page:
367<URL:http://www.cwi.nl/~guido/Python.html> or at the U.S. copy:
368<URL:http://www.python.org/~guido/Python.html>.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000369
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003701.8. Q. Is the Python documentation available on the WWW?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000371
Guido van Rossum7be34a81995-05-31 15:17:12 +0000372A. Yes, see <URL:http://www.python.org/> (Python's home page). It
373contains pointers to hypertext versions of the whole documentation set
374(as hypertext, not just PostScript).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000375
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000376If you wish to browse this collection of HTML files on your own
377machine, it is available bundled up by anonymous ftp,
Guido van Rossum7be34a81995-05-31 15:17:12 +0000378e.g. <URL:ftp://ftp.python.org/pub/python/doc/html.tar.gz>.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000379
380An Emacs-INFO set containing the library manual is also available by
Guido van Rossum7be34a81995-05-31 15:17:12 +0000381ftp, e.g. <URL:ftp://ftp.python.org/pub/python/doc/lib-info.tar.gz>.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000382
3831.9. Q. Is there a book on Python, or will there be one out soon?
384
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000385A. Mark Lutz is writing a Python book for O'Reilly and Associates, to
386be published early 1996. See the outline (in PostScript):
387<URL:http://www.python.org/workshops/1995-05/outlinep.eps>.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000388
3891.10. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000390
391A. So far the only refereed and published article that describes
392Python in some detail is:
393
394 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
395 Servers Using the Python Programming Language", CWI Quarterly, Volume
396 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
397
398LaTeX source for this paper is available as part of the Python source
399distribution.
400
Guido van Rossum05151e01995-09-28 13:24:46 +0000401See also the next section (supposedly Aaron Watters' paper has been
402refereed).
403
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00004041.11. Q. Are there short introductory papers or talks on Python?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000405
Guido van Rossum05151e01995-09-28 13:24:46 +0000406A. A recent, very entertaining introduction to Python is the tutorial by
407Aaron Watters in UnixWorld Online:
408
409 Aaron R. Watters: "The What, Why, Who, and Where of Python",
410 <URL:http://www.wcmh.com/uworld/archives/95/tutorial/005.html>
411
412An olded paper is:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000413
414 Guido van Rossum, "An Introduction to Python for UNIX/C
415 Programmers", in the proceedings of the NLUUG najaarsconferentie
Guido van Rossum061f1821994-10-06 16:03:45 +0000416 1993 (dutch UNIX users group meeting November 1993).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000417
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000418PostScript for this paper and for the slides used for the accompanying
419presentation is available by ftp as
Guido van Rossum7be34a81995-05-31 15:17:12 +0000420<URL:ftp://ftp.python.org/pub/python/doc/nluug-paper.ps> and
421<URL:ftp://ftp.python.org/pub/python/doc/nluug-slides.ps>, respectively.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000422
423Slides for a talk on Python that I gave at the Usenix Symposium on
Guido van Rossum05151e01995-09-28 13:24:46 +0000424Very High Level Languages in Santa Fe, NM, USA in October 1994 are
Guido van Rossum7be34a81995-05-31 15:17:12 +0000425available as <URL:ftp://ftp.python.org/pub/python/doc/vhll-slides.ps>.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000426
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00004271.12. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000428
Guido van Rossum05151e01995-09-28 13:24:46 +0000429A. Python versions are numbered A.B.C or A.B. A is the major version
430number -- it is only incremented for major changes in functionality or
431source structure. B is the minor version number, incremented for less
Guido van Rossum95f61a71994-01-26 17:23:37 +0000432earth-shattering changes to a release. C is the patchlevel -- it is
Guido van Rossum05151e01995-09-28 13:24:46 +0000433incremented for each new patch release. Not all releases have patch
434releases. Note that in the past, patches have added significant
435changes; in fact the changeover from 0.9.9 to 1.0.0 was the first time
436that either A or B changed!
Guido van Rossum95f61a71994-01-26 17:23:37 +0000437
Guido van Rossum8727df41996-09-09 15:16:39 +0000438Beta versions have an additional suffix of "betaN" for some small
439number N. Note that (for instance) all versions labeled 1.4betaN
440*precede* the actual release of 1.4. 1.4b3 is short for 1.4beta3.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000441
4421.13. Q. How do I get a beta test version of Python?
443
Guido van Rossum05151e01995-09-28 13:24:46 +0000444A. If there are any beta releases, they are published in the normal
445source directory (e.g. <URL:ftp://ftp.python.org/pub/python/src/>).
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000446
Guido van Rossum05151e01995-09-28 13:24:46 +00004471.14. Q. Are there copyright restrictions on the use of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000448
449A. Hardly. You can do anything you want with the source, as long as
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000450you leave the copyrights in, and display those copyrights in any
451documentation about Python that you produce. Also, don't use the
452author's institute's name in publicity without prior written
453permission, and don't hold them responsible for anything (read the
454actual copyright for a precise legal wording).
455
456In particular, if you honor the copyright rules, it's OK to use Python
457for commercial use, to sell copies of Python in source or binary form,
458or to sell products that enhance Python or incorporate Python (or part
459of it) in some form. I would still like to know about all commercial
460use of Python!
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000461
Guido van Rossum05151e01995-09-28 13:24:46 +00004621.15. Q. Why was Python created in the first place?
Guido van Rossum7be34a81995-05-31 15:17:12 +0000463
464A. Here's a *very* brief summary of what got me started:
465
466- I had extensive experience with implementing an interpreted language
467in the ABC group at CWI, and from working with this group I had
468learned a lot about language design. This is the origin of many
469Python features, including the use of indentation for statement
470grouping and the inclusion of very-high-level data types (although the
471details are all different in Python).
472
473- I had a number of gripes about the ABC language, but also liked many
474of its features. It was impossible to extend the ABC language (or its
475implementation) to remedy my complaints -- in fact its lack of
476extensibility was one of its biggest problems.
477
478- I had some experience with using Modula-2+ and talked with the
479designers of Modula-3 (and read the M3 report). M3 is the origin of
480the syntax and semantics used for exceptions, and some other Python
481features.
482
483- I was working in the Amoeba distributed operating system group at
484CWI. We needed a better way to do system administration than by
485writing either C programs or Bourne shell scripts, since Amoeba had
486its own system call interface which wasn't easily accessible from the
Guido van Rossumbf8e7d51995-08-28 03:09:13 +0000487Bourne shell. My experience with error handling in Amoeba made me
488acutely aware of the importance of exceptions as a programming
489language feature.
Guido van Rossum7be34a81995-05-31 15:17:12 +0000490
491- It occurred to me that a scripting language with a syntax like ABC
492but with access to the Amoeba system calls would fill the need. I
493realized that it would be foolish to write an Amoeba-specific
494language, so I decided that I needed a language that was generally
495extensible.
496
497- During the 1989 Christmas holidays, I had a lot of time on my hand,
498so I decided to give it a try. During the next year, while still
499mostly working on it in my own time, Python was used in the Amoeba
500project with increasing success, and the feedback from colleagues made
501me add many early improvements.
502
503- In February 1991, after just over a year of development, I decided
504to post to USENET. The rest is in the Misc/HISTORY file.
505
Guido van Rossuma7925f11994-01-26 10:20:16 +0000506
5072. Python in the real world
508===========================
509
5102.1. Q. How many people are using Python?
511
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000512A. I don't know, but the maximum number of simultaneous subscriptions
513to the Python mailing list before it was gatewayed into the newsgroup
514was about 180 (several of which were local redistribution lists). I
515believe that many active Python users don't bother to subscribe to the
516list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000517is even less meaningful. I see new names on the newsgroup all the
518time and my best guess is that there are currently at least several
519thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000520
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000521Another statistic is the number of accesses to the Python WWW server.
522Have a look at <URL:http://www.python.org/stats/>.
523
Guido van Rossuma7925f11994-01-26 10:20:16 +00005242.2. Q. Have any significant projects been done in Python?
525
526A. Here at CWI (the home of Python), we have written a 20,000 line
527authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00005285,000 line multimedia teleconferencing tool, as well as many many
529smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000530
531The University of Virginia uses Python to control a virtual reality
532engine. Contact: Matt Conway <conway@virginia.edu>.
533
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000534The ILU project at Xerox PARC can generate Python glue for ILU
535interfaces. See <URL:ftp://ftp.parc.xerox.com/pub/ilu/ilu.html>.
536
Guido van Rossumac3f2121995-04-10 11:53:42 +0000537The University of California, Irvine uses a student administration
538system called TELE-Vision written entirely in Python. Contact: Ray
539Price <rlprice@uci.edu>.
540
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000541See also the next question.
542
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000543If you have done a significant project in Python that you'd like to be
544included in the list above, send me email!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000545
5462.3. Q. Are there any commercial projects going on using Python?
547
Guido van Rossum17e973c1997-02-26 16:11:55 +0000548A. Yes, there's lots of commercial activity using Python. See
549<URL:http://www.python.org/python/Users.html> for a list.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000550
Guido van Rossum95f61a71994-01-26 17:23:37 +00005512.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000552
Guido van Rossum3de27361994-07-25 14:19:33 +0000553A. Very stable. While the current version number would suggest it is
554in the early stages of development, in fact new, stable releases
Guido van Rossumba469ba1996-12-05 22:26:17 +0000555(numbered 0.9.x through 1.4) have been coming out roughly every 3 to
5566 or 12 months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000557
Guido van Rossum8727df41996-09-09 15:16:39 +00005582.5. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000559
Guido van Rossumba469ba1996-12-05 22:26:17 +0000560A. Follow the newsgroup discussions! The workshop proceedings
561(<URL:http://www.python.org/workshops/>) may also contain interesting
562looks into the future.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000563
Guido van Rossum8727df41996-09-09 15:16:39 +00005642.6. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossum3de27361994-07-25 14:19:33 +0000565
566A. In general, no. There are already millions of lines of Python code
567around the world, so any changes in the language that invalidates more
568than a very small fraction of existing programs has to be frowned
569upon. Even if you can provide a conversion program, there still is
570the problem of updating all documentation. Providing a gradual
571upgrade path is the only way if a feature has to be changed.
572
Guido van Rossum8727df41996-09-09 15:16:39 +00005732.7. Q. What is the future of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000574
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000575A. If I knew, I'd be rich :-)
576
577Seriously, the formation of the PSA (Pyton Software Activity, see
578<URL:http://www.python.org/psa/>) ensures some kind of support even in
579the (unlikely! event that I'd be hit by a bus (actually, here in the
580US, a car accident would be more likely :-), were to join a nunnery,
581or would be head-hunted. A large number of Python users have become
582experts at Python programming as well as maintenance of the
583implementation, and would easily fill the vacuum created by my
584disappearance.
585
586In the mean time, I have no plans to disappear -- rather, I am
587committed to improving Python, and my current benefactor, CNRI (see
588<URL:http://www.cnri.reston.va.us>) is just as committed to continue
589its support of Python and the PSA. In fact, we have great plans for
590Python -- we just can't tell yet!
591
Guido van Rossum8727df41996-09-09 15:16:39 +00005922.8. Q. What is the PSA, anyway?
Guido van Rossum05151e01995-09-28 13:24:46 +0000593
594A. The Python Software Activity <URL:http://www.python.org/psa/> was
595created by a number of Python aficionados who want Python to be more
596than the product and responsibility of a single individual. It has
597found a home at CNRI <URL:http://www.cnri.reston.va.us>. Anybody who
598wishes Python well should join the PSA.
599
Guido van Rossum8727df41996-09-09 15:16:39 +00006002.9. Q. How do I join the PSA?
Guido van Rossum05151e01995-09-28 13:24:46 +0000601
602A. The full scoop is available on the web, see
603<URL:http://www.python.org/psa/Joining.html>. Summary: send a check
604of at least $50 to CNRI/PSA, 1895 Preston White Drive, Suite 100, in
Guido van Rossum81300541996-09-06 16:37:56 +0000605Reston, VA 20191. Full-time students pay $25. Companies can join for
Guido van Rossum05151e01995-09-28 13:24:46 +0000606a mere $500.
607
Guido van Rossum8727df41996-09-09 15:16:39 +00006082.10. Q. What are the benefits of joining the PSA?
Guido van Rossum05151e01995-09-28 13:24:46 +0000609
610A. Like National Public Radio, if not enough people join, Python will
611wither. Your name will be mentioned on the PSA's web server.
612Workshops organized by the PSA <URL:http://www.python.org/workshops/>
613are only accessible to PSA members (you can join at the door). The
614PSA is working on additional benefits, such as reduced prices for
615books and software, and early access to beta versions of Python.
616
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000617
6183. Building Python and Other Known Bugs
619=======================================
Guido van Rossuma7925f11994-01-26 10:20:16 +0000620
Guido van Rossum91f60831994-02-15 15:52:27 +00006213.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000622
623A. Yes, simply do "import testall" (or "import autotest" if you aren't
624interested in the output). The standard modules whose name begins
625with "test" together comprise the test. The test set doesn't test
626*all* features of Python but it goes a long way to confirm that a new
627port is actually working. The Makefile contains an entry "make test"
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000628which runs the autotest module. NOTE: if "make test" fails, run the
629tests manually ("import testall") to see what goes wrong before
630reporting the error.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000631
Guido van Rossum91f60831994-02-15 15:52:27 +00006323.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000633operations, but when playing with floating point operations I cannot
634find anything wrong with them.
635
636A. The test set makes occasional unwarranted assumptions about the
637semantics of C floating point operations. Until someone donates a
638better floating point test set, you will have to comment out the
639offending floating point tests and execute similar tests manually.
640
Guido van Rossum7be34a81995-05-31 15:17:12 +00006413.3. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000642
643A. It is generally necessary to run "make clean" after a configuration
644change.
645
Guido van Rossum7be34a81995-05-31 15:17:12 +00006463.4. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000647script (after the script name).
648
649A. You are probably linking with GNU getopt, e.g. through -liberty.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000650Don't. The reason for the complaint is that GNU getopt, unlike System
651V getopt and other getopt implementations, doesn't consider a
652non-option to be the end of the option list. A quick (and compatible)
653fix for scripts is to add "--" to the interpreter, like this:
654
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000655 #! /usr/local/bin/python --
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000656
657You can also use this interactively:
658
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000659 python -- script.py [options]
660
661Note that a working getopt implementation is provided in the Python
662distribution (in Python/getopt.c) but not automatically used.
Guido van Rossum24349991994-02-02 14:12:45 +0000663
Guido van Rossum7be34a81995-05-31 15:17:12 +00006643.5. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000665glmodule.c, but python hasn't been built or installed yet.
666
667A. Comment out the line mentioning glmodule.c in Setup and build a
668python without gl first; install it or make sure it is in your $PATH,
669then edit the Setup file again to turn on the gl module, and make
670again. You don't need to do "make clean"; you do need to run "make
671Makefile" in the Modules subdirectory (or just run "make" at the
672toplevel).
673
Guido van Rossum8727df41996-09-09 15:16:39 +00006743.6. Q. I use VPATH but some targets are built in the source directory.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000675
676A. On some systems (e.g. Sun), if the target already exists in the
677source directory, it is created there instead of in the build
678directory. This is usually because you have previously built without
679VPATH. Try running "make clobber" in the source directory.
680
Guido van Rossum8727df41996-09-09 15:16:39 +00006813.7. Q. Trouble building or linking with the GNU readline library.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000682
Guido van Rossumac3f2121995-04-10 11:53:42 +0000683A. Consider using readline 2.0. Some hints:
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000684
685- You can use the GNU readline library to improve the interactive user
686interface: this gives you line editing and command history when
Guido van Rossum796b2591995-01-20 23:05:52 +0000687calling python interactively. You need to configure and build the GNU
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000688readline library before running the configure script. Its sources are
689no longer distributed with Python; you can ftp them from any GNU
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000690mirror site, or from its home site
691<URL:ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz> (or a
692higher version number -- using version 1.x is not recommended). Pass
693the Python configure script the option --with-readline=DIRECTORY where
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000694DIRECTORY is the absolute pathname of the directory where you've built
695the readline library. Some hints on building and using the readline
696library:
697
698- On SGI IRIX 5, you may have to add the following
699to rldefs.h:
700
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000701 #ifndef sigmask
702 #define sigmask(sig) (1L << ((sig)-1))
703 #endif
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000704
705- On most systems, you will have to add #include "rldefs.h" to the
706top of several source files, and if you use the VPATH feature, you
707will have to add dependencies of the form foo.o: foo.c to the
708Makefile for several values of foo.
709
710- The readline library requires use of the termcap library. A
711known problem with this is that it contains entry points which
Guido van Rossum061f1821994-10-06 16:03:45 +0000712cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000713conflict can be solved (and will be, in the next release of
Guido van Rossum061f1821994-10-06 16:03:45 +0000714STDWIN) by adding a line saying '#define werase w_erase' to the
715stdwin.h file (in the STDWIN distribution, subdirectory H). The
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000716GL conflict has been solved in the Python configure script by a
717hack that forces use of the static version of the termcap library.
718
Guido van Rossumac3f2121995-04-10 11:53:42 +0000719- Check the newsgroup gnu.bash.bug <URL:news:gnu.bash.bug> for
720specific problems with the readline library (I don't read this group
721but I've been told that it is the place for readline bugs).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000722
Guido van Rossum8727df41996-09-09 15:16:39 +00007233.8. Q. Trouble with socket I/O on older Linux 1.x versions.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000724
725A. Once you've built Python, use it to run the regen.py script in the
726Lib/linux1 directory. Apparently the files as distributed don't match
727the system headers on some Linux versions.
728
Guido van Rossum8727df41996-09-09 15:16:39 +00007293.9. Q. Trouble with prototypes on Ultrix.
Guido van Rossum72eb83c1994-10-07 11:33:28 +0000730
731A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef
732HAVE_PROTOTYPES.
733
Guido van Rossum8a913021996-10-08 17:18:30 +00007343.10. Q. Other trouble building Python on platform X.
Guido van Rossum95f61a71994-01-26 17:23:37 +0000735
Guido van Rossum81300541996-09-06 16:37:56 +0000736A. Please email the details to <guido@cnri.reston.va.us> and I'll look
737into it. Please provide as many details as possible. In particular,
738if you don't tell me what type of computer and what operating system
739(and version) you are using it will be difficult for me to figure out
740what is the matter. If you get a specific error message, please email
741it to me too.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000742
Guido van Rossum8a913021996-10-08 17:18:30 +00007433.11. Q. How to configure dynamic loading on Linux.
Guido van Rossum07779351995-02-07 16:59:56 +0000744
Guido van Rossum8727df41996-09-09 15:16:39 +0000745A. This is now automatic as long as your Linux version uses the ELF
746object format (all recent Linuxes do).
Guido van Rossum07779351995-02-07 16:59:56 +0000747
Guido van Rossum9c5dc291996-10-13 15:48:56 +00007483.12. Q: I can't get shared modules to work on Linux 2.0 (Slackware96)?
749
750A: This is a bug in the Slackware96 release. The fix is simple:
751
752Make sure that there is a link from /lib/libdl.so to /lib/libdl.so.1
753so that the following links are setup:
754
755 /lib/libdl.so -> /lib/libdl.so.1
756 /lib/libdl.so.1 -> /lib/libdl.so.1.7.14
757
Guido van Rossum8651d271997-02-17 18:27:32 +0000758You may have to rerun the configure script, after rm'ing the
759config.cache file, before you attempt to rebuild python after this
760fix.
761
Guido van Rossumcaa83c41996-11-13 15:06:24 +00007623.13. Q: Trouble when making modules shared on Linux.
763
764A. This happens when you have built Python for static linking and then
765enable *shared* in the Setup file. Shared library code must be
766compiled with "-fpic". If a .o file for the module already exist that
767was compiled for static linking, you must remove it or do "make clean"
768in the Modules directory.
769
7703.14. Q. How to use threads on Linux.
Guido van Rossum9e0e4dd1996-10-23 20:52:55 +0000771
772A. [Greg Stein] I built myself a libpthreads.so from the libc.5.3.12
773distribution (the binary distribution doesn't have pthreads in
774it). Then, I configured Python with --with-threads and then tweaked
775config.h to include a #define _MIT_POSIX_THREADS (or something like
776that, see /usr/include/pthreads.h). It worked fine at that point.
777
778Note that I couldn't get threading to "operate well" with any of the
779other thread packages. Prior libc versions didn't integrate well with
780threads, either, so I couldn't use them (e.g. sleep() blocked all
781threads :-( ).
782
Guido van Rossumcaa83c41996-11-13 15:06:24 +00007833.15. Q. Errors when linking with a shared library containing C++ code.
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000784
785A. Link the main Python binary with C++. Change the definition of
786LINKCC in Modules/Makefile to be your C++ compiler. You may have to
787edit config.c slightly to make it compilable with C++.
Guido van Rossum07779351995-02-07 16:59:56 +0000788
Guido van Rossumcaa83c41996-11-13 15:06:24 +00007893.16. Q. I built with tkintermodule.c enabled but get "Tkinter not found".
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000790
791A. Tkinter.py (note: upper case T) lives in a subdirectory of Lib,
792Lib/tkinter. If you are using the default module search path, you
793probably didn't enable the line in the Modules/Setup file defining
794TKPATH; if you use the environment variable PYTHONPATH, you'll have to
795add the proper tkinter subdirectory.
796
Guido van Rossumcaa83c41996-11-13 15:06:24 +00007973.17. Q. I built with Tk 4.0 but Tkinter complains about the Tk version.
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000798
799A. Several things could cause this. You most likely have a Tk 3.6
800installation that wasn't completely eradicated by the Tk 4.0
801installation (which tends to add "4.0" to its installed files). You
802may have the Tk 3.6 support library installed in the place where the
803Tk 4.0 support files should be (default /usr/local/lib/tk/); you may
804have compiled Python with the old tk.h header file (yes, this actually
805compiles!); you may actually have linked with Tk 3.6 even though Tk
8064.0 is also around. Similar for Tcl 7.4 vs. Tcl 7.3.
807
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008083.18. Q. Link errors for Tcl/Tk symbols when linking with Tcl/Tk.
Guido van Rossum8727df41996-09-09 15:16:39 +0000809
810Quite possibly, there's a version mismatch between the Tcl/Tk header
811files (tcl.h and tk.h) and the tck/tk libraries you are using (the
812"-ltk4.0" and "-ltcl7.4" arguments for _tkinter in the Setup file).
813If you have installed both versions 7.4/4.0 and 7.5/4.1 of Tcl/Tk,
814most likely your header files are for The newer versions, but the
815Setup line for _tkinter in some Python distributions references
8167.4/4.0 by default. Changing this to 7.5/4.1 should take care of
817this.
818
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008193.19. Q. I configured and built Python for Tcl/Tk but "import Tkinter"
Guido van Rossum8727df41996-09-09 15:16:39 +0000820fails.
821
822A. Most likely, you forgot to enable the line in Setup that says
823"TKPATH=:$(DESTLIB)/tkinter".
824
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008253.20. Q. Tk doesn't work right on DEC Alpha.
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000826
827A. You probably compiled either Tcl, Tk or Python with gcc. Don't.
828For this platform, which has 64-bit integers, gcc is known to generate
829broken code. The standard cc (which comes bundled with the OS!)
830works. If you still prefer gcc, at least try recompiling with cc
831before reporting problems to the newsgroup or the author; if this
832fixes the problem, report the bug to the gcc developers instead. (As
833far as we know, there are no problem with gcc on other platforms --
834the instabilities seem to be restricted to the DEC Alpha.) See also
835question 3.6.
836
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008373.21. Q. Several common system calls are missing from the posix module.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000838
839A. Most likely, *all* test compilations run by the configure script
840are failing for some reason or another. Have a look in config.log to
841see what could be the reason. A common reason is specifying a
842directory to the --with-readline option that doesn't contain the
843libreadline.a file.
844
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008453.22. Q. ImportError: No module named string, on MS Windows.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000846
847A. Most likely, your PYTHONPATH environment variable should be set to
848something like:
849
850set PYTHONPATH=c:\python;c:\python\lib;c:\python\scripts
851
852(assuming Python was installed in c:\python)
853
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008543.23. Q. Core dump on SGI when using the gl module.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000855
856There are conflicts between entry points in the termcap and curses
857libraries and an entry point in the GL library. There's a hack of a
858fix for the termcap library if it's needed for the GNU readline
859library, but it doesn't work when you're using curses. Concluding,
860you can't build a Python binary containing both the curses and gl
861modules.
862
863
Guido van Rossuma7925f11994-01-26 10:20:16 +0000864
8654. Programming in Python
866========================
867
Guido van Rossum24349991994-02-02 14:12:45 +00008684.1. Q. Is there a source code level debugger with breakpoints, step,
869etc.?
870
871A. Yes. Check out module pdb; pdb.help() prints the documentation (or
872you can read it as Lib/pdb.doc). If you use the STDWIN option,
873there's also a windowing interface, wdb. You can write your own
874debugger by using the code for pdb or wdb as an example.
875
8764.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000877C and others in Python (e.g. through inheritance)? (Also phrased as:
878Can I use a built-in type as base class?)
879
880A. No, but you can easily create a Python class which serves as a
881wrapper around a built-in object, e.g. (for dictionaries):
882
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000883 # A user-defined class behaving almost identical
884 # to a built-in dictionary.
885 class UserDict:
886 def __init__(self): self.data = {}
887 def __repr__(self): return repr(self.data)
888 def __cmp__(self, dict):
889 if type(dict) == type(self.data):
890 return cmp(self.data, dict)
891 else:
892 return cmp(self.data, dict.data)
893 def __len__(self): return len(self.data)
894 def __getitem__(self, key): return self.data[key]
895 def __setitem__(self, key, item): self.data[key] = item
896 def __delitem__(self, key): del self.data[key]
897 def keys(self): return self.data.keys()
898 def items(self): return self.data.items()
899 def values(self): return self.data.values()
900 def has_key(self, key): return self.data.has_key(key)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000901
Guido van Rossum8651d271997-02-17 18:27:32 +0000902A2. See Jim Fulton's ExtensionClass for an example of a mechanism
903which allows you to have superclasses which you can inherit from in
904Python -- that way you can have some methods from a C superclass (call
905it a mixin) and some methods from either a Python superclass or your
906subclass. See <URL:http://www.digicool.com/papers/ExtensionClass.html>.
907
Guido van Rossum24349991994-02-02 14:12:45 +00009084.3. Q. Is there a curses/termcap package for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000909
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000910A. Yes -- Lance Ellinghaus has written a module that interfaces to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000911System V's "ncurses". If you know a little curses and some Python,
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000912it's straightforward to use. It is part of the standard Python
913distribution, but not configured by default -- you must enable it by
914editing Modules/Setup. It requires a System V curses implementation.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000915
916You could also consider using the "alfa" (== character cell) version
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000917of STDWIN. (Standard Window System Interface, a portable windowing
918system interface by myself <URL:ftp://ftp.cwi.nl/pub/stdwin/>.) This
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000919will also prepare your program for porting to windowing environments
920such as X11 or the Macintosh.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000921
Guido van Rossum24349991994-02-02 14:12:45 +00009224.4. Q. Is there an equivalent to C's onexit() in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000923
924A. Yes, if you import sys and assign a function to sys.exitfunc, it
925will be called when your program exits, is killed by an unhandled
926exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
927
Guido van Rossum24349991994-02-02 14:12:45 +00009284.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000929nested function seemingly can't access the local variables of the
930outer function. What is going on? How do I pass local data to a
931nested function?
932
933A. Python does not have arbitrarily nested scopes. When you need to
934create a function that needs to access some data which you have
935available locally, create a new class to hold the data and return a
936method of an instance of that class, e.g.:
937
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000938 class MultiplierClass:
939 def __init__(self, factor):
940 self.factor = factor
941 def multiplier(self, argument):
942 return argument * self.factor
Guido van Rossuma7925f11994-01-26 10:20:16 +0000943
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000944 def generate_multiplier(factor):
945 return MultiplierClass(factor).multiplier
Guido van Rossuma7925f11994-01-26 10:20:16 +0000946
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000947 twice = generate_multiplier(2)
948 print twice(10)
949 # Output: 20
950
951An alternative solution uses default arguments, e.g.:
952
953 def generate_multiplier(factor):
954 def multiplier(arg, fact = factor):
955 return arg*fact
956 return multiplier
957
958 twice = generate_multiplier(2)
959 print twice(10)
960 # Output: 20
Guido van Rossuma7925f11994-01-26 10:20:16 +0000961
Guido van Rossum24349991994-02-02 14:12:45 +00009624.6. Q. How do I iterate over a sequence in reverse order?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000963
964A. If it is a list, the fastest solution is
965
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000966 list.reverse()
967 try:
968 for x in list:
969 "do something with x"
970 finally:
971 list.reverse()
Guido van Rossuma7925f11994-01-26 10:20:16 +0000972
973This has the disadvantage that while you are in the loop, the list
974is temporarily reversed. If you don't like this, you can make a copy.
975This appears expensive but is actually faster than other solutions:
976
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000977 rev = list[:]
978 rev.reverse()
979 for x in rev:
980 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000981
982If it isn't a list, a more general but slower solution is:
983
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000984 i = len(list)
985 while i > 0:
986 i = i-1
987 x = list[i]
988 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000989
990A more elegant solution, is to define a class which acts as a sequence
991and yields the elements in reverse order (solution due to Steve
992Majewski):
993
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000994 class Rev:
995 def __init__(self, seq):
996 self.forw = seq
997 def __len__(self):
998 return len(self.forw)
999 def __getitem__(self, i):
1000 return self.forw[-(i + 1)]
Guido van Rossuma7925f11994-01-26 10:20:16 +00001001
1002You can now simply write:
1003
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001004 for x in Rev(list):
1005 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +00001006
Guido van Rossum061f1821994-10-06 16:03:45 +00001007Unfortunately, this solution is slowest of all, due to the method
Guido van Rossuma7925f11994-01-26 10:20:16 +00001008call overhead...
1009
Guido van Rossum24349991994-02-02 14:12:45 +000010104.7. Q. My program is too slow. How do I speed it up?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001011
1012A. That's a tough one, in general. There are many tricks to speed up
1013Python code; I would consider rewriting parts in C only as a last
1014resort. One thing to notice is that function and (especially) method
1015calls are rather expensive; if you have designed a purely OO interface
1016with lots of tiny functions that don't do much more than get or set an
1017instance variable or call another method, you may consider using a
1018more direct way, e.g. directly accessing instance variables. Also see
1019the standard module "profile" (described in the file
1020"python/lib/profile.doc") which makes it possible to find out where
1021your program is spending most of its time (if you have some patience
1022-- the profiling itself can slow your program down by an order of
1023magnitude).
1024
Guido van Rossum24349991994-02-02 14:12:45 +000010254.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +00001026again (into the same Python process), the changes don't seem to take
1027place. What is going on?
1028
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001029A. For reasons of efficiency as well as consistency, Python only reads
Guido van Rossum796b2591995-01-20 23:05:52 +00001030the module file on the first time a module is imported. (Otherwise a
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001031program consisting of many modules, each of which imports the same
Guido van Rossum796b2591995-01-20 23:05:52 +00001032basic module, would read the basic module over and over again.) To
1033force rereading of a changed module, do this:
Guido van Rossuma7925f11994-01-26 10:20:16 +00001034
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001035 import modname
1036 reload(modname)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001037
1038Warning: this technique is not 100% fool-proof. In particular,
1039modules containing statements like
1040
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001041 from modname import some_objects
Guido van Rossuma7925f11994-01-26 10:20:16 +00001042
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001043will continue to work with the old version of the imported objects.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001044
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000010454.9. Q. How do I find the current module name?
Guido van Rossum24349991994-02-02 14:12:45 +00001046
Guido van Rossum061f1821994-10-06 16:03:45 +00001047A. A module can find out its own module name by looking at the
Guido van Rossum24349991994-02-02 14:12:45 +00001048(predefined) global variable __name__. If this has the value
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001049'__main__' you are running as a script.
1050
Guido van Rossuma6c707c1995-01-02 17:32:28 +000010514.10. Q. I have a module in which I want to execute some extra code
1052when it is run as a script. How do I find out whether I am running as
1053a script?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001054
1055A. See the previous question. E.g. if you put the following on the
1056last line of your module, main() is called only when your module is
1057running as a script:
Guido van Rossum24349991994-02-02 14:12:45 +00001058
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001059 if __name__ == '__main__': main()
Guido van Rossum24349991994-02-02 14:12:45 +00001060
Guido van Rossuma6c707c1995-01-02 17:32:28 +000010614.11. Q. I try to run a program from the Demo directory but it fails
1062with ImportError: No module named ...; what gives?
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001063
Guido van Rossum061f1821994-10-06 16:03:45 +00001064A. This is probably an optional module (written in C!) which hasn't
1065been configured on your system. This especially happens with modules
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001066like "Tkinter", "stdwin", "gl", "Xt" or "Xm". For Tkinter, STDWIN and
1067many other modules, see Modules/Setup.in for info on how to add these
1068modules to your Python, if it is possible at all. Sometimes you will
1069have to ftp and build another package first (e.g. STDWIN). Sometimes
1070the module only works on specific platforms (e.g. gl only works on SGI
1071machines).
1072
1073NOTE: if the complaint is about "Tkinter" (upper case T) and you have
Guido van Rossumca318ec1996-06-26 19:50:09 +00001074already configured module "tkinter" (lower case t), the solution is
1075*not* to rename tkinter to Tkinter or vice versa. There is probably
1076something wrong with your module search path. Check out the value of
1077sys.path.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001078
Guido van Rossum061f1821994-10-06 16:03:45 +00001079For X-related modules (Xt and Xm) you will have to do more work: they
1080are currently not part of the standard Python distribution. You will
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001081have to ftp the Extensions tar file, e.g.
Guido van Rossum7be34a81995-05-31 15:17:12 +00001082<URL:ftp://ftp.python.org/pub/python/src/extensions.tar.gz> and follow
1083the instructions there.
Guido van Rossum061f1821994-10-06 16:03:45 +00001084
1085See also the next question.
1086
10874.12. Q. I have successfully built Python with STDWIN but it can't
1088find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001089
1090A. There's a subdirectory of the library directory named 'stdwin'
1091which should be in the default module search path. There's a line in
1092Modules/Setup(.in) that you have to enable for this purpose --
Guido van Rossum061f1821994-10-06 16:03:45 +00001093unfortunately in the latest release it's not near the other
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001094STDWIN-related lines so it's easy to miss it.
1095
10964.13. Q. What GUI toolkits exist for Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001097
1098A. Depending on what platform(s) you are aiming at, there are several.
1099
Guido van Rossumc458e941996-09-11 15:43:13 +00001100Currently supported solutions:
1101
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001102- There's a neat object-oriented interface to the Tcl/Tk widget set,
Guido van Rossumc458e941996-09-11 15:43:13 +00001103called Tkinter. It is part of the standard Python distribution and
1104well-supported -- all you need to do is build and install Tcl/Tk and
1105enable the _tkinter module and the TKPATH definition in Modules/Setup
1106when building Python. This is probably the easiest to install and
1107use, and the most complete widget set. It is also very likely that in
1108the future the standard Python GUI API will be based on or at least
1109look very much like the Tkinter interface. For more info about Tk,
1110including pointers to the source, see the Tcl/Tk home page
1111<URL:http://www.sunlabs.com/research/tcl/>. Tcl/Tk is now fully
1112portable to the Mac and Windows platforms (NT and 95 only); you need
1113Python 1.4beta3 or later and Tk 4.1patch1 or later.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001114
1115- There's an interface to X11, including the Athena and Motif widget
1116sets (and a few individual widgets, like Mosaic's HTML widget and
Guido van Rossumc458e941996-09-11 15:43:13 +00001117SGI's GL widget) available from
1118<URL:ftp://ftp.python.org/pub/python/src/X-extension.tar.gz>.
1119Support by Sjoerd Mullender <sjoerd@cwi.nl>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001120
Guido van Rossum8a913021996-10-08 17:18:30 +00001121- On top of the X11 interface there's the (recently revived) vpApp
1122toolkit by Per Spilling, now also maintained by Sjoerd Mullender
1123<sjoerd@cwi.nl>. See <URL:ftp://ftp.cwi.nl/pub/sjoerd/vpApp.tar.gz>.
1124
Guido van Rossumc458e941996-09-11 15:43:13 +00001125- The Mac port has a rich and ever-growing set of modules that support
1126the native Mac toolbox calls. See the documentation that comes with
1127the Mac port. See <URL:ftp://ftp.python.org/pub/python/mac>. Support
1128by Jack Jansen <jack@cwi.nl>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001129
Guido van Rossumc458e941996-09-11 15:43:13 +00001130- The NT port supported by Mark Hammond <MHammond@skippinet.com.au>
1131(see question 7.2) includes an interface to the Microsoft Foundation
1132Classes and a Python programming environment using it that's written
1133mostly in Python. See
1134<URL:ftp://ftp.python.org/pub/python/pythonwin/>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001135
Guido van Rossumc458e941996-09-11 15:43:13 +00001136- There's an object-oriented GUI based on the Microsoft Foundation
1137Classes model called WPY, supported by Jim Ahlstrom <jim@interet.com>.
1138Programs written in WPY run unchanged and with native look and feel on
1139Windows NT/95, Windows 3.1 (using win32s), and on Unix (using Tk).
1140Source and binaries for Windows and Linux are available in
1141<URL:ftp://ftp.python.org/pub/python/wpy/>.
1142
1143Obsolete or minority solutions:
Guido van Rossumbf8e7d51995-08-28 03:09:13 +00001144
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001145- There's an interface to wxWindows. wxWindows is a portable GUI
1146class library written in C++. It supports XView, Motif, MS-Windows as
Guido van Rossumc458e941996-09-11 15:43:13 +00001147targets. There is some support for Macs and CURSES as well.
1148wxWindows preserves the look and feel of the underlying graphics
1149toolkit. See the wxPython WWW page at
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001150<URL:http://www.aiai.ed.ac.uk/~jacs/wx/wxpython/wxpython.html>.
Guido van Rossumc458e941996-09-11 15:43:13 +00001151Support for wxPython (by Harri Pasanen <pa@tekla.fi>) appears
1152to have a low priority.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001153
Guido van Rossumc458e941996-09-11 15:43:13 +00001154- For SGI IRIX only, there are unsupported interfaces to the complete
1155GL (Graphics Library -- low level but very good 3D capabilities) as
1156well as to FORMS (a buttons-and-sliders-etc package built on top of GL
1157by Mark Overmars -- ftp'able from
1158<URL:ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/>). This is probably also
1159becoming obsolete, as OpenGL takes over.
1160
1161- There's an interface to STDWIN, a platform-independent low-level
1162windowing interface for Mac and X11. This is totally unsupported and
1163rapidly becoming obsolete. The STDWIN sources are at
1164<URL:ftp://ftp.cwi.nl/pub/stdwin/>. (For info about STDWIN 2.0,
1165please refer to Steven Pemberton <steven@cwi.nl> -- I believe it is
1166also dead.)
1167
1168- There once was an interface to WAFE, a Tcl interface to the X11
1169Motif and Athena widget sets. WAFE is at
1170<URL:ftp://ftp.wu-wien.ac.at/pub/src/X11/wafe/>. It's not clear what
1171the status of the Python support is.
Guido van Rossum3fc9d731995-07-25 15:10:56 +00001172
Guido van Rossum0d20cfa1996-07-30 18:53:05 +00001173- (The Fresco port that was mentioned in earlier versions of this FAQ
1174no longer seems to exist. Inquire with Mark Linton.)
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001175
Guido van Rossum061f1821994-10-06 16:03:45 +000011764.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001177
Guido van Rossum8727df41996-09-09 15:16:39 +00001178A. There's a whole collection of them in the contrib area of the ftp
1179server, see <URL:http://www.python.org/ftp/python/contrib/Database/>.
Guido van Rossum796b2591995-01-20 23:05:52 +00001180
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000011814.15. Q. Is it possible to write obfuscated one-liners in Python?
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001182
1183A. Yes. See the following three examples, due to Ulf Bartelt:
1184
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001185 # Primes < 1000
1186 print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
1187 map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001188
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001189 # First 10 Fibonacci numbers
1190 print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
1191 range(10))
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001192
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001193 # Mandelbrot set
1194 print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
1195 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
1196 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
1197 i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
1198 >=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(
1199 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
1200 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
1201 # \___ ___/ \___ ___/ | | |__ lines on screen
1202 # V V | |______ columns on screen
1203 # | | |__________ maximum of "iterations"
1204 # | |_________________ range on y axis
1205 # |____________________________ range on x axis
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001206
1207Don't try this at home, kids!
1208
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000012094.16. Q. Is there an equivalent of C's "?:" ternary operator?
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001210
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001211A. Not directly. In many cases you can mimic a?b:c with "a and b or
1212c", but there's a flaw: if b is zero (or empty, or None -- anything
1213that tests false) then c will be selected instead. In many cases you
1214can prove by looking at the code that this can't happen (e.g. because
1215b is a constant or has a type that can never be false), but in general
1216this can be a problem.
1217
Guido van Rossumc458e941996-09-11 15:43:13 +00001218Tim Peters (who wishes it was Steve Majewski) suggested the following
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001219solution: (a and [b] or [c])[0]. Because [b] is a singleton list it
1220is never false, so the wrong path is never taken; then applying [0] to
1221the whole thing gets the b or c that you really wanted. Ugly, but it
1222gets you there in the rare cases where it is really inconvenient to
1223rewrite your code using 'if'.
1224
12254.17. Q. My class defines __del__ but it is not called when I delete the
1226object.
1227
1228A. There are several possible reasons for this.
1229
1230- The del statement does not necessarily call __del__ -- it simply
1231decrements the object's reference count, and if this reaches zero
1232__del__ is called.
1233
1234- If your data structures contain circular links (e.g. a tree where
1235each child has a parent pointer and each parent has a list of
1236children) the reference counts will never go back to zero. You'll
Guido van Rossum061f1821994-10-06 16:03:45 +00001237have to define an explicit close() method which removes those
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001238pointers. Please don't ever call __del__ directly -- __del__ should
Guido van Rossum061f1821994-10-06 16:03:45 +00001239call close() and close() should make sure that it can be called more
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001240than once for the same object.
1241
1242- If the object has ever been a local variable (or argument, which is
1243really the same thing) to a function that caught an expression in an
1244except clause, chances are that a reference to the object still exists
1245in that function's stack frame as contained in the stack trace.
1246Normally, deleting (better: assigning None to) sys.exc_traceback will
1247take care of this. If you a stack was printed for an unhandled
1248exception in an interactive interpreter, delete sys.last_traceback
1249instead.
1250
1251- There is code that deletes all objects when the interpreter exits,
1252but if your Python has been configured to support threads, it is not
1253called (because other threads may still be active). You can define
Guido van Rossum061f1821994-10-06 16:03:45 +00001254your own cleanup function using sys.exitfunc (see question 4.4).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001255
Guido van Rossum8727df41996-09-09 15:16:39 +00001256- Finally, if your __del__ method raises an exception, this will be
1257ignored. Starting with Python 1.4beta3, a warning message is printed
1258to sys.stderr when this happens.
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001259
12604.18. Q. How do I change the shell environment for programs called
1261using os.popen() or os.system()? Changing os.environ doesn't work.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001262
Guido van Rossum01094e41997-02-17 18:40:02 +00001263A. You must be using either a version of python before 1.4, or on a
1264(rare) system that doesn't have the putenv() library function.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001265
Guido van Rossum01094e41997-02-17 18:40:02 +00001266Before Python 1.4, modifying the environment passed to subshells was
1267left out of the interpreter because there seemed to be no
1268well-established portable way to do it (in particular, some systems,
1269have putenv(), others have setenv(), and some have none at all). As
1270of Python 1.4, almost all Unix systems *do* have putenv(), and so does
1271the Win32 API, and thus the os module was modified so that changes to
1272os.environ are trapped and the corresponding putenv() call is made.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001273
12744.19. Q. What is a class?
1275
1276A. A class is the particular object type that is created by executing
Guido van Rossum796b2591995-01-20 23:05:52 +00001277a class statement. Class objects are used as templates, to create
1278class instance objects, which embody both the data structure and
1279program routines specific to a datatype.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001280
12814.20. Q. What is a method?
1282
1283A. A method is a function that you normally call as
Guido van Rossum796b2591995-01-20 23:05:52 +00001284x.name(arguments...) for some object x. The term is used for methods
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001285of classes and class instances as well as for methods of built-in
Guido van Rossum796b2591995-01-20 23:05:52 +00001286objects. (The latter have a completely different implementation and
1287only share the way their calls look in Python code.) Methods of
1288classes (and class instances) are defined as functions inside the
1289class definition.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001290
12914.21. Q. What is self?
1292
1293A. Self is merely a conventional name for the first argument of a
1294method -- i.e. a function defined inside a class definition. A method
1295defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
1296some instance x of the class in which the definition occurs;
1297the called method will think it is called as meth(x, a, b, c).
1298
12994.22. Q. What is a unbound method?
1300
1301A. An unbound method is a method defined in a class that is not yet
1302bound to an instance. You get an unbound method if you ask for a
1303class attribute that happens to be a function. You get a bound method
1304if you ask for an instance attribute. A bound method knows which
Guido van Rossum061f1821994-10-06 16:03:45 +00001305instance it belongs to and calling it supplies the instance automatically;
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001306an unbound method only knows which class it wants for its first
1307argument (a derived class is also OK). Calling an unbound method
1308doesn't "magically" derive the first argument from the context -- you
1309have to provide it explicitly.
1310
Guido van Rossuma6c707c1995-01-02 17:32:28 +000013114.23. Q. How do I call a method defined in a base class from a derived
1312class that overrides it?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001313
1314A. If your class definition starts with "class Derived(Base): ..."
1315then you can call method meth defined in Base (or one of Base's base
1316classes) as Base.meth(self, arguments...). Here, Base.meth is an
1317unbound method (see previous question).
1318
Guido van Rossuma6c707c1995-01-02 17:32:28 +000013194.24. Q. How do I call a method from a base class without using the
1320name of the base class?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001321
1322A. DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call
1323self.__class__.__bases__[0].meth(self, arguments...) but this fails when
Guido van Rossum061f1821994-10-06 16:03:45 +00001324a doubly-derived method is derived from your class: for its instances,
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001325self.__class__.__bases__[0] is your class, not its base class -- so
1326(assuming you are doing this from within Derived.meth) you would start
1327a recursive call.
1328
13294.25. Q. How can I organize my code to make it easier to change the base
1330class?
1331
1332A. You could define an alias for the base class, assign the real base
1333class to it before your class definition, and use the alias throughout
1334your class. Then all you have to change is the value assigned to the
1335alias. Incidentally, this trick is also handy if you want to decide
1336dynamically (e.g. depending on availability of resources) which base
1337class to use. Example:
1338
Guido van Rossumc458e941996-09-11 15:43:13 +00001339 BaseAlias = <real base class>
1340 class Derived(BaseAlias):
1341 def meth(self):
1342 BaseAlias.meth(self)
1343 ...
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001344
13454.26. Q. How can I find the methods or attributes of an object?
1346
1347A. This depends on the object type.
1348
1349For an instance x of a user-defined class, instance attributes are
1350found in the dictionary x.__dict__, and methods and attributes defined
1351by its class are found in x.__class__.__bases__[i].__dict__ (for i in
1352range(len(x.__class__.__bases__))). You'll have to walk the tree of
1353base classes to find *all* class methods and attributes.
1354
1355Many, but not all built-in types define a list of their method names
1356in x.__methods__, and if they have data attributes, their names may be
1357found in x.__members__. However this is only a convention.
1358
1359For more information, read the source of the standard (but
1360undocumented) module newdir.
1361
13624.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
1363
1364A. os.read() is a low-level function which takes a file descriptor (a
1365small integer). os.popen() creates a high-level file object -- the
1366same type used for sys.std{in,out,err} and returned by the builtin
1367open() function. Thus, to read n bytes from a pipe p created with
1368os.popen(), you need to use p.read(n).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001369
Guido van Rossum061f1821994-10-06 16:03:45 +000013704.28. Q. How can I create a stand-alone binary from a Python script?
1371
1372The demo script "Demo/scripts/freeze.py" does what you want. (It's
1373actually not a demo but a support tool -- there is some extra code in
1374the interpreter to accommodate it.) It requires that you have the
1375Python build tree handy, complete with all the lib*.a files.
1376
1377This works by scanning your source recursively for import statements
1378(both forms) and looking for the modules on the standard Python path
1379as well as in the source directory (for built-in modules). It then
1380"compiles" the modules written in Python to C code (array initializers
1381that can be turned into code objects using the marshal module) and
1382creates a custom-made config file that only contains those built-in
1383modules which are actually used in the program. It then compiles the
1384generated C code and links it with the rest of the Python interpreter
1385to form a self-contained binary which acts exactly like your script.
1386
Guido van Rossum7be34a81995-05-31 15:17:12 +00001387Hint: the freeze program only works if your script's filename ends in
1388".py".
Guido van Rossum061f1821994-10-06 16:03:45 +00001389
Guido van Rossum7be34a81995-05-31 15:17:12 +000013904.29. Q. What WWW tools are there for Python?
Guido van Rossum061f1821994-10-06 16:03:45 +00001391
Guido van Rossum8727df41996-09-09 15:16:39 +00001392A. See the chapter titled "Internet and WWW" in the Library Reference
1393Manual. There's also a web browser written in Python, called Grail --
Guido van Rossum4662b871996-11-27 15:24:34 +00001394see <URL:http://grail.cnri.reston.va.us/grail/>.
Guido van Rossum061f1821994-10-06 16:03:45 +00001395
1396Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser
1397called Dancer. An alpha version can be FTP'ed from
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001398<URL:ftp://ftp.cs.indiana.edu/pub/smiale/dancer.tar.gz>. (There are a
1399few articles about Dancer in the (hyper)mail archive
1400<URL:http://www.cwi.nl/~guido/hypermail/python-1994q3/index.html>.)
Guido van Rossum061f1821994-10-06 16:03:45 +00001401
Guido van Rossum7be34a81995-05-31 15:17:12 +000014024.30. Q. How do I run a subprocess with pipes connected to both input
Guido van Rossum796b2591995-01-20 23:05:52 +00001403and output?
1404
1405A. This is really a UNIX question. Also, in general, it is unwise to
1406do so, because you can easily cause a deadlock where the parent
1407process is blocked waiting for output from the child, while the child
1408is blocked waiting for input from the child. This can be caused
1409because the parent expects the child to output more text than it does,
1410or it can be caused by data being stuck in stdio buffers due to lack
1411of flushing. The Python parent can of course explicitly flush the data
1412it sends to the child before it reads any output, but if the child is
1413a naive C program it can easily have been written to never explicitly
1414flush its output, even if it is interactive, since flushing is
1415normally automatic.
1416
1417In many cases, all you really need is to run some data through a
1418command and get the result back. Unless the data is infinite in size,
1419the easiest (and often the most efficient!) way to do this is to write
1420it to a temporary file and run the command with that temporary file as
1421input. The standard module tempfile exports a function mktemp() which
1422generates unique temporary file names.
1423
1424If after reading all of the above you still want to connect two pipes
1425to a subprocess's standard input and output, here's a simple solution,
1426due to Jack Jansen:
1427
Guido van Rossume7d92d51995-10-11 18:06:54 +00001428 import os
1429 import sys
1430 import string
Guido van Rossum796b2591995-01-20 23:05:52 +00001431
Guido van Rossume7d92d51995-10-11 18:06:54 +00001432 MAXFD = 100 # Max number of file descriptors in this system
Guido van Rossum796b2591995-01-20 23:05:52 +00001433
Guido van Rossume7d92d51995-10-11 18:06:54 +00001434 def popen2(cmd):
1435 cmd = string.split(cmd)
1436 p2cread, p2cwrite = os.pipe()
1437 c2pread, c2pwrite = os.pipe()
1438 pid = os.fork()
1439 if pid == 0:
1440 # Child
1441 os.close(0)
1442 os.close(1)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001443 if os.dup(p2cread) != 0:
Guido van Rossume7d92d51995-10-11 18:06:54 +00001444 sys.stderr.write('popen2: bad read dup\n')
Guido van Rossumca318ec1996-06-26 19:50:09 +00001445 if os.dup(c2pwrite) != 1:
Guido van Rossume7d92d51995-10-11 18:06:54 +00001446 sys.stderr.write('popen2: bad write dup\n')
1447 for i in range(3, MAXFD):
1448 try:
1449 os.close(i)
1450 except:
1451 pass
1452 try:
1453 os.execv(cmd[0], cmd)
1454 finally:
1455 os._exit(1)
1456 os.close(p2cread)
1457 tochild = os.fdopen(p2cwrite, 'w')
1458 os.close(c2pwrite)
1459 fromchild = os.fdopen(c2pread, 'r')
1460 return fromchild, tochild
Guido van Rossum796b2591995-01-20 23:05:52 +00001461
1462Note that many interactive programs (e.g. vi) don't work well with
1463pipes substituted for standard input and output. You will have to use
1464pseudo ttys ("ptys") instead of pipes. There is some undocumented
1465code to use these in the library module pty.py -- I'm afraid you're on
Guido van Rossum3fc9d731995-07-25 15:10:56 +00001466your own here.
1467
1468A different answer is a Python interface to Don Libes' "expect"
1469library. A prerelease of this is available on the Python ftp mirror
1470sites in the contrib subdirectory as expy-0.3.tar.gz, e.g.
1471<URL:ftp://ftp.python.org/pub/python/contrib/expy-0.3.tar.gz>.
Guido van Rossum796b2591995-01-20 23:05:52 +00001472
Guido van Rossum7be34a81995-05-31 15:17:12 +000014734.31. Q. How do I call a function if I have the arguments in a tuple?
Guido van Rossumac3f2121995-04-10 11:53:42 +00001474
1475A. Use the built-in function apply(). For instance,
1476
1477 func(1, 2, 3)
1478
1479is equivalent to
1480
1481 args = (1, 2, 3)
1482 apply(func, args)
1483
1484Note that func(args) is not the same -- it calls func() with exactly
1485one argument, the tuple args, instead of three arguments, the integers
14861, 2 and 3.
1487
Guido van Rossum7be34a81995-05-31 15:17:12 +000014884.32. Q. How do I enable font-lock-mode for Python in Emacs?
1489
1490A. Assuming you're already using python-mode and font-lock-mode
1491separately, all you need to do is put this in your .emacs file:
1492
Guido van Rossume7d92d51995-10-11 18:06:54 +00001493 (defun my-python-mode-hook ()
1494 (setq font-lock-keywords python-font-lock-keywords)
1495 (font-lock-mode 1))
1496 (add-hook 'python-mode-hook 'my-python-mode-hook)
Guido van Rossum7be34a81995-05-31 15:17:12 +00001497
14984.33. Q. Is there an inverse to the format operator (a la C's scanf())?
1499
1500A. Not as such.
1501
1502For simple input parsing, the easiest approach is usually to split
1503the line into whitespace-delimited words using string.split(), and to
1504convert decimal strings to numeric values using string.atoi(),
1505string.atol() or string.atof(). (Python's atoi() is 32-bit and its
1506atol() is arbitrary precision.) If you want to use another delimiter
1507than whitespace, use string.splitfield() (possibly combining it with
1508string.strip() which removes surrounding whitespace from a string).
1509
1510For more complicated input parsing, regular expressions (see module
1511regex) are better suited and more powerful than C's scanf().
1512
Guido van Rossumca318ec1996-06-26 19:50:09 +000015134.34. Q. Can I have Tk events handled while waiting for I/O?
1514
1515A. Yes, and you don't even need threads! But you'll have to
1516restructure your I/O code a bit. Tk has the equivalent of Xt's
1517XtAddInput() call, which allows you to register a callback function
1518which will be called from the Tk mainloop when I/O is possible on a
1519file descriptor. Here's what you need:
1520
Guido van Rossumc458e941996-09-11 15:43:13 +00001521 from Tkinter import tkinter
1522 tkinter.createfilehandler(file, mask, callback)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001523
1524The file may be a Python file or socket object (actually, anything
1525with a fileno() method), or an integer file descriptor. The mask is
1526one of the constants tkinter.READABLE or tkinter.WRITABLE. The
1527callback is called as follows:
1528
Guido van Rossumc458e941996-09-11 15:43:13 +00001529 callback(file, mask)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001530
1531You must unregister the callback when you're done, using
1532
Guido van Rossumc458e941996-09-11 15:43:13 +00001533 tkinter.deletefilehandler(file)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001534
1535Note: since you don't know *how many bytes* are available for reading,
1536you can't use the Python file object's read or readline methods, since
1537these will insist on reading a predefined number of bytes. For
1538sockets, the recv() or recvfrom() methods will work fine; for other
1539files, use os.read(file.fileno(), maxbytecount).
1540
15414.35. Q. How do I write a function with output parameters (call by reference)?
1542
1543A. [Mark Lutz] The thing to remember is that arguments are passed by
1544assignment in Python. Since assignment just creates references to
1545objects, there's no alias between an argument name in the caller and
1546callee, and so no call-by-reference per se. But you can simulate it
1547in a number of ways:
1548
15491) By using global variables; but you probably shouldn't :-)
1550
15512) By passing a mutable (changeable in-place) object:
1552
1553 def func1(a):
1554 a[0] = 'new-value' # 'a' references a mutable list
1555 a[1] = a[1] + 1 # changes a shared object
1556
1557 args = ['old-value', 99]
1558 func1(args)
1559 print args[0], args[1] # output: new-value 100
1560
15613) By return a tuple, holding the final values of arguments:
1562
1563 def func2(a, b):
1564 a = 'new-value' # a and b are local names
1565 b = b + 1 # assigned to new objects
1566 return a, b # return new values
1567
1568 x, y = 'old-value', 99
1569 x, y = func2(x, y)
1570 print x, y # output: new-value 100
1571
15724) And other ideas that fall-out from Python's object model. For
1573 instance, it might be clearer to pass in a mutable dictionary:
1574
1575 def func3(args):
1576 args['a'] = 'new-value' # args is a mutable dictionary
1577 args['b'] = args['b'] + 1 # change it in-place
1578
1579 args = {'a':' old-value', 'b': 99}
1580 func3(args)
1581 print args['a'], args['b']
1582
15835) Or bundle-up values in a class instance:
1584
1585 class callByRef:
1586 def __init__(self, **args):
1587 for (key, value) in args.items():
1588 setattr(self, key, value)
1589
1590 def func4(args):
1591 args.a = 'new-value' # args is a mutable callByRef
1592 args.b = args.b + 1 # change object in-place
1593
1594 args = callByRef(a='old-value', b=99)
1595 func4(args)
1596 print args.a, args.b
1597
1598 But there's probably no good reason to get this complicated :-).
1599
1600[Python' author favors solution 3 in most cases.]
1601
Guido van Rossum0d20cfa1996-07-30 18:53:05 +000016024.36. Q. Please explain the rules for local and global variables in Python.
1603
1604A. [Ken Manheimer] In Python, procedure variables are implicitly
1605global, unless they assigned anywhere within the block. In that case
1606they are implicitly local, and you need to explicitly declare them as
1607'global'.
1608
1609Though a bit surprising at first, a moments consideration explains
1610this. On one hand, requirement of 'global' for assigned vars provides
1611a bar against unintended side-effects. On the other hand, if global
1612were required for all global references, you'd be using global all the
1613time. Eg, you'd have to declare as global every reference to a
1614builtin function, or to a component of an imported module. This
1615clutter would defeat the usefulness of the 'global' declaration for
1616identifying side-effects.
1617
16184.37. Q. How can I have modules that mutually import each other?
1619
1620A. Jim Roskind recommends the following order in each module:
1621
1622First: all exports (like globals, functions, and classes that don't
1623need imported bases classes).
1624
1625Then: all import statements.
1626
1627Finally: all active code (including globals that are initialized from
1628imported values).
1629
1630Python's author doesn't like this approach much because the imports
1631appear in a strange place, but has to admit that it works. His
1632recommended strategy is to avoid all uses of "from <module> import *"
1633(so everything from an imported module is referenced as
1634<module>.<name>) and to place all code inside functions.
1635Initializations of global variables and class variables should use
1636constants or built-in functions only.
1637
Guido van Rossum8727df41996-09-09 15:16:39 +000016384.38. Q. How do I copy an object in Python?
1639
1640A. There is no generic copying operation built into Python, however
1641most object types have some way to create a clone. Here's how for the
1642most common objects:
1643
1644- For immutable objects (numbers, strings, tuples), cloning is
1645unnecessary since their value can't change.
1646
1647- For lists (and generally for mutable sequence types), a clone is
1648created by the expression l[:].
1649
1650- For dictionaries, the following function returns a clone:
1651
Guido van Rossumc458e941996-09-11 15:43:13 +00001652 def dictclone(o):
1653 n = {}
1654 for k in o.keys(): n[k] = o[k]
1655 return n
Guido van Rossum8727df41996-09-09 15:16:39 +00001656
1657- Finally, for generic objects, the "copy" module defines two
1658functions for copying objects. copy.copy(x) returns a copy as shown
1659by the above rules. copy.deepcopy(x) also copies the elements of
1660composite objects. See the section on this module in the Library
1661Reference Manual.
1662
16634.39. Q. How to implement persistent objects in Python? (Persistent ==
1664automatically saved to and restored from disk.)
1665
1666A. The library module "pickle" now solves this in a very general way
1667(though you still can't store things like open files, sockests or
1668windows), and the library module "shelve" uses pickle and (g)dbm to
1669create presistent mappings containing arbitrary Python objects.
1670
Guido van Rossuma4e41a81996-10-22 03:00:43 +000016714.40. Q. I try to use __spam and I get an error about _SomeClassName__spam.
1672
1673A. Variables with double leading underscore are "mangled" to provide a
1674simple but effective way to define class private variables. See the
1675chapter "New in Release 1.4" in the Python Tutorial.
1676
Guido van Rossumc59120b1996-11-14 14:10:11 +000016774.41. Q. How do I delete a file? And other file questions.
1678
1679A. Use os.remove(filename) or os.unlink(filename); for documentation,
1680see the posix section of the library manual. They are the same,
1681unlink() is simply the Unix name for this function. In earlier
1682versions of Python, only os.unlink() was available.
1683
1684To remove a directory, use os.rmdir(); use os.mkdir() to create one.
1685
1686To rename a file, use os.rename().
1687
1688To truncate a file, open it using f = open(filename, "w+"), and use
1689f.truncate(offset); offset defaults to the current seek position.
1690There's also os.ftruncate(fd, offset) for files opened with os.open()
1691-- for advanced Unix hacks only.
1692
Guido van Rossum061f1821994-10-06 16:03:45 +00001693
Guido van Rossuma7925f11994-01-26 10:20:16 +000016945. Extending Python
1695===================
1696
16975.1. Q. Can I create my own functions in C?
1698
1699A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +00001700variables, exceptions and even new types in C. This is explained in
1701the document "Extending and Embedding the Python Interpreter" (the
1702LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001703
17045.2. Q. Can I create my own functions in C++?
1705
1706A. Yes, using the C-compatibility features found in C++. Basically
1707you place extern "C" { ... } around the Python include files and put
1708extern "C" before each function that is going to be called by the
1709Python interpreter. Global or static C++ objects with constructors
1710are probably not a good idea.
1711
Guido van Rossum7ce61c11994-06-13 15:13:56 +000017125.3. Q. How can I execute arbitrary Python statements from C?
1713
1714A. The highest-level function to do this is run_command() which takes
1715a single string argument which is executed in the context of module
1716__main__ and returns 0 for success and -1 when an exception occurred
1717(including SyntaxError). If you want more control, use run_string();
1718see the source for run_command() in Python/pythonrun.c.
1719
17205.4. Q. How can I evaluate an arbitrary Python expression from C?
1721
1722A. Call the function run_string() from the previous question with the
1723start symbol eval_input; it then parses an expression, evaluates it
1724and returns its value. See exec_eval() in Python/bltinmodule.c.
1725
17265.5. Q. How do I extract C values from a Python object?
1727
1728A. That depends on the object's type. If it's a tuple,
1729gettuplesize(o) returns its length and gettupleitem(o, i) returns its
1730i'th item; similar for lists with getlistsize(o) and getlistitem(o,
1731i). For strings, getstringsize(o) returns its length and
1732getstringvalue(o) a pointer to its value (note that Python strings may
1733contain null bytes so strlen() is not safe). To test which type an
1734object is, first make sure it isn't NULL, and then use
1735is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
1736
17375.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
1738
1739A. You can't. Use t = newtupleobject(n) instead, and fill it with
1740objects using settupleitem(t, i, o) -- note that this "eats" a
1741reference count of o. Similar for lists with newlistobject(n) and
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001742setlistitem(l, i, o). Note that you *must* set all the tuple items to
1743some value before you pass the tuple to Python code --
1744newtupleobject(n) initializes them to NULL, which isn't a valid Python
1745value.
1746
Guido van Rossum8727df41996-09-09 15:16:39 +000017475.7. Q. How do I call an object's method from C?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001748
1749A. Here's a function (untested) that might become part of the next
1750release in some form. It uses <stdarg.h> to allow passing the
1751argument list on to vmkvalue():
1752
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001753 object *call_method(object *inst, char *methodname, char *format, ...)
1754 {
1755 object *method;
1756 object *args;
1757 object *result;
1758 va_list va;
1759 method = getattr(inst, methodname);
1760 if (method == NULL) return NULL;
1761 va_start(va, format);
1762 args = vmkvalue(format, va);
1763 va_end(va);
1764 if (args == NULL) {
1765 DECREF(method);
1766 return NULL;
1767 }
1768 result = call_object(method, args);
1769 DECREF(method);
1770 DECREF(args);
1771 return result;
1772 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001773
1774This works for any instance that has methods -- whether built-in or
1775user-defined. You are responsible for eventually DECREF'ing the
1776return value.
1777
1778To call, e.g., a file object's "seek" method with arguments 10, 0
1779(assuming the file object pointer is "f"):
1780
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001781 res = call_method(f, "seek", "(OO)", 10, 0);
1782 if (res == NULL) {
1783 ... an exception occurred ...
1784 }
1785 else {
1786 DECREF(res);
1787 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001788
1789Note that since call_object() *always* wants a tuple for the argument
1790list, to call a function without arguments, pass "()" for the format,
1791and to call a function with one argument, surround the argument in
1792parentheses, e.g. "(i)".
1793
Guido van Rossum8727df41996-09-09 15:16:39 +000017945.8. Q. How do I catch the output from print_error()?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001795
1796A. (Due to Mark Hammond):
1797
1798* in Python code, define an object that supports the "write()" method.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001799
1800* redirect sys.stdout and sys.stderr to this object.
1801
Guido van Rossum061f1821994-10-06 16:03:45 +00001802* call print_error, or just allow the standard traceback mechanism to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001803work.
1804
Guido van Rossum061f1821994-10-06 16:03:45 +00001805Then, the output will go wherever your write() method sends it.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001806
Guido van Rossum8727df41996-09-09 15:16:39 +000018075.9. Q. How do I access a module written in Python from C?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001808
1809A. You can get a pointer to the module object as follows:
1810
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001811 module = import_module("<modulename>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001812
1813If the module hasn't been imported yet (i.e. it is not yet present in
1814sys.modules), this initializes the module; otherwise it simply returns
1815the value of sys.modules["<modulename>"]. Note that it doesn't enter
1816the module into any namespace -- it only ensures it has been
1817initialized and is stored in sys.modules.
1818
1819You can then access the module's attributes (i.e. any name defined in
1820the module) as follows:
1821
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001822 attr = getattr(module, "<attrname>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001823
1824Calling setattr(), to assign to variables in the module, also works.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001825
Guido van Rossum8727df41996-09-09 15:16:39 +000018265.10. Q. How do I interface to C++ objects from Python?
Guido van Rossumb0a2ce51995-08-28 19:41:35 +00001827
1828A. Depending on your requirements, there are many approaches. Begin
1829by reading the "Extending and Embedding" document (Doc/ext.tex, see
1830also <URL:http://www.python.org/doc/>). Realize that for the Python
1831run-time system, there isn't a whole lot of difference between C and
1832C++ -- so the strategy to build a new Python type around a C structure
1833(pointer) type will also work for C++ objects.
1834
1835Automatic generation of interfaces between Python and C++ is still at
1836the horizon -- parsing C++ header files requires an almost complete
1837C++ parser, and many features aren't easily translated from C++ to
1838Python: certain forms of operator oveloading, function overloading
1839(best approached by a varargs function which explicitly type-checks
1840its arguments), and reference arguments are just a number of features
1841that are hard to translate correctly if at all.
1842
1843The hardest problem is to transparently translate the C++ class
1844hierarchy to Python, so that Python programs derive classes from C++
1845classes. Given suitable constraints, this may be possible, but it
1846would require more space than I have in this FAQ to explain how.
1847In any case, you can get quite a bit done without this, using just the
1848existing classes from Python.
1849
1850If this all seems rather daunting, that may be because it is -- C++
1851isn't exactly a baby to handle without gloves! However, people have
1852accomplished amazing feats of interfacing between Python and C++, and
1853a detailed question posted to the Python list is likely to elicit some
1854interesting and useful responses.
1855
Guido van Rossuma7925f11994-01-26 10:20:16 +00001856
18576. Python's design
1858==================
1859
Guido van Rossum8727df41996-09-09 15:16:39 +000018606.1. Q. Why isn't there a switch or case statement in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001861
1862A. You can do this easily enough with a sequence of
1863if... elif... elif... else. There have been some proposals for switch
Guido van Rossum061f1821994-10-06 16:03:45 +00001864statement syntax, but there is no consensus (yet) on whether and how
Guido van Rossuma7925f11994-01-26 10:20:16 +00001865to do range tests.
1866
Guido van Rossum8727df41996-09-09 15:16:39 +000018676.2. Q. Why does Python use indentation for grouping of statements?
Guido van Rossumc50158e1994-05-31 09:18:50 +00001868
1869A. Basically I believe that using indentation for grouping is
1870extremely elegant and contributes a lot to the clarity of the average
1871Python program. Most people learn to love this feature after a while.
1872Some arguments for it:
1873
1874- Since there are no begin/end brackets there cannot be a disagreement
1875between grouping perceived by the parser and the human reader. I
1876remember long ago seeing a C fragment like this:
1877
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001878 if (x <= y)
1879 x++;
1880 y--;
1881 z++;
Guido van Rossumc50158e1994-05-31 09:18:50 +00001882
1883and staring a long time at it wondering why y was being decremented
1884even for x > y... (And I wasn't a C newbie then either.)
1885
Guido van Rossum7be34a81995-05-31 15:17:12 +00001886- Since there are no begin/end brackets, Python is much less prone to
1887coding-style conflicts. In C there are loads of different ways to
1888place the braces (including the choice whether to place braces around
1889single statements in certain cases, for consistency). If you're used
1890to reading (and writing) code that uses one style, you will feel at
1891least slightly uneasy when reading (or being required to write)
1892another style.
Guido van Rossumc50158e1994-05-31 09:18:50 +00001893
1894- Many coding styles place begin/end brackets on a line by themself.
1895This makes programs considerably longer and wastes valuable screen
1896space, making it harder to get a good overview over a program.
1897Ideally, a function should fit on one basic tty screen (say, 20
1898lines). 20 lines of Python are worth a LOT more than 20 lines of C.
1899This is not solely due to the lack of begin/end brackets (the lack of
1900declarations also helps, and the powerful operations of course), but
1901it certainly helps!
1902
Guido van Rossum8727df41996-09-09 15:16:39 +000019036.3. Q. Why are Python strings immutable?
Guido van Rossum3de27361994-07-25 14:19:33 +00001904
1905A. There are two advantages. One is performance: knowing that a
1906string is immutable makes it easy to lay it out at construction time
1907-- fixed and unchanging storage requirements. (This is also one of
Guido van Rossum061f1821994-10-06 16:03:45 +00001908the reasons for the distinction between tuples and lists.) The
Guido van Rossum3de27361994-07-25 14:19:33 +00001909other is that strings in Python are considered as "elemental" as
1910numbers. No amount of activity will change the value 8 to anything
1911else, and in Python, no amount of activity will change the string
1912"eight" to anything else. (Adapted from Jim Roskind)
1913
Guido van Rossum8727df41996-09-09 15:16:39 +000019146.4. Q. Why don't strings have methods like index() or sort(), like
Guido van Rossum3de27361994-07-25 14:19:33 +00001915lists?
1916
1917A. Good question. Strings currently don't have methods at all
1918(likewise tuples and numbers). Long ago, it seemed unnecessary to
1919implement any of these functions in C, so a standard library module
1920"string" written in Python was created that performs string related
1921operations. Since then, the cry for performance has moved most of
1922them into the built-in module strop (this is imported by module
Guido van Rossumf8c76d01994-08-17 12:19:53 +00001923string, which is still the preferred interface, without loss of
Guido van Rossum3de27361994-07-25 14:19:33 +00001924performance except during initialization). Some of these functions
1925(e.g. index()) could easily be implemented as string methods instead,
1926but others (e.g. sort()) can't, since their interface prescribes that
1927they modify the object, while strings are immutable (see the previous
1928question).
1929
Guido van Rossum8727df41996-09-09 15:16:39 +000019306.5. Q. Why does Python use methods for some functionality
Guido van Rossum3de27361994-07-25 14:19:33 +00001931(e.g. list.index()) but functions for other (e.g. len(list))?
1932
1933A. Functions are used for those operations that are generic for a
1934group of types and which should work even for objects that don't have
1935methods at all (e.g. numbers, strings, tuples). Also, implementing
1936len(), max(), min() as a built-in function is actually less code than
1937implementing them as methods for each type. One can quibble about
1938individual cases but it's really too late to change such things
1939fundamentally now.
1940
Guido van Rossum8727df41996-09-09 15:16:39 +000019416.6. Q. Why can't I derive a class from built-in types (e.g. lists or
Guido van Rossum3de27361994-07-25 14:19:33 +00001942files)?
1943
1944A. This is caused by the relatively late addition of (user-defined)
1945classes to the language -- the implementation framework doesn't easily
1946allow it. See the answer to question 4.2 for a work-around. This
1947*may* be fixed in the (distant) future.
1948
Guido van Rossum8727df41996-09-09 15:16:39 +000019496.7. Q. Why must 'self' be declared and used explicitly in method
Guido van Rossum3de27361994-07-25 14:19:33 +00001950definitions and calls?
1951
1952A. By asking this question you reveal your C++ background. :-)
1953When I added classes, this was (again) the simplest way of
1954implementing methods without too many changes to the interpreter. I
1955borrowed the idea from Modula-3. It turns out to be very useful, for
1956a variety of reasons.
1957
1958First, it makes it more obvious that you are using a method or
1959instance attribute instead of a local variable. Reading "self.x" or
1960"self.meth()" makes it absolutely clear that an instance variable or
1961method is used even if you don't know the class definition by heart.
1962In C++, you can sort of tell by the lack of a local variable
Guido van Rossum061f1821994-10-06 16:03:45 +00001963declaration (assuming globals are rare or easily recognizable) -- but
Guido van Rossum3de27361994-07-25 14:19:33 +00001964in Python, there are no local variable declarations, so you'd have to
1965look up the class definition to be sure.
1966
1967Second, it means that no special syntax is necessary if you want to
1968explicitly reference or call the method from a particular class. In
1969C++, if you want to use a method from base class that is overridden in
1970a derived class, you have to use the :: operator -- in Python you can
1971write baseclass.methodname(self, <argument list>). This is
1972particularly useful for __init__() methods, and in general in cases
1973where a derived class method wants to extend the base class method of
1974the same name and thus has to call the base class method somehow.
1975
1976Lastly, for instance variables, it solves a syntactic problem with
1977assignment: since local variables in Python are (by definition!) those
1978variables to which a value assigned in a function body (and that
1979aren't explicitly declared global), there has to be some way to tell
1980the interpreter that an assignment was meant to assign to an instance
1981variable instead of to a local variable, and it should preferably be
1982syntactic (for efficiency reasons). C++ does this through
1983declarations, but Python doesn't have declarations and it would be a
1984pity having to introduce them just for this purpose. Using the
1985explicit "self.var" solves this nicely. Similarly, for using instance
1986variables, having to write "self.var" means that references to
1987unqualified names inside a method don't have to search the instance's
1988directories.
1989
Guido van Rossum8727df41996-09-09 15:16:39 +000019906.8. Q. Can't you emulate threads in the interpreter instead of
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001991relying on an OS-specific thread implementation?
1992
1993A. Unfortunately, the interpreter pushes at least one C stack frame
1994for each Python stack frame. Also, extensions can call back into
1995Python at almost random moments. Therefore a complete threads
1996implementation requires thread support for C.
1997
Guido van Rossum8727df41996-09-09 15:16:39 +000019986.9. Q. Why can't lambda forms contain statements?
Guido van Rossum061f1821994-10-06 16:03:45 +00001999
2000A. Python lambda forms cannot contain statements because Python's
Guido van Rossum796b2591995-01-20 23:05:52 +00002001syntactic framework can't handle statements nested inside expressions.
Guido van Rossum061f1821994-10-06 16:03:45 +00002002
2003However, in Python, this is not a serious problem. Unlike lambda
2004forms in other languages, where they add functionality, Python lambdas
2005are only a shorthand notation if you're too lazy to define a function.
2006
2007Functions are already first class objects in Python, and can be
2008declared in a local scope. Therefore the only advantage of using a
2009lambda form instead of a locally-defined function is that you'll have
2010to invent a name for the function -- but that's just a local variable
2011to which the function object (which is exactly the same type of object
2012that a lambda form yields) is assigned!
2013
Guido van Rossum8727df41996-09-09 15:16:39 +000020146.10. Q. Why don't lambdas have access to variables defined in the
2015containing scope?
2016
Guido van Rossumc458e941996-09-11 15:43:13 +00002017A. Because they are implemented as ordinary functions.
2018See question 4.5 above.
Guido van Rossum8727df41996-09-09 15:16:39 +00002019
20206.11. Q. Why can't recursive functions be defined inside other functions?
2021
2022A. See question 4.5 above.
2023
Guido van Rossum061f1821994-10-06 16:03:45 +000020246.12. Q. Why is there no more efficient way of iterating over a dictionary
2025than first constructing the list of keys()?
2026
2027A. Have you tried it? I bet it's fast enough for your purposes! In
2028most cases such a list takes only a few percent of the space occupied
2029by the dictionary -- it needs only 4 bytes (the size of a pointer) per
2030key -- a dictionary costs 8 bytes per key plus between 30 and 70
2031percent hash table overhead, plus the space for the keys and values --
2032by necessity all keys are unique objects and a string object (the most
2033common key type) costs at least 18 bytes plus the length of the
2034string. Add to that the values contained in the dictionary, and you
2035see that 4 bytes more per item really isn't that much more memory...
2036
2037A call to dict.keys() makes one fast scan over the dictionary
2038(internally, the iteration function does exist) copying the pointers
2039to the key objects into a pre-allocated list object of the right size.
2040The iteration time isn't lost (since you'll have to iterate anyway --
2041unless in the majority of cases your loop terminates very prematurely
2042(which I doubt since you're getting the keys in random order).
2043
2044I don't expose the dictionary iteration operation to Python
2045programmers because the dictionary shouldn't be modified during the
2046entire iteration -- if it is, there's a very small chance that the
2047dictionary is reorganized because the hash table becomes too full, and
2048then the iteration may miss some items and see others twice. Exactly
2049because this only occurs rarely, it would lead to hidden bugs in
2050programs: it's easy never to have it happen during test runs if you
2051only insert or delete a few items per iteration -- but your users will
2052surely hit upon it sooner or later.
2053
Guido van Rossumb0a2ce51995-08-28 19:41:35 +000020546.13. Q. Can Python be compiled to machine code, C or some other language?
2055
2056A. Not easily. Python's high level data types, dynamic typing of
2057objects and run-time invocation of the interpreter (using eval() or
2058exec) together mean that a "compiled" Python program would probably
2059consist mostly of calls into the Python run-time system, even for
2060seemingly simple operations like "x+1". Thus, the performance gain
2061would probably be minimal.
2062
2063Internally, Python source code is always translated into a "virtual
2064machine code" or "byte code" representation before it is interpreted
2065(by the "Python virtual machine" or "bytecode interpreter"). In order
2066to avoid the overhead of parsing and translating modules that rarely
2067change over and over again, this byte code is written on a file whose
2068name ends in ".pyc" whenever a module is parsed (from a file whose
2069name ends in ".py"). When the corresponding .py file is changed, it
2070is parsed and translated again and the .pyc file is rewritten. There
2071is no performance difference once the .pyc file has been loaded (the
2072bytecode read from the .pyc file is exactly the same as the bytecode
2073created by direct translation). The only difference is that loading
2074code from a .pyc file is faster than parsing and translating a .py
2075file, so the presence of precompiled .pyc files will generally improve
2076start-up time of Python scripts. If desired, the Lib/compileall.py
2077module/script can be used to force creation of valid .pyc files for a
2078given set of modules.
2079
2080If you are looking for a way to translate Python programs in order to
2081distribute them in binary form, without the need to distribute the
2082interpreter and library as well, have a look at the freeze.py script
2083in the Tools/freeze directory. This creates a single binary file
2084incorporating your program, the Python interpreter, and those parts of
2085the Python library that are needed by your program. Of course, the
2086resulting binary will only run on the same type of platform as that
2087used to create it.
2088
2089Hints for proper usage of freeze.py:
2090
2091- the script must be in a file whose name ends in .py
2092
2093- you must have installed Python fully:
2094
Guido van Rossume7d92d51995-10-11 18:06:54 +00002095 make install
2096 make libinstall
2097 make inclinstall
2098 make libainstall
Guido van Rossumb0a2ce51995-08-28 19:41:35 +00002099
Guido van Rossum05151e01995-09-28 13:24:46 +000021006.14. Q. Why doesn't Python use proper garbage collection?
2101
2102A. It's looking less and less likely that Python will ever get
2103"automatic" garbage collection (GC). For one thing, unless this were
2104added to C as a standard feature, it's a portability pain in the ass.
2105And yes, I know about the Xerox library. It has bits of assembler
2106code for *most* *common* platforms. Not for all. And although it is
2107mostly transparent, it isn't completely transparent (when I once
2108linked Python with it, it dumped core).
2109
2110"Proper" GC also becomes a problem when Python gets embedded into
2111other applications. While in a stand-alone Python it may be fine to
2112replace the standard malloc() and free() with versions provided by the
2113GC library, an application embedding Python may want to have its *own*
2114substitute for malloc() and free(), and may not want Python's. Right
2115now, Python works with anything that implements malloc() and free()
2116properly.
2117
2118Besides, the predictability of destructor calls in Python is kind of
2119attractive. With GC, the following code (which is fine in current
2120Python) will run out of file descriptors long before it runs out of
2121memory:
2122
Guido van Rossume7d92d51995-10-11 18:06:54 +00002123 for file in <very long list of files>:
2124 f = open(file)
2125 c = file.read(1)
Guido van Rossum05151e01995-09-28 13:24:46 +00002126
2127Using the current reference counting and destructor scheme, each new
2128assignment to f closes the previous file. Using GC, this is not
2129guaranteed. Sure, you can think of ways to fix this. But it's not
2130off-the-shelf technology.
2131
Guido van Rossuma7925f11994-01-26 10:20:16 +00002132
21337. Using Python on non-UNIX platforms
2134=====================================
2135
Guido van Rossum91f60831994-02-15 15:52:27 +000021367.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002137
Guido van Rossume530c581995-04-10 12:32:16 +00002138A. Yes, see the "mac" subdirectory of the distribution sites,
Guido van Rossum7be34a81995-05-31 15:17:12 +00002139e.g. <URL:ftp://ftp.python.org/pub/python/mac/>.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002140
Guido van Rossumc458e941996-09-11 15:43:13 +000021417.2. Q. Are there DOS and Windows versions of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002142
Guido van Rossumc458e941996-09-11 15:43:13 +00002143A. Yes. There is a plethora of not-always-compatible versions. See
2144the "pythonwin", "wpy", "nt" and "pc" subdirectories of the
2145distribution sites. A quick comparison:
Guido van Rossuma7925f11994-01-26 10:20:16 +00002146
Guido van Rossumc458e941996-09-11 15:43:13 +00002147PythonWin: Extensive support for the 32-bit native Windows API and GUI
2148building using MFC. Windows NT and Windows 95 only (and Windows
21493.1(1) using win32s, until Microsoft stops supporting it :-( ).
2150<URL:ftp://ftp.python.org/pub/python/pythonwin/>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002151
Guido van Rossumc458e941996-09-11 15:43:13 +00002152WPY: Ports to DOS, Windows 3.1(1), Windows 95, Windows NT and OS/2.
2153Also contains a GUI package that offers portability between Windows
2154(not DOS) and Unix, and native look and feel on both.
2155<URL:ftp://ftp.python.org/pub/python/wpy/>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002156
Guido van Rossumc458e941996-09-11 15:43:13 +00002157NT: Basic ports built straight from the 1.4 distribution for Windows
215895 and Windows NT. This will eventually provide core support for
2159both PythonWin and WPY on all 32-bit Microsoft platforms.
Guido van Rossum3fc9d731995-07-25 15:10:56 +00002160<URL:ftp://ftp.python.org/pub/python/nt/>.
2161
Guido van Rossumc458e941996-09-11 15:43:13 +00002162PC: Old, unsupported ports to DOS, Windows 3.1(1) and OS/2.
2163<URL:ftp://ftp.python.org/pub/python/pc/>.
Guido van Rossum91f60831994-02-15 15:52:27 +00002164
Guido van Rossumc458e941996-09-11 15:43:13 +000021657.3. Q. Is there an OS/2 version of Python?
Guido van Rossum061f1821994-10-06 16:03:45 +00002166
Guido van Rossumc458e941996-09-11 15:43:13 +00002167A. Yes, see the "pc" and "wpy" subdirectory of the distribution sites
2168(see above).
Guido van Rossum061f1821994-10-06 16:03:45 +00002169
Guido van Rossumc458e941996-09-11 15:43:13 +000021707.4. Q. Is there a VMS version of Python?
Guido van Rossume530c581995-04-10 12:32:16 +00002171
Guido van Rossum3fc9d731995-07-25 15:10:56 +00002172A. Donn Cave <donn@cac.washington.edu> did a partial port. The
2173results of his efforts are on public display in
Guido van Rossumbf8e7d51995-08-28 03:09:13 +00002174<<URL:ftp://ftp.python.org/pub/python/contrib/vms.tar.gz/>. Someone
2175else is working on a more complete port, for details watch the list.
Guido van Rossume530c581995-04-10 12:32:16 +00002176
Guido van Rossumc458e941996-09-11 15:43:13 +000021777.5. Q. What about IBM mainframes, or other non-UNIX platforms?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002178
Guido van Rossumb0a2ce51995-08-28 19:41:35 +00002179A. I haven't heard about these, except I remember hearing about an
2180OS/9 port and a port to Vxworks (both operating systems for embedded
2181systems). If you're interested in any of this, go directly to the
2182newsgroup and ask there, you may find exactly what you need. For
2183example, a port to MPE/iX 5.0 on HP3000 computers was just announced,
2184see <URL:http://www.allegro.com/software/>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002185
Guido van Rossumc458e941996-09-11 15:43:13 +000021867.6. Q. Where are the source or Makefiles for the non-UNIX versions?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002187
Guido van Rossume530c581995-04-10 12:32:16 +00002188A. The standard sources can (almost) be used. Additional sources can
2189be found in the platform-specific subdirectories of the distribution.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002190
Guido van Rossumc458e941996-09-11 15:43:13 +000021917.7. Q. What is the status and support for the non-UNIX versions?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002192
2193A. I don't have access to most of these platforms, so in general I am
2194dependent on material submitted by volunteers(*). However I strive to
2195integrate all changes needed to get it to compile on a particular
2196platform back into the standard sources, so porting of the next
2197version to the various non-UNIX platforms should be easy.
2198
Guido van Rossuma6c707c1995-01-02 17:32:28 +00002199(*) For the Macintosh, that volunteer is me, with help from Jack
2200Jansen <jack@cwi.nl>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002201
Guido van Rossumc458e941996-09-11 15:43:13 +000022027.8. Q. I have a PC version but it appears to be only a binary.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00002203Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002204
2205A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +00002206"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossume530c581995-04-10 12:32:16 +00002207you can get the file lib<version>.tar.gz from most ftp sites carrying
2208Python; this is a subset of the distribution containing just those
Guido van Rossum7be34a81995-05-31 15:17:12 +00002209files, e.g. <URL:ftp://ftp.python.org/pub/python/src/lib1.1.tar.gz>.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002210
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002211Once you have installed the library, you need to point sys.path to it.
2212Assuming the library is in C:\misc\python\lib, the following commands
2213will point your Python interpreter to it (note the doubled backslashes
2214-- you can also use single forward slashes instead):
2215
Guido van Rossuma6c707c1995-01-02 17:32:28 +00002216 >>> import sys
2217 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
2218 >>>
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002219
2220For a more permanent effect, set the environment variable PYTHONPATH,
2221as follows (talking to a DOS prompt):
2222
Guido van Rossuma6c707c1995-01-02 17:32:28 +00002223 C> SET PYTHONPATH=C:\misc\python\lib
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002224
Guido van Rossumc458e941996-09-11 15:43:13 +000022257.9. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002226
Guido van Rossume530c581995-04-10 12:32:16 +00002227A. The documentation for the Unix version also applies to the Mac and
2228PC versions. Where applicable, differences are indicated in the text.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002229
Guido van Rossumc458e941996-09-11 15:43:13 +000022307.10. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +00002231creating or editing programs apart from entering it interactively, and
2232there seems to be no way to save code that was entered interactively.
2233How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002234
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002235A. Use an external editor. On the Mac, BBEdit seems to be a popular
2236no-frills text editor. I work like this: start the interpreter; edit
2237a module file using BBedit; import and test it in the interpreter;
2238edit again in BBedit; then use the built-in function reload() to
2239re-read the imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002240
2241Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
2242anyone with a pulse could certainly figure out how to do the same on
2243MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
2244Not only can you easily resave and "reload()" from Python after making
2245changes, but since WinNot auto-copies to the clipboard any text you
2246select, you can simply select the entire procedure (function) which
2247you changed in WinNot, switch to QWPython, and shift-ins to reenter
2248the changed program unit."