home *** CD-ROM | disk | FTP | other *** search
/ Amiga Tools 5 / Amiga Tools 5.iso / tools / developer-tools / andere sprachen / python-1.3 / docs / python_faq.txt < prev    next >
Encoding:
Text File  |  1996-07-16  |  98.8 KB  |  2,287 lines

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