home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / python-faq / part1 next >
Text File  |  1996-09-15  |  100KB  |  2,258 lines

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