home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !Python / Misc / HTMLFAQ < prev    next >
Encoding:
Text File  |  1996-11-14  |  113.7 KB  |  1,766 lines

  1. <!doctype html public "-//IETF//DTD HTML 2.0//EN"><html>
  2. <head><title>Python Frequently-Asked Questions v$Revision: 1.39 $
  3.  
  4. </title></head><body>(This file was generated using Ping's
  5. <a href="faq2html.py">faq2html.py</a>.)
  6. <pre>Subject: FAQ: Python -- an object-oriented language
  7. Newsgroups: comp.lang.python,comp.answers,news.answers
  8. Followup-to: comp.lang.python
  9. From: guido@cnri.reston.va.us (Guido van Rossum)
  10. Reply-to: guido@cnri.reston.va.us (Guido van Rossum)
  11. Expires: Sun, 1 Dec 1996 00:00:00 GMT
  12. Supersedes: <a href="mailto:DxJ3t1.CJv@cwi.nl">DxJ3t1.CJv@cwi.nl</a>
  13. Approved: news-answers-request@MIT.Edu
  14. </pre><pre>Archive-name: python-faq/part1
  15. Submitted-by: Guido van Rossum <a href="mailto:guido@cnri.reston.va.us">guido@cnri.reston.va.us</a>
  16. Version: $Revision: 1.39 $
  17. Last-modified: $Date: 1996/10/23 20:52:55 $
  18. </pre><p>This article contains answers to Frequently Asked Questions about
  19. Python (an object-oriented interpreted programming language -- see
  20. the answer to <a href="#1.1">question 1.1</a> for a short overview).
  21. </p><p>Copyright 1993-1996 Guido van Rossum.  Unchanged electronic
  22. redistribution of this FAQ is allowed.  Printed redistribution only
  23. with permission of the author.  No warranties.
  24. </p><p>Author's address:
  25. </p><pre>        Guido van Rossum
  26.         C.N.R.I.
  27.         1895 Preston White Drive
  28.         Reston, VA 20191
  29.         U.S.A.
  30. Email:  <a href="mailto:guido@python.org">guido@python.org</a>, <a href="mailto:guido@cnri.reston.va.us">guido@cnri.reston.va.us</a>
  31. </pre><p>The latest version of this FAQ is available by anonymous ftp from
  32. <a href="ftp://ftp.python.org/pub/python/doc/FAQ">ftp://ftp.python.org/pub/python/doc/FAQ</a>.  It will also be posted
  33. regularly to the newsgroups comp.answers <a href="news:comp.answers">news:comp.answers</a> and
  34. comp.lang.python <a href="news:comp.lang.python">news:comp.lang.python</a>.
  35. </p><p>Many FAQs, including this one, are available by anonymous ftp
  36. <a href="ftp://rtfm.mit.edu/pub/usenet/news.answers/">ftp://rtfm.mit.edu/pub/usenet/news.answers/</a>.  The name under
  37. which a FAQ is archived appears in the Archive-name line at the top of
  38. the article.  This FAQ is archived as python-faq/part1
  39. <a href="ftp://rtfm.mit.edu/pub/usenet/news.answers/python-faq/part1">ftp://rtfm.mit.edu/pub/usenet/news.answers/python-faq/part1</a>.
  40. </p><p>There's a mail server on that machine which will send you files from
  41. the archive by e-mail if you have no ftp access.  You send a e-mail
  42. message to <a href="mailto:mail-server@rtfm.mit.edu">mail-server@rtfm.mit.edu</a> containing the single word help
  43. in the message body to receive instructions.
  44. </p><p>This FAQ is divided in the following chapters:
  45. </p><ol><li>General information and availability
  46. </li><li>Python in the real world
  47. </li><li>Building Python and Other Known Bugs
  48. </li><li>Programming in Python
  49. </li><li>Extending Python
  50. </li><li>Python's design
  51. </li><li>Using Python on non-UNIX platforms
  52. </li></ol><p>To find the start of a particular chapter, search for the chapter number
  53. followed by a dot and a space at the beginning of a line (e.g. to
  54. find chapter 4 in vi, type /^4\. /).
  55. </p><p>Here's an overview of the questions per chapter:
  56. </p><ol><li>General information and availability
  57. <ol><li><a href="#1.1"><em>What is Python?
  58. </em></a></li><li><a href="#1.2"><em>Why is it called Python?
  59. </em></a></li><li><a href="#1.3"><em>How do I obtain a copy of the Python source?
  60. </em></a></li><li><a href="#1.4"><em>How do I get documentation on Python?
  61. </em></a></li><li><a href="#1.5"><em>Are there other ftp sites that mirror the Python distribution?
  62. </em></a></li><li><a href="#1.6"><em>Is there a newsgroup or mailing list devoted to Python?
  63. </em></a></li><li><a href="#1.7"><em>Is there a WWW page devoted to Python?
  64. </em></a></li><li><a href="#1.8"><em>Is the Python documentation available on the WWW?
  65. </em></a></li><li><a href="#1.9"><em>Is there a book on Python, or will there be one out soon?
  66. </em></a></li><li><a href="#1.10"><em>Are there any published articles about Python that I can quote?
  67. </em></a></li><li><a href="#1.11"><em>Are there short introductory papers or talks on Python?
  68. </em></a></li><li><a href="#1.12"><em>How does the Python version numbering scheme work?
  69. </em></a></li><li><a href="#1.13"><em>How do I get a beta test version of Python?
  70. </em></a></li><li><a href="#1.14"><em>Are there copyright restrictions on the use of Python?
  71. </em></a></li><li><a href="#1.15"><em>Why was Python created in the first place?
  72. </em></a></li></ol></li><li>Python in the real world
  73. <ol><li><a href="#2.1"><em>How many people are using Python?
  74. </em></a></li><li><a href="#2.2"><em>Have any significant projects been done in Python?
  75. </em></a></li><li><a href="#2.3"><em>Are there any commercial projects going on using Python?
  76. </em></a></li><li><a href="#2.4"><em>How stable is Python?
  77. </em></a></li><li><a href="#2.5"><em>What new developments are expected for Python in the future?
  78. </em></a></li><li><a href="#2.6"><em>Is it reasonable to propose incompatible changes to Python?
  79. </em></a></li><li><a href="#2.7"><em>What is the future of Python?
  80. </em></a></li><li><a href="#2.8"><em>What is the PSA, anyway?
  81. </em></a></li><li><a href="#2.9"><em>How do I join the PSA?
  82. </em></a></li><li><a href="#2.10"><em>What are the benefits of joining the PSA?
  83. </em></a></li></ol></li><li>Building Python and Other Known Bugs
  84. <ol><li><a href="#3.1"><em>Is there a test set?
  85. </em></a></li><li><a href="#3.2"><em>When running the test set, I get complaints about floating point
  86.        operations, but when playing with floating point operations I cannot
  87.        find anything wrong with them.
  88. </em></a></li><li><a href="#3.3"><em>Link errors after rerunning the configure script.
  89. </em></a></li><li><a href="#3.4"><em>The python interpreter complains about options passed to a
  90.        script (after the script name).
  91. </em></a></li><li><a href="#3.5"><em>When building on the SGI, make tries to run python to create
  92.        glmodule.c, but python hasn't been built or installed yet.
  93. </em></a></li><li><a href="#3.6"><em>I use VPATH but some targets are built in the source directory.
  94. </em></a></li><li><a href="#3.7"><em>Trouble building or linking with the GNU readline library.
  95. </em></a></li><li><a href="#3.8"><em>Trouble with socket I/O on older Linux 1.x versions.
  96. </em></a></li><li><a href="#3.9"><em>Trouble with prototypes on Ultrix.
  97. </em></a></li><li><a href="#3.10"><em>Other trouble building Python on platform X.
  98. </em></a></li><li><a href="#3.11"><em>How to configure dynamic loading on Linux.
  99. </em></a></li><li>Q: I can't get shared modules to work on Linux 2.0 (Slackware96)?
  100. </li><li><a href="#3.13"><em>How to use threads on Linux.
  101. </em></a></li><li><a href="#3.14"><em>Errors when linking with a shared library containing C++ code.
  102. </em></a></li><li><a href="#3.15"><em>I built with tkintermodule.c enabled but get "Tkinter not found".
  103. </em></a></li><li><a href="#3.16"><em>I built with Tk 4.0 but Tkinter complains about the Tk version.
  104. </em></a></li><li><a href="#3.17"><em>Link errors for Tcl/Tk symbols when linking with Tcl/Tk.
  105. </em></a></li><li><a href="#3.18"><em>I configured and built Python for Tcl/Tk but "import Tkinter"
  106.         fails.
  107. </em></a></li><li><a href="#3.19"><em>Tk doesn't work right on DEC Alpha.
  108. </em></a></li><li><a href="#3.20"><em>Several common system calls are missing from the posix module.
  109. </em></a></li><li><a href="#3.21"><em>ImportError: No module named string, on MS Windows.
  110. </em></a></li><li><a href="#3.22"><em>Core dump on SGI when using the gl module.
  111. </em></a></li></ol></li><li>Programming in Python
  112. <ol><li><a href="#4.1"><em>Is there a source code level debugger with breakpoints, step,
  113.        etc.?
  114. </em></a></li><li><a href="#4.2"><em>Can I create an object class with some methods implemented in
  115.        C and others in Python (e.g. through inheritance)?  (Also phrased as:
  116.        Can I use a built-in type as base class?)
  117. </em></a></li><li><a href="#4.3"><em>Is there a curses/termcap package for Python?
  118. </em></a></li><li><a href="#4.4"><em>Is there an equivalent to C's onexit() in Python?
  119. </em></a></li><li><a href="#4.5"><em>When I define a function nested inside another function, the
  120.        nested function seemingly can't access the local variables of the
  121.        outer function.  What is going on?  How do I pass local data to a
  122.        nested function?
  123. </em></a></li><li><a href="#4.6"><em>How do I iterate over a sequence in reverse order?
  124. </em></a></li><li><a href="#4.7"><em>My program is too slow.  How do I speed it up?
  125. </em></a></li><li><a href="#4.8"><em>When I have imported a module, then edit it, and import it
  126.        again (into the same Python process), the changes don't seem to take
  127.        place.  What is going on?
  128. </em></a></li><li><a href="#4.9"><em>How do I find the current module name?
  129. </em></a></li><li><a href="#4.10"><em>I have a module in which I want to execute some extra code
  130.         when it is run as a script.  How do I find out whether I am running as
  131.         a script?
  132. </em></a></li><li><a href="#4.11"><em>I try to run a program from the Demo directory but it fails
  133.         with ImportError: No module named ...; what gives?
  134. </em></a></li><li><a href="#4.12"><em>I have successfully built Python with STDWIN but it can't
  135.         find some modules (e.g. stdwinevents).
  136. </em></a></li><li><a href="#4.13"><em>What GUI toolkits exist for Python?
  137. </em></a></li><li><a href="#4.14"><em>Are there any interfaces to database packages in Python?
  138. </em></a></li><li><a href="#4.15"><em>Is it possible to write obfuscated one-liners in Python?
  139. </em></a></li><li><a href="#4.16"><em>Is there an equivalent of C's "?:" ternary operator?
  140. </em></a></li><li><a href="#4.17"><em>My class defines __del__ but it is not called when I delete the
  141.         object.
  142. </em></a></li><li><a href="#4.18"><em>How do I change the shell environment for programs called
  143.         using os.popen() or os.system()?  Changing os.environ doesn't work.
  144. </em></a></li><li><a href="#4.19"><em>What is a class?
  145. </em></a></li><li><a href="#4.20"><em>What is a method?
  146. </em></a></li><li><a href="#4.21"><em>What is self?
  147. </em></a></li><li><a href="#4.22"><em>What is a unbound method?
  148. </em></a></li><li><a href="#4.23"><em>How do I call a method defined in a base class from a derived
  149.         class that overrides it?
  150. </em></a></li><li><a href="#4.24"><em>How do I call a method from a base class without using the
  151.         name of the base class?
  152. </em></a></li><li><a href="#4.25"><em>How can I organize my code to make it easier to change the base
  153.         class?
  154. </em></a></li><li><a href="#4.26"><em>How can I find the methods or attributes of an object?
  155. </em></a></li><li><a href="#4.27"><em>I can't seem to use os.read() on a pipe created with os.popen().
  156. </em></a></li><li><a href="#4.28"><em>How can I create a stand-alone binary from a Python script?
  157. </em></a></li><li><a href="#4.29"><em>What WWW tools are there for Python?
  158. </em></a></li><li><a href="#4.30"><em>How do I run a subprocess with pipes connected to both input
  159.         and output?
  160. </em></a></li><li><a href="#4.31"><em>How do I call a function if I have the arguments in a tuple?
  161. </em></a></li><li><a href="#4.32"><em>How do I enable font-lock-mode for Python in Emacs?
  162. </em></a></li><li><a href="#4.33"><em>Is there an inverse to the format operator (a la C's scanf())?
  163. </em></a></li><li><a href="#4.34"><em>Can I have Tk events handled while waiting for I/O?
  164. </em></a></li><li><a href="#4.35"><em>How do I write a function with output parameters (call by reference)?
  165. </em></a></li><li><a href="#4.36"><em>Please explain the rules for local and global variables in Python.
  166. </em></a></li><li><a href="#4.37"><em>How can I have modules that mutually import each other?
  167. </em></a></li><li><a href="#4.38"><em>How do I copy an object in Python?
  168. </em></a></li><li><a href="#4.39"><em>How to implement persistent objects in Python?  (Persistent ==
  169.         automatically saved to and restored from disk.)
  170. </em></a></li><li><a href="#4.40"><em>I try to use __spam and I get an error about _SomeClassName__spam.
  171. </em></a></li></ol></li><li>Extending Python
  172. <ol><li><a href="#5.1"><em>Can I create my own functions in C?
  173. </em></a></li><li><a href="#5.2"><em>Can I create my own functions in C++?
  174. </em></a></li><li><a href="#5.3"><em>How can I execute arbitrary Python statements from C?
  175. </em></a></li><li><a href="#5.4"><em>How can I evaluate an arbitrary Python expression from C?
  176. </em></a></li><li><a href="#5.5"><em>How do I extract C values from a Python object?
  177. </em></a></li><li><a href="#5.6"><em>How do I use mkvalue() to create a tuple of arbitrary length?
  178. </em></a></li><li><a href="#5.7"><em>How do I call an object's method from C?
  179. </em></a></li><li><a href="#5.8"><em>How do I catch the output from print_error()?
  180. </em></a></li><li><a href="#5.9"><em>How do I access a module written in Python from C?
  181. </em></a></li><li><a href="#5.10"><em>How do I interface to C++ objects from Python?
  182. </em></a></li></ol></li><li>Python's design
  183. <ol><li><a href="#6.1"><em>Why isn't there a switch or case statement in Python?
  184. </em></a></li><li><a href="#6.2"><em>Why does Python use indentation for grouping of statements?
  185. </em></a></li><li><a href="#6.3"><em>Why are Python strings immutable?
  186. </em></a></li><li><a href="#6.4"><em>Why don't strings have methods like index() or sort(), like
  187.        lists?
  188. </em></a></li><li><a href="#6.5"><em>Why does Python use methods for some functionality
  189.        (e.g. list.index()) but functions for other (e.g. len(list))?
  190. </em></a></li><li><a href="#6.6"><em>Why can't I derive a class from built-in types (e.g. lists or
  191.        files)?
  192. </em></a></li><li><a href="#6.7"><em>Why must 'self' be declared and used explicitly in method
  193.        definitions and calls?
  194. </em></a></li><li><a href="#6.8"><em>Can't you emulate threads in the interpreter instead of
  195.        relying on an OS-specific thread implementation?
  196. </em></a></li><li><a href="#6.9"><em>Why can't lambda forms contain statements?
  197. </em></a></li><li><a href="#6.10"><em>Why don't lambdas have access to variables defined in the
  198.         containing scope?
  199. </em></a></li><li><a href="#6.11"><em>Why can't recursive functions be defined inside other functions?
  200. </em></a></li><li><a href="#6.12"><em>Why is there no more efficient way of iterating over a dictionary
  201.         than first constructing the list of keys()?
  202. </em></a></li><li><a href="#6.13"><em>Can Python be compiled to machine code, C or some other language?
  203. </em></a></li><li><a href="#6.14"><em>Why doesn't Python use proper garbage collection?
  204. </em></a></li></ol></li><li>Using Python on non-UNIX platforms
  205. <ol><li><a href="#7.1"><em>Is there a Mac version of Python?
  206. </em></a></li><li><a href="#7.2"><em>Are there DOS and Windows versions of Python?
  207. </em></a></li><li><a href="#7.3"><em>Is there an OS/2 version of Python?
  208. </em></a></li><li><a href="#7.4"><em>Is there a VMS version of Python?
  209. </em></a></li><li><a href="#7.5"><em>What about IBM mainframes, or other non-UNIX platforms?
  210. </em></a></li><li><a href="#7.6"><em>Where are the source or Makefiles for the non-UNIX versions?
  211. </em></a></li><li><a href="#7.7"><em>What is the status and support for the non-UNIX versions?
  212. </em></a></li><li><a href="#7.8"><em>I have a PC version but it appears to be only a binary.
  213.        Where's the library?
  214. </em></a></li><li><a href="#7.9"><em>Where's the documentation for the Mac or PC version?
  215. </em></a></li><li><a href="#7.10"><em>The Mac (PC) version doesn't seem to have any facilities for
  216.         creating or editing programs apart from entering it interactively, and
  217.         there seems to be no way to save code that was entered interactively.
  218.         How do I create a Python program on the Mac (PC)?
  219. </em></a></li></ol></li></ol><p>To find a particular question, search for the question number followed
  220. by a dot, a space, and a Q at the beginning of a line (e.g. to find
  221. <a href="#4.2">question 4.2</a> in vi, type /^4\.2\. Q/).
  222. </p><hr><h1>1. <a name="1">General information and availability
  223. </a></h1><h2>1.1. <a name="1.1"><em>What is Python?
  224. </em></a></h2><p><strong>Python is an interpreted, interactive, object-oriented programming
  225. language.</strong>  It incorporates modules, exceptions, dynamic typing, very
  226. high level dynamic data types, and classes.  Python combines
  227. remarkable power with very clear syntax.  It has interfaces to many
  228. system calls and libraries, as well as to various window systems, and
  229. is extensible in C or C++.  It is also usable as an extension language
  230. for applications that need a programmable interface.  Finally, Python
  231. is portable: it runs on many brands of UNIX, on the Mac, and on PCs
  232. under MS-DOS, Windows, Windows NT, and OS/2.
  233. </p><p>To find out more, the best thing to do is to start reading the
  234. tutorial from the documentation set (see a few questions further
  235. down).
  236. </p><h2>1.2. <a name="1.2"><em>Why is it called Python?
  237. </em></a></h2><p><strong>Apart from being a computer scientist, I'm also a fan of "Monty
  238. Python's Flying Circus" </strong>(a BBC comedy series from the seventies, in
  239. the -- unlikely -- case you didn't know).  It occurred to me one day
  240. that I needed a name that was short, unique, and slightly mysterious.
  241. And I happened to be reading some scripts from the series at the
  242. time...  So then I decided to call my language Python.  But Python is
  243. not a joke.  And don't you associate it with dangerous reptiles
  244. either!  (If you need an icon, use an image of the 16-ton weight from
  245. the TV series or of a can of SPAM :-)
  246. </p><h2>1.3. <a name="1.3"><em>How do I obtain a copy of the Python source?
  247. </em></a></h2><p><strong>The latest complete Python source distribution is always available
  248. by anonymous ftp, e.g.</strong>
  249. <a href="ftp://ftp.python.org/pub/python/src/python1.3.tar.gz">ftp://ftp.python.org/pub/python/src/python1.3.tar.gz</a>.  It is a
  250. gzipped tar file containing the complete C source, LaTeX
  251. documentation, Python library modules, example programs, and several
  252. useful pieces of freely distributable software.  This will compile and
  253. run out of the box on most UNIX platforms.  (See <a href="#7">section 7</a> for
  254. non-UNIX information.)
  255. </p><p>Sometimes beta versions of a newer release are available; check the
  256. subdirectory "beta" of the above-mentioned URL (i.e.
  257. <a href="ftp://ftp.python.org/pub/python/src/beta/">ftp://ftp.python.org/pub/python/src/beta/</a>).  (At the time of
  258. writing, beta3 for Python 1.4 is available there, and should be
  259. checked before reporting problems with version 1.3.)
  260. </p><p>Occasionally a set of patches is issued which has to be applied using
  261. the patch program.  These patches are placed in the same directory,
  262. e.g. <a href="ftp://ftp.python.org/pub/python/src/patch1.1.1">ftp://ftp.python.org/pub/python/src/patch1.1.1</a>.  (At the time
  263. of writing, no patches exist.)
  264. </p><p>An index of said ftp directory can be found in the file INDEX.  An
  265. HTML version of the index can be found in the file index.html,
  266. <a href="ftp://ftp.python.org/pub/python/index.html">ftp://ftp.python.org/pub/python/index.html</a>.
  267. </p><h2>1.4. <a name="1.4"><em>How do I get documentation on Python?
  268. </em></a></h2><p><strong>The LaTeX source for the documentation is part of the source
  269. distribution.</strong>  If you don't have LaTeX, the latest Python
  270. documentation set is always available by anonymous ftp, e.g.
  271. <a href="ftp://ftp.python.org/pub/python/doc/postscript.tar.gz">ftp://ftp.python.org/pub/python/doc/postscript.tar.gz</a>.  It is a
  272. gzipped tar file containing PostScript files of the reference manual,
  273. the library manual, and the tutorial.  Note that the library manual is
  274. the most important one of the set, as much of Python's power stems
  275. from the standard or built-in types, functions and modules, all of
  276. which are described here.  PostScript for a high-level description of
  277. Python is in the file nluug-paper.ps (a separate file on the ftp
  278. site).
  279. </p><h2>1.5. <a name="1.5"><em>Are there other ftp sites that mirror the Python distribution?
  280. </em></a></h2><p><strong>The following anonymous ftp sites keep mirrors of the Python
  281. distribution:</strong>
  282. </p><p>USA:
  283. </p><pre>        <a href="ftp://ftp.python.org/pub/python/">ftp://ftp.python.org/pub/python/</a>
  284.         <a href="ftp://gatekeeper.dec.com/pub/plan/python/">ftp://gatekeeper.dec.com/pub/plan/python/</a>
  285.         <a href="ftp://ftp.uu.net/languages/python/">ftp://ftp.uu.net/languages/python/</a>
  286.         <a href="ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/">ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/</a>
  287.         <a href="ftp://ftp.sterling.com/programming/languages/python/">ftp://ftp.sterling.com/programming/languages/python/</a>
  288.         <a href="ftp://uiarchive.cso.uiuc.edu/pub/lang/python/">ftp://uiarchive.cso.uiuc.edu/pub/lang/python/</a>
  289.         <a href="ftp://ftp.pht.com/mirrors/python/python/">ftp://ftp.pht.com/mirrors/python/python/</a>
  290. </pre><p>Europe:
  291. </p><pre>        <a href="ftp://ftp.cwi.nl/pub/python/">ftp://ftp.cwi.nl/pub/python/</a>
  292.         <a href="ftp://ftp.funet.fi/pub/languages/python/">ftp://ftp.funet.fi/pub/languages/python/</a>
  293.         <a href="ftp://ftp.sunet.se/pub/lang/python/">ftp://ftp.sunet.se/pub/lang/python/</a>
  294.         <a href="ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/">ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/</a>
  295.         <a href="ftp://ftp.ibp.fr/pub/python/">ftp://ftp.ibp.fr/pub/python/</a>
  296.         <a href="ftp://ftp.switch.ch/software/sources/python/">ftp://ftp.switch.ch/software/sources/python/</a>
  297.         <a href="ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/">ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/</a>
  298. </pre><p>Australia:
  299. </p><pre>        <a href="ftp://ftp.dstc.edu.au/pub/python/">ftp://ftp.dstc.edu.au/pub/python/</a>
  300. </pre><p>Or try archie on the string "python".
  301. </p><h2>1.6. <a name="1.6"><em>Is there a newsgroup or mailing list devoted to Python?
  302. </em></a></h2><p><strong>There is a newsgroup, comp.lang.python <a href="news:comp.lang.python">news:comp.lang.python</a>,
  303. and a mailing list.</strong>  The newsgroup and mailing list are gatewayed into
  304. each other -- if you can read news it's unnecessary to subscribe to
  305. the mailing list.  Send e-mail to <a href="mailto:python-list-request@cwi.nl">python-list-request@cwi.nl</a> to
  306. (un)subscribe to the mailing list.  Hypermail archives of (nearly)
  307. everything posted to the mailing list (and thus the newsgroup) are
  308. available on our WWW server,
  309. <a href="http://www.cwi.nl/~guido/hypermail/index.html">http://www.cwi.nl/~guido/hypermail/index.html</a>.  The raw archives
  310. are also available by ftp, e.g.
  311. <a href="ftp://ftp.python.org/pub/python/mail/mailinglist.gz">ftp://ftp.python.org/pub/python/mail/mailinglist.gz</a>.  The
  312. uncompressed versions of these files can be read with the standard
  313. UNIX Mail program ("Mail -f file") or with nn ("nn file").  To read
  314. them using MH, you could use "inc -file file".  (The archival service
  315. has stopped archiving new articles around the end of April 1995.  I
  316. hope to revive it on the PSA server www.python.org sometime in the
  317. future.)
  318. </p><h2>1.7. <a name="1.7"><em>Is there a WWW page devoted to Python?
  319. </em></a></h2><p><strong>Yes, <a href="http://www.python.org/">http://www.python.org/</a></strong> is the official Python home page.
  320. At the time of writing, this page is not yet completely operational;
  321. you may have a look at the old Python home page:
  322. <a href="http://www.cwi.nl/~guido/Python.html">http://www.cwi.nl/~guido/Python.html</a> or at the U.S. copy:
  323. <a href="http://www.python.org/~guido/Python.html">http://www.python.org/~guido/Python.html</a>.
  324. </p><h2>1.8. <a name="1.8"><em>Is the Python documentation available on the WWW?
  325. </em></a></h2><p><strong>Yes, see <a href="http://www.python.org/">http://www.python.org/</a></strong> (Python's home page).  It
  326. contains pointers to hypertext versions of the whole documentation set
  327. (as hypertext, not just PostScript).
  328. </p><p>If you wish to browse this collection of HTML files on your own
  329. machine, it is available bundled up by anonymous ftp,
  330. e.g. <a href="ftp://ftp.python.org/pub/python/doc/html.tar.gz">ftp://ftp.python.org/pub/python/doc/html.tar.gz</a>.
  331. </p><p>An Emacs-INFO set containing the library manual is also available by
  332. ftp, e.g. <a href="ftp://ftp.python.org/pub/python/doc/lib-info.tar.gz">ftp://ftp.python.org/pub/python/doc/lib-info.tar.gz</a>.
  333. </p><h2>1.9. <a name="1.9"><em>Is there a book on Python, or will there be one out soon?
  334. </em></a></h2><p><strong>Mark Lutz is writing a Python book for O'Reilly and Associates, to
  335. be published early 1996.</strong>  See the outline (in PostScript):
  336. <a href="http://www.python.org/workshops/1995-05/outlinep.eps">http://www.python.org/workshops/1995-05/outlinep.eps</a>.
  337. </p><h2>1.10. <a name="1.10"><em>Are there any published articles about Python that I can quote?
  338. </em></a></h2><p><strong>So far the only refereed and published article that describes
  339. Python in some detail is:</strong>
  340. </p><pre>    Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
  341.     Servers Using the Python Programming Language", CWI Quarterly, Volume
  342.     4, Issue 4 (December 1991), Amsterdam, pp 283-303.
  343. </pre><p>LaTeX source for this paper is available as part of the Python source
  344. distribution.
  345. </p><p>See also the next section (supposedly Aaron Watters' paper has been
  346. refereed).
  347. </p><h2>1.11. <a name="1.11"><em>Are there short introductory papers or talks on Python?
  348. </em></a></h2><p><strong>A recent, very entertaining introduction to Python is the tutorial by
  349. Aaron Watters in UnixWorld Online:</strong>
  350. </p><pre>    Aaron R. Watters: "The What, Why, Who, and Where of Python",
  351.     <a href="http://www.wcmh.com/uworld/archives/95/tutorial/005.html">http://www.wcmh.com/uworld/archives/95/tutorial/005.html</a>
  352. </pre><p>An olded paper is:
  353. </p><pre>    Guido van Rossum, "An Introduction to Python for UNIX/C
  354.     Programmers", in the proceedings of the NLUUG najaarsconferentie
  355.     1993 (dutch UNIX users group meeting November 1993).
  356. </pre><p>PostScript for this paper and for the slides used for the accompanying
  357. presentation is available by ftp as
  358. <a href="ftp://ftp.python.org/pub/python/doc/nluug-paper.ps">ftp://ftp.python.org/pub/python/doc/nluug-paper.ps</a> and
  359. <a href="ftp://ftp.python.org/pub/python/doc/nluug-slides.ps">ftp://ftp.python.org/pub/python/doc/nluug-slides.ps</a>, respectively.
  360. </p><p>Slides for a talk on Python that I gave at the Usenix Symposium on
  361. Very High Level Languages in Santa Fe, NM, USA in October 1994 are
  362. available as <a href="ftp://ftp.python.org/pub/python/doc/vhll-slides.ps">ftp://ftp.python.org/pub/python/doc/vhll-slides.ps</a>.
  363. </p><h2>1.12. <a name="1.12"><em>How does the Python version numbering scheme work?
  364. </em></a></h2><p><strong>Python versions are numbered A.B.C or A.B.</strong>  A is the major version
  365. number -- it is only incremented for major changes in functionality or
  366. source structure.  B is the minor version number, incremented for less
  367. earth-shattering changes to a release.  C is the patchlevel -- it is
  368. incremented for each new patch release.  Not all releases have patch
  369. releases.  Note that in the past, patches have added significant
  370. changes; in fact the changeover from 0.9.9 to 1.0.0 was the first time
  371. that either A or B changed!
  372. </p><p>Beta versions have an additional suffix of "betaN" for some small
  373. number N.  Note that (for instance) all versions labeled 1.4betaN
  374. *precede* the actual release of 1.4.  1.4b3 is short for 1.4beta3.
  375. </p><h2>1.13. <a name="1.13"><em>How do I get a beta test version of Python?
  376. </em></a></h2><p><strong>If there are any beta releases, they are published in the normal
  377. source directory </strong>(e.g. <a href="ftp://ftp.python.org/pub/python/src/">ftp://ftp.python.org/pub/python/src/</a>).
  378. </p><h2>1.14. <a name="1.14"><em>Are there copyright restrictions on the use of Python?
  379. </em></a></h2><p><strong>Hardly.</strong>  You can do anything you want with the source, as long as
  380. you leave the copyrights in, and display those copyrights in any
  381. documentation about Python that you produce.  Also, don't use the
  382. author's institute's name in publicity without prior written
  383. permission, and don't hold them responsible for anything (read the
  384. actual copyright for a precise legal wording).
  385. </p><p>In particular, if you honor the copyright rules, it's OK to use Python
  386. for commercial use, to sell copies of Python in source or binary form,
  387. or to sell products that enhance Python or incorporate Python (or part
  388. of it) in some form.  I would still like to know about all commercial
  389. use of Python!
  390. </p><h2>1.15. <a name="1.15"><em>Why was Python created in the first place?
  391. </em></a></h2><p><strong>Here's a *very* brief summary of what got me started:</strong>
  392. </p><ul><li>I had extensive experience with implementing an interpreted language
  393. in the ABC group at CWI, and from working with this group I had
  394. learned a lot about language design.  This is the origin of many
  395. Python features, including the use of indentation for statement
  396. grouping and the inclusion of very-high-level data types (although the
  397. details are all different in Python).
  398. </li><li>I had a number of gripes about the ABC language, but also liked many
  399. of its features.  It was impossible to extend the ABC language (or its
  400. implementation) to remedy my complaints -- in fact its lack of
  401. extensibility was one of its biggest problems.
  402. </li><li>I had some experience with using Modula-2+ and talked with the
  403. designers of Modula-3 (and read the M3 report).  M3 is the origin of
  404. the syntax and semantics used for exceptions, and some other Python
  405. features.
  406. </li><li>I was working in the Amoeba distributed operating system group at
  407. CWI.  We needed a better way to do system administration than by
  408. writing either C programs or Bourne shell scripts, since Amoeba had
  409. its own system call interface which wasn't easily accessible from the
  410. Bourne shell.  My experience with error handling in Amoeba made me
  411. acutely aware of the importance of exceptions as a programming
  412. language feature.
  413. </li><li>It occurred to me that a scripting language with a syntax like ABC
  414. but with access to the Amoeba system calls would fill the need.  I
  415. realized that it would be foolish to write an Amoeba-specific
  416. language, so I decided that I needed a language that was generally
  417. extensible.
  418. </li><li>During the 1989 Christmas holidays, I had a lot of time on my hand,
  419. so I decided to give it a try.  During the next year, while still
  420. mostly working on it in my own time, Python was used in the Amoeba
  421. project with increasing success, and the feedback from colleagues made
  422. me add many early improvements.
  423. </li><li>In February 1991, after just over a year of development, I decided
  424. to post to USENET.  The rest is in the Misc/HISTORY file.
  425. </li></ul><hr><h1>2. <a name="2">Python in the real world
  426. </a></h1><h2>2.1. <a name="2.1"><em>How many people are using Python?
  427. </em></a></h2><p><strong>I don't know, but the maximum number of simultaneous subscriptions
  428. to the Python mailing list before it was gatewayed into the newsgroup
  429. was about 180 </strong>(several of which were local redistribution lists).  I
  430. believe that many active Python users don't bother to subscribe to the
  431. list, and now that there's a newsgroup the mailing list subscription
  432. is even less meaningful.  I see new names on the newsgroup all the
  433. time and my best guess is that there are currently at least several
  434. thousands of users.
  435. </p><p>Another statistic is the number of accesses to the Python WWW server.
  436. Have a look at <a href="http://www.python.org/stats/">http://www.python.org/stats/</a>.
  437. </p><h2>2.2. <a name="2.2"><em>Have any significant projects been done in Python?
  438. </em></a></h2><p><strong>Here at CWI </strong>(the home of Python), we have written a 20,000 line
  439. authoring environment for transportable hypermedia presentations, a
  440. 5,000 line multimedia teleconferencing tool, as well as many many
  441. smaller programs.
  442. </p><p>The University of Virginia uses Python to control a virtual reality
  443. engine.  Contact: Matt Conway <a href="mailto:conway@virginia.edu">conway@virginia.edu</a>.
  444. </p><p>The ILU project at Xerox PARC can generate Python glue for ILU
  445. interfaces.  See <a href="ftp://ftp.parc.xerox.com/pub/ilu/ilu.html">ftp://ftp.parc.xerox.com/pub/ilu/ilu.html</a>.
  446. </p><p>The University of California, Irvine uses a student administration
  447. system called TELE-Vision written entirely in Python.  Contact: Ray
  448. Price <a href="mailto:rlprice@uci.edu">rlprice@uci.edu</a>.
  449. </p><p>See also the next question.
  450. </p><p>If you have done a significant project in Python that you'd like to be
  451. included in the list above, send me email!
  452. </p><h2>2.3. <a name="2.3"><em>Are there any commercial projects going on using Python?
  453. </em></a></h2><p><strong>Several companies have revealed to me that they are planning or
  454. considering use of Python in a future product.</strong>
  455. </p><p>Sunrise Software has a product out using Python -- they use Python
  456. for a GUI management application and an SNMP network management
  457. application.  Contact: <a href="mailto:info@sunrise.com">info@sunrise.com</a>.
  458. </p><p>Infoseek uses Python to implement their commercial WWW information
  459. retrieval service <a href="http://www.infoseek.com/">http://www.infoseek.com/</a>.  Contact:
  460. <a href="mailto:info@infoseek.com">info@infoseek.com</a>.
  461. </p><p>Paul Everitt of Connecting Minds is planning a Lotus Notes gateway.
  462. Contact: <a href="mailto:Paul.Everitt@cminds.com">Paul.Everitt@cminds.com</a>.  Or see their WWW server
  463. <a href="http://www.cminds.com/">http://www.cminds.com/</a>.
  464. </p><p>KaPRE in Boulder, CO is using Python for on-site customization of C++
  465. applications, rapid-prototyping/development,
  466. language-based-components, and possibly more.  This is pretty solid:
  467. Python's being shipped with their tool-set now, to beta sites.
  468. Contact: <a href="mailto:lutz@KaPRE.COM">lutz@KaPRE.COM</a> (Mark Lutz).
  469. </p><p>Individuals at many other companies are using Python for internal
  470. development or for as yet unannounced products (witness their
  471. contributions to the Python mailing list or newsgroup).
  472. </p><p>SGI has advertised in the Python list looking for Python programmers
  473. for a project involving interactive television.
  474. </p><p>See also the workshop minutes at
  475. <a href="http://www.python.org/workshops/">http://www.python.org/workshops/</a> -- in general the WWW server is
  476. more up to date than the FAQ for these issues.
  477. </p><p>Python has also been elected as an extension language by MADE, a
  478. consortium supported by the European Committee's ESPRIT program and
  479. consisting of Bull, CWI and some other European companies.  Contact:
  480. Ivan Herman <a href="mailto:ivan@cwi.nl">ivan@cwi.nl</a>.
  481. </p><p>If you'd like to be included in the list above, send me email!
  482. </p><h2>2.4. <a name="2.4"><em>How stable is Python?
  483. </em></a></h2><p><strong>Very stable.</strong>  While the current version number would suggest it is
  484. in the early stages of development, in fact new, stable releases
  485. (numbered 0.9.x through 1.3) have been coming out roughly every 3 to
  486. 6 months for the past four years.
  487. </p><h2>2.5. <a name="2.5"><em>What new developments are expected for Python in the future?
  488. </em></a></h2><p><strong>See my Work-In-Progress web page, currently at
  489. <a href="http://www.python.org:~guido/WIP.html">http://www.python.org:~guido/WIP.html</a>, and the pages for the
  490. Second Python Workshop </strong>(best reached via the Python home page,
  491. <a href="http://www.python.org/">http://www.python.org/</a>).  Also follow the newsgroup discussions!
  492. </p><h2>2.6. <a name="2.6"><em>Is it reasonable to propose incompatible changes to Python?
  493. </em></a></h2><p><strong>In general, no.</strong>  There are already millions of lines of Python code
  494. around the world, so any changes in the language that invalidates more
  495. than a very small fraction of existing programs has to be frowned
  496. upon.  Even if you can provide a conversion program, there still is
  497. the problem of updating all documentation.  Providing a gradual
  498. upgrade path is the only way if a feature has to be changed.
  499. </p><h2>2.7. <a name="2.7"><em>What is the future of Python?
  500. </em></a></h2><p><strong>If I knew, I'd be rich :-)
  501. </strong></p><p>Seriously, the formation of the PSA (Pyton Software Activity, see
  502. <a href="http://www.python.org/psa/">http://www.python.org/psa/</a>) ensures some kind of support even in
  503. the (unlikely! event that I'd be hit by a bus (actually, here in the
  504. US, a car accident would be more likely :-), were to join a nunnery,
  505. or would be head-hunted.  A large number of Python users have become
  506. experts at Python programming as well as maintenance of the
  507. implementation, and would easily fill the vacuum created by my
  508. disappearance.
  509. </p><p>In the mean time, I have no plans to disappear -- rather, I am
  510. committed to improving Python, and my current benefactor, CNRI (see
  511. <a href="http://www.cnri.reston.va.us">http://www.cnri.reston.va.us</a>) is just as committed to continue
  512. its support of Python and the PSA.  In fact, we have great plans for
  513. Python -- we just can't tell yet!
  514. </p><h2>2.8. <a name="2.8"><em>What is the PSA, anyway?
  515. </em></a></h2><p><strong>The Python Software Activity <a href="http://www.python.org/psa/">http://www.python.org/psa/</a></strong> was
  516. created by a number of Python aficionados who want Python to be more
  517. than the product and responsibility of a single individual.  It has
  518. found a home at CNRI <a href="http://www.cnri.reston.va.us">http://www.cnri.reston.va.us</a>.  Anybody who
  519. wishes Python well should join the PSA.
  520. </p><h2>2.9. <a name="2.9"><em>How do I join the PSA?
  521. </em></a></h2><p><strong>The full scoop is available on the web, see
  522. <a href="http://www.python.org/psa/Joining.html">http://www.python.org/psa/Joining.html</a>.  Summary:</strong> send a check
  523. of at least $50 to CNRI/PSA, 1895 Preston White Drive, Suite 100, in
  524. Reston, VA 20191.  Full-time students pay $25.  Companies can join for
  525. a mere $500.
  526. </p><h2>2.10. <a name="2.10"><em>What are the benefits of joining the PSA?
  527. </em></a></h2><p><strong>Like National Public Radio, if not enough people join, Python will
  528. wither.</strong>  Your name will be mentioned on the PSA's web server.
  529. Workshops organized by the PSA <a href="http://www.python.org/workshops/">http://www.python.org/workshops/</a>
  530. are only accessible to PSA members (you can join at the door).  The
  531. PSA is working on additional benefits, such as reduced prices for
  532. books and software, and early access to beta versions of Python.
  533. </p><hr><h1>3. <a name="3">Building Python and Other Known Bugs
  534. </a></h1><h2>3.1. <a name="3.1"><em>Is there a test set?
  535. </em></a></h2><p><strong>Yes, simply do "import testall" </strong>(or "import autotest" if you aren't
  536. interested in the output).  The standard modules whose name begins
  537. with "test" together comprise the test.  The test set doesn't test
  538. *all* features of Python but it goes a long way to confirm that a new
  539. port is actually working.  The Makefile contains an entry "make test"
  540. which runs the autotest module.  NOTE: if "make test" fails, run the
  541. tests manually ("import testall") to see what goes wrong before
  542. reporting the error.
  543. </p><h2>3.2. <a name="3.2"><em>When running the test set, I get complaints about floating point
  544. operations, but when playing with floating point operations I cannot
  545. find anything wrong with them.
  546. </em></a></h2><p><strong>The test set makes occasional unwarranted assumptions about the
  547. semantics of C floating point operations.</strong>  Until someone donates a
  548. better floating point test set, you will have to comment out the
  549. offending floating point tests and execute similar tests manually.
  550. </p><h2>3.3. <a name="3.3"><em>Link errors after rerunning the configure script.
  551. </em></a></h2><p><strong>It is generally necessary to run "make clean" after a configuration
  552. change.</strong>
  553. </p><h2>3.4. <a name="3.4"><em>The python interpreter complains about options passed to a
  554. script (after the script name).
  555. </em></a></h2><p><strong>You are probably linking with GNU getopt, e.g.</strong> through -liberty.
  556. Don't.  The reason for the complaint is that GNU getopt, unlike System
  557. V getopt and other getopt implementations, doesn't consider a
  558. non-option to be the end of the option list.  A quick (and compatible)
  559. fix for scripts is to add "--" to the interpreter, like this:
  560. </p><pre>        #! /usr/local/bin/python --
  561. </pre><p>You can also use this interactively:
  562. </p><pre>        python -- script.py [options]
  563. </pre><p>Note that a working getopt implementation is provided in the Python
  564. distribution (in Python/getopt.c) but not automatically used.
  565. </p><h2>3.5. <a name="3.5"><em>When building on the SGI, make tries to run python to create
  566. glmodule.c, but python hasn't been built or installed yet.
  567. </em></a></h2><p><strong>Comment out the line mentioning glmodule.c in Setup and build a
  568. python without gl first;</strong> install it or make sure it is in your $PATH,
  569. then edit the Setup file again to turn on the gl module, and make
  570. again.  You don't need to do "make clean"; you do need to run "make
  571. Makefile" in the Modules subdirectory (or just run "make" at the
  572. toplevel).
  573. </p><h2>3.6. <a name="3.6"><em>I use VPATH but some targets are built in the source directory.
  574. </em></a></h2><p><strong>On some systems </strong>(e.g. Sun), if the target already exists in the
  575. source directory, it is created there instead of in the build
  576. directory.  This is usually because you have previously built without
  577. VPATH.  Try running "make clobber" in the source directory.
  578. </p><h2>3.7. <a name="3.7"><em>Trouble building or linking with the GNU readline library.
  579. </em></a></h2><p><strong>Consider using readline 2.0.</strong>  Some hints:
  580. </p><ul><li>You can use the GNU readline library to improve the interactive user
  581. interface: this gives you line editing and command history when
  582. calling python interactively. You need to configure and build the GNU
  583. readline library before running the configure script. Its sources are
  584. no longer distributed with Python; you can ftp them from any GNU
  585. mirror site, or from its home site
  586. <a href="ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz">ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz</a> (or a
  587. higher version number -- using version 1.x is not recommended). Pass
  588. the Python configure script the option --with-readline=DIRECTORY where
  589. DIRECTORY is the absolute pathname of the directory where you've built
  590. the readline library. Some hints on building and using the readline
  591. library:
  592. </li><li>On SGI IRIX 5, you may have to add the following
  593. to rldefs.h:
  594. </li></ul><pre>        #ifndef sigmask
  595.         #define sigmask(sig) (1L << ((sig)-1))
  596.         #endif
  597. </pre><ul><li>On most systems, you will have to add #include "rldefs.h" to the
  598. top of several source files, and if you use the VPATH feature, you
  599. will have to add dependencies of the form foo.o: foo.c to the
  600. Makefile for several values of foo.
  601. </li><li>The readline library requires use of the termcap library. A
  602. known problem with this is that it contains entry points which
  603. cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
  604. conflict can be solved (and will be, in the next release of
  605. STDWIN) by adding a line saying '#define werase w_erase' to the
  606. stdwin.h file (in the STDWIN distribution, subdirectory H). The
  607. GL conflict has been solved in the Python configure script by a
  608. hack that forces use of the static version of the termcap library.
  609. </li><li>Check the newsgroup gnu.bash.bug <a href="news:gnu.bash.bug">news:gnu.bash.bug</a> for
  610. specific problems with the readline library (I don't read this group
  611. but I've been told that it is the place for readline bugs).
  612. </li></ul><h2>3.8. <a name="3.8"><em>Trouble with socket I/O on older Linux 1.x versions.
  613. </em></a></h2><p><strong>Once you've built Python, use it to run the regen.py script in the
  614. Lib/linux1 directory.</strong>  Apparently the files as distributed don't match
  615. the system headers on some Linux versions.
  616. </p><h2>3.9. <a name="3.9"><em>Trouble with prototypes on Ultrix.
  617. </em></a></h2><p><strong>Ultrix cc seems broken -- use gcc, or edit config.h to #undef
  618. HAVE_PROTOTYPES.</strong>
  619. </p><h2>3.10. <a name="3.10"><em>Other trouble building Python on platform X.
  620. </em></a></h2><p><strong>Please email the details to <a href="mailto:guido@cnri.reston.va.us">guido@cnri.reston.va.us</a></strong> and I'll look
  621. into it.  Please provide as many details as possible.  In particular,
  622. if you don't tell me what type of computer and what operating system
  623. (and version) you are using it will be difficult for me to figure out
  624. what is the matter.  If you get a specific error message, please email
  625. it to me too.
  626. </p><h2>3.11. <a name="3.11"><em>How to configure dynamic loading on Linux.
  627. </em></a></h2><p><strong>This is now automatic as long as your Linux version uses the ELF
  628. object format </strong>(all recent Linuxes do).
  629. </p><h2>3.12. <a name="3.12">Q: I can't get shared modules to work on Linux 2.0 (Slackware96)?
  630. </a></h2><p>A: This is a bug in the Slackware96 release.   The fix is simple:
  631. </p><p>Make sure that there is a link from /lib/libdl.so to /lib/libdl.so.1
  632. so that the following links are setup:
  633. </p><p>    /lib/libdl.so -> /lib/libdl.so.1
  634.     /lib/libdl.so.1 -> /lib/libdl.so.1.7.14
  635. </p><h2>3.13. <a name="3.13"><em>How to use threads on Linux.
  636. </em></a></h2><p><strong>[Greg Stein] I built myself a libpthreads.so from the libc.5.3.12
  637. distribution </strong>(the binary distribution doesn't have pthreads in
  638. it).  Then, I configured Python with --with-threads and then tweaked
  639. config.h to include a #define _MIT_POSIX_THREADS (or something like
  640. that, see /usr/include/pthreads.h).  It worked fine at that point.
  641. </p><p>Note that I couldn't get threading to "operate well" with any of the
  642. other thread packages.  Prior libc versions didn't integrate well with
  643. threads, either, so I couldn't use them (e.g. sleep() blocked all
  644. threads :-( ).
  645. </p><h2>3.14. <a name="3.14"><em>Errors when linking with a shared library containing C++ code.
  646. </em></a></h2><p><strong>Link the main Python binary with C++.</strong>  Change the definition of
  647. LINKCC in Modules/Makefile to be your C++ compiler.  You may have to
  648. edit config.c slightly to make it compilable with C++.
  649. </p><h2>3.15. <a name="3.15"><em>I built with tkintermodule.c enabled but get "Tkinter not found".
  650. </em></a></h2><p><strong>Tkinter.py </strong>(note: upper case T) lives in a subdirectory of Lib,
  651. Lib/tkinter.  If you are using the default module search path, you
  652. probably didn't enable the line in the Modules/Setup file defining
  653. TKPATH; if you use the environment variable PYTHONPATH, you'll have to
  654. add  the proper tkinter subdirectory.
  655. </p><h2>3.16. <a name="3.16"><em>I built with Tk 4.0 but Tkinter complains about the Tk version.
  656. </em></a></h2><p><strong>Several things could cause this.</strong>  You most likely have a Tk 3.6
  657. installation that wasn't completely eradicated by the Tk 4.0
  658. installation (which tends to add "4.0" to its installed files).  You
  659. may have the Tk 3.6 support library installed in the place where the
  660. Tk 4.0 support files should be (default /usr/local/lib/tk/); you may
  661. have compiled Python with the old tk.h header file (yes, this actually
  662. compiles!); you may actually have linked with Tk 3.6 even though Tk
  663. 4.0 is also around.  Similar for Tcl 7.4 vs. Tcl 7.3.
  664. </p><h2>3.17. <a name="3.17"><em>Link errors for Tcl/Tk symbols when linking with Tcl/Tk.
  665. </em></a></h2><p>Quite possibly, there's a version mismatch between the Tcl/Tk header
  666. files (tcl.h and tk.h) and the tck/tk libraries you are using (the
  667. "-ltk4.0" and "-ltcl7.4" arguments for _tkinter in the Setup file).
  668. If you have installed both versions 7.4/4.0 and 7.5/4.1 of Tcl/Tk,
  669. most likely your header files are for The newer versions, but the
  670. Setup line for _tkinter in some Python distributions references
  671. 7.4/4.0 by default.  Changing this to 7.5/4.1 should take care of
  672. this.
  673. </p><h2>3.18. <a name="3.18"><em>I configured and built Python for Tcl/Tk but "import Tkinter"
  674. fails.
  675. </em></a></h2><p><strong>Most likely, you forgot to enable the line in Setup that says
  676. "TKPATH=:$</strong>(DESTLIB)/tkinter".
  677. </p><h2>3.19. <a name="3.19"><em>Tk doesn't work right on DEC Alpha.
  678. </em></a></h2><p><strong>You probably compiled either Tcl, Tk or Python with gcc.</strong>  Don't.
  679. For this platform, which has 64-bit integers, gcc is known to generate
  680. broken code.  The standard cc (which comes bundled with the OS!)
  681. works.  If you still prefer gcc, at least try recompiling with cc
  682. before reporting problems to the newsgroup or the author; if this
  683. fixes the problem, report the bug to the gcc developers instead.  (As
  684. far as we know, there are no problem with gcc on other platforms --
  685. the instabilities seem to be restricted to the DEC Alpha.)  See also
  686. <a href="#3.6">question 3.6</a>.
  687. </p><h2>3.20. <a name="3.20"><em>Several common system calls are missing from the posix module.
  688. </em></a></h2><p><strong>Most likely, *all* test compilations run by the configure script
  689. are failing for some reason or another.</strong>  Have a look in config.log to
  690. see what could be the reason.  A common reason is specifying a
  691. directory to the --with-readline option that doesn't contain the
  692. libreadline.a file.
  693. </p><h2>3.21. <a name="3.21"><em>ImportError: No module named string, on MS Windows.
  694. </em></a></h2><p><strong>Most likely, your PYTHONPATH environment variable should be set to
  695. something like:</strong>
  696. </p><p>set PYTHONPATH=c:\python;c:\python\lib;c:\python\scripts
  697. </p><p>(assuming Python was installed in c:\python)
  698. </p><h2>3.22. <a name="3.22"><em>Core dump on SGI when using the gl module.
  699. </em></a></h2><p>There are conflicts between entry points in the termcap and curses
  700. libraries and an entry point in the GL library.  There's a hack of a
  701. fix for the termcap library if it's needed for the GNU readline
  702. library, but it doesn't work when you're using curses.  Concluding,
  703. you can't build a Python binary containing both the curses and gl
  704. modules.
  705. </p><hr><h1>4. <a name="4">Programming in Python
  706. </a></h1><h2>4.1. <a name="4.1"><em>Is there a source code level debugger with breakpoints, step,
  707. etc.?
  708. </em></a></h2><p><strong>Yes.</strong>  Check out module pdb; pdb.help() prints the documentation (or
  709. you can read it as Lib/pdb.doc).  If you use the STDWIN option,
  710. there's also a windowing interface, wdb.  You can write your own
  711. debugger by using the code for pdb or wdb as an example.
  712. </p><h2>4.2. <a name="4.2"><em>Can I create an object class with some methods implemented in
  713. C and others in Python (e.g. through inheritance)?  (Also phrased as:
  714. Can I use a built-in type as base class?)
  715. </em></a></h2><p><strong>No, but you can easily create a Python class which serves as a
  716. wrapper around a built-in object, e.g.</strong> (for dictionaries):
  717. </p><pre>        # A user-defined class behaving almost identical
  718.         # to a built-in dictionary.
  719.         class UserDict:
  720.                 def __init__(self): self.data = {}
  721.                 def __repr__(self): return repr(self.data)
  722.                 def __cmp__(self, dict):
  723.                         if type(dict) == type(self.data):
  724.                                 return cmp(self.data, dict)
  725.                         else:
  726.                                 return cmp(self.data, dict.data)
  727.                 def __len__(self): return len(self.data)
  728.                 def __getitem__(self, key): return self.data[key]
  729.                 def __setitem__(self, key, item): self.data[key] = item
  730.                 def __delitem__(self, key): del self.data[key]
  731.                 def keys(self): return self.data.keys()
  732.                 def items(self): return self.data.items()
  733.                 def values(self): return self.data.values()
  734.                 def has_key(self, key): return self.data.has_key(key)
  735. </pre><h2>4.3. <a name="4.3"><em>Is there a curses/termcap package for Python?
  736. </em></a></h2><p><strong>Yes -- Lance Ellinghaus has written a module that interfaces to
  737. System V's "ncurses".</strong>  If you know a little curses and some Python,
  738. it's straightforward to use.  It is part of the standard Python
  739. distribution, but not configured by default -- you must enable it by
  740. editing Modules/Setup.  It requires a System V curses implementation.
  741. </p><p>You could also consider using the "alfa" (== character cell) version
  742. of STDWIN.  (Standard Window System Interface, a portable windowing
  743. system interface by myself <a href="ftp://ftp.cwi.nl/pub/stdwin/">ftp://ftp.cwi.nl/pub/stdwin/</a>.)  This
  744. will also prepare your program for porting to windowing environments
  745. such as X11 or the Macintosh.
  746. </p><h2>4.4. <a name="4.4"><em>Is there an equivalent to C's onexit() in Python?
  747. </em></a></h2><p><strong>Yes, if you import sys and assign a function to sys.exitfunc, it
  748. will be called when your program exits, is killed by an unhandled
  749. exception, or </strong>(on UNIX) receives a SIGHUP or SIGTERM signal.
  750. </p><h2>4.5. <a name="4.5"><em>When I define a function nested inside another function, the
  751. nested function seemingly can't access the local variables of the
  752. outer function.  What is going on?  How do I pass local data to a
  753. nested function?
  754. </em></a></h2><p><strong>Python does not have arbitrarily nested scopes.</strong>  When you need to
  755. create a function that needs to access some data which you have
  756. available locally, create a new class to hold the data and return a
  757. method of an instance of that class, e.g.:
  758. </p><pre>        class MultiplierClass:
  759.             def __init__(self, factor):
  760.                 self.factor = factor
  761.             def multiplier(self, argument):
  762.                 return argument * self.factor
  763. </pre><pre>        def generate_multiplier(factor):
  764.             return MultiplierClass(factor).multiplier
  765. </pre><pre>        twice = generate_multiplier(2)
  766.         print twice(10)
  767.         # Output: 20
  768. </pre><p>An alternative solution uses default arguments, e.g.:
  769. </p><pre>        def generate_multiplier(factor):
  770.             def multiplier(arg, fact = factor):
  771.                 return arg*fact
  772.             return multiplier
  773. </pre><pre>        twice = generate_multiplier(2)
  774.         print twice(10)
  775.         # Output: 20
  776. </pre><h2>4.6. <a name="4.6"><em>How do I iterate over a sequence in reverse order?
  777. </em></a></h2><p><strong>If it is a list, the fastest solution is
  778. </strong></p><pre>        list.reverse()
  779.         try:
  780.                 for x in list:
  781.                         "do something with x"
  782.         finally:
  783.                 list.reverse()
  784. </pre><p>This has the disadvantage that while you are in the loop, the list
  785. is temporarily reversed.  If you don't like this, you can make a copy.
  786. This appears expensive but is actually faster than other solutions:
  787. </p><pre>        rev = list[:]
  788.         rev.reverse()
  789.         for x in rev:
  790.                 <do something with x>
  791. </pre><p>If it isn't a list, a more general but slower solution is:
  792. </p><pre>        i = len(list)
  793.         while i > 0:
  794.                 i = i-1
  795.                 x = list[i]
  796.                 <do something with x>
  797. </pre><p>A more elegant solution, is to define a class which acts as a sequence
  798. and yields the elements in reverse order (solution due to Steve
  799. Majewski):
  800. </p><pre>        class Rev:
  801.                 def __init__(self, seq):
  802.                         self.forw = seq
  803.                 def __len__(self):
  804.                         return len(self.forw)
  805.                 def __getitem__(self, i):
  806.                         return self.forw[-(i + 1)]
  807. </pre><p>You can now simply write:
  808. </p><pre>        for x in Rev(list):
  809.                 <do something with x>
  810. </pre><p>Unfortunately, this solution is slowest of all, due to the method
  811. call overhead...
  812. </p><h2>4.7. <a name="4.7"><em>My program is too slow.  How do I speed it up?
  813. </em></a></h2><p><strong>That's a tough one, in general.</strong>  There are many tricks to speed up
  814. Python code; I would consider rewriting parts in C only as a last
  815. resort.  One thing to notice is that function and (especially) method
  816. calls are rather expensive; if you have designed a purely OO interface
  817. with lots of tiny functions that don't do much more than get or set an
  818. instance variable or call another method, you may consider using a
  819. more direct way, e.g. directly accessing instance variables.  Also see
  820. the standard module "profile" (described in the file
  821. "python/lib/profile.doc") which makes it possible to find out where
  822. your program is spending most of its time (if you have some patience
  823. -- the profiling itself can slow your program down by an order of
  824. magnitude).
  825. </p><h2>4.8. <a name="4.8"><em>When I have imported a module, then edit it, and import it
  826. again (into the same Python process), the changes don't seem to take
  827. place.  What is going on?
  828. </em></a></h2><p><strong>For reasons of efficiency as well as consistency, Python only reads
  829. the module file on the first time a module is imported.</strong>  (Otherwise a
  830. program consisting of many modules, each of which imports the same
  831. basic module, would read the basic module over and over again.)  To
  832. force rereading of a changed module, do this:
  833. </p><pre>        import modname
  834.         reload(modname)
  835. </pre><p>Warning: this technique is not 100% fool-proof.  In particular,
  836. modules containing statements like
  837. </p><pre>        from modname import some_objects
  838. </pre><p>will continue to work with the old version of the imported objects.
  839. </p><h2>4.9. <a name="4.9"><em>How do I find the current module name?
  840. </em></a></h2><p><strong>A module can find out its own module name by looking at the
  841. </strong>(predefined) global variable __name__.  If this has the value
  842. '__main__' you are running as a script.  
  843. </p><h2>4.10. <a name="4.10"><em>I have a module in which I want to execute some extra code
  844. when it is run as a script.  How do I find out whether I am running as
  845. a script?
  846. </em></a></h2><p><strong>See the previous question.</strong>  E.g. if you put the following on the
  847. last line of your module, main() is called only when your module is
  848. running as a script:
  849. </p><pre>        if __name__ == '__main__': main()
  850. </pre><h2>4.11. <a name="4.11"><em>I try to run a program from the Demo directory but it fails
  851. with ImportError: No module named ...; what gives?
  852. </em></a></h2><p><strong>This is probably an optional module </strong>(written in C!) which hasn't
  853. been configured on your system.  This especially happens with modules
  854. like "Tkinter", "stdwin", "gl", "Xt" or "Xm".  For Tkinter, STDWIN and
  855. many other modules, see Modules/Setup.in for info on how to add these
  856. modules to your Python, if it is possible at all.  Sometimes you will
  857. have to ftp and build another package first (e.g. STDWIN).  Sometimes
  858. the module only works on specific platforms (e.g. gl only works on SGI
  859. machines).
  860. </p><p>NOTE: if the complaint is about "Tkinter" (upper case T) and you have
  861. already configured module "tkinter" (lower case t), the solution is
  862. *not* to rename tkinter to Tkinter or vice versa.  There is probably
  863. something wrong with your module search path.  Check out the value of
  864. sys.path.
  865. </p><p>For X-related modules (Xt and Xm) you will have to do more work: they
  866. are currently not part of the standard Python distribution.  You will
  867. have to ftp the Extensions tar file, e.g.
  868. <a href="ftp://ftp.python.org/pub/python/src/extensions.tar.gz">ftp://ftp.python.org/pub/python/src/extensions.tar.gz</a> and follow
  869. the instructions there.
  870. </p><p>See also the next question.
  871. </p><h2>4.12. <a name="4.12"><em>I have successfully built Python with STDWIN but it can't
  872. find some modules (e.g. stdwinevents).
  873. </em></a></h2><p><strong>There's a subdirectory of the library directory named 'stdwin'
  874. which should be in the default module search path.</strong>  There's a line in
  875. Modules/Setup(.in) that you have to enable for this purpose --
  876. unfortunately in the latest release it's not near the other
  877. STDWIN-related lines so it's easy to miss it.
  878. </p><h2>4.13. <a name="4.13"><em>What GUI toolkits exist for Python?
  879. </em></a></h2><p><strong>Depending on what platform</strong>(s) you are aiming at, there are several.
  880. </p><p>Currently supported solutions:
  881. </p><ul><li>There's a neat object-oriented interface to the Tcl/Tk widget set,
  882. called Tkinter.  It is part of the standard Python distribution and
  883. well-supported -- all you need to do is build and install Tcl/Tk and
  884. enable the _tkinter module and the TKPATH definition in Modules/Setup
  885. when building Python.  This is probably the easiest to install and
  886. use, and the most complete widget set.  It is also very likely that in
  887. the future the standard Python GUI API will be based on or at least
  888. look very much like the Tkinter interface.  For more info about Tk,
  889. including pointers to the source, see the Tcl/Tk home page
  890. <a href="http://www.sunlabs.com/research/tcl/">http://www.sunlabs.com/research/tcl/</a>.  Tcl/Tk is now fully
  891. portable to the Mac and Windows platforms (NT and 95 only); you need
  892. Python 1.4beta3 or later and Tk 4.1patch1 or later.
  893. </li><li>There's an interface to X11, including the Athena and Motif widget
  894. sets (and a few individual widgets, like Mosaic's HTML widget and
  895. SGI's GL widget) available from
  896. <a href="ftp://ftp.python.org/pub/python/src/X-extension.tar.gz">ftp://ftp.python.org/pub/python/src/X-extension.tar.gz</a>.
  897. Support by Sjoerd Mullender <a href="mailto:sjoerd@cwi.nl">sjoerd@cwi.nl</a>.
  898. </li><li>On top of the X11 interface there's the (recently revived) vpApp
  899. toolkit by Per Spilling, now also maintained by Sjoerd Mullender
  900. <a href="mailto:sjoerd@cwi.nl">sjoerd@cwi.nl</a>.  See <a href="ftp://ftp.cwi.nl/pub/sjoerd/vpApp.tar.gz">ftp://ftp.cwi.nl/pub/sjoerd/vpApp.tar.gz</a>.
  901. </li><li>The Mac port has a rich and ever-growing set of modules that support
  902. the native Mac toolbox calls.  See the documentation that comes with
  903. the Mac port.  See <a href="ftp://ftp.python.org/pub/python/mac">ftp://ftp.python.org/pub/python/mac</a>.  Support
  904. by Jack Jansen <a href="mailto:jack@cwi.nl">jack@cwi.nl</a>.
  905. </li><li>The NT port supported by Mark Hammond <a href="mailto:MHammond@skippinet.com.au">MHammond@skippinet.com.au</a>
  906. (see <a href="#7.2">question 7.2</a>) includes an interface to the Microsoft Foundation
  907. Classes and a Python programming environment using it that's written
  908. mostly in Python.  See
  909. <a href="ftp://ftp.python.org/pub/python/pythonwin/">ftp://ftp.python.org/pub/python/pythonwin/</a>.
  910. </li><li>There's an object-oriented GUI based on the Microsoft Foundation
  911. Classes model called WPY, supported by Jim Ahlstrom <a href="mailto:jim@interet.com">jim@interet.com</a>.
  912. Programs written in WPY run unchanged and with native look and feel on
  913. Windows NT/95, Windows 3.1 (using win32s), and on Unix (using Tk).
  914. Source and binaries for Windows and Linux are available in
  915. <a href="ftp://ftp.python.org/pub/python/wpy/">ftp://ftp.python.org/pub/python/wpy/</a>.
  916. </li></ul><p>Obsolete or minority solutions:
  917. </p><ul><li>There's an interface to wxWindows.  wxWindows is a portable GUI
  918. class library written in C++.  It supports XView, Motif, MS-Windows as
  919. targets.  There is some support for Macs and CURSES as well.
  920. wxWindows preserves the look and feel of the underlying graphics
  921. toolkit.  See the wxPython WWW page at
  922. <a href="http://www.aiai.ed.ac.uk/~jacs/wx/wxpython/wxpython.html">http://www.aiai.ed.ac.uk/~jacs/wx/wxpython/wxpython.html</a>.
  923. Support for wxPython (by Harri Pasanen <a href="mailto:pa@tekla.fi">pa@tekla.fi</a>) appears
  924. to have a low priority.
  925. </li><li>For SGI IRIX only, there are unsupported interfaces to the complete
  926. GL (Graphics Library -- low level but very good 3D capabilities) as
  927. well as to FORMS (a buttons-and-sliders-etc package built on top of GL
  928. by Mark Overmars -- ftp'able from
  929. <a href="ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/">ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/</a>).  This is probably also
  930. becoming obsolete, as OpenGL takes over.
  931. </li><li>There's an interface to STDWIN, a platform-independent low-level
  932. windowing interface for Mac and X11.  This is totally unsupported and
  933. rapidly becoming obsolete.  The STDWIN sources are at
  934. <a href="ftp://ftp.cwi.nl/pub/stdwin/">ftp://ftp.cwi.nl/pub/stdwin/</a>.  (For info about STDWIN 2.0,
  935. please refer to Steven Pemberton <a href="mailto:steven@cwi.nl">steven@cwi.nl</a> -- I believe it is
  936. also dead.)
  937. </li><li>There once was an interface to WAFE, a Tcl interface to the X11
  938. Motif and Athena widget sets.  WAFE is at
  939. <a href="ftp://ftp.wu-wien.ac.at/pub/src/X11/wafe/">ftp://ftp.wu-wien.ac.at/pub/src/X11/wafe/</a>.  It's not clear what
  940. the status of the Python support is.
  941. </li><li>(The Fresco port that was mentioned in earlier versions of this FAQ
  942. no longer seems to exist.  Inquire with Mark Linton.)
  943. </li></ul><h2>4.14. <a name="4.14"><em>Are there any interfaces to database packages in Python?
  944. </em></a></h2><p><strong>There's a whole collection of them in the contrib area of the ftp
  945. server, see <a href="http://www.python.org/ftp/python/contrib/Database/">http://www.python.org/ftp/python/contrib/Database/</a>.
  946. </strong></p><h2>4.15. <a name="4.15"><em>Is it possible to write obfuscated one-liners in Python?
  947. </em></a></h2><p><strong>Yes.</strong>  See the following three examples, due to Ulf Bartelt:
  948. </p><pre>        # Primes < 1000
  949.         print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
  950.         map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
  951. </pre><pre>        # First 10 Fibonacci numbers
  952.         print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
  953.         range(10))
  954. </pre><pre>        # Mandelbrot set
  955.         print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
  956.         Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
  957.         Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
  958.         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
  959.         >=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(
  960.         64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
  961.         ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
  962.         #    \___ ___/  \___ ___/  |   |   |__ lines on screen
  963.         #        V          V      |   |______ columns on screen
  964.         #        |          |      |__________ maximum of "iterations"
  965.         #        |          |_________________ range on y axis
  966.         #        |____________________________ range on x axis
  967. </pre><p>Don't try this at home, kids!
  968. </p><h2>4.16. <a name="4.16"><em>Is there an equivalent of C's "?:" ternary operator?
  969. </em></a></h2><p><strong>Not directly.</strong>  In many cases you can mimic a?b:c with "a and b or
  970. c", but there's a flaw: if b is zero (or empty, or None -- anything
  971. that tests false) then c will be selected instead.  In many cases you
  972. can prove by looking at the code that this can't happen (e.g. because
  973. b is a constant or has a type that can never be false), but in general
  974. this can be a problem.
  975. </p><p>Tim Peters (who wishes it was Steve Majewski) suggested the following
  976. solution: (a and [b] or [c])[0].  Because [b] is a singleton list it
  977. is never false, so the wrong path is never taken; then applying [0] to
  978. the whole thing gets the b or c that you really wanted.  Ugly, but it
  979. gets you there in the rare cases where it is really inconvenient to
  980. rewrite your code using 'if'.
  981. </p><h2>4.17. <a name="4.17"><em>My class defines __del__ but it is not called when I delete the
  982. object.
  983. </em></a></h2><p><strong>There are several possible reasons for this.</strong>
  984. </p><ul><li>The del statement does not necessarily call __del__ -- it simply
  985. decrements the object's reference count, and if this reaches zero
  986. __del__ is called.
  987. </li><li>If your data structures contain circular links (e.g. a tree where
  988. each child has a parent pointer and each parent has a list of
  989. children) the reference counts will never go back to zero.  You'll
  990. have to define an explicit close() method which removes those
  991. pointers.  Please don't ever call __del__ directly -- __del__ should
  992. call close() and close() should make sure that it can be called more
  993. than once for the same object.
  994. </li><li>If the object has ever been a local variable (or argument, which is
  995. really the same thing) to a function that caught an expression in an
  996. except clause, chances are that a reference to the object still exists
  997. in that function's stack frame as contained in the stack trace.
  998. Normally, deleting (better: assigning None to) sys.exc_traceback will
  999. take care of this.  If you a stack was printed for an unhandled
  1000. exception in an interactive interpreter, delete sys.last_traceback
  1001. instead.
  1002. </li><li>There is code that deletes all objects when the interpreter exits,
  1003. but if your Python has been configured to support threads, it is not
  1004. called (because other threads may still be active).  You can define
  1005. your own cleanup function using sys.exitfunc (see <a href="#4.4">question 4.4</a>).
  1006. </li><li>Finally, if your __del__ method raises an exception, this will be
  1007. ignored.  Starting with Python 1.4beta3, a warning message is printed
  1008. to sys.stderr when this happens.
  1009. </li></ul><h2>4.18. <a name="4.18"><em>How do I change the shell environment for programs called
  1010. using os.popen() or os.system()?  Changing os.environ doesn't work.
  1011. </em></a></h2><p><strong>Modifying the environment passed to subshells was left out of the
  1012. interpreter because there seemed to be no well-established portable
  1013. way to do it </strong>(in particular, some systems, have putenv(), others have
  1014. setenv(), and some have none at all).
  1015. </p><p>However if all you want is to pass environment variables to the
  1016. commands run by os.system() or os.popen(), there's a simple solution:
  1017. prefix the command string with a couple of variable assignments and
  1018. export statements.  The following would be universal for popen:
  1019. </p><pre>        import os
  1020.         from commands import mkarg # nifty routine to add shell quoting
  1021.         def epopen(cmd, mode, env = {}):
  1022.                 # env is a dictionary of environment variables
  1023.                 prefix = ''
  1024.                 for key, value in env.items():
  1025.                         prefix = prefix + '%s=%s\n' % (key, mkarg(value)[1:])
  1026.                         prefix = prefix + 'export %s\n' % key
  1027.                 return os.popen(prefix + cmd, mode)
  1028. </pre><h2>4.19. <a name="4.19"><em>What is a class?
  1029. </em></a></h2><p><strong>A class is the particular object type that is created by executing
  1030. a class statement.</strong>  Class objects are used as templates, to create
  1031. class instance objects, which embody both the data structure and
  1032. program routines specific to a datatype.
  1033. </p><h2>4.20. <a name="4.20"><em>What is a method?
  1034. </em></a></h2><p><strong>A method is a function that you normally call as
  1035. x.name</strong>(arguments...) for some object x.  The term is used for methods
  1036. of classes and class instances as well as for methods of built-in
  1037. objects.  (The latter have a completely different implementation and
  1038. only share the way their calls look in Python code.)  Methods of
  1039. classes (and class instances) are defined as functions inside the
  1040. class definition.
  1041. </p><h2>4.21. <a name="4.21"><em>What is self?
  1042. </em></a></h2><p><strong>Self is merely a conventional name for the first argument of a
  1043. method -- i.e.</strong> a function defined inside a class definition.  A method
  1044. defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
  1045. some instance x of the class in which the definition occurs;
  1046. the called method will think it is called as meth(x, a, b, c).
  1047. </p><h2>4.22. <a name="4.22"><em>What is a unbound method?
  1048. </em></a></h2><p><strong>An unbound method is a method defined in a class that is not yet
  1049. bound to an instance.</strong>  You get an unbound method if you ask for a
  1050. class attribute that happens to be a function. You get a bound method
  1051. if you ask for an instance attribute.  A bound method knows which
  1052. instance it belongs to and calling it supplies the instance automatically;
  1053. an unbound method only knows which class it wants for its first
  1054. argument (a derived class is also OK).  Calling an unbound method
  1055. doesn't "magically" derive the first argument from the context -- you
  1056. have to provide it explicitly.
  1057. </p><h2>4.23. <a name="4.23"><em>How do I call a method defined in a base class from a derived
  1058. class that overrides it?
  1059. </em></a></h2><p><strong>If your class definition starts with "class Derived</strong>(Base): ..."
  1060. then you can call method meth defined in Base (or one of Base's base
  1061. classes) as Base.meth(self, arguments...).  Here, Base.meth is an
  1062. unbound method (see previous question).
  1063. </p><h2>4.24. <a name="4.24"><em>How do I call a method from a base class without using the
  1064. name of the base class?
  1065. </em></a></h2><p><strong>DON'T DO THIS.</strong>  REALLY.  I MEAN IT.  It appears that you could call
  1066. self.__class__.__bases__[0].meth(self, arguments...) but this fails when
  1067. a doubly-derived method is derived from your class: for its instances,
  1068. self.__class__.__bases__[0] is your class, not its base class -- so
  1069. (assuming you are doing this from within Derived.meth) you would start
  1070. a recursive call.
  1071. </p><h2>4.25. <a name="4.25"><em>How can I organize my code to make it easier to change the base
  1072. class?
  1073. </em></a></h2><p><strong>You could define an alias for the base class, assign the real base
  1074. class to it before your class definition, and use the alias throughout
  1075. your class.</strong>  Then all you have to change is the value assigned to the
  1076. alias.  Incidentally, this trick is also handy if you want to decide
  1077. dynamically (e.g. depending on availability of resources) which base
  1078. class to use.  Example:
  1079. </p><pre>        BaseAlias = <real base class>
  1080.         class Derived(BaseAlias):
  1081.                 def meth(self):
  1082.                         BaseAlias.meth(self)
  1083.                         ...
  1084. </pre><h2>4.26. <a name="4.26"><em>How can I find the methods or attributes of an object?
  1085. </em></a></h2><p><strong>This depends on the object type.</strong>
  1086. </p><p>For an instance x of a user-defined class, instance attributes are
  1087. found in the dictionary x.__dict__, and methods and attributes defined
  1088. by its class are found in x.__class__.__bases__[i].__dict__ (for i in
  1089. range(len(x.__class__.__bases__))).  You'll have to walk the tree of
  1090. base classes to find *all* class methods and attributes.
  1091. </p><p>Many, but not all built-in types define a list of their method names
  1092. in x.__methods__, and if they have data attributes, their names may be
  1093. found in x.__members__.  However this is only a convention.
  1094. </p><p>For more information, read the source of the standard (but
  1095. undocumented) module newdir.
  1096. </p><h2>4.27. <a name="4.27"><em>I can't seem to use os.read() on a pipe created with os.popen().
  1097. </em></a></h2><p><strong>os.read</strong>() is a low-level function which takes a file descriptor (a
  1098. small integer).  os.popen() creates a high-level file object -- the
  1099. same type used for sys.std{in,out,err} and returned by the builtin
  1100. open() function.  Thus, to read n bytes from a pipe p created with
  1101. os.popen(), you need to use p.read(n).
  1102. </p><h2>4.28. <a name="4.28"><em>How can I create a stand-alone binary from a Python script?
  1103. </em></a></h2><p>The demo script "Demo/scripts/freeze.py" does what you want.  (It's
  1104. actually not a demo but a support tool -- there is some extra code in
  1105. the interpreter to accommodate it.)  It requires that you have the
  1106. Python build tree handy, complete with all the lib*.a files.
  1107. </p><p>This works by scanning your source recursively for import statements
  1108. (both forms) and looking for the modules on the standard Python path
  1109. as well as in the source directory (for built-in modules).  It then
  1110. "compiles" the modules written in Python to C code (array initializers
  1111. that can be turned into code objects using the marshal module) and
  1112. creates a custom-made config file that only contains those built-in
  1113. modules which are actually used in the program.  It then compiles the
  1114. generated C code and links it with the rest of the Python interpreter
  1115. to form a self-contained binary which acts exactly like your script.
  1116. </p><p>Hint: the freeze program only works if your script's filename ends in
  1117. ".py".
  1118. </p><h2>4.29. <a name="4.29"><em>What WWW tools are there for Python?
  1119. </em></a></h2><p><strong>See the chapter titled "Internet and WWW" in the Library Reference
  1120. Manual.</strong>  There's also a web browser written in Python, called Grail --
  1121. see <a href="http://monty.cnri.reston.va.us/grail/">http://monty.cnri.reston.va.us/grail/</a>.
  1122. </p><p>Steve Miale <a href="mailto:smiale@cs.indiana.edu">smiale@cs.indiana.edu</a> has written a modular WWW browser
  1123. called Dancer.  An alpha version can be FTP'ed from
  1124. <a href="ftp://ftp.cs.indiana.edu/pub/smiale/dancer.tar.gz">ftp://ftp.cs.indiana.edu/pub/smiale/dancer.tar.gz</a>.  (There are a
  1125. few articles about Dancer in the (hyper)mail archive
  1126. <a href="http://www.cwi.nl/~guido/hypermail/python-1994q3/index.html">http://www.cwi.nl/~guido/hypermail/python-1994q3/index.html</a>.)
  1127. </p><h2>4.30. <a name="4.30"><em>How do I run a subprocess with pipes connected to both input
  1128. and output?
  1129. </em></a></h2><p><strong>This is really a UNIX question.</strong>  Also, in general, it is unwise to
  1130. do so, because you can easily cause a deadlock where the parent
  1131. process is blocked waiting for output from the child, while the child
  1132. is blocked waiting for input from the child.  This can be caused
  1133. because the parent expects the child to output more text than it does,
  1134. or it can be caused by data being stuck in stdio buffers due to lack
  1135. of flushing.  The Python parent can of course explicitly flush the data
  1136. it sends to the child before it reads any output, but if the child is
  1137. a naive C program it can easily have been written to never explicitly
  1138. flush its output, even if it is interactive, since flushing is
  1139. normally automatic.
  1140. </p><p>In many cases, all you really need is to run some data through a
  1141. command and get the result back.  Unless the data is infinite in size,
  1142. the easiest (and often the most efficient!) way to do this is to write
  1143. it to a temporary file and run the command with that temporary file as
  1144. input.  The standard module tempfile exports a function mktemp() which
  1145. generates unique temporary file names.
  1146. </p><p>If after reading all of the above you still want to connect two pipes
  1147. to a subprocess's standard input and output, here's a simple solution,
  1148. due to Jack Jansen:
  1149. </p><pre>        import os
  1150.         import sys
  1151.         import string
  1152. </pre><pre>        MAXFD = 100     # Max number of file descriptors in this system
  1153. </pre><pre>        def popen2(cmd):
  1154.                 cmd = string.split(cmd)
  1155.                 p2cread, p2cwrite = os.pipe()
  1156.                 c2pread, c2pwrite = os.pipe()
  1157.                 pid = os.fork()
  1158.                 if pid == 0:
  1159.                         # Child
  1160.                         os.close(0)
  1161.                         os.close(1)
  1162.                         if os.dup(p2cread) != 0:
  1163.                                 sys.stderr.write('popen2: bad read dup\n')
  1164.                         if os.dup(c2pwrite) != 1:
  1165.                                 sys.stderr.write('popen2: bad write dup\n')
  1166.                         for i in range(3, MAXFD):
  1167.                                 try:
  1168.                                         os.close(i)
  1169.                                 except:
  1170.                                         pass
  1171.                         try:
  1172.                                 os.execv(cmd[0], cmd)
  1173.                         finally:
  1174.                                 os._exit(1)
  1175.                 os.close(p2cread)
  1176.                 tochild = os.fdopen(p2cwrite, 'w')
  1177.                 os.close(c2pwrite)
  1178.                 fromchild = os.fdopen(c2pread, 'r')
  1179.                 return fromchild, tochild
  1180. </pre><p>Note that many interactive programs (e.g. vi) don't work well with
  1181. pipes substituted for standard input and output.  You will have to use
  1182. pseudo ttys ("ptys") instead of pipes.  There is some undocumented
  1183. code to use these in the library module pty.py -- I'm afraid you're on
  1184. your own here.
  1185. </p><p>A different answer is a Python interface to Don Libes' "expect"
  1186. library.  A prerelease of this is available on the Python ftp mirror
  1187. sites in the contrib subdirectory as expy-0.3.tar.gz, e.g.
  1188. <a href="ftp://ftp.python.org/pub/python/contrib/expy-0.3.tar.gz">ftp://ftp.python.org/pub/python/contrib/expy-0.3.tar.gz</a>.
  1189. </p><h2>4.31. <a name="4.31"><em>How do I call a function if I have the arguments in a tuple?
  1190. </em></a></h2><p><strong>Use the built-in function apply</strong>().  For instance,
  1191. </p><pre>    func(1, 2, 3)
  1192. </pre><p>is equivalent to
  1193. </p><pre>    args = (1, 2, 3)
  1194.     apply(func, args)
  1195. </pre><p>Note that func(args) is not the same -- it calls func() with exactly
  1196. one argument, the tuple args, instead of three arguments, the integers
  1197. 1, 2 and 3.
  1198. </p><h2>4.32. <a name="4.32"><em>How do I enable font-lock-mode for Python in Emacs?
  1199. </em></a></h2><p><strong>Assuming you're already using python-mode and font-lock-mode
  1200. separately, all you need to do is put this in your .emacs file:</strong>
  1201. </p><pre>        (defun my-python-mode-hook ()
  1202.           (setq font-lock-keywords python-font-lock-keywords)
  1203.           (font-lock-mode 1))
  1204.         (add-hook 'python-mode-hook 'my-python-mode-hook)
  1205. </pre><h2>4.33. <a name="4.33"><em>Is there an inverse to the format operator (a la C's scanf())?
  1206. </em></a></h2><p><strong>Not as such.</strong>
  1207. </p><p>For simple input parsing, the easiest approach is usually to split
  1208. the line into whitespace-delimited words using string.split(), and to
  1209. convert decimal strings to numeric values using string.atoi(),
  1210. string.atol() or string.atof().  (Python's atoi() is 32-bit and its
  1211. atol() is arbitrary precision.)  If you want to use another delimiter
  1212. than whitespace, use string.splitfield() (possibly combining it with
  1213. string.strip() which removes surrounding whitespace from a string).
  1214. </p><p>For more complicated input parsing, regular expressions (see module
  1215. regex) are better suited and more powerful than C's scanf().
  1216. </p><h2>4.34. <a name="4.34"><em>Can I have Tk events handled while waiting for I/O?
  1217. </em></a></h2><p><strong>Yes, and you don't even need threads!</strong>  But you'll have to
  1218. restructure your I/O code a bit.  Tk has the equivalent of Xt's
  1219. XtAddInput() call, which allows you to register a callback function
  1220. which will be called from the Tk mainloop when I/O is possible on a
  1221. file descriptor.  Here's what you need:
  1222. </p><pre>        from Tkinter import tkinter
  1223.         tkinter.createfilehandler(file, mask, callback)
  1224. </pre><p>The file may be a Python file or socket object (actually, anything
  1225. with a fileno() method), or an integer file descriptor.  The mask is
  1226. one of the constants tkinter.READABLE or tkinter.WRITABLE.  The
  1227. callback is called as follows:
  1228. </p><pre>        callback(file, mask)
  1229. </pre><p>You must unregister the callback when you're done, using
  1230. </p><pre>        tkinter.deletefilehandler(file)
  1231. </pre><p>Note: since you don't know *how many bytes* are available for reading,
  1232. you can't use the Python file object's read or readline methods, since
  1233. these will insist on reading a predefined number of bytes.  For
  1234. sockets, the recv() or recvfrom() methods will work fine; for other
  1235. files, use os.read(file.fileno(), maxbytecount).
  1236. </p><h2>4.35. <a name="4.35"><em>How do I write a function with output parameters (call by reference)?
  1237. </em></a></h2><p><strong>[Mark Lutz] The thing to remember is that arguments are passed by
  1238. assignment in Python.</strong>  Since assignment just creates references to
  1239. objects, there's no alias between an argument name in the caller and
  1240. callee, and so no call-by-reference per se.  But you can simulate it
  1241. in a number of ways:
  1242. </p><p>1) By using global variables; but you probably shouldn't :-)
  1243. </p><p>2) By passing a mutable (changeable in-place) object:
  1244. </p><pre>      def func1(a):
  1245.           a[0] = 'new-value'     # 'a' references a mutable list
  1246.           a[1] = a[1] + 1        # changes a shared object
  1247. </pre><pre>      args = ['old-value', 99]
  1248.       func1(args)
  1249.       print args[0], args[1]     # output: new-value 100
  1250. </pre><p>3) By return a tuple, holding the final values of arguments:
  1251. </p><pre>      def func2(a, b):
  1252.           a = 'new-value'        # a and b are local names
  1253.           b = b + 1              # assigned to new objects
  1254.           return a, b            # return new values
  1255. </pre><pre>      x, y = 'old-value', 99
  1256.       x, y = func2(x, y)
  1257.       print x, y                 # output: new-value 100
  1258. </pre><p>4) And other ideas that fall-out from Python's object model. For
  1259. </p><pre>   instance, it might be clearer to pass in a mutable dictionary:
  1260. </pre><pre>      def func3(args):
  1261.           args['a'] = 'new-value'     # args is a mutable dictionary
  1262.           args['b'] = args['b'] + 1   # change it in-place
  1263. </pre><pre>      args = {'a':' old-value', 'b': 99}
  1264.       func3(args)
  1265.       print args['a'], args['b']
  1266. </pre><p>5) Or bundle-up values in a class instance:
  1267. </p><pre>      class callByRef:
  1268.           def __init__(self, **args):
  1269.               for (key, value) in args.items():
  1270.                   setattr(self, key, value)
  1271. </pre><pre>      def func4(args):
  1272.           args.a = 'new-value'        # args is a mutable callByRef
  1273.           args.b = args.b + 1         # change object in-place
  1274. </pre><pre>      args = callByRef(a='old-value', b=99)
  1275.       func4(args)
  1276.       print args.a, args.b
  1277. </pre><pre>   But there's probably no good reason to get this complicated :-).
  1278. </pre><p>[Python' author favors solution 3 in most cases.]
  1279. </p><h2>4.36. <a name="4.36"><em>Please explain the rules for local and global variables in Python.
  1280. </em></a></h2><p><strong>[Ken Manheimer] In Python, procedure variables are implicitly
  1281. global, unless they assigned anywhere within the block.</strong>  In that case
  1282. they are implicitly local, and you need to explicitly declare them as
  1283. 'global'.
  1284. </p><p>Though a bit surprising at first, a moments consideration explains
  1285. this.  On one hand, requirement of 'global' for assigned vars provides
  1286. a bar against unintended side-effects.  On the other hand, if global
  1287. were required for all global references, you'd be using global all the
  1288. time.  Eg, you'd have to declare as global every reference to a
  1289. builtin function, or to a component of an imported module.  This
  1290. clutter would defeat the usefulness of the 'global' declaration for
  1291. identifying side-effects.
  1292. </p><h2>4.37. <a name="4.37"><em>How can I have modules that mutually import each other?
  1293. </em></a></h2><p><strong>Jim Roskind recommends the following order in each module:</strong>
  1294. </p><p>First: all exports (like globals, functions, and classes that don't
  1295. need imported bases classes).
  1296. </p><p>Then: all import statements.
  1297. </p><p>Finally: all active code (including globals that are initialized from
  1298. imported values).
  1299. </p><p>Python's author doesn't like this approach much because the imports
  1300. appear in a strange place, but has to admit that it works.  His
  1301. recommended strategy is to avoid all uses of "from <module> import *"
  1302. (so everything from an imported module is referenced as
  1303. <module>.<name>) and to place all code inside functions.
  1304. Initializations of global variables and class variables should use
  1305. constants or built-in functions only.
  1306. </p><h2>4.38. <a name="4.38"><em>How do I copy an object in Python?
  1307. </em></a></h2><p><strong>There is no generic copying operation built into Python, however
  1308. most object types have some way to create a clone.</strong>  Here's how for the
  1309. most common objects:
  1310. </p><ul><li>For immutable objects (numbers, strings, tuples), cloning is
  1311. unnecessary since their value can't change.
  1312. </li><li>For lists (and generally for mutable sequence types), a clone is
  1313. created by the expression l[:].
  1314. </li><li>For dictionaries, the following function returns a clone:
  1315. </li></ul><pre>        def dictclone(o):
  1316.             n = {}
  1317.             for k in o.keys(): n[k] = o[k]
  1318.             return n
  1319. </pre><ul><li>Finally, for generic objects, the "copy" module defines two
  1320. functions for copying objects.  copy.copy(x) returns a copy as shown
  1321. by the above rules.  copy.deepcopy(x) also copies the elements of
  1322. composite objects.  See the section on this module in the Library
  1323. Reference Manual.
  1324. </li></ul><h2>4.39. <a name="4.39"><em>How to implement persistent objects in Python?  (Persistent ==
  1325. automatically saved to and restored from disk.)
  1326. </em></a></h2><p><strong>The library module "pickle" now solves this in a very general way
  1327. </strong>(though you still can't store things like open files, sockests or
  1328. windows), and the library module "shelve" uses pickle and (g)dbm to
  1329. create presistent mappings containing arbitrary Python objects.
  1330. </p><h2>4.40. <a name="4.40"><em>I try to use __spam and I get an error about _SomeClassName__spam.
  1331. </em></a></h2><p><strong>Variables with double leading underscore are "mangled" to provide a
  1332. simple but effective way to define class private variables.</strong>  See the
  1333. chapter "New in Release 1.4" in the Python Tutorial.
  1334. </p><hr><h1>5. <a name="5">Extending Python
  1335. </a></h1><h2>5.1. <a name="5.1"><em>Can I create my own functions in C?
  1336. </em></a></h2><p><strong>Yes, you can create built-in modules containing functions,
  1337. variables, exceptions and even new types in C.</strong>  This is explained in
  1338. the document "Extending and Embedding the Python Interpreter" (the
  1339. LaTeX file Doc/ext.tex).  Also read the chapter on dynamic loading.
  1340. </p><h2>5.2. <a name="5.2"><em>Can I create my own functions in C++?
  1341. </em></a></h2><p><strong>Yes, using the C-compatibility features found in C++.</strong>  Basically
  1342. you place extern "C" { ... } around the Python include files and put
  1343. extern "C" before each function that is going to be called by the
  1344. Python interpreter.  Global or static C++ objects with constructors
  1345. are probably not a good idea.
  1346. </p><h2>5.3. <a name="5.3"><em>How can I execute arbitrary Python statements from C?
  1347. </em></a></h2><p><strong>The highest-level function to do this is run_command</strong>() which takes
  1348. a single string argument which is executed in the context of module
  1349. __main__ and returns 0 for success and -1 when an exception occurred
  1350. (including SyntaxError).  If you want more control, use run_string();
  1351. see the source for run_command() in Python/pythonrun.c.
  1352. </p><h2>5.4. <a name="5.4"><em>How can I evaluate an arbitrary Python expression from C?
  1353. </em></a></h2><p><strong>Call the function run_string</strong>() from the previous question with the
  1354. start symbol eval_input; it then parses an expression, evaluates it
  1355. and returns its value.  See exec_eval() in Python/bltinmodule.c.
  1356. </p><h2>5.5. <a name="5.5"><em>How do I extract C values from a Python object?
  1357. </em></a></h2><p><strong>That depends on the object's type.</strong>  If it's a tuple,
  1358. gettuplesize(o) returns its length and gettupleitem(o, i) returns its
  1359. i'th item; similar for lists with getlistsize(o) and getlistitem(o,
  1360. i).  For strings, getstringsize(o) returns its length and
  1361. getstringvalue(o) a pointer to its value (note that Python strings may
  1362. contain null bytes so strlen() is not safe).  To test which type an
  1363. object is, first make sure it isn't NULL, and then use
  1364. is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
  1365. </p><h2>5.6. <a name="5.6"><em>How do I use mkvalue() to create a tuple of arbitrary length?
  1366. </em></a></h2><p><strong>You can't.</strong>  Use t = newtupleobject(n) instead, and fill it with
  1367. objects using settupleitem(t, i, o) -- note that this "eats" a
  1368. reference count of o.  Similar for lists with newlistobject(n) and
  1369. setlistitem(l, i, o).  Note that you *must* set all the tuple items to
  1370. some value before you pass the tuple to Python code --
  1371. newtupleobject(n) initializes them to NULL, which isn't a valid Python
  1372. value.
  1373. </p><h2>5.7. <a name="5.7"><em>How do I call an object's method from C?
  1374. </em></a></h2><p><strong>Here's a function </strong>(untested) that might become part of the next
  1375. release in some form.  It uses <stdarg.h> to allow passing the
  1376. argument list on to vmkvalue():
  1377. </p><pre>        object *call_method(object *inst, char *methodname, char *format, ...)
  1378.         {
  1379.                 object *method;
  1380.                 object *args;
  1381.                 object *result;
  1382.                 va_list va;
  1383.                 method = getattr(inst, methodname);
  1384.                 if (method == NULL) return NULL;
  1385.                 va_start(va, format);
  1386.                 args = vmkvalue(format, va);
  1387.                 va_end(va);
  1388.                 if (args == NULL) {
  1389.                         DECREF(method);
  1390.                         return NULL;
  1391.                 }
  1392.                 result = call_object(method, args);
  1393.                 DECREF(method);
  1394.                 DECREF(args);
  1395.                 return result;
  1396.         }
  1397. </pre><p>This works for any instance that has methods -- whether built-in or
  1398. user-defined.  You are responsible for eventually DECREF'ing the
  1399. return value.
  1400. </p><p>To call, e.g., a file object's "seek" method with arguments 10, 0
  1401. (assuming the file object pointer is "f"):
  1402. </p><pre>        res = call_method(f, "seek", "(OO)", 10, 0);
  1403.         if (res == NULL) {
  1404.                 ... an exception occurred ...
  1405.         }
  1406.         else {
  1407.                 DECREF(res);
  1408.         }
  1409. </pre><p>Note that since call_object() *always* wants a tuple for the argument
  1410. list, to call a function without arguments, pass "()" for the format,
  1411. and to call a function with one argument, surround the argument in
  1412. parentheses, e.g. "(i)".
  1413. </p><h2>5.8. <a name="5.8"><em>How do I catch the output from print_error()?
  1414. </em></a></h2><p>(<strong>Due to Mark Hammond):</strong>
  1415. </p><ul><li>in Python code, define an object that supports the "write()" method.
  1416. </li><li>redirect sys.stdout and sys.stderr to this object.
  1417. </li><li>call print_error, or just allow the standard traceback mechanism to
  1418. work.
  1419. </li></ul><p>Then, the output will go wherever your write() method sends it.
  1420. </p><h2>5.9. <a name="5.9"><em>How do I access a module written in Python from C?
  1421. </em></a></h2><p><strong>You can get a pointer to the module object as follows:</strong>
  1422. </p><pre>        module = import_module("<modulename>");
  1423. </pre><p>If the module hasn't been imported yet (i.e. it is not yet present in
  1424. sys.modules), this initializes the module; otherwise it simply returns
  1425. the value of sys.modules["<modulename>"].  Note that it doesn't enter
  1426. the module into any namespace -- it only ensures it has been
  1427. initialized and is stored in sys.modules.
  1428. </p><p>You can then access the module's attributes (i.e. any name defined in
  1429. the module) as follows:
  1430. </p><pre>        attr = getattr(module, "<attrname>");
  1431. </pre><p>Calling setattr(), to assign to variables in the module, also works.
  1432. </p><h2>5.10. <a name="5.10"><em>How do I interface to C++ objects from Python?
  1433. </em></a></h2><p><strong>Depending on your requirements, there are many approaches.</strong>  Begin
  1434. by reading the "Extending and Embedding" document (Doc/ext.tex, see
  1435. also <a href="http://www.python.org/doc/">http://www.python.org/doc/</a>).  Realize that for the Python
  1436. run-time system, there isn't a whole lot of difference between C and
  1437. C++ -- so the strategy to build a new Python type around a C structure
  1438. (pointer) type will also work for C++ objects.
  1439. </p><p>Automatic generation of interfaces between Python and C++ is still at
  1440. the horizon -- parsing C++ header files requires an almost complete
  1441. C++ parser, and many features aren't easily translated from C++ to
  1442. Python: certain forms of operator oveloading, function overloading
  1443. (best approached by a varargs function which explicitly type-checks
  1444. its arguments), and reference arguments are just a number of features
  1445. that are hard to translate correctly if at all.
  1446. </p><p>The hardest problem is to transparently translate the C++ class
  1447. hierarchy to Python, so that Python programs derive classes from C++
  1448. classes.  Given suitable constraints, this may be possible, but it
  1449. would require more space than I have in this FAQ to explain how.
  1450. In any case, you can get quite a bit done without this, using just the
  1451. existing classes from Python.
  1452. </p><p>If this all seems rather daunting, that may be because it is -- C++
  1453. isn't exactly a baby to handle without gloves!  However, people have
  1454. accomplished amazing feats of interfacing between Python and C++, and
  1455. a detailed question posted to the Python list is likely to elicit some
  1456. interesting and useful responses.
  1457. </p><hr><h1>6. <a name="6">Python's design
  1458. </a></h1><h2>6.1. <a name="6.1"><em>Why isn't there a switch or case statement in Python?
  1459. </em></a></h2><p><strong>You can do this easily enough with a sequence of
  1460. if...</strong> elif... elif... else.  There have been some proposals for switch
  1461. statement syntax, but there is no consensus (yet) on whether and how
  1462. to do range tests.
  1463. </p><h2>6.2. <a name="6.2"><em>Why does Python use indentation for grouping of statements?
  1464. </em></a></h2><p><strong>Basically I believe that using indentation for grouping is
  1465. extremely elegant and contributes a lot to the clarity of the average
  1466. Python program.</strong>  Most people learn to love this feature after a while.
  1467. Some arguments for it:
  1468. </p><ul><li>Since there are no begin/end brackets there cannot be a disagreement
  1469. between grouping perceived by the parser and the human reader.  I
  1470. remember long ago seeing a C fragment like this:
  1471. </li></ul><pre>        if (x <= y)
  1472.                 x++;
  1473.                 y--;
  1474.         z++;
  1475. </pre><p>and staring a long time at it wondering why y was being decremented
  1476. even for x > y...  (And I wasn't a C newbie then either.)
  1477. </p><ul><li>Since there are no begin/end brackets, Python is much less prone to
  1478. coding-style conflicts.  In C there are loads of different ways to
  1479. place the braces (including the choice whether to place braces around
  1480. single statements in certain cases, for consistency).  If you're used
  1481. to reading (and writing) code that uses one style, you will feel at
  1482. least slightly uneasy when reading (or being required to write)
  1483. another style.
  1484. </li><li>Many coding styles place begin/end brackets on a line by themself.
  1485. This makes programs considerably longer and wastes valuable screen
  1486. space, making it harder to get a good overview over a program.
  1487. Ideally, a function should fit on one basic tty screen (say, 20
  1488. lines).  20 lines of Python are worth a LOT more than 20 lines of C.
  1489. This is not solely due to the lack of begin/end brackets (the lack of
  1490. declarations also helps, and the powerful operations of course), but
  1491. it certainly helps!
  1492. </li></ul><h2>6.3. <a name="6.3"><em>Why are Python strings immutable?
  1493. </em></a></h2><p><strong>There are two advantages.</strong>  One is performance: knowing that a
  1494. string is immutable makes it easy to lay it out at construction time
  1495. -- fixed and unchanging storage requirements.  (This is also one of
  1496. the reasons for the distinction between tuples and lists.)  The
  1497. other is that strings in Python are considered as "elemental" as
  1498. numbers.  No amount of activity will change the value 8 to anything
  1499. else, and in Python, no amount of activity will change the string
  1500. "eight" to anything else.  (Adapted from Jim Roskind)
  1501. </p><h2>6.4. <a name="6.4"><em>Why don't strings have methods like index() or sort(), like
  1502. lists?
  1503. </em></a></h2><p><strong>Good question.</strong>  Strings currently don't have methods at all
  1504. (likewise tuples and numbers).  Long ago, it seemed unnecessary to
  1505. implement any of these functions in C, so a standard library module
  1506. "string" written in Python was created that performs string related
  1507. operations.  Since then, the cry for performance has moved most of
  1508. them into the built-in module strop (this is imported by module
  1509. string, which is still the preferred interface, without loss of
  1510. performance except during initialization).  Some of these functions
  1511. (e.g. index()) could easily be implemented as string methods instead,
  1512. but others (e.g. sort()) can't, since their interface prescribes that
  1513. they modify the object, while strings are immutable (see the previous
  1514. question).
  1515. </p><h2>6.5. <a name="6.5"><em>Why does Python use methods for some functionality
  1516. (e.g. list.index()) but functions for other (e.g. len(list))?
  1517. </em></a></h2><p><strong>Functions are used for those operations that are generic for a
  1518. group of types and which should work even for objects that don't have
  1519. methods at all </strong>(e.g. numbers, strings, tuples).  Also, implementing
  1520. len(), max(), min() as a built-in function is actually less code than
  1521. implementing them as methods for each type.  One can quibble about
  1522. individual cases but it's really too late to change such things
  1523. fundamentally now.
  1524. </p><h2>6.6. <a name="6.6"><em>Why can't I derive a class from built-in types (e.g. lists or
  1525. files)?
  1526. </em></a></h2><p><strong>This is caused by the relatively late addition of </strong>(user-defined)
  1527. classes to the language -- the implementation framework doesn't easily
  1528. allow it.  See the answer to <a href="#4.2">question 4.2</a> for a work-around.  This
  1529. *may* be fixed in the (distant) future.
  1530. </p><h2>6.7. <a name="6.7"><em>Why must 'self' be declared and used explicitly in method
  1531. definitions and calls?
  1532. </em></a></h2><p><strong>By asking this question you reveal your C++ background.</strong> :-)
  1533. When I added classes, this was (again) the simplest way of
  1534. implementing methods without too many changes to the interpreter.  I
  1535. borrowed the idea from Modula-3.  It turns out to be very useful, for
  1536. a variety of reasons.
  1537. </p><p>First, it makes it more obvious that you are using a method or
  1538. instance attribute instead of a local variable.  Reading "self.x" or
  1539. "self.meth()" makes it absolutely clear that an instance variable or
  1540. method is used even if you don't know the class definition by heart.
  1541. In C++, you can sort of tell by the lack of a local variable
  1542. declaration (assuming globals are rare or easily recognizable) -- but
  1543. in Python, there are no local variable declarations, so you'd have to
  1544. look up the class definition to be sure.
  1545. </p><p>Second, it means that no special syntax is necessary if you want to
  1546. explicitly reference or call the method from a particular class.  In
  1547. C++, if you want to use a method from base class that is overridden in
  1548. a derived class, you have to use the :: operator -- in Python you can
  1549. write baseclass.methodname(self, <argument list>).  This is
  1550. particularly useful for __init__() methods, and in general in cases
  1551. where a derived class method wants to extend the base class method of
  1552. the same name and thus has to call the base class method somehow.
  1553. </p><p>Lastly, for instance variables, it solves a syntactic problem with
  1554. assignment: since local variables in Python are (by definition!) those
  1555. variables to which a value assigned in a function body (and that
  1556. aren't explicitly declared global), there has to be some way to tell
  1557. the interpreter that an assignment was meant to assign to an instance
  1558. variable instead of to a local variable, and it should preferably be
  1559. syntactic (for efficiency reasons).  C++ does this through
  1560. declarations, but Python doesn't have declarations and it would be a
  1561. pity having to introduce them just for this purpose.  Using the
  1562. explicit "self.var" solves this nicely.  Similarly, for using instance
  1563. variables, having to write "self.var" means that references to
  1564. unqualified names inside a method don't have to search the instance's
  1565. directories.
  1566. </p><h2>6.8. <a name="6.8"><em>Can't you emulate threads in the interpreter instead of
  1567. relying on an OS-specific thread implementation?
  1568. </em></a></h2><p><strong>Unfortunately, the interpreter pushes at least one C stack frame
  1569. for each Python stack frame.</strong>  Also, extensions can call back into
  1570. Python at almost random moments.  Therefore a complete threads
  1571. implementation requires thread support for C.
  1572. </p><h2>6.9. <a name="6.9"><em>Why can't lambda forms contain statements?
  1573. </em></a></h2><p><strong>Python lambda forms cannot contain statements because Python's
  1574. syntactic framework can't handle statements nested inside expressions.</strong>
  1575. </p><p>However, in Python, this is not a serious problem.  Unlike lambda
  1576. forms in other languages, where they add functionality, Python lambdas
  1577. are only a shorthand notation if you're too lazy to define a function.
  1578. </p><p>Functions are already first class objects in Python, and can be
  1579. declared in a local scope.  Therefore the only advantage of using a
  1580. lambda form instead of a locally-defined function is that you'll have
  1581. to invent a name for the function -- but that's just a local variable
  1582. to which the function object (which is exactly the same type of object
  1583. that a lambda form yields) is assigned!
  1584. </p><h2>6.10. <a name="6.10"><em>Why don't lambdas have access to variables defined in the
  1585. containing scope?
  1586. </em></a></h2><p><strong>Because they are implemented as ordinary functions.</strong>
  1587. See <a href="#4.5">question 4.5</a> above.
  1588. </p><h2>6.11. <a name="6.11"><em>Why can't recursive functions be defined inside other functions?
  1589. </em></a></h2><p><strong>See <a href="#4.5">question 4.5</a> above.</strong>
  1590. </p><h2>6.12. <a name="6.12"><em>Why is there no more efficient way of iterating over a dictionary
  1591. than first constructing the list of keys()?
  1592. </em></a></h2><p><strong>Have you tried it?</strong>  I bet it's fast enough for your purposes!  In
  1593. most cases such a list takes only a few percent of the space occupied
  1594. by the dictionary -- it needs only 4 bytes (the size of a pointer) per
  1595. key -- a dictionary costs 8 bytes per key plus between 30 and 70
  1596. percent hash table overhead, plus the space for the keys and values --
  1597. by necessity all keys are unique objects and a string object (the most
  1598. common key type) costs at least 18 bytes plus the length of the
  1599. string.  Add to that the values contained in the dictionary, and you
  1600. see that 4 bytes more per item really isn't that much more memory...
  1601. </p><p>A call to dict.keys() makes one fast scan over the dictionary
  1602. (internally, the iteration function does exist) copying the pointers
  1603. to the key objects into a pre-allocated list object of the right size.
  1604. The iteration time isn't lost (since you'll have to iterate anyway --
  1605. unless in the majority of cases your loop terminates very prematurely
  1606. (which I doubt since you're getting the keys in random order).
  1607. </p><p>I don't expose the dictionary iteration operation to Python
  1608. programmers because the dictionary shouldn't be modified during the
  1609. entire iteration -- if it is, there's a very small chance that the
  1610. dictionary is reorganized because the hash table becomes too full, and
  1611. then the iteration may miss some items and see others twice.  Exactly
  1612. because this only occurs rarely, it would lead to hidden bugs in
  1613. programs: it's easy never to have it happen during test runs if you
  1614. only insert or delete a few items per iteration -- but your users will 
  1615. surely hit upon it sooner or later.
  1616. </p><h2>6.13. <a name="6.13"><em>Can Python be compiled to machine code, C or some other language?
  1617. </em></a></h2><p><strong>Not easily.</strong>  Python's high level data types, dynamic typing of
  1618. objects and run-time invocation of the interpreter (using eval() or
  1619. exec) together mean that a "compiled" Python program would probably
  1620. consist mostly of calls into the Python run-time system, even for
  1621. seemingly simple operations like "x+1".  Thus, the performance gain
  1622. would probably be minimal.
  1623. </p><p>Internally, Python source code is always translated into a "virtual
  1624. machine code" or "byte code" representation before it is interpreted
  1625. (by the "Python virtual machine" or "bytecode interpreter").  In order
  1626. to avoid the overhead of parsing and translating modules that rarely
  1627. change over and over again, this byte code is written on a file whose
  1628. name ends in ".pyc" whenever a module is parsed (from a file whose
  1629. name ends in ".py").  When the corresponding .py file is changed, it
  1630. is parsed and translated again and the .pyc file is rewritten.  There
  1631. is no performance difference once the .pyc file has been loaded (the
  1632. bytecode read from the .pyc file is exactly the same as the bytecode
  1633. created by direct translation).  The only difference is that loading
  1634. code from a .pyc file is faster than parsing and translating a .py
  1635. file, so the presence of precompiled .pyc files will generally improve
  1636. start-up time of Python scripts.  If desired, the Lib/compileall.py
  1637. module/script can be used to force creation of valid .pyc files for a
  1638. given set of modules.
  1639. </p><p>If you are looking for a way to translate Python programs in order to
  1640. distribute them in binary form, without the need to distribute the
  1641. interpreter and library as well, have a look at the freeze.py script
  1642. in the Tools/freeze directory.  This creates a single binary file
  1643. incorporating your program, the Python interpreter, and those parts of
  1644. the Python library that are needed by your program.  Of course, the
  1645. resulting binary will only run on the same type of platform as that
  1646. used to create it.
  1647. </p><p>Hints for proper usage of freeze.py:
  1648. </p><ul><li>the script must be in a file whose name ends in .py
  1649. </li><li>you must have installed Python fully:
  1650. </li></ul><pre>        make install
  1651.         make libinstall
  1652.         make inclinstall
  1653.         make libainstall
  1654. </pre><h2>6.14. <a name="6.14"><em>Why doesn't Python use proper garbage collection?
  1655. </em></a></h2><p><strong>It's looking less and less likely that Python will ever get
  1656. "automatic" garbage collection </strong>(GC).  For one thing, unless this were
  1657. added to C as a standard feature, it's a portability pain in the ass.
  1658. And yes, I know about the Xerox library.  It has bits of assembler
  1659. code for *most* *common* platforms.  Not for all.  And although it is
  1660. mostly transparent, it isn't completely transparent (when I once
  1661. linked Python with it, it dumped core).
  1662. </p><p>"Proper" GC also becomes a problem when Python gets embedded into
  1663. other applications.  While in a stand-alone Python it may be fine to
  1664. replace the standard malloc() and free() with versions provided by the
  1665. GC library, an application embedding Python may want to have its *own*
  1666. substitute for malloc() and free(), and may not want Python's.  Right
  1667. now, Python works with anything that implements malloc() and free()
  1668. properly.
  1669. </p><p>Besides, the predictability of destructor calls in Python is kind of
  1670. attractive.  With GC, the following code (which is fine in current
  1671. Python) will run out of file descriptors long before it runs out of
  1672. memory:
  1673. </p><pre>        for file in <very long list of files>:
  1674.                 f = open(file)
  1675.                 c = file.read(1)
  1676. </pre><p>Using the current reference counting and destructor scheme, each new
  1677. assignment to f closes the previous file.  Using GC, this is not
  1678. guaranteed.  Sure, you can think of ways to fix this.  But it's not
  1679. off-the-shelf technology.
  1680. </p><hr><h1>7. <a name="7">Using Python on non-UNIX platforms
  1681. </a></h1><h2>7.1. <a name="7.1"><em>Is there a Mac version of Python?
  1682. </em></a></h2><p><strong>Yes, see the "mac" subdirectory of the distribution sites,
  1683. e.g.</strong> <a href="ftp://ftp.python.org/pub/python/mac/">ftp://ftp.python.org/pub/python/mac/</a>.
  1684. </p><h2>7.2. <a name="7.2"><em>Are there DOS and Windows versions of Python?
  1685. </em></a></h2><p><strong>Yes.</strong>  There is a plethora of not-always-compatible versions.  See
  1686. the "pythonwin", "wpy", "nt" and "pc" subdirectories of the
  1687. distribution sites.  A quick comparison:
  1688. </p><p>PythonWin: Extensive support for the 32-bit native Windows API and GUI
  1689. building using MFC.  Windows NT and Windows 95 only (and Windows
  1690. 3.1(1) using win32s, until Microsoft stops supporting it :-( ).
  1691. <a href="ftp://ftp.python.org/pub/python/pythonwin/">ftp://ftp.python.org/pub/python/pythonwin/</a>.
  1692. </p><p>WPY: Ports to DOS, Windows 3.1(1), Windows 95, Windows NT and OS/2.
  1693. Also contains a GUI package that offers portability between Windows 
  1694. (not DOS) and Unix, and native look and feel on both.
  1695. <a href="ftp://ftp.python.org/pub/python/wpy/">ftp://ftp.python.org/pub/python/wpy/</a>.
  1696. </p><p>NT: Basic ports built straight from the 1.4 distribution for Windows
  1697. 95 and Windows NT.  This will eventually provide core support for
  1698. both PythonWin and WPY on all 32-bit Microsoft platforms.
  1699. <a href="ftp://ftp.python.org/pub/python/nt/">ftp://ftp.python.org/pub/python/nt/</a>.
  1700. </p><p>PC: Old, unsupported ports to DOS, Windows 3.1(1) and OS/2.
  1701. <a href="ftp://ftp.python.org/pub/python/pc/">ftp://ftp.python.org/pub/python/pc/</a>.
  1702. </p><h2>7.3. <a name="7.3"><em>Is there an OS/2 version of Python?
  1703. </em></a></h2><p><strong>Yes, see the "pc" and "wpy" subdirectory of the distribution sites
  1704. </strong>(see above).
  1705. </p><h2>7.4. <a name="7.4"><em>Is there a VMS version of Python?
  1706. </em></a></h2><p><strong>Donn Cave <a href="mailto:donn@cac.washington.edu">donn@cac.washington.edu</a></strong> did a partial port.  The
  1707. results of his efforts are on public display in
  1708. <<a href="ftp://ftp.python.org/pub/python/contrib/vms.tar.gz/">ftp://ftp.python.org/pub/python/contrib/vms.tar.gz/</a>.  Someone
  1709. else is working on a more complete port, for details watch the list.
  1710. </p><h2>7.5. <a name="7.5"><em>What about IBM mainframes, or other non-UNIX platforms?
  1711. </em></a></h2><p><strong>I haven't heard about these, except I remember hearing about an
  1712. OS/9 port and a port to Vxworks </strong>(both operating systems for embedded
  1713. systems).  If you're interested in any of this, go directly to the
  1714. newsgroup and ask there, you may find exactly what you need.  For
  1715. example, a port to MPE/iX 5.0 on HP3000 computers was just announced,
  1716. see <a href="http://www.allegro.com/software/">http://www.allegro.com/software/</a>.
  1717. </p><h2>7.6. <a name="7.6"><em>Where are the source or Makefiles for the non-UNIX versions?
  1718. </em></a></h2><p><strong>The standard sources can </strong>(almost) be used.  Additional sources can
  1719. be found in the platform-specific subdirectories of the distribution.
  1720. </p><h2>7.7. <a name="7.7"><em>What is the status and support for the non-UNIX versions?
  1721. </em></a></h2><p><strong>I don't have access to most of these platforms, so in general I am
  1722. dependent on material submitted by volunteers</strong>(*).  However I strive to
  1723. integrate all changes needed to get it to compile on a particular
  1724. platform back into the standard sources, so porting of the next
  1725. version to the various non-UNIX platforms should be easy.
  1726. </p><p>(*) For the Macintosh, that volunteer is me, with help from Jack
  1727. Jansen <a href="mailto:jack@cwi.nl">jack@cwi.nl</a>.
  1728. </p><h2>7.8. <a name="7.8"><em>I have a PC version but it appears to be only a binary.
  1729. Where's the library?
  1730. </em></a></h2><p><strong>You still need to copy the files from the distribution directory
  1731. "python/Lib" to your system.</strong>  If you don't have the full distribution,
  1732. you can get the file lib<version>.tar.gz from most ftp sites carrying
  1733. Python; this is a subset of the distribution containing just those
  1734. files, e.g.  <a href="ftp://ftp.python.org/pub/python/src/lib1.1.tar.gz">ftp://ftp.python.org/pub/python/src/lib1.1.tar.gz</a>.
  1735. </p><p>Once you have installed the library, you need to point sys.path to it.
  1736. Assuming the library is in C:\misc\python\lib, the following commands
  1737. will point your Python interpreter to it (note the doubled backslashes
  1738. -- you can also use single forward slashes instead):
  1739. </p><pre>        >>> import sys
  1740.         >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
  1741.         >>>
  1742. </pre><p>For a more permanent effect, set the environment variable PYTHONPATH,
  1743. as follows (talking to a DOS prompt):
  1744. </p><pre>        C> SET PYTHONPATH=C:\misc\python\lib
  1745. </pre><h2>7.9. <a name="7.9"><em>Where's the documentation for the Mac or PC version?
  1746. </em></a></h2><p><strong>The documentation for the Unix version also applies to the Mac and
  1747. PC versions.</strong>  Where applicable, differences are indicated in the text.
  1748. </p><h2>7.10. <a name="7.10"><em>The Mac (PC) version doesn't seem to have any facilities for
  1749. creating or editing programs apart from entering it interactively, and
  1750. there seems to be no way to save code that was entered interactively.
  1751. How do I create a Python program on the Mac (PC)?
  1752. </em></a></h2><p><strong>Use an external editor.</strong>  On the Mac, BBEdit seems to be a popular
  1753. no-frills text editor.  I work like this: start the interpreter; edit
  1754. a module file using BBedit; import and test it in the interpreter;
  1755. edit again in BBedit; then use the built-in function reload() to
  1756. re-read the imported module; etc.
  1757. </p><p>Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
  1758. anyone with a pulse could certainly figure out how to do the same on
  1759. MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
  1760. Not only can you easily resave and "reload()" from Python after making
  1761. changes, but since WinNot auto-copies to the clipboard any text you
  1762. select, you can simply select the entire procedure (function) which
  1763. you changed in WinNot, switch to QWPython, and shift-ins to reenter
  1764. the changed program unit."
  1765. </p></body></html>
  1766.