blob: 5a34c7f493a9b8053bf61667eb6159db3fd36f6c [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/>
325
326Europe:
327
328 <URL:ftp://ftp.cwi.nl/pub/python/>
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000329 <URL:ftp://ftp.funet.fi/pub/languages/python/>
330 <URL:ftp://ftp.sunet.se/pub/lang/python/>
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000331 <URL:ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/>
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000332 <URL:ftp://ftp.ibp.fr/pub/python/>
Guido van Rossum79413791996-12-05 22:01:11 +0000333 <URL:ftp://sunsite.cnlab-switch.ch/mirror/python/>
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000334 <URL:ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/>
Guido van Rossuma7925f11994-01-26 10:20:16 +0000335
Guido van Rossume7d92d51995-10-11 18:06:54 +0000336Australia:
337
338 <URL:ftp://ftp.dstc.edu.au/pub/python/>
339
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000340Or try archie on the string "python".
Guido van Rossuma7925f11994-01-26 10:20:16 +0000341
Guido van Rossumc50158e1994-05-31 09:18:50 +00003421.6. Q. Is there a newsgroup or mailing list devoted to Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000343
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000344A. There is a newsgroup, comp.lang.python <URL:news:comp.lang.python>,
345and a mailing list. The newsgroup and mailing list are gatewayed into
346each other -- if you can read news it's unnecessary to subscribe to
347the mailing list. Send e-mail to <python-list-request@cwi.nl> to
Guido van Rossume530c581995-04-10 12:32:16 +0000348(un)subscribe to the mailing list. Hypermail archives of (nearly)
349everything posted to the mailing list (and thus the newsgroup) are
350available on our WWW server,
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000351<URL:http://www.cwi.nl/~guido/hypermail/index.html>. The raw archives
352are also available by ftp, e.g.
Guido van Rossum7be34a81995-05-31 15:17:12 +0000353<URL:ftp://ftp.python.org/pub/python/mail/mailinglist.gz>. The
Guido van Rossume530c581995-04-10 12:32:16 +0000354uncompressed versions of these files can be read with the standard
355UNIX Mail program ("Mail -f file") or with nn ("nn file"). To read
Guido van Rossumbf8e7d51995-08-28 03:09:13 +0000356them using MH, you could use "inc -file file". (The archival service
357has stopped archiving new articles around the end of April 1995. I
358hope to revive it on the PSA server www.python.org sometime in the
359future.)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000360
Guido van Rossuma6c707c1995-01-02 17:32:28 +00003611.7. Q. Is there a WWW page devoted to Python?
362
Guido van Rossum7be34a81995-05-31 15:17:12 +0000363A. Yes, <URL:http://www.python.org/> is the official Python home page.
364At the time of writing, this page is not yet completely operational;
365you may have a look at the old Python home page:
366<URL:http://www.cwi.nl/~guido/Python.html> or at the U.S. copy:
367<URL:http://www.python.org/~guido/Python.html>.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000368
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00003691.8. Q. Is the Python documentation available on the WWW?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000370
Guido van Rossum7be34a81995-05-31 15:17:12 +0000371A. Yes, see <URL:http://www.python.org/> (Python's home page). It
372contains pointers to hypertext versions of the whole documentation set
373(as hypertext, not just PostScript).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000374
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000375If you wish to browse this collection of HTML files on your own
376machine, it is available bundled up by anonymous ftp,
Guido van Rossum7be34a81995-05-31 15:17:12 +0000377e.g. <URL:ftp://ftp.python.org/pub/python/doc/html.tar.gz>.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000378
379An Emacs-INFO set containing the library manual is also available by
Guido van Rossum7be34a81995-05-31 15:17:12 +0000380ftp, e.g. <URL:ftp://ftp.python.org/pub/python/doc/lib-info.tar.gz>.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000381
3821.9. Q. Is there a book on Python, or will there be one out soon?
383
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000384A. Mark Lutz is writing a Python book for O'Reilly and Associates, to
385be published early 1996. See the outline (in PostScript):
386<URL:http://www.python.org/workshops/1995-05/outlinep.eps>.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000387
3881.10. Q. Are there any published articles about Python that I can quote?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000389
390A. So far the only refereed and published article that describes
391Python in some detail is:
392
393 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
394 Servers Using the Python Programming Language", CWI Quarterly, Volume
395 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
396
397LaTeX source for this paper is available as part of the Python source
398distribution.
399
Guido van Rossum05151e01995-09-28 13:24:46 +0000400See also the next section (supposedly Aaron Watters' paper has been
401refereed).
402
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00004031.11. Q. Are there short introductory papers or talks on Python?
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000404
Guido van Rossum05151e01995-09-28 13:24:46 +0000405A. A recent, very entertaining introduction to Python is the tutorial by
406Aaron Watters in UnixWorld Online:
407
408 Aaron R. Watters: "The What, Why, Who, and Where of Python",
409 <URL:http://www.wcmh.com/uworld/archives/95/tutorial/005.html>
410
411An olded paper is:
Guido van Rossuma7925f11994-01-26 10:20:16 +0000412
413 Guido van Rossum, "An Introduction to Python for UNIX/C
414 Programmers", in the proceedings of the NLUUG najaarsconferentie
Guido van Rossum061f1821994-10-06 16:03:45 +0000415 1993 (dutch UNIX users group meeting November 1993).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000416
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000417PostScript for this paper and for the slides used for the accompanying
418presentation is available by ftp as
Guido van Rossum7be34a81995-05-31 15:17:12 +0000419<URL:ftp://ftp.python.org/pub/python/doc/nluug-paper.ps> and
420<URL:ftp://ftp.python.org/pub/python/doc/nluug-slides.ps>, respectively.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000421
422Slides for a talk on Python that I gave at the Usenix Symposium on
Guido van Rossum05151e01995-09-28 13:24:46 +0000423Very High Level Languages in Santa Fe, NM, USA in October 1994 are
Guido van Rossum7be34a81995-05-31 15:17:12 +0000424available as <URL:ftp://ftp.python.org/pub/python/doc/vhll-slides.ps>.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000425
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00004261.12. Q. How does the Python version numbering scheme work?
Guido van Rossum95f61a71994-01-26 17:23:37 +0000427
Guido van Rossum05151e01995-09-28 13:24:46 +0000428A. Python versions are numbered A.B.C or A.B. A is the major version
429number -- it is only incremented for major changes in functionality or
430source structure. B is the minor version number, incremented for less
Guido van Rossum95f61a71994-01-26 17:23:37 +0000431earth-shattering changes to a release. C is the patchlevel -- it is
Guido van Rossum05151e01995-09-28 13:24:46 +0000432incremented for each new patch release. Not all releases have patch
433releases. Note that in the past, patches have added significant
434changes; in fact the changeover from 0.9.9 to 1.0.0 was the first time
435that either A or B changed!
Guido van Rossum95f61a71994-01-26 17:23:37 +0000436
Guido van Rossum8727df41996-09-09 15:16:39 +0000437Beta versions have an additional suffix of "betaN" for some small
438number N. Note that (for instance) all versions labeled 1.4betaN
439*precede* the actual release of 1.4. 1.4b3 is short for 1.4beta3.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000440
4411.13. Q. How do I get a beta test version of Python?
442
Guido van Rossum05151e01995-09-28 13:24:46 +0000443A. If there are any beta releases, they are published in the normal
444source directory (e.g. <URL:ftp://ftp.python.org/pub/python/src/>).
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +0000445
Guido van Rossum05151e01995-09-28 13:24:46 +00004461.14. Q. Are there copyright restrictions on the use of Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000447
448A. Hardly. You can do anything you want with the source, as long as
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000449you leave the copyrights in, and display those copyrights in any
450documentation about Python that you produce. Also, don't use the
451author's institute's name in publicity without prior written
452permission, and don't hold them responsible for anything (read the
453actual copyright for a precise legal wording).
454
455In particular, if you honor the copyright rules, it's OK to use Python
456for commercial use, to sell copies of Python in source or binary form,
457or to sell products that enhance Python or incorporate Python (or part
458of it) in some form. I would still like to know about all commercial
459use of Python!
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000460
Guido van Rossum05151e01995-09-28 13:24:46 +00004611.15. Q. Why was Python created in the first place?
Guido van Rossum7be34a81995-05-31 15:17:12 +0000462
463A. Here's a *very* brief summary of what got me started:
464
465- I had extensive experience with implementing an interpreted language
466in the ABC group at CWI, and from working with this group I had
467learned a lot about language design. This is the origin of many
468Python features, including the use of indentation for statement
469grouping and the inclusion of very-high-level data types (although the
470details are all different in Python).
471
472- I had a number of gripes about the ABC language, but also liked many
473of its features. It was impossible to extend the ABC language (or its
474implementation) to remedy my complaints -- in fact its lack of
475extensibility was one of its biggest problems.
476
477- I had some experience with using Modula-2+ and talked with the
478designers of Modula-3 (and read the M3 report). M3 is the origin of
479the syntax and semantics used for exceptions, and some other Python
480features.
481
482- I was working in the Amoeba distributed operating system group at
483CWI. We needed a better way to do system administration than by
484writing either C programs or Bourne shell scripts, since Amoeba had
485its own system call interface which wasn't easily accessible from the
Guido van Rossumbf8e7d51995-08-28 03:09:13 +0000486Bourne shell. My experience with error handling in Amoeba made me
487acutely aware of the importance of exceptions as a programming
488language feature.
Guido van Rossum7be34a81995-05-31 15:17:12 +0000489
490- It occurred to me that a scripting language with a syntax like ABC
491but with access to the Amoeba system calls would fill the need. I
492realized that it would be foolish to write an Amoeba-specific
493language, so I decided that I needed a language that was generally
494extensible.
495
496- During the 1989 Christmas holidays, I had a lot of time on my hand,
497so I decided to give it a try. During the next year, while still
498mostly working on it in my own time, Python was used in the Amoeba
499project with increasing success, and the feedback from colleagues made
500me add many early improvements.
501
502- In February 1991, after just over a year of development, I decided
503to post to USENET. The rest is in the Misc/HISTORY file.
504
Guido van Rossuma7925f11994-01-26 10:20:16 +0000505
5062. Python in the real world
507===========================
508
5092.1. Q. How many people are using Python?
510
Guido van Rossum5333c5d1994-04-11 11:06:22 +0000511A. I don't know, but the maximum number of simultaneous subscriptions
512to the Python mailing list before it was gatewayed into the newsgroup
513was about 180 (several of which were local redistribution lists). I
514believe that many active Python users don't bother to subscribe to the
515list, and now that there's a newsgroup the mailing list subscription
Guido van Rossum7ce61c11994-06-13 15:13:56 +0000516is even less meaningful. I see new names on the newsgroup all the
517time and my best guess is that there are currently at least several
518thousands of users.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000519
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000520Another statistic is the number of accesses to the Python WWW server.
521Have a look at <URL:http://www.python.org/stats/>.
522
Guido van Rossuma7925f11994-01-26 10:20:16 +00005232.2. Q. Have any significant projects been done in Python?
524
525A. Here at CWI (the home of Python), we have written a 20,000 line
526authoring environment for transportable hypermedia presentations, a
Guido van Rossum5333c5d1994-04-11 11:06:22 +00005275,000 line multimedia teleconferencing tool, as well as many many
528smaller programs.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000529
530The University of Virginia uses Python to control a virtual reality
531engine. Contact: Matt Conway <conway@virginia.edu>.
532
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000533The ILU project at Xerox PARC can generate Python glue for ILU
534interfaces. See <URL:ftp://ftp.parc.xerox.com/pub/ilu/ilu.html>.
535
Guido van Rossumac3f2121995-04-10 11:53:42 +0000536The University of California, Irvine uses a student administration
537system called TELE-Vision written entirely in Python. Contact: Ray
538Price <rlprice@uci.edu>.
539
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000540See also the next question.
541
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000542If you have done a significant project in Python that you'd like to be
543included in the list above, send me email!
Guido van Rossuma7925f11994-01-26 10:20:16 +0000544
5452.3. Q. Are there any commercial projects going on using Python?
546
547A. Several companies have revealed to me that they are planning or
Guido van Rossum796b2591995-01-20 23:05:52 +0000548considering use of Python in a future product.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000549
Guido van Rossumbf8e7d51995-08-28 03:09:13 +0000550Sunrise Software has a product out using Python -- they use Python
Guido van Rossumac3f2121995-04-10 11:53:42 +0000551for a GUI management application and an SNMP network management
552application. Contact: <info@sunrise.com>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000553
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000554Infoseek uses Python to implement their commercial WWW information
555retrieval service <URL:http://www.infoseek.com/>. Contact:
556<info@infoseek.com>.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000557
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000558Paul Everitt of Connecting Minds is planning a Lotus Notes gateway.
559Contact: <Paul.Everitt@cminds.com>. Or see their WWW server
560<URL:http://www.cminds.com/>.
561
Guido van Rossumac3f2121995-04-10 11:53:42 +0000562KaPRE in Boulder, CO is using Python for on-site customization of C++
563applications, rapid-prototyping/development,
564language-based-components, and possibly more. This is pretty solid:
565Python's being shipped with their tool-set now, to beta sites.
566Contact: <lutz@KaPRE.COM> (Mark Lutz).
567
568Individuals at many other companies are using Python for internal
569development or for as yet unannounced products (witness their
570contributions to the Python mailing list or newsgroup).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000571
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000572SGI has advertised in the Python list looking for Python programmers
573for a project involving interactive television.
574
575See also the workshop minutes at
576<URL:http://www.python.org/workshops/> -- in general the WWW server is
577more up to date than the FAQ for these issues.
578
Guido van Rossuma7925f11994-01-26 10:20:16 +0000579Python has also been elected as an extension language by MADE, a
580consortium supported by the European Committee's ESPRIT program and
581consisting of Bull, CWI and some other European companies. Contact:
582Ivan Herman <ivan@cwi.nl>.
583
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000584If you'd like to be included in the list above, send me email!
585
Guido van Rossum95f61a71994-01-26 17:23:37 +00005862.4. Q. How stable is Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000587
Guido van Rossum3de27361994-07-25 14:19:33 +0000588A. Very stable. While the current version number would suggest it is
589in the early stages of development, in fact new, stable releases
Guido van Rossumba469ba1996-12-05 22:26:17 +0000590(numbered 0.9.x through 1.4) have been coming out roughly every 3 to
5916 or 12 months for the past four years.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000592
Guido van Rossum8727df41996-09-09 15:16:39 +00005932.5. Q. What new developments are expected for Python in the future?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000594
Guido van Rossumba469ba1996-12-05 22:26:17 +0000595A. Follow the newsgroup discussions! The workshop proceedings
596(<URL:http://www.python.org/workshops/>) may also contain interesting
597looks into the future.
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000598
Guido van Rossum8727df41996-09-09 15:16:39 +00005992.6. Q. Is it reasonable to propose incompatible changes to Python?
Guido van Rossum3de27361994-07-25 14:19:33 +0000600
601A. In general, no. There are already millions of lines of Python code
602around the world, so any changes in the language that invalidates more
603than a very small fraction of existing programs has to be frowned
604upon. Even if you can provide a conversion program, there still is
605the problem of updating all documentation. Providing a gradual
606upgrade path is the only way if a feature has to be changed.
607
Guido van Rossum8727df41996-09-09 15:16:39 +00006082.7. Q. What is the future of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000609
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000610A. If I knew, I'd be rich :-)
611
612Seriously, the formation of the PSA (Pyton Software Activity, see
613<URL:http://www.python.org/psa/>) ensures some kind of support even in
614the (unlikely! event that I'd be hit by a bus (actually, here in the
615US, a car accident would be more likely :-), were to join a nunnery,
616or would be head-hunted. A large number of Python users have become
617experts at Python programming as well as maintenance of the
618implementation, and would easily fill the vacuum created by my
619disappearance.
620
621In the mean time, I have no plans to disappear -- rather, I am
622committed to improving Python, and my current benefactor, CNRI (see
623<URL:http://www.cnri.reston.va.us>) is just as committed to continue
624its support of Python and the PSA. In fact, we have great plans for
625Python -- we just can't tell yet!
626
Guido van Rossum8727df41996-09-09 15:16:39 +00006272.8. Q. What is the PSA, anyway?
Guido van Rossum05151e01995-09-28 13:24:46 +0000628
629A. The Python Software Activity <URL:http://www.python.org/psa/> was
630created by a number of Python aficionados who want Python to be more
631than the product and responsibility of a single individual. It has
632found a home at CNRI <URL:http://www.cnri.reston.va.us>. Anybody who
633wishes Python well should join the PSA.
634
Guido van Rossum8727df41996-09-09 15:16:39 +00006352.9. Q. How do I join the PSA?
Guido van Rossum05151e01995-09-28 13:24:46 +0000636
637A. The full scoop is available on the web, see
638<URL:http://www.python.org/psa/Joining.html>. Summary: send a check
639of at least $50 to CNRI/PSA, 1895 Preston White Drive, Suite 100, in
Guido van Rossum81300541996-09-06 16:37:56 +0000640Reston, VA 20191. Full-time students pay $25. Companies can join for
Guido van Rossum05151e01995-09-28 13:24:46 +0000641a mere $500.
642
Guido van Rossum8727df41996-09-09 15:16:39 +00006432.10. Q. What are the benefits of joining the PSA?
Guido van Rossum05151e01995-09-28 13:24:46 +0000644
645A. Like National Public Radio, if not enough people join, Python will
646wither. Your name will be mentioned on the PSA's web server.
647Workshops organized by the PSA <URL:http://www.python.org/workshops/>
648are only accessible to PSA members (you can join at the door). The
649PSA is working on additional benefits, such as reduced prices for
650books and software, and early access to beta versions of Python.
651
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000652
6533. Building Python and Other Known Bugs
654=======================================
Guido van Rossuma7925f11994-01-26 10:20:16 +0000655
Guido van Rossum91f60831994-02-15 15:52:27 +00006563.1. Q. Is there a test set?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000657
658A. Yes, simply do "import testall" (or "import autotest" if you aren't
659interested in the output). The standard modules whose name begins
660with "test" together comprise the test. The test set doesn't test
661*all* features of Python but it goes a long way to confirm that a new
662port is actually working. The Makefile contains an entry "make test"
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000663which runs the autotest module. NOTE: if "make test" fails, run the
664tests manually ("import testall") to see what goes wrong before
665reporting the error.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000666
Guido van Rossum91f60831994-02-15 15:52:27 +00006673.2. Q. When running the test set, I get complaints about floating point
Guido van Rossuma7925f11994-01-26 10:20:16 +0000668operations, but when playing with floating point operations I cannot
669find anything wrong with them.
670
671A. The test set makes occasional unwarranted assumptions about the
672semantics of C floating point operations. Until someone donates a
673better floating point test set, you will have to comment out the
674offending floating point tests and execute similar tests manually.
675
Guido van Rossum7be34a81995-05-31 15:17:12 +00006763.3. Q. Link errors after rerunning the configure script.
Guido van Rossum24349991994-02-02 14:12:45 +0000677
678A. It is generally necessary to run "make clean" after a configuration
679change.
680
Guido van Rossum7be34a81995-05-31 15:17:12 +00006813.4. Q. The python interpreter complains about options passed to a
Guido van Rossum24349991994-02-02 14:12:45 +0000682script (after the script name).
683
684A. You are probably linking with GNU getopt, e.g. through -liberty.
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000685Don't. The reason for the complaint is that GNU getopt, unlike System
686V getopt and other getopt implementations, doesn't consider a
687non-option to be the end of the option list. A quick (and compatible)
688fix for scripts is to add "--" to the interpreter, like this:
689
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000690 #! /usr/local/bin/python --
Guido van Rossumf8c76d01994-08-17 12:19:53 +0000691
692You can also use this interactively:
693
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000694 python -- script.py [options]
695
696Note that a working getopt implementation is provided in the Python
697distribution (in Python/getopt.c) but not automatically used.
Guido van Rossum24349991994-02-02 14:12:45 +0000698
Guido van Rossum7be34a81995-05-31 15:17:12 +00006993.5. Q. When building on the SGI, make tries to run python to create
Guido van Rossum24349991994-02-02 14:12:45 +0000700glmodule.c, but python hasn't been built or installed yet.
701
702A. Comment out the line mentioning glmodule.c in Setup and build a
703python without gl first; install it or make sure it is in your $PATH,
704then edit the Setup file again to turn on the gl module, and make
705again. You don't need to do "make clean"; you do need to run "make
706Makefile" in the Modules subdirectory (or just run "make" at the
707toplevel).
708
Guido van Rossum8727df41996-09-09 15:16:39 +00007093.6. Q. I use VPATH but some targets are built in the source directory.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000710
711A. On some systems (e.g. Sun), if the target already exists in the
712source directory, it is created there instead of in the build
713directory. This is usually because you have previously built without
714VPATH. Try running "make clobber" in the source directory.
715
Guido van Rossum8727df41996-09-09 15:16:39 +00007163.7. Q. Trouble building or linking with the GNU readline library.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000717
Guido van Rossumac3f2121995-04-10 11:53:42 +0000718A. Consider using readline 2.0. Some hints:
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000719
720- You can use the GNU readline library to improve the interactive user
721interface: this gives you line editing and command history when
Guido van Rossum796b2591995-01-20 23:05:52 +0000722calling python interactively. You need to configure and build the GNU
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000723readline library before running the configure script. Its sources are
724no longer distributed with Python; you can ftp them from any GNU
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000725mirror site, or from its home site
726<URL:ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz> (or a
727higher version number -- using version 1.x is not recommended). Pass
728the Python configure script the option --with-readline=DIRECTORY where
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000729DIRECTORY is the absolute pathname of the directory where you've built
730the readline library. Some hints on building and using the readline
731library:
732
733- On SGI IRIX 5, you may have to add the following
734to rldefs.h:
735
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000736 #ifndef sigmask
737 #define sigmask(sig) (1L << ((sig)-1))
738 #endif
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000739
740- On most systems, you will have to add #include "rldefs.h" to the
741top of several source files, and if you use the VPATH feature, you
742will have to add dependencies of the form foo.o: foo.c to the
743Makefile for several values of foo.
744
745- The readline library requires use of the termcap library. A
746known problem with this is that it contains entry points which
Guido van Rossum061f1821994-10-06 16:03:45 +0000747cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000748conflict can be solved (and will be, in the next release of
Guido van Rossum061f1821994-10-06 16:03:45 +0000749STDWIN) by adding a line saying '#define werase w_erase' to the
750stdwin.h file (in the STDWIN distribution, subdirectory H). The
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000751GL conflict has been solved in the Python configure script by a
752hack that forces use of the static version of the termcap library.
753
Guido van Rossumac3f2121995-04-10 11:53:42 +0000754- Check the newsgroup gnu.bash.bug <URL:news:gnu.bash.bug> for
755specific problems with the readline library (I don't read this group
756but I've been told that it is the place for readline bugs).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000757
Guido van Rossum8727df41996-09-09 15:16:39 +00007583.8. Q. Trouble with socket I/O on older Linux 1.x versions.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000759
760A. Once you've built Python, use it to run the regen.py script in the
761Lib/linux1 directory. Apparently the files as distributed don't match
762the system headers on some Linux versions.
763
Guido van Rossum8727df41996-09-09 15:16:39 +00007643.9. Q. Trouble with prototypes on Ultrix.
Guido van Rossum72eb83c1994-10-07 11:33:28 +0000765
766A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef
767HAVE_PROTOTYPES.
768
Guido van Rossum8a913021996-10-08 17:18:30 +00007693.10. Q. Other trouble building Python on platform X.
Guido van Rossum95f61a71994-01-26 17:23:37 +0000770
Guido van Rossum81300541996-09-06 16:37:56 +0000771A. Please email the details to <guido@cnri.reston.va.us> and I'll look
772into it. Please provide as many details as possible. In particular,
773if you don't tell me what type of computer and what operating system
774(and version) you are using it will be difficult for me to figure out
775what is the matter. If you get a specific error message, please email
776it to me too.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000777
Guido van Rossum8a913021996-10-08 17:18:30 +00007783.11. Q. How to configure dynamic loading on Linux.
Guido van Rossum07779351995-02-07 16:59:56 +0000779
Guido van Rossum8727df41996-09-09 15:16:39 +0000780A. This is now automatic as long as your Linux version uses the ELF
781object format (all recent Linuxes do).
Guido van Rossum07779351995-02-07 16:59:56 +0000782
Guido van Rossum9c5dc291996-10-13 15:48:56 +00007833.12. Q: I can't get shared modules to work on Linux 2.0 (Slackware96)?
784
785A: This is a bug in the Slackware96 release. The fix is simple:
786
787Make sure that there is a link from /lib/libdl.so to /lib/libdl.so.1
788so that the following links are setup:
789
790 /lib/libdl.so -> /lib/libdl.so.1
791 /lib/libdl.so.1 -> /lib/libdl.so.1.7.14
792
Guido van Rossumcaa83c41996-11-13 15:06:24 +00007933.13. Q: Trouble when making modules shared on Linux.
794
795A. This happens when you have built Python for static linking and then
796enable *shared* in the Setup file. Shared library code must be
797compiled with "-fpic". If a .o file for the module already exist that
798was compiled for static linking, you must remove it or do "make clean"
799in the Modules directory.
800
8013.14. Q. How to use threads on Linux.
Guido van Rossum9e0e4dd1996-10-23 20:52:55 +0000802
803A. [Greg Stein] I built myself a libpthreads.so from the libc.5.3.12
804distribution (the binary distribution doesn't have pthreads in
805it). Then, I configured Python with --with-threads and then tweaked
806config.h to include a #define _MIT_POSIX_THREADS (or something like
807that, see /usr/include/pthreads.h). It worked fine at that point.
808
809Note that I couldn't get threading to "operate well" with any of the
810other thread packages. Prior libc versions didn't integrate well with
811threads, either, so I couldn't use them (e.g. sleep() blocked all
812threads :-( ).
813
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008143.15. Q. Errors when linking with a shared library containing C++ code.
Guido van Rossum3fc9d731995-07-25 15:10:56 +0000815
816A. Link the main Python binary with C++. Change the definition of
817LINKCC in Modules/Makefile to be your C++ compiler. You may have to
818edit config.c slightly to make it compilable with C++.
Guido van Rossum07779351995-02-07 16:59:56 +0000819
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008203.16. Q. I built with tkintermodule.c enabled but get "Tkinter not found".
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000821
822A. Tkinter.py (note: upper case T) lives in a subdirectory of Lib,
823Lib/tkinter. If you are using the default module search path, you
824probably didn't enable the line in the Modules/Setup file defining
825TKPATH; if you use the environment variable PYTHONPATH, you'll have to
826add the proper tkinter subdirectory.
827
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008283.17. Q. I built with Tk 4.0 but Tkinter complains about the Tk version.
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000829
830A. Several things could cause this. You most likely have a Tk 3.6
831installation that wasn't completely eradicated by the Tk 4.0
832installation (which tends to add "4.0" to its installed files). You
833may have the Tk 3.6 support library installed in the place where the
834Tk 4.0 support files should be (default /usr/local/lib/tk/); you may
835have compiled Python with the old tk.h header file (yes, this actually
836compiles!); you may actually have linked with Tk 3.6 even though Tk
8374.0 is also around. Similar for Tcl 7.4 vs. Tcl 7.3.
838
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008393.18. Q. Link errors for Tcl/Tk symbols when linking with Tcl/Tk.
Guido van Rossum8727df41996-09-09 15:16:39 +0000840
841Quite possibly, there's a version mismatch between the Tcl/Tk header
842files (tcl.h and tk.h) and the tck/tk libraries you are using (the
843"-ltk4.0" and "-ltcl7.4" arguments for _tkinter in the Setup file).
844If you have installed both versions 7.4/4.0 and 7.5/4.1 of Tcl/Tk,
845most likely your header files are for The newer versions, but the
846Setup line for _tkinter in some Python distributions references
8477.4/4.0 by default. Changing this to 7.5/4.1 should take care of
848this.
849
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008503.19. Q. I configured and built Python for Tcl/Tk but "import Tkinter"
Guido van Rossum8727df41996-09-09 15:16:39 +0000851fails.
852
853A. Most likely, you forgot to enable the line in Setup that says
854"TKPATH=:$(DESTLIB)/tkinter".
855
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008563.20. Q. Tk doesn't work right on DEC Alpha.
Guido van Rossumb0a2ce51995-08-28 19:41:35 +0000857
858A. You probably compiled either Tcl, Tk or Python with gcc. Don't.
859For this platform, which has 64-bit integers, gcc is known to generate
860broken code. The standard cc (which comes bundled with the OS!)
861works. If you still prefer gcc, at least try recompiling with cc
862before reporting problems to the newsgroup or the author; if this
863fixes the problem, report the bug to the gcc developers instead. (As
864far as we know, there are no problem with gcc on other platforms --
865the instabilities seem to be restricted to the DEC Alpha.) See also
866question 3.6.
867
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008683.21. Q. Several common system calls are missing from the posix module.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000869
870A. Most likely, *all* test compilations run by the configure script
871are failing for some reason or another. Have a look in config.log to
872see what could be the reason. A common reason is specifying a
873directory to the --with-readline option that doesn't contain the
874libreadline.a file.
875
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008763.22. Q. ImportError: No module named string, on MS Windows.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000877
878A. Most likely, your PYTHONPATH environment variable should be set to
879something like:
880
881set PYTHONPATH=c:\python;c:\python\lib;c:\python\scripts
882
883(assuming Python was installed in c:\python)
884
Guido van Rossumcaa83c41996-11-13 15:06:24 +00008853.23. Q. Core dump on SGI when using the gl module.
Guido van Rossumca318ec1996-06-26 19:50:09 +0000886
887There are conflicts between entry points in the termcap and curses
888libraries and an entry point in the GL library. There's a hack of a
889fix for the termcap library if it's needed for the GNU readline
890library, but it doesn't work when you're using curses. Concluding,
891you can't build a Python binary containing both the curses and gl
892modules.
893
894
Guido van Rossuma7925f11994-01-26 10:20:16 +0000895
8964. Programming in Python
897========================
898
Guido van Rossum24349991994-02-02 14:12:45 +00008994.1. Q. Is there a source code level debugger with breakpoints, step,
900etc.?
901
902A. Yes. Check out module pdb; pdb.help() prints the documentation (or
903you can read it as Lib/pdb.doc). If you use the STDWIN option,
904there's also a windowing interface, wdb. You can write your own
905debugger by using the code for pdb or wdb as an example.
906
9074.2. Q. Can I create an object class with some methods implemented in
Guido van Rossuma7925f11994-01-26 10:20:16 +0000908C and others in Python (e.g. through inheritance)? (Also phrased as:
909Can I use a built-in type as base class?)
910
911A. No, but you can easily create a Python class which serves as a
912wrapper around a built-in object, e.g. (for dictionaries):
913
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000914 # A user-defined class behaving almost identical
915 # to a built-in dictionary.
916 class UserDict:
917 def __init__(self): self.data = {}
918 def __repr__(self): return repr(self.data)
919 def __cmp__(self, dict):
920 if type(dict) == type(self.data):
921 return cmp(self.data, dict)
922 else:
923 return cmp(self.data, dict.data)
924 def __len__(self): return len(self.data)
925 def __getitem__(self, key): return self.data[key]
926 def __setitem__(self, key, item): self.data[key] = item
927 def __delitem__(self, key): del self.data[key]
928 def keys(self): return self.data.keys()
929 def items(self): return self.data.items()
930 def values(self): return self.data.values()
931 def has_key(self, key): return self.data.has_key(key)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000932
Guido van Rossum24349991994-02-02 14:12:45 +00009334.3. Q. Is there a curses/termcap package for Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000934
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000935A. Yes -- Lance Ellinghaus has written a module that interfaces to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000936System V's "ncurses". If you know a little curses and some Python,
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000937it's straightforward to use. It is part of the standard Python
938distribution, but not configured by default -- you must enable it by
939editing Modules/Setup. It requires a System V curses implementation.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000940
941You could also consider using the "alfa" (== character cell) version
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000942of STDWIN. (Standard Window System Interface, a portable windowing
943system interface by myself <URL:ftp://ftp.cwi.nl/pub/stdwin/>.) This
Guido van Rossumb34e8aa1994-09-23 14:20:38 +0000944will also prepare your program for porting to windowing environments
945such as X11 or the Macintosh.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000946
Guido van Rossum24349991994-02-02 14:12:45 +00009474.4. Q. Is there an equivalent to C's onexit() in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000948
949A. Yes, if you import sys and assign a function to sys.exitfunc, it
950will be called when your program exits, is killed by an unhandled
951exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
952
Guido van Rossum24349991994-02-02 14:12:45 +00009534.5. Q. When I define a function nested inside another function, the
Guido van Rossuma7925f11994-01-26 10:20:16 +0000954nested function seemingly can't access the local variables of the
955outer function. What is going on? How do I pass local data to a
956nested function?
957
958A. Python does not have arbitrarily nested scopes. When you need to
959create a function that needs to access some data which you have
960available locally, create a new class to hold the data and return a
961method of an instance of that class, e.g.:
962
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000963 class MultiplierClass:
964 def __init__(self, factor):
965 self.factor = factor
966 def multiplier(self, argument):
967 return argument * self.factor
Guido van Rossuma7925f11994-01-26 10:20:16 +0000968
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000969 def generate_multiplier(factor):
970 return MultiplierClass(factor).multiplier
Guido van Rossuma7925f11994-01-26 10:20:16 +0000971
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000972 twice = generate_multiplier(2)
973 print twice(10)
974 # Output: 20
975
976An alternative solution uses default arguments, e.g.:
977
978 def generate_multiplier(factor):
979 def multiplier(arg, fact = factor):
980 return arg*fact
981 return multiplier
982
983 twice = generate_multiplier(2)
984 print twice(10)
985 # Output: 20
Guido van Rossuma7925f11994-01-26 10:20:16 +0000986
Guido van Rossum24349991994-02-02 14:12:45 +00009874.6. Q. How do I iterate over a sequence in reverse order?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000988
989A. If it is a list, the fastest solution is
990
Guido van Rossuma6c707c1995-01-02 17:32:28 +0000991 list.reverse()
992 try:
993 for x in list:
994 "do something with x"
995 finally:
996 list.reverse()
Guido van Rossuma7925f11994-01-26 10:20:16 +0000997
998This has the disadvantage that while you are in the loop, the list
999is temporarily reversed. If you don't like this, you can make a copy.
1000This appears expensive but is actually faster than other solutions:
1001
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001002 rev = list[:]
1003 rev.reverse()
1004 for x in rev:
1005 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +00001006
1007If it isn't a list, a more general but slower solution is:
1008
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001009 i = len(list)
1010 while i > 0:
1011 i = i-1
1012 x = list[i]
1013 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +00001014
1015A more elegant solution, is to define a class which acts as a sequence
1016and yields the elements in reverse order (solution due to Steve
1017Majewski):
1018
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001019 class Rev:
1020 def __init__(self, seq):
1021 self.forw = seq
1022 def __len__(self):
1023 return len(self.forw)
1024 def __getitem__(self, i):
1025 return self.forw[-(i + 1)]
Guido van Rossuma7925f11994-01-26 10:20:16 +00001026
1027You can now simply write:
1028
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001029 for x in Rev(list):
1030 <do something with x>
Guido van Rossuma7925f11994-01-26 10:20:16 +00001031
Guido van Rossum061f1821994-10-06 16:03:45 +00001032Unfortunately, this solution is slowest of all, due to the method
Guido van Rossuma7925f11994-01-26 10:20:16 +00001033call overhead...
1034
Guido van Rossum24349991994-02-02 14:12:45 +000010354.7. Q. My program is too slow. How do I speed it up?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001036
1037A. That's a tough one, in general. There are many tricks to speed up
1038Python code; I would consider rewriting parts in C only as a last
1039resort. One thing to notice is that function and (especially) method
1040calls are rather expensive; if you have designed a purely OO interface
1041with lots of tiny functions that don't do much more than get or set an
1042instance variable or call another method, you may consider using a
1043more direct way, e.g. directly accessing instance variables. Also see
1044the standard module "profile" (described in the file
1045"python/lib/profile.doc") which makes it possible to find out where
1046your program is spending most of its time (if you have some patience
1047-- the profiling itself can slow your program down by an order of
1048magnitude).
1049
Guido van Rossum24349991994-02-02 14:12:45 +000010504.8. Q. When I have imported a module, then edit it, and import it
Guido van Rossuma7925f11994-01-26 10:20:16 +00001051again (into the same Python process), the changes don't seem to take
1052place. What is going on?
1053
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001054A. For reasons of efficiency as well as consistency, Python only reads
Guido van Rossum796b2591995-01-20 23:05:52 +00001055the module file on the first time a module is imported. (Otherwise a
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001056program consisting of many modules, each of which imports the same
Guido van Rossum796b2591995-01-20 23:05:52 +00001057basic module, would read the basic module over and over again.) To
1058force rereading of a changed module, do this:
Guido van Rossuma7925f11994-01-26 10:20:16 +00001059
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001060 import modname
1061 reload(modname)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001062
1063Warning: this technique is not 100% fool-proof. In particular,
1064modules containing statements like
1065
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001066 from modname import some_objects
Guido van Rossuma7925f11994-01-26 10:20:16 +00001067
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001068will continue to work with the old version of the imported objects.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001069
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000010704.9. Q. How do I find the current module name?
Guido van Rossum24349991994-02-02 14:12:45 +00001071
Guido van Rossum061f1821994-10-06 16:03:45 +00001072A. A module can find out its own module name by looking at the
Guido van Rossum24349991994-02-02 14:12:45 +00001073(predefined) global variable __name__. If this has the value
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001074'__main__' you are running as a script.
1075
Guido van Rossuma6c707c1995-01-02 17:32:28 +000010764.10. Q. I have a module in which I want to execute some extra code
1077when it is run as a script. How do I find out whether I am running as
1078a script?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001079
1080A. See the previous question. E.g. if you put the following on the
1081last line of your module, main() is called only when your module is
1082running as a script:
Guido van Rossum24349991994-02-02 14:12:45 +00001083
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001084 if __name__ == '__main__': main()
Guido van Rossum24349991994-02-02 14:12:45 +00001085
Guido van Rossuma6c707c1995-01-02 17:32:28 +000010864.11. Q. I try to run a program from the Demo directory but it fails
1087with ImportError: No module named ...; what gives?
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001088
Guido van Rossum061f1821994-10-06 16:03:45 +00001089A. This is probably an optional module (written in C!) which hasn't
1090been configured on your system. This especially happens with modules
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001091like "Tkinter", "stdwin", "gl", "Xt" or "Xm". For Tkinter, STDWIN and
1092many other modules, see Modules/Setup.in for info on how to add these
1093modules to your Python, if it is possible at all. Sometimes you will
1094have to ftp and build another package first (e.g. STDWIN). Sometimes
1095the module only works on specific platforms (e.g. gl only works on SGI
1096machines).
1097
1098NOTE: if the complaint is about "Tkinter" (upper case T) and you have
Guido van Rossumca318ec1996-06-26 19:50:09 +00001099already configured module "tkinter" (lower case t), the solution is
1100*not* to rename tkinter to Tkinter or vice versa. There is probably
1101something wrong with your module search path. Check out the value of
1102sys.path.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001103
Guido van Rossum061f1821994-10-06 16:03:45 +00001104For X-related modules (Xt and Xm) you will have to do more work: they
1105are currently not part of the standard Python distribution. You will
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001106have to ftp the Extensions tar file, e.g.
Guido van Rossum7be34a81995-05-31 15:17:12 +00001107<URL:ftp://ftp.python.org/pub/python/src/extensions.tar.gz> and follow
1108the instructions there.
Guido van Rossum061f1821994-10-06 16:03:45 +00001109
1110See also the next question.
1111
11124.12. Q. I have successfully built Python with STDWIN but it can't
1113find some modules (e.g. stdwinevents).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001114
1115A. There's a subdirectory of the library directory named 'stdwin'
1116which should be in the default module search path. There's a line in
1117Modules/Setup(.in) that you have to enable for this purpose --
Guido van Rossum061f1821994-10-06 16:03:45 +00001118unfortunately in the latest release it's not near the other
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001119STDWIN-related lines so it's easy to miss it.
1120
11214.13. Q. What GUI toolkits exist for Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001122
1123A. Depending on what platform(s) you are aiming at, there are several.
1124
Guido van Rossumc458e941996-09-11 15:43:13 +00001125Currently supported solutions:
1126
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001127- There's a neat object-oriented interface to the Tcl/Tk widget set,
Guido van Rossumc458e941996-09-11 15:43:13 +00001128called Tkinter. It is part of the standard Python distribution and
1129well-supported -- all you need to do is build and install Tcl/Tk and
1130enable the _tkinter module and the TKPATH definition in Modules/Setup
1131when building Python. This is probably the easiest to install and
1132use, and the most complete widget set. It is also very likely that in
1133the future the standard Python GUI API will be based on or at least
1134look very much like the Tkinter interface. For more info about Tk,
1135including pointers to the source, see the Tcl/Tk home page
1136<URL:http://www.sunlabs.com/research/tcl/>. Tcl/Tk is now fully
1137portable to the Mac and Windows platforms (NT and 95 only); you need
1138Python 1.4beta3 or later and Tk 4.1patch1 or later.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001139
1140- There's an interface to X11, including the Athena and Motif widget
1141sets (and a few individual widgets, like Mosaic's HTML widget and
Guido van Rossumc458e941996-09-11 15:43:13 +00001142SGI's GL widget) available from
1143<URL:ftp://ftp.python.org/pub/python/src/X-extension.tar.gz>.
1144Support by Sjoerd Mullender <sjoerd@cwi.nl>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001145
Guido van Rossum8a913021996-10-08 17:18:30 +00001146- On top of the X11 interface there's the (recently revived) vpApp
1147toolkit by Per Spilling, now also maintained by Sjoerd Mullender
1148<sjoerd@cwi.nl>. See <URL:ftp://ftp.cwi.nl/pub/sjoerd/vpApp.tar.gz>.
1149
Guido van Rossumc458e941996-09-11 15:43:13 +00001150- The Mac port has a rich and ever-growing set of modules that support
1151the native Mac toolbox calls. See the documentation that comes with
1152the Mac port. See <URL:ftp://ftp.python.org/pub/python/mac>. Support
1153by Jack Jansen <jack@cwi.nl>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001154
Guido van Rossumc458e941996-09-11 15:43:13 +00001155- The NT port supported by Mark Hammond <MHammond@skippinet.com.au>
1156(see question 7.2) includes an interface to the Microsoft Foundation
1157Classes and a Python programming environment using it that's written
1158mostly in Python. See
1159<URL:ftp://ftp.python.org/pub/python/pythonwin/>.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001160
Guido van Rossumc458e941996-09-11 15:43:13 +00001161- There's an object-oriented GUI based on the Microsoft Foundation
1162Classes model called WPY, supported by Jim Ahlstrom <jim@interet.com>.
1163Programs written in WPY run unchanged and with native look and feel on
1164Windows NT/95, Windows 3.1 (using win32s), and on Unix (using Tk).
1165Source and binaries for Windows and Linux are available in
1166<URL:ftp://ftp.python.org/pub/python/wpy/>.
1167
1168Obsolete or minority solutions:
Guido van Rossumbf8e7d51995-08-28 03:09:13 +00001169
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001170- There's an interface to wxWindows. wxWindows is a portable GUI
1171class library written in C++. It supports XView, Motif, MS-Windows as
Guido van Rossumc458e941996-09-11 15:43:13 +00001172targets. There is some support for Macs and CURSES as well.
1173wxWindows preserves the look and feel of the underlying graphics
1174toolkit. See the wxPython WWW page at
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001175<URL:http://www.aiai.ed.ac.uk/~jacs/wx/wxpython/wxpython.html>.
Guido van Rossumc458e941996-09-11 15:43:13 +00001176Support for wxPython (by Harri Pasanen <pa@tekla.fi>) appears
1177to have a low priority.
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001178
Guido van Rossumc458e941996-09-11 15:43:13 +00001179- For SGI IRIX only, there are unsupported interfaces to the complete
1180GL (Graphics Library -- low level but very good 3D capabilities) as
1181well as to FORMS (a buttons-and-sliders-etc package built on top of GL
1182by Mark Overmars -- ftp'able from
1183<URL:ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/>). This is probably also
1184becoming obsolete, as OpenGL takes over.
1185
1186- There's an interface to STDWIN, a platform-independent low-level
1187windowing interface for Mac and X11. This is totally unsupported and
1188rapidly becoming obsolete. The STDWIN sources are at
1189<URL:ftp://ftp.cwi.nl/pub/stdwin/>. (For info about STDWIN 2.0,
1190please refer to Steven Pemberton <steven@cwi.nl> -- I believe it is
1191also dead.)
1192
1193- There once was an interface to WAFE, a Tcl interface to the X11
1194Motif and Athena widget sets. WAFE is at
1195<URL:ftp://ftp.wu-wien.ac.at/pub/src/X11/wafe/>. It's not clear what
1196the status of the Python support is.
Guido van Rossum3fc9d731995-07-25 15:10:56 +00001197
Guido van Rossum0d20cfa1996-07-30 18:53:05 +00001198- (The Fresco port that was mentioned in earlier versions of this FAQ
1199no longer seems to exist. Inquire with Mark Linton.)
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00001200
Guido van Rossum061f1821994-10-06 16:03:45 +000012014.14. Q. Are there any interfaces to database packages in Python?
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001202
Guido van Rossum8727df41996-09-09 15:16:39 +00001203A. There's a whole collection of them in the contrib area of the ftp
1204server, see <URL:http://www.python.org/ftp/python/contrib/Database/>.
Guido van Rossum796b2591995-01-20 23:05:52 +00001205
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000012064.15. Q. Is it possible to write obfuscated one-liners in Python?
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001207
1208A. Yes. See the following three examples, due to Ulf Bartelt:
1209
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001210 # Primes < 1000
1211 print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
1212 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 +00001213
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001214 # First 10 Fibonacci numbers
1215 print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
1216 range(10))
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001217
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001218 # Mandelbrot set
1219 print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
1220 Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
1221 Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
1222 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
1223 >=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(
1224 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
1225 ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
1226 # \___ ___/ \___ ___/ | | |__ lines on screen
1227 # V V | |______ columns on screen
1228 # | | |__________ maximum of "iterations"
1229 # | |_________________ range on y axis
1230 # |____________________________ range on x axis
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001231
1232Don't try this at home, kids!
1233
Guido van Rossumb34e8aa1994-09-23 14:20:38 +000012344.16. Q. Is there an equivalent of C's "?:" ternary operator?
Guido van Rossumc24da7c1994-09-23 14:08:41 +00001235
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001236A. Not directly. In many cases you can mimic a?b:c with "a and b or
1237c", but there's a flaw: if b is zero (or empty, or None -- anything
1238that tests false) then c will be selected instead. In many cases you
1239can prove by looking at the code that this can't happen (e.g. because
1240b is a constant or has a type that can never be false), but in general
1241this can be a problem.
1242
Guido van Rossumc458e941996-09-11 15:43:13 +00001243Tim Peters (who wishes it was Steve Majewski) suggested the following
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001244solution: (a and [b] or [c])[0]. Because [b] is a singleton list it
1245is never false, so the wrong path is never taken; then applying [0] to
1246the whole thing gets the b or c that you really wanted. Ugly, but it
1247gets you there in the rare cases where it is really inconvenient to
1248rewrite your code using 'if'.
1249
12504.17. Q. My class defines __del__ but it is not called when I delete the
1251object.
1252
1253A. There are several possible reasons for this.
1254
1255- The del statement does not necessarily call __del__ -- it simply
1256decrements the object's reference count, and if this reaches zero
1257__del__ is called.
1258
1259- If your data structures contain circular links (e.g. a tree where
1260each child has a parent pointer and each parent has a list of
1261children) the reference counts will never go back to zero. You'll
Guido van Rossum061f1821994-10-06 16:03:45 +00001262have to define an explicit close() method which removes those
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001263pointers. Please don't ever call __del__ directly -- __del__ should
Guido van Rossum061f1821994-10-06 16:03:45 +00001264call close() and close() should make sure that it can be called more
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001265than once for the same object.
1266
1267- If the object has ever been a local variable (or argument, which is
1268really the same thing) to a function that caught an expression in an
1269except clause, chances are that a reference to the object still exists
1270in that function's stack frame as contained in the stack trace.
1271Normally, deleting (better: assigning None to) sys.exc_traceback will
1272take care of this. If you a stack was printed for an unhandled
1273exception in an interactive interpreter, delete sys.last_traceback
1274instead.
1275
1276- There is code that deletes all objects when the interpreter exits,
1277but if your Python has been configured to support threads, it is not
1278called (because other threads may still be active). You can define
Guido van Rossum061f1821994-10-06 16:03:45 +00001279your own cleanup function using sys.exitfunc (see question 4.4).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001280
Guido van Rossum8727df41996-09-09 15:16:39 +00001281- Finally, if your __del__ method raises an exception, this will be
1282ignored. Starting with Python 1.4beta3, a warning message is printed
1283to sys.stderr when this happens.
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001284
12854.18. Q. How do I change the shell environment for programs called
1286using os.popen() or os.system()? Changing os.environ doesn't work.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001287
1288A. Modifying the environment passed to subshells was left out of the
1289interpreter because there seemed to be no well-established portable
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001290way to do it (in particular, some systems, have putenv(), others have
1291setenv(), and some have none at all).
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001292
1293However if all you want is to pass environment variables to the
1294commands run by os.system() or os.popen(), there's a simple solution:
1295prefix the command string with a couple of variable assignments and
Guido van Rossum796b2591995-01-20 23:05:52 +00001296export statements. The following would be universal for popen:
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001297
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001298 import os
1299 from commands import mkarg # nifty routine to add shell quoting
1300 def epopen(cmd, mode, env = {}):
1301 # env is a dictionary of environment variables
1302 prefix = ''
Guido van Rossum796b2591995-01-20 23:05:52 +00001303 for key, value in env.items():
1304 prefix = prefix + '%s=%s\n' % (key, mkarg(value)[1:])
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001305 prefix = prefix + 'export %s\n' % key
1306 return os.popen(prefix + cmd, mode)
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001307
13084.19. Q. What is a class?
1309
1310A. A class is the particular object type that is created by executing
Guido van Rossum796b2591995-01-20 23:05:52 +00001311a class statement. Class objects are used as templates, to create
1312class instance objects, which embody both the data structure and
1313program routines specific to a datatype.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001314
13154.20. Q. What is a method?
1316
1317A. A method is a function that you normally call as
Guido van Rossum796b2591995-01-20 23:05:52 +00001318x.name(arguments...) for some object x. The term is used for methods
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001319of classes and class instances as well as for methods of built-in
Guido van Rossum796b2591995-01-20 23:05:52 +00001320objects. (The latter have a completely different implementation and
1321only share the way their calls look in Python code.) Methods of
1322classes (and class instances) are defined as functions inside the
1323class definition.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001324
13254.21. Q. What is self?
1326
1327A. Self is merely a conventional name for the first argument of a
1328method -- i.e. a function defined inside a class definition. A method
1329defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
1330some instance x of the class in which the definition occurs;
1331the called method will think it is called as meth(x, a, b, c).
1332
13334.22. Q. What is a unbound method?
1334
1335A. An unbound method is a method defined in a class that is not yet
1336bound to an instance. You get an unbound method if you ask for a
1337class attribute that happens to be a function. You get a bound method
1338if you ask for an instance attribute. A bound method knows which
Guido van Rossum061f1821994-10-06 16:03:45 +00001339instance it belongs to and calling it supplies the instance automatically;
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001340an unbound method only knows which class it wants for its first
1341argument (a derived class is also OK). Calling an unbound method
1342doesn't "magically" derive the first argument from the context -- you
1343have to provide it explicitly.
1344
Guido van Rossuma6c707c1995-01-02 17:32:28 +000013454.23. Q. How do I call a method defined in a base class from a derived
1346class that overrides it?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001347
1348A. If your class definition starts with "class Derived(Base): ..."
1349then you can call method meth defined in Base (or one of Base's base
1350classes) as Base.meth(self, arguments...). Here, Base.meth is an
1351unbound method (see previous question).
1352
Guido van Rossuma6c707c1995-01-02 17:32:28 +000013534.24. Q. How do I call a method from a base class without using the
1354name of the base class?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001355
1356A. DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call
1357self.__class__.__bases__[0].meth(self, arguments...) but this fails when
Guido van Rossum061f1821994-10-06 16:03:45 +00001358a doubly-derived method is derived from your class: for its instances,
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001359self.__class__.__bases__[0] is your class, not its base class -- so
1360(assuming you are doing this from within Derived.meth) you would start
1361a recursive call.
1362
13634.25. Q. How can I organize my code to make it easier to change the base
1364class?
1365
1366A. You could define an alias for the base class, assign the real base
1367class to it before your class definition, and use the alias throughout
1368your class. Then all you have to change is the value assigned to the
1369alias. Incidentally, this trick is also handy if you want to decide
1370dynamically (e.g. depending on availability of resources) which base
1371class to use. Example:
1372
Guido van Rossumc458e941996-09-11 15:43:13 +00001373 BaseAlias = <real base class>
1374 class Derived(BaseAlias):
1375 def meth(self):
1376 BaseAlias.meth(self)
1377 ...
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001378
13794.26. Q. How can I find the methods or attributes of an object?
1380
1381A. This depends on the object type.
1382
1383For an instance x of a user-defined class, instance attributes are
1384found in the dictionary x.__dict__, and methods and attributes defined
1385by its class are found in x.__class__.__bases__[i].__dict__ (for i in
1386range(len(x.__class__.__bases__))). You'll have to walk the tree of
1387base classes to find *all* class methods and attributes.
1388
1389Many, but not all built-in types define a list of their method names
1390in x.__methods__, and if they have data attributes, their names may be
1391found in x.__members__. However this is only a convention.
1392
1393For more information, read the source of the standard (but
1394undocumented) module newdir.
1395
13964.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
1397
1398A. os.read() is a low-level function which takes a file descriptor (a
1399small integer). os.popen() creates a high-level file object -- the
1400same type used for sys.std{in,out,err} and returned by the builtin
1401open() function. Thus, to read n bytes from a pipe p created with
1402os.popen(), you need to use p.read(n).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001403
Guido van Rossum061f1821994-10-06 16:03:45 +000014044.28. Q. How can I create a stand-alone binary from a Python script?
1405
1406The demo script "Demo/scripts/freeze.py" does what you want. (It's
1407actually not a demo but a support tool -- there is some extra code in
1408the interpreter to accommodate it.) It requires that you have the
1409Python build tree handy, complete with all the lib*.a files.
1410
1411This works by scanning your source recursively for import statements
1412(both forms) and looking for the modules on the standard Python path
1413as well as in the source directory (for built-in modules). It then
1414"compiles" the modules written in Python to C code (array initializers
1415that can be turned into code objects using the marshal module) and
1416creates a custom-made config file that only contains those built-in
1417modules which are actually used in the program. It then compiles the
1418generated C code and links it with the rest of the Python interpreter
1419to form a self-contained binary which acts exactly like your script.
1420
Guido van Rossum7be34a81995-05-31 15:17:12 +00001421Hint: the freeze program only works if your script's filename ends in
1422".py".
Guido van Rossum061f1821994-10-06 16:03:45 +00001423
Guido van Rossum7be34a81995-05-31 15:17:12 +000014244.29. Q. What WWW tools are there for Python?
Guido van Rossum061f1821994-10-06 16:03:45 +00001425
Guido van Rossum8727df41996-09-09 15:16:39 +00001426A. See the chapter titled "Internet and WWW" in the Library Reference
1427Manual. There's also a web browser written in Python, called Grail --
Guido van Rossum4662b871996-11-27 15:24:34 +00001428see <URL:http://grail.cnri.reston.va.us/grail/>.
Guido van Rossum061f1821994-10-06 16:03:45 +00001429
1430Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser
1431called Dancer. An alpha version can be FTP'ed from
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001432<URL:ftp://ftp.cs.indiana.edu/pub/smiale/dancer.tar.gz>. (There are a
1433few articles about Dancer in the (hyper)mail archive
1434<URL:http://www.cwi.nl/~guido/hypermail/python-1994q3/index.html>.)
Guido van Rossum061f1821994-10-06 16:03:45 +00001435
Guido van Rossum7be34a81995-05-31 15:17:12 +000014364.30. Q. How do I run a subprocess with pipes connected to both input
Guido van Rossum796b2591995-01-20 23:05:52 +00001437and output?
1438
1439A. This is really a UNIX question. Also, in general, it is unwise to
1440do so, because you can easily cause a deadlock where the parent
1441process is blocked waiting for output from the child, while the child
1442is blocked waiting for input from the child. This can be caused
1443because the parent expects the child to output more text than it does,
1444or it can be caused by data being stuck in stdio buffers due to lack
1445of flushing. The Python parent can of course explicitly flush the data
1446it sends to the child before it reads any output, but if the child is
1447a naive C program it can easily have been written to never explicitly
1448flush its output, even if it is interactive, since flushing is
1449normally automatic.
1450
1451In many cases, all you really need is to run some data through a
1452command and get the result back. Unless the data is infinite in size,
1453the easiest (and often the most efficient!) way to do this is to write
1454it to a temporary file and run the command with that temporary file as
1455input. The standard module tempfile exports a function mktemp() which
1456generates unique temporary file names.
1457
1458If after reading all of the above you still want to connect two pipes
1459to a subprocess's standard input and output, here's a simple solution,
1460due to Jack Jansen:
1461
Guido van Rossume7d92d51995-10-11 18:06:54 +00001462 import os
1463 import sys
1464 import string
Guido van Rossum796b2591995-01-20 23:05:52 +00001465
Guido van Rossume7d92d51995-10-11 18:06:54 +00001466 MAXFD = 100 # Max number of file descriptors in this system
Guido van Rossum796b2591995-01-20 23:05:52 +00001467
Guido van Rossume7d92d51995-10-11 18:06:54 +00001468 def popen2(cmd):
1469 cmd = string.split(cmd)
1470 p2cread, p2cwrite = os.pipe()
1471 c2pread, c2pwrite = os.pipe()
1472 pid = os.fork()
1473 if pid == 0:
1474 # Child
1475 os.close(0)
1476 os.close(1)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001477 if os.dup(p2cread) != 0:
Guido van Rossume7d92d51995-10-11 18:06:54 +00001478 sys.stderr.write('popen2: bad read dup\n')
Guido van Rossumca318ec1996-06-26 19:50:09 +00001479 if os.dup(c2pwrite) != 1:
Guido van Rossume7d92d51995-10-11 18:06:54 +00001480 sys.stderr.write('popen2: bad write dup\n')
1481 for i in range(3, MAXFD):
1482 try:
1483 os.close(i)
1484 except:
1485 pass
1486 try:
1487 os.execv(cmd[0], cmd)
1488 finally:
1489 os._exit(1)
1490 os.close(p2cread)
1491 tochild = os.fdopen(p2cwrite, 'w')
1492 os.close(c2pwrite)
1493 fromchild = os.fdopen(c2pread, 'r')
1494 return fromchild, tochild
Guido van Rossum796b2591995-01-20 23:05:52 +00001495
1496Note that many interactive programs (e.g. vi) don't work well with
1497pipes substituted for standard input and output. You will have to use
1498pseudo ttys ("ptys") instead of pipes. There is some undocumented
1499code to use these in the library module pty.py -- I'm afraid you're on
Guido van Rossum3fc9d731995-07-25 15:10:56 +00001500your own here.
1501
1502A different answer is a Python interface to Don Libes' "expect"
1503library. A prerelease of this is available on the Python ftp mirror
1504sites in the contrib subdirectory as expy-0.3.tar.gz, e.g.
1505<URL:ftp://ftp.python.org/pub/python/contrib/expy-0.3.tar.gz>.
Guido van Rossum796b2591995-01-20 23:05:52 +00001506
Guido van Rossum7be34a81995-05-31 15:17:12 +000015074.31. Q. How do I call a function if I have the arguments in a tuple?
Guido van Rossumac3f2121995-04-10 11:53:42 +00001508
1509A. Use the built-in function apply(). For instance,
1510
1511 func(1, 2, 3)
1512
1513is equivalent to
1514
1515 args = (1, 2, 3)
1516 apply(func, args)
1517
1518Note that func(args) is not the same -- it calls func() with exactly
1519one argument, the tuple args, instead of three arguments, the integers
15201, 2 and 3.
1521
Guido van Rossum7be34a81995-05-31 15:17:12 +000015224.32. Q. How do I enable font-lock-mode for Python in Emacs?
1523
1524A. Assuming you're already using python-mode and font-lock-mode
1525separately, all you need to do is put this in your .emacs file:
1526
Guido van Rossume7d92d51995-10-11 18:06:54 +00001527 (defun my-python-mode-hook ()
1528 (setq font-lock-keywords python-font-lock-keywords)
1529 (font-lock-mode 1))
1530 (add-hook 'python-mode-hook 'my-python-mode-hook)
Guido van Rossum7be34a81995-05-31 15:17:12 +00001531
15324.33. Q. Is there an inverse to the format operator (a la C's scanf())?
1533
1534A. Not as such.
1535
1536For simple input parsing, the easiest approach is usually to split
1537the line into whitespace-delimited words using string.split(), and to
1538convert decimal strings to numeric values using string.atoi(),
1539string.atol() or string.atof(). (Python's atoi() is 32-bit and its
1540atol() is arbitrary precision.) If you want to use another delimiter
1541than whitespace, use string.splitfield() (possibly combining it with
1542string.strip() which removes surrounding whitespace from a string).
1543
1544For more complicated input parsing, regular expressions (see module
1545regex) are better suited and more powerful than C's scanf().
1546
Guido van Rossumca318ec1996-06-26 19:50:09 +000015474.34. Q. Can I have Tk events handled while waiting for I/O?
1548
1549A. Yes, and you don't even need threads! But you'll have to
1550restructure your I/O code a bit. Tk has the equivalent of Xt's
1551XtAddInput() call, which allows you to register a callback function
1552which will be called from the Tk mainloop when I/O is possible on a
1553file descriptor. Here's what you need:
1554
Guido van Rossumc458e941996-09-11 15:43:13 +00001555 from Tkinter import tkinter
1556 tkinter.createfilehandler(file, mask, callback)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001557
1558The file may be a Python file or socket object (actually, anything
1559with a fileno() method), or an integer file descriptor. The mask is
1560one of the constants tkinter.READABLE or tkinter.WRITABLE. The
1561callback is called as follows:
1562
Guido van Rossumc458e941996-09-11 15:43:13 +00001563 callback(file, mask)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001564
1565You must unregister the callback when you're done, using
1566
Guido van Rossumc458e941996-09-11 15:43:13 +00001567 tkinter.deletefilehandler(file)
Guido van Rossumca318ec1996-06-26 19:50:09 +00001568
1569Note: since you don't know *how many bytes* are available for reading,
1570you can't use the Python file object's read or readline methods, since
1571these will insist on reading a predefined number of bytes. For
1572sockets, the recv() or recvfrom() methods will work fine; for other
1573files, use os.read(file.fileno(), maxbytecount).
1574
15754.35. Q. How do I write a function with output parameters (call by reference)?
1576
1577A. [Mark Lutz] The thing to remember is that arguments are passed by
1578assignment in Python. Since assignment just creates references to
1579objects, there's no alias between an argument name in the caller and
1580callee, and so no call-by-reference per se. But you can simulate it
1581in a number of ways:
1582
15831) By using global variables; but you probably shouldn't :-)
1584
15852) By passing a mutable (changeable in-place) object:
1586
1587 def func1(a):
1588 a[0] = 'new-value' # 'a' references a mutable list
1589 a[1] = a[1] + 1 # changes a shared object
1590
1591 args = ['old-value', 99]
1592 func1(args)
1593 print args[0], args[1] # output: new-value 100
1594
15953) By return a tuple, holding the final values of arguments:
1596
1597 def func2(a, b):
1598 a = 'new-value' # a and b are local names
1599 b = b + 1 # assigned to new objects
1600 return a, b # return new values
1601
1602 x, y = 'old-value', 99
1603 x, y = func2(x, y)
1604 print x, y # output: new-value 100
1605
16064) And other ideas that fall-out from Python's object model. For
1607 instance, it might be clearer to pass in a mutable dictionary:
1608
1609 def func3(args):
1610 args['a'] = 'new-value' # args is a mutable dictionary
1611 args['b'] = args['b'] + 1 # change it in-place
1612
1613 args = {'a':' old-value', 'b': 99}
1614 func3(args)
1615 print args['a'], args['b']
1616
16175) Or bundle-up values in a class instance:
1618
1619 class callByRef:
1620 def __init__(self, **args):
1621 for (key, value) in args.items():
1622 setattr(self, key, value)
1623
1624 def func4(args):
1625 args.a = 'new-value' # args is a mutable callByRef
1626 args.b = args.b + 1 # change object in-place
1627
1628 args = callByRef(a='old-value', b=99)
1629 func4(args)
1630 print args.a, args.b
1631
1632 But there's probably no good reason to get this complicated :-).
1633
1634[Python' author favors solution 3 in most cases.]
1635
Guido van Rossum0d20cfa1996-07-30 18:53:05 +000016364.36. Q. Please explain the rules for local and global variables in Python.
1637
1638A. [Ken Manheimer] In Python, procedure variables are implicitly
1639global, unless they assigned anywhere within the block. In that case
1640they are implicitly local, and you need to explicitly declare them as
1641'global'.
1642
1643Though a bit surprising at first, a moments consideration explains
1644this. On one hand, requirement of 'global' for assigned vars provides
1645a bar against unintended side-effects. On the other hand, if global
1646were required for all global references, you'd be using global all the
1647time. Eg, you'd have to declare as global every reference to a
1648builtin function, or to a component of an imported module. This
1649clutter would defeat the usefulness of the 'global' declaration for
1650identifying side-effects.
1651
16524.37. Q. How can I have modules that mutually import each other?
1653
1654A. Jim Roskind recommends the following order in each module:
1655
1656First: all exports (like globals, functions, and classes that don't
1657need imported bases classes).
1658
1659Then: all import statements.
1660
1661Finally: all active code (including globals that are initialized from
1662imported values).
1663
1664Python's author doesn't like this approach much because the imports
1665appear in a strange place, but has to admit that it works. His
1666recommended strategy is to avoid all uses of "from <module> import *"
1667(so everything from an imported module is referenced as
1668<module>.<name>) and to place all code inside functions.
1669Initializations of global variables and class variables should use
1670constants or built-in functions only.
1671
Guido van Rossum8727df41996-09-09 15:16:39 +000016724.38. Q. How do I copy an object in Python?
1673
1674A. There is no generic copying operation built into Python, however
1675most object types have some way to create a clone. Here's how for the
1676most common objects:
1677
1678- For immutable objects (numbers, strings, tuples), cloning is
1679unnecessary since their value can't change.
1680
1681- For lists (and generally for mutable sequence types), a clone is
1682created by the expression l[:].
1683
1684- For dictionaries, the following function returns a clone:
1685
Guido van Rossumc458e941996-09-11 15:43:13 +00001686 def dictclone(o):
1687 n = {}
1688 for k in o.keys(): n[k] = o[k]
1689 return n
Guido van Rossum8727df41996-09-09 15:16:39 +00001690
1691- Finally, for generic objects, the "copy" module defines two
1692functions for copying objects. copy.copy(x) returns a copy as shown
1693by the above rules. copy.deepcopy(x) also copies the elements of
1694composite objects. See the section on this module in the Library
1695Reference Manual.
1696
16974.39. Q. How to implement persistent objects in Python? (Persistent ==
1698automatically saved to and restored from disk.)
1699
1700A. The library module "pickle" now solves this in a very general way
1701(though you still can't store things like open files, sockests or
1702windows), and the library module "shelve" uses pickle and (g)dbm to
1703create presistent mappings containing arbitrary Python objects.
1704
Guido van Rossuma4e41a81996-10-22 03:00:43 +000017054.40. Q. I try to use __spam and I get an error about _SomeClassName__spam.
1706
1707A. Variables with double leading underscore are "mangled" to provide a
1708simple but effective way to define class private variables. See the
1709chapter "New in Release 1.4" in the Python Tutorial.
1710
Guido van Rossumc59120b1996-11-14 14:10:11 +000017114.41. Q. How do I delete a file? And other file questions.
1712
1713A. Use os.remove(filename) or os.unlink(filename); for documentation,
1714see the posix section of the library manual. They are the same,
1715unlink() is simply the Unix name for this function. In earlier
1716versions of Python, only os.unlink() was available.
1717
1718To remove a directory, use os.rmdir(); use os.mkdir() to create one.
1719
1720To rename a file, use os.rename().
1721
1722To truncate a file, open it using f = open(filename, "w+"), and use
1723f.truncate(offset); offset defaults to the current seek position.
1724There's also os.ftruncate(fd, offset) for files opened with os.open()
1725-- for advanced Unix hacks only.
1726
Guido van Rossum061f1821994-10-06 16:03:45 +00001727
Guido van Rossuma7925f11994-01-26 10:20:16 +000017285. Extending Python
1729===================
1730
17315.1. Q. Can I create my own functions in C?
1732
1733A. Yes, you can create built-in modules containing functions,
Guido van Rossum24349991994-02-02 14:12:45 +00001734variables, exceptions and even new types in C. This is explained in
1735the document "Extending and Embedding the Python Interpreter" (the
1736LaTeX file Doc/ext.tex). Also read the chapter on dynamic loading.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001737
17385.2. Q. Can I create my own functions in C++?
1739
1740A. Yes, using the C-compatibility features found in C++. Basically
1741you place extern "C" { ... } around the Python include files and put
1742extern "C" before each function that is going to be called by the
1743Python interpreter. Global or static C++ objects with constructors
1744are probably not a good idea.
1745
Guido van Rossum7ce61c11994-06-13 15:13:56 +000017465.3. Q. How can I execute arbitrary Python statements from C?
1747
1748A. The highest-level function to do this is run_command() which takes
1749a single string argument which is executed in the context of module
1750__main__ and returns 0 for success and -1 when an exception occurred
1751(including SyntaxError). If you want more control, use run_string();
1752see the source for run_command() in Python/pythonrun.c.
1753
17545.4. Q. How can I evaluate an arbitrary Python expression from C?
1755
1756A. Call the function run_string() from the previous question with the
1757start symbol eval_input; it then parses an expression, evaluates it
1758and returns its value. See exec_eval() in Python/bltinmodule.c.
1759
17605.5. Q. How do I extract C values from a Python object?
1761
1762A. That depends on the object's type. If it's a tuple,
1763gettuplesize(o) returns its length and gettupleitem(o, i) returns its
1764i'th item; similar for lists with getlistsize(o) and getlistitem(o,
1765i). For strings, getstringsize(o) returns its length and
1766getstringvalue(o) a pointer to its value (note that Python strings may
1767contain null bytes so strlen() is not safe). To test which type an
1768object is, first make sure it isn't NULL, and then use
1769is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
1770
17715.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
1772
1773A. You can't. Use t = newtupleobject(n) instead, and fill it with
1774objects using settupleitem(t, i, o) -- note that this "eats" a
1775reference count of o. Similar for lists with newlistobject(n) and
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001776setlistitem(l, i, o). Note that you *must* set all the tuple items to
1777some value before you pass the tuple to Python code --
1778newtupleobject(n) initializes them to NULL, which isn't a valid Python
1779value.
1780
Guido van Rossum8727df41996-09-09 15:16:39 +000017815.7. Q. How do I call an object's method from C?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001782
1783A. Here's a function (untested) that might become part of the next
1784release in some form. It uses <stdarg.h> to allow passing the
1785argument list on to vmkvalue():
1786
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001787 object *call_method(object *inst, char *methodname, char *format, ...)
1788 {
1789 object *method;
1790 object *args;
1791 object *result;
1792 va_list va;
1793 method = getattr(inst, methodname);
1794 if (method == NULL) return NULL;
1795 va_start(va, format);
1796 args = vmkvalue(format, va);
1797 va_end(va);
1798 if (args == NULL) {
1799 DECREF(method);
1800 return NULL;
1801 }
1802 result = call_object(method, args);
1803 DECREF(method);
1804 DECREF(args);
1805 return result;
1806 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001807
1808This works for any instance that has methods -- whether built-in or
1809user-defined. You are responsible for eventually DECREF'ing the
1810return value.
1811
1812To call, e.g., a file object's "seek" method with arguments 10, 0
1813(assuming the file object pointer is "f"):
1814
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001815 res = call_method(f, "seek", "(OO)", 10, 0);
1816 if (res == NULL) {
1817 ... an exception occurred ...
1818 }
1819 else {
1820 DECREF(res);
1821 }
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001822
1823Note that since call_object() *always* wants a tuple for the argument
1824list, to call a function without arguments, pass "()" for the format,
1825and to call a function with one argument, surround the argument in
1826parentheses, e.g. "(i)".
1827
Guido van Rossum8727df41996-09-09 15:16:39 +000018285.8. Q. How do I catch the output from print_error()?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001829
1830A. (Due to Mark Hammond):
1831
1832* in Python code, define an object that supports the "write()" method.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001833
1834* redirect sys.stdout and sys.stderr to this object.
1835
Guido van Rossum061f1821994-10-06 16:03:45 +00001836* call print_error, or just allow the standard traceback mechanism to
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001837work.
1838
Guido van Rossum061f1821994-10-06 16:03:45 +00001839Then, the output will go wherever your write() method sends it.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001840
Guido van Rossum8727df41996-09-09 15:16:39 +000018415.9. Q. How do I access a module written in Python from C?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001842
1843A. You can get a pointer to the module object as follows:
1844
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001845 module = import_module("<modulename>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001846
1847If the module hasn't been imported yet (i.e. it is not yet present in
1848sys.modules), this initializes the module; otherwise it simply returns
1849the value of sys.modules["<modulename>"]. Note that it doesn't enter
1850the module into any namespace -- it only ensures it has been
1851initialized and is stored in sys.modules.
1852
1853You can then access the module's attributes (i.e. any name defined in
1854the module) as follows:
1855
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001856 attr = getattr(module, "<attrname>");
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00001857
1858Calling setattr(), to assign to variables in the module, also works.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00001859
Guido van Rossum8727df41996-09-09 15:16:39 +000018605.10. Q. How do I interface to C++ objects from Python?
Guido van Rossumb0a2ce51995-08-28 19:41:35 +00001861
1862A. Depending on your requirements, there are many approaches. Begin
1863by reading the "Extending and Embedding" document (Doc/ext.tex, see
1864also <URL:http://www.python.org/doc/>). Realize that for the Python
1865run-time system, there isn't a whole lot of difference between C and
1866C++ -- so the strategy to build a new Python type around a C structure
1867(pointer) type will also work for C++ objects.
1868
1869Automatic generation of interfaces between Python and C++ is still at
1870the horizon -- parsing C++ header files requires an almost complete
1871C++ parser, and many features aren't easily translated from C++ to
1872Python: certain forms of operator oveloading, function overloading
1873(best approached by a varargs function which explicitly type-checks
1874its arguments), and reference arguments are just a number of features
1875that are hard to translate correctly if at all.
1876
1877The hardest problem is to transparently translate the C++ class
1878hierarchy to Python, so that Python programs derive classes from C++
1879classes. Given suitable constraints, this may be possible, but it
1880would require more space than I have in this FAQ to explain how.
1881In any case, you can get quite a bit done without this, using just the
1882existing classes from Python.
1883
1884If this all seems rather daunting, that may be because it is -- C++
1885isn't exactly a baby to handle without gloves! However, people have
1886accomplished amazing feats of interfacing between Python and C++, and
1887a detailed question posted to the Python list is likely to elicit some
1888interesting and useful responses.
1889
Guido van Rossuma7925f11994-01-26 10:20:16 +00001890
18916. Python's design
1892==================
1893
Guido van Rossum8727df41996-09-09 15:16:39 +000018946.1. Q. Why isn't there a switch or case statement in Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00001895
1896A. You can do this easily enough with a sequence of
1897if... elif... elif... else. There have been some proposals for switch
Guido van Rossum061f1821994-10-06 16:03:45 +00001898statement syntax, but there is no consensus (yet) on whether and how
Guido van Rossuma7925f11994-01-26 10:20:16 +00001899to do range tests.
1900
Guido van Rossum8727df41996-09-09 15:16:39 +000019016.2. Q. Why does Python use indentation for grouping of statements?
Guido van Rossumc50158e1994-05-31 09:18:50 +00001902
1903A. Basically I believe that using indentation for grouping is
1904extremely elegant and contributes a lot to the clarity of the average
1905Python program. Most people learn to love this feature after a while.
1906Some arguments for it:
1907
1908- Since there are no begin/end brackets there cannot be a disagreement
1909between grouping perceived by the parser and the human reader. I
1910remember long ago seeing a C fragment like this:
1911
Guido van Rossuma6c707c1995-01-02 17:32:28 +00001912 if (x <= y)
1913 x++;
1914 y--;
1915 z++;
Guido van Rossumc50158e1994-05-31 09:18:50 +00001916
1917and staring a long time at it wondering why y was being decremented
1918even for x > y... (And I wasn't a C newbie then either.)
1919
Guido van Rossum7be34a81995-05-31 15:17:12 +00001920- Since there are no begin/end brackets, Python is much less prone to
1921coding-style conflicts. In C there are loads of different ways to
1922place the braces (including the choice whether to place braces around
1923single statements in certain cases, for consistency). If you're used
1924to reading (and writing) code that uses one style, you will feel at
1925least slightly uneasy when reading (or being required to write)
1926another style.
Guido van Rossumc50158e1994-05-31 09:18:50 +00001927
1928- Many coding styles place begin/end brackets on a line by themself.
1929This makes programs considerably longer and wastes valuable screen
1930space, making it harder to get a good overview over a program.
1931Ideally, a function should fit on one basic tty screen (say, 20
1932lines). 20 lines of Python are worth a LOT more than 20 lines of C.
1933This is not solely due to the lack of begin/end brackets (the lack of
1934declarations also helps, and the powerful operations of course), but
1935it certainly helps!
1936
Guido van Rossum8727df41996-09-09 15:16:39 +000019376.3. Q. Why are Python strings immutable?
Guido van Rossum3de27361994-07-25 14:19:33 +00001938
1939A. There are two advantages. One is performance: knowing that a
1940string is immutable makes it easy to lay it out at construction time
1941-- fixed and unchanging storage requirements. (This is also one of
Guido van Rossum061f1821994-10-06 16:03:45 +00001942the reasons for the distinction between tuples and lists.) The
Guido van Rossum3de27361994-07-25 14:19:33 +00001943other is that strings in Python are considered as "elemental" as
1944numbers. No amount of activity will change the value 8 to anything
1945else, and in Python, no amount of activity will change the string
1946"eight" to anything else. (Adapted from Jim Roskind)
1947
Guido van Rossum8727df41996-09-09 15:16:39 +000019486.4. Q. Why don't strings have methods like index() or sort(), like
Guido van Rossum3de27361994-07-25 14:19:33 +00001949lists?
1950
1951A. Good question. Strings currently don't have methods at all
1952(likewise tuples and numbers). Long ago, it seemed unnecessary to
1953implement any of these functions in C, so a standard library module
1954"string" written in Python was created that performs string related
1955operations. Since then, the cry for performance has moved most of
1956them into the built-in module strop (this is imported by module
Guido van Rossumf8c76d01994-08-17 12:19:53 +00001957string, which is still the preferred interface, without loss of
Guido van Rossum3de27361994-07-25 14:19:33 +00001958performance except during initialization). Some of these functions
1959(e.g. index()) could easily be implemented as string methods instead,
1960but others (e.g. sort()) can't, since their interface prescribes that
1961they modify the object, while strings are immutable (see the previous
1962question).
1963
Guido van Rossum8727df41996-09-09 15:16:39 +000019646.5. Q. Why does Python use methods for some functionality
Guido van Rossum3de27361994-07-25 14:19:33 +00001965(e.g. list.index()) but functions for other (e.g. len(list))?
1966
1967A. Functions are used for those operations that are generic for a
1968group of types and which should work even for objects that don't have
1969methods at all (e.g. numbers, strings, tuples). Also, implementing
1970len(), max(), min() as a built-in function is actually less code than
1971implementing them as methods for each type. One can quibble about
1972individual cases but it's really too late to change such things
1973fundamentally now.
1974
Guido van Rossum8727df41996-09-09 15:16:39 +000019756.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 +00001976files)?
1977
1978A. This is caused by the relatively late addition of (user-defined)
1979classes to the language -- the implementation framework doesn't easily
1980allow it. See the answer to question 4.2 for a work-around. This
1981*may* be fixed in the (distant) future.
1982
Guido van Rossum8727df41996-09-09 15:16:39 +000019836.7. Q. Why must 'self' be declared and used explicitly in method
Guido van Rossum3de27361994-07-25 14:19:33 +00001984definitions and calls?
1985
1986A. By asking this question you reveal your C++ background. :-)
1987When I added classes, this was (again) the simplest way of
1988implementing methods without too many changes to the interpreter. I
1989borrowed the idea from Modula-3. It turns out to be very useful, for
1990a variety of reasons.
1991
1992First, it makes it more obvious that you are using a method or
1993instance attribute instead of a local variable. Reading "self.x" or
1994"self.meth()" makes it absolutely clear that an instance variable or
1995method is used even if you don't know the class definition by heart.
1996In C++, you can sort of tell by the lack of a local variable
Guido van Rossum061f1821994-10-06 16:03:45 +00001997declaration (assuming globals are rare or easily recognizable) -- but
Guido van Rossum3de27361994-07-25 14:19:33 +00001998in Python, there are no local variable declarations, so you'd have to
1999look up the class definition to be sure.
2000
2001Second, it means that no special syntax is necessary if you want to
2002explicitly reference or call the method from a particular class. In
2003C++, if you want to use a method from base class that is overridden in
2004a derived class, you have to use the :: operator -- in Python you can
2005write baseclass.methodname(self, <argument list>). This is
2006particularly useful for __init__() methods, and in general in cases
2007where a derived class method wants to extend the base class method of
2008the same name and thus has to call the base class method somehow.
2009
2010Lastly, for instance variables, it solves a syntactic problem with
2011assignment: since local variables in Python are (by definition!) those
2012variables to which a value assigned in a function body (and that
2013aren't explicitly declared global), there has to be some way to tell
2014the interpreter that an assignment was meant to assign to an instance
2015variable instead of to a local variable, and it should preferably be
2016syntactic (for efficiency reasons). C++ does this through
2017declarations, but Python doesn't have declarations and it would be a
2018pity having to introduce them just for this purpose. Using the
2019explicit "self.var" solves this nicely. Similarly, for using instance
2020variables, having to write "self.var" means that references to
2021unqualified names inside a method don't have to search the instance's
2022directories.
2023
Guido van Rossum8727df41996-09-09 15:16:39 +000020246.8. Q. Can't you emulate threads in the interpreter instead of
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002025relying on an OS-specific thread implementation?
2026
2027A. Unfortunately, the interpreter pushes at least one C stack frame
2028for each Python stack frame. Also, extensions can call back into
2029Python at almost random moments. Therefore a complete threads
2030implementation requires thread support for C.
2031
Guido van Rossum8727df41996-09-09 15:16:39 +000020326.9. Q. Why can't lambda forms contain statements?
Guido van Rossum061f1821994-10-06 16:03:45 +00002033
2034A. Python lambda forms cannot contain statements because Python's
Guido van Rossum796b2591995-01-20 23:05:52 +00002035syntactic framework can't handle statements nested inside expressions.
Guido van Rossum061f1821994-10-06 16:03:45 +00002036
2037However, in Python, this is not a serious problem. Unlike lambda
2038forms in other languages, where they add functionality, Python lambdas
2039are only a shorthand notation if you're too lazy to define a function.
2040
2041Functions are already first class objects in Python, and can be
2042declared in a local scope. Therefore the only advantage of using a
2043lambda form instead of a locally-defined function is that you'll have
2044to invent a name for the function -- but that's just a local variable
2045to which the function object (which is exactly the same type of object
2046that a lambda form yields) is assigned!
2047
Guido van Rossum8727df41996-09-09 15:16:39 +000020486.10. Q. Why don't lambdas have access to variables defined in the
2049containing scope?
2050
Guido van Rossumc458e941996-09-11 15:43:13 +00002051A. Because they are implemented as ordinary functions.
2052See question 4.5 above.
Guido van Rossum8727df41996-09-09 15:16:39 +00002053
20546.11. Q. Why can't recursive functions be defined inside other functions?
2055
2056A. See question 4.5 above.
2057
Guido van Rossum061f1821994-10-06 16:03:45 +000020586.12. Q. Why is there no more efficient way of iterating over a dictionary
2059than first constructing the list of keys()?
2060
2061A. Have you tried it? I bet it's fast enough for your purposes! In
2062most cases such a list takes only a few percent of the space occupied
2063by the dictionary -- it needs only 4 bytes (the size of a pointer) per
2064key -- a dictionary costs 8 bytes per key plus between 30 and 70
2065percent hash table overhead, plus the space for the keys and values --
2066by necessity all keys are unique objects and a string object (the most
2067common key type) costs at least 18 bytes plus the length of the
2068string. Add to that the values contained in the dictionary, and you
2069see that 4 bytes more per item really isn't that much more memory...
2070
2071A call to dict.keys() makes one fast scan over the dictionary
2072(internally, the iteration function does exist) copying the pointers
2073to the key objects into a pre-allocated list object of the right size.
2074The iteration time isn't lost (since you'll have to iterate anyway --
2075unless in the majority of cases your loop terminates very prematurely
2076(which I doubt since you're getting the keys in random order).
2077
2078I don't expose the dictionary iteration operation to Python
2079programmers because the dictionary shouldn't be modified during the
2080entire iteration -- if it is, there's a very small chance that the
2081dictionary is reorganized because the hash table becomes too full, and
2082then the iteration may miss some items and see others twice. Exactly
2083because this only occurs rarely, it would lead to hidden bugs in
2084programs: it's easy never to have it happen during test runs if you
2085only insert or delete a few items per iteration -- but your users will
2086surely hit upon it sooner or later.
2087
Guido van Rossumb0a2ce51995-08-28 19:41:35 +000020886.13. Q. Can Python be compiled to machine code, C or some other language?
2089
2090A. Not easily. Python's high level data types, dynamic typing of
2091objects and run-time invocation of the interpreter (using eval() or
2092exec) together mean that a "compiled" Python program would probably
2093consist mostly of calls into the Python run-time system, even for
2094seemingly simple operations like "x+1". Thus, the performance gain
2095would probably be minimal.
2096
2097Internally, Python source code is always translated into a "virtual
2098machine code" or "byte code" representation before it is interpreted
2099(by the "Python virtual machine" or "bytecode interpreter"). In order
2100to avoid the overhead of parsing and translating modules that rarely
2101change over and over again, this byte code is written on a file whose
2102name ends in ".pyc" whenever a module is parsed (from a file whose
2103name ends in ".py"). When the corresponding .py file is changed, it
2104is parsed and translated again and the .pyc file is rewritten. There
2105is no performance difference once the .pyc file has been loaded (the
2106bytecode read from the .pyc file is exactly the same as the bytecode
2107created by direct translation). The only difference is that loading
2108code from a .pyc file is faster than parsing and translating a .py
2109file, so the presence of precompiled .pyc files will generally improve
2110start-up time of Python scripts. If desired, the Lib/compileall.py
2111module/script can be used to force creation of valid .pyc files for a
2112given set of modules.
2113
2114If you are looking for a way to translate Python programs in order to
2115distribute them in binary form, without the need to distribute the
2116interpreter and library as well, have a look at the freeze.py script
2117in the Tools/freeze directory. This creates a single binary file
2118incorporating your program, the Python interpreter, and those parts of
2119the Python library that are needed by your program. Of course, the
2120resulting binary will only run on the same type of platform as that
2121used to create it.
2122
2123Hints for proper usage of freeze.py:
2124
2125- the script must be in a file whose name ends in .py
2126
2127- you must have installed Python fully:
2128
Guido van Rossume7d92d51995-10-11 18:06:54 +00002129 make install
2130 make libinstall
2131 make inclinstall
2132 make libainstall
Guido van Rossumb0a2ce51995-08-28 19:41:35 +00002133
Guido van Rossum05151e01995-09-28 13:24:46 +000021346.14. Q. Why doesn't Python use proper garbage collection?
2135
2136A. It's looking less and less likely that Python will ever get
2137"automatic" garbage collection (GC). For one thing, unless this were
2138added to C as a standard feature, it's a portability pain in the ass.
2139And yes, I know about the Xerox library. It has bits of assembler
2140code for *most* *common* platforms. Not for all. And although it is
2141mostly transparent, it isn't completely transparent (when I once
2142linked Python with it, it dumped core).
2143
2144"Proper" GC also becomes a problem when Python gets embedded into
2145other applications. While in a stand-alone Python it may be fine to
2146replace the standard malloc() and free() with versions provided by the
2147GC library, an application embedding Python may want to have its *own*
2148substitute for malloc() and free(), and may not want Python's. Right
2149now, Python works with anything that implements malloc() and free()
2150properly.
2151
2152Besides, the predictability of destructor calls in Python is kind of
2153attractive. With GC, the following code (which is fine in current
2154Python) will run out of file descriptors long before it runs out of
2155memory:
2156
Guido van Rossume7d92d51995-10-11 18:06:54 +00002157 for file in <very long list of files>:
2158 f = open(file)
2159 c = file.read(1)
Guido van Rossum05151e01995-09-28 13:24:46 +00002160
2161Using the current reference counting and destructor scheme, each new
2162assignment to f closes the previous file. Using GC, this is not
2163guaranteed. Sure, you can think of ways to fix this. But it's not
2164off-the-shelf technology.
2165
Guido van Rossuma7925f11994-01-26 10:20:16 +00002166
21677. Using Python on non-UNIX platforms
2168=====================================
2169
Guido van Rossum91f60831994-02-15 15:52:27 +000021707.1. Q. Is there a Mac version of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002171
Guido van Rossume530c581995-04-10 12:32:16 +00002172A. Yes, see the "mac" subdirectory of the distribution sites,
Guido van Rossum7be34a81995-05-31 15:17:12 +00002173e.g. <URL:ftp://ftp.python.org/pub/python/mac/>.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002174
Guido van Rossumc458e941996-09-11 15:43:13 +000021757.2. Q. Are there DOS and Windows versions of Python?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002176
Guido van Rossumc458e941996-09-11 15:43:13 +00002177A. Yes. There is a plethora of not-always-compatible versions. See
2178the "pythonwin", "wpy", "nt" and "pc" subdirectories of the
2179distribution sites. A quick comparison:
Guido van Rossuma7925f11994-01-26 10:20:16 +00002180
Guido van Rossumc458e941996-09-11 15:43:13 +00002181PythonWin: Extensive support for the 32-bit native Windows API and GUI
2182building using MFC. Windows NT and Windows 95 only (and Windows
21833.1(1) using win32s, until Microsoft stops supporting it :-( ).
2184<URL:ftp://ftp.python.org/pub/python/pythonwin/>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002185
Guido van Rossumc458e941996-09-11 15:43:13 +00002186WPY: Ports to DOS, Windows 3.1(1), Windows 95, Windows NT and OS/2.
2187Also contains a GUI package that offers portability between Windows
2188(not DOS) and Unix, and native look and feel on both.
2189<URL:ftp://ftp.python.org/pub/python/wpy/>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002190
Guido van Rossumc458e941996-09-11 15:43:13 +00002191NT: Basic ports built straight from the 1.4 distribution for Windows
219295 and Windows NT. This will eventually provide core support for
2193both PythonWin and WPY on all 32-bit Microsoft platforms.
Guido van Rossum3fc9d731995-07-25 15:10:56 +00002194<URL:ftp://ftp.python.org/pub/python/nt/>.
2195
Guido van Rossumc458e941996-09-11 15:43:13 +00002196PC: Old, unsupported ports to DOS, Windows 3.1(1) and OS/2.
2197<URL:ftp://ftp.python.org/pub/python/pc/>.
Guido van Rossum91f60831994-02-15 15:52:27 +00002198
Guido van Rossumc458e941996-09-11 15:43:13 +000021997.3. Q. Is there an OS/2 version of Python?
Guido van Rossum061f1821994-10-06 16:03:45 +00002200
Guido van Rossumc458e941996-09-11 15:43:13 +00002201A. Yes, see the "pc" and "wpy" subdirectory of the distribution sites
2202(see above).
Guido van Rossum061f1821994-10-06 16:03:45 +00002203
Guido van Rossumc458e941996-09-11 15:43:13 +000022047.4. Q. Is there a VMS version of Python?
Guido van Rossume530c581995-04-10 12:32:16 +00002205
Guido van Rossum3fc9d731995-07-25 15:10:56 +00002206A. Donn Cave <donn@cac.washington.edu> did a partial port. The
2207results of his efforts are on public display in
Guido van Rossumbf8e7d51995-08-28 03:09:13 +00002208<<URL:ftp://ftp.python.org/pub/python/contrib/vms.tar.gz/>. Someone
2209else is working on a more complete port, for details watch the list.
Guido van Rossume530c581995-04-10 12:32:16 +00002210
Guido van Rossumc458e941996-09-11 15:43:13 +000022117.5. Q. What about IBM mainframes, or other non-UNIX platforms?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002212
Guido van Rossumb0a2ce51995-08-28 19:41:35 +00002213A. I haven't heard about these, except I remember hearing about an
2214OS/9 port and a port to Vxworks (both operating systems for embedded
2215systems). If you're interested in any of this, go directly to the
2216newsgroup and ask there, you may find exactly what you need. For
2217example, a port to MPE/iX 5.0 on HP3000 computers was just announced,
2218see <URL:http://www.allegro.com/software/>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002219
Guido van Rossumc458e941996-09-11 15:43:13 +000022207.6. Q. Where are the source or Makefiles for the non-UNIX versions?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002221
Guido van Rossume530c581995-04-10 12:32:16 +00002222A. The standard sources can (almost) be used. Additional sources can
2223be found in the platform-specific subdirectories of the distribution.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002224
Guido van Rossumc458e941996-09-11 15:43:13 +000022257.7. Q. What is the status and support for the non-UNIX versions?
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002226
2227A. I don't have access to most of these platforms, so in general I am
2228dependent on material submitted by volunteers(*). However I strive to
2229integrate all changes needed to get it to compile on a particular
2230platform back into the standard sources, so porting of the next
2231version to the various non-UNIX platforms should be easy.
2232
Guido van Rossuma6c707c1995-01-02 17:32:28 +00002233(*) For the Macintosh, that volunteer is me, with help from Jack
2234Jansen <jack@cwi.nl>.
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002235
Guido van Rossumc458e941996-09-11 15:43:13 +000022367.8. Q. I have a PC version but it appears to be only a binary.
Guido van Rossum7ce61c11994-06-13 15:13:56 +00002237Where's the library?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002238
2239A. You still need to copy the files from the distribution directory
Guido van Rossum91f60831994-02-15 15:52:27 +00002240"python/Lib" to your system. If you don't have the full distribution,
Guido van Rossume530c581995-04-10 12:32:16 +00002241you can get the file lib<version>.tar.gz from most ftp sites carrying
2242Python; this is a subset of the distribution containing just those
Guido van Rossum7be34a81995-05-31 15:17:12 +00002243files, e.g. <URL:ftp://ftp.python.org/pub/python/src/lib1.1.tar.gz>.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002244
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002245Once you have installed the library, you need to point sys.path to it.
2246Assuming the library is in C:\misc\python\lib, the following commands
2247will point your Python interpreter to it (note the doubled backslashes
2248-- you can also use single forward slashes instead):
2249
Guido van Rossuma6c707c1995-01-02 17:32:28 +00002250 >>> import sys
2251 >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
2252 >>>
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002253
2254For a more permanent effect, set the environment variable PYTHONPATH,
2255as follows (talking to a DOS prompt):
2256
Guido van Rossuma6c707c1995-01-02 17:32:28 +00002257 C> SET PYTHONPATH=C:\misc\python\lib
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002258
Guido van Rossumc458e941996-09-11 15:43:13 +000022597.9. Q. Where's the documentation for the Mac or PC version?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002260
Guido van Rossume530c581995-04-10 12:32:16 +00002261A. The documentation for the Unix version also applies to the Mac and
2262PC versions. Where applicable, differences are indicated in the text.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002263
Guido van Rossumc458e941996-09-11 15:43:13 +000022647.10. Q. The Mac (PC) version doesn't seem to have any facilities for
Guido van Rossum91f60831994-02-15 15:52:27 +00002265creating or editing programs apart from entering it interactively, and
2266there seems to be no way to save code that was entered interactively.
2267How do I create a Python program on the Mac (PC)?
Guido van Rossuma7925f11994-01-26 10:20:16 +00002268
Guido van Rossumb34e8aa1994-09-23 14:20:38 +00002269A. Use an external editor. On the Mac, BBEdit seems to be a popular
2270no-frills text editor. I work like this: start the interpreter; edit
2271a module file using BBedit; import and test it in the interpreter;
2272edit again in BBedit; then use the built-in function reload() to
2273re-read the imported module; etc.
Guido van Rossum5333c5d1994-04-11 11:06:22 +00002274
2275Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
2276anyone with a pulse could certainly figure out how to do the same on
2277MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
2278Not only can you easily resave and "reload()" from Python after making
2279changes, but since WinNot auto-copies to the clipboard any text you
2280select, you can simply select the entire procedure (function) which
2281you changed in WinNot, switch to QWPython, and shift-ins to reenter
2282the changed program unit."