home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Information / Languages / Python / python-faq⁄part1
Encoding:
Text File  |  1994-12-03  |  69.8 KB  |  1,387 lines  |  [TEXT/R*ch]

  1. Newsgroups: comp.lang.python,comp.answers,news.answers
  2. Path: bloom-beacon.mit.edu!hookup!news.moneng.mei.com!howland.reston.ans.net!news.sprintlink.net!EU.net!sun4nl!cwi.nl!guido
  3. From: guido@cwi.nl (Guido van Rossum)
  4. Subject: FAQ: Python -- an object-oriented language
  5. Message-ID: <Cz2r1D.KCG@cwi.nl>
  6. Followup-To: comp.lang.python
  7. Originator: guido@voorn.cwi.nl
  8. Sender: news@cwi.nl (The Daily Dross)
  9. Nntp-Posting-Host: voorn.cwi.nl
  10. Reply-To: guido@cwi.nl (Guido van Rossum)
  11. Organization: CWI, Amsterdam
  12. Date: Thu, 10 Nov 1994 23:10:25 GMT
  13. Approved: news-answers-request@MIT.Edu
  14. Lines: 1629
  15. Xref: bloom-beacon.mit.edu comp.lang.python:2571 comp.answers:8281 news.answers:29141
  16.  
  17. Archive-name: python-faq/part1
  18. Version: 1.16
  19. Last-modified: 10 November 1994
  20.  
  21. This article contains answers to Frequently Asked Questions about
  22. Python (an object-oriented interpreted programming language -- see
  23. the answer to question 1.1 for a short overview).
  24.  
  25. Copyright 1993, 1994 Guido van Rossum.  Unchanged electronic
  26. redistribution of this FAQ is allowed.  Printed redistribution only
  27. with permission of the author.  No warranties.
  28.  
  29. Author's address:
  30.     Guido van Rossum
  31.     CWI, dept. CST
  32.     Kruislaan 413
  33.     P.O. Box 94079
  34.     1090 GB  Amsterdam
  35.     The Netherlands
  36. Email:    guido@cwi.nl
  37.  
  38. The latest version of this FAQ is available by anonymous ftp from
  39. ftp.cwi.nl [192.16.191.128] in the directory /pub/python, with
  40. filename python-FAQ.  It will also be posted regularly to the
  41. newsgroups comp.answers and comp.lang.python.
  42.  
  43. Many FAQs, including this one, are available by anonymous ftp from
  44. rtfm.mit.edu [18.181.0.24] in the directory pub/usenet/news.answers.  
  45. The name under which a FAQ is archived appears in the Archive-name line 
  46. at the top of the article.  This FAQ is archived as python-faq/part1.
  47.  
  48. There's a mail server on that machine which will send you files from
  49. the archive by e-mail if you have no ftp access.  You send a e-mail
  50. message to mail-server@rtfm.mit.edu containing the single word help in
  51. the message body to receive instructions.
  52.  
  53. Skip Montanaro <skip@automatrix.com> maintains an HTML version of this
  54. FAQ.  The URL is <http://www.automatrix.com/~skip/python-faq.html>.
  55.  
  56. This FAQ is divided in the following chapters:
  57.  
  58.  1. General information and availability
  59.  2. Python in the real world
  60.  3. Building Python
  61.  4. Programming in Python
  62.  5. Extending Python
  63.  6. Python's design
  64.  7. Using Python on non-UNIX platforms
  65.  
  66. To find the start of a particular chapter, search for the chapter number
  67. followed by a dot and a space at the beginning of a line (e.g. to
  68. find chapter 4 in vi, type /^4\. /).
  69.  
  70. Here's an overview of the questions per chapter:
  71.  
  72.  1. General information and availability
  73.   1.1. Q. What is Python?
  74.   1.2. Q. Why is it called Python?
  75.   1.3. Q. How do I obtain a copy of the Python source?
  76.   1.4. Q. How do I get documentation on Python?
  77.   1.5. Q. Are there other ftp sites that mirror the Python distribution?
  78.   1.6. Q. Is there a newsgroup or mailing list devoted to Python?
  79.   1.7. Q. Is there a book on Python, or will there be one out soon?
  80.   1.8. Q. Are there any published articles about Python that I can quote?
  81.   1.9. Q. How does the Python version numbering scheme work?
  82.   1.10. Q. Are there other ftp sites that carry Python related material?
  83.   1.11. Q. Are there copyright restrictions on the use of Python?
  84.  
  85.  2. Python in the real world
  86.   2.1. Q. How many people are using Python?
  87.   2.2. Q. Have any significant projects been done in Python?
  88.   2.3. Q. Are there any commercial projects going on using Python?
  89.   2.4. Q. How stable is Python?
  90.   2.5. Q. When will the next version be released?
  91.   2.6. Q. What new developments are expected for Python in the future?
  92.   2.7. Q. Is it reasonable to propose incompatible changes to Python?
  93.  
  94.  3. Building Python
  95.   3.1. Q. Is there a test set?
  96.   3.2. Q. When running the test set, I get complaints about floating point
  97.        operations, but when playing with floating point operations I cannot
  98.        find anything wrong with them.
  99.   3.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
  100.   3.4. Q. Link errors building Python with STDWIN 0.9.9.
  101.   3.5. Q. Link errors after rerunning the configure script.
  102.   3.6. Q. The python interpreter complains about options passed to a
  103.        script (after the script name).
  104.   3.7. Q. When building on the SGI, make tries to run python to create
  105.        glmodule.c, but python hasn't been built or installed yet.
  106.   3.8. Q. Python built with gcc for the DEC Alpha doesn't work.
  107.   3.9. Q. I use VPATH but some targets are built in the source directory.
  108.   3.10. Q. Trouble building or linking with thPython's power stems
  109. from the standard or built-in types, functions and modules, all of
  110. which are described here.  PostScript for a high-level description of
  111. Python is in the file nluug-paper.ps.
  112.  
  113. 1.5. Q. Are there other ftp sites that mirror the Python distribution?
  114.  
  115. A. The following sites keep mirrors of the Python distribution:
  116.  
  117. Site            IP address     Directory
  118.  
  119. gatekeeper.dec.com    16.1.0.2    /pub/plan/python
  120. ftp.uu.net        192.48.96.9    /languages/python
  121. ftp.wustl.edu        128.252.135.4    /graphics/graphics/sgi-stuff/python
  122. ftp.funet.fi        128.214.6.100    /pub/languages/python
  123. ftp.fu-berlin.de    130.133.1.18    /unix/languages/python (*python* only)
  124. ftp.sunet.se        130.238.127.3    /pub/lang/python
  125. unix.hensa.ac.uk    129.12.43.16    /uunet/languages/python
  126. ftp.sterlng.com         192.124.9.3     /programming/languages/python
  127.  
  128. Or try archie on e.g. "python1." to locate the nearest copy of that
  129. version...
  130.  
  131. 1.6. Q. Is there a newsgroup or mailing list devoted to Python?
  132.  
  133. A. There is a newsgroup, comp.lang.python, and a mailing list.  The
  134. newsgroup and mailing list are gatewayed into each other -- if you can
  135. read news it's unnecessary to subscribe to the mailing list.  Send
  136. e-mail to python-list-request@cwi.nl to (un)subscribe to the mailing
  137. list.  Once you're on, send e-mail tp python-list@cwi.nl to send mail
  138. to the entire mailing list and newsgroup.  Hypermail archives of
  139. (nearly) everything posted to the mailing list (and thus the
  140. newsgroup) are available -- the URL for the complete set of archives
  141. is <http://www.cwi.nl/~guido/hypermail/index.html>.  The raw archives
  142. are also available by ftp from ftp.cwi.nl in /pub/python (and most
  143. mirrors), files mail*.gz.  The uncompressed versions of these files
  144. can be read with the standard UNIX Mail program ("Mail -f file") or
  145. with nn ("nn file").  To read them using MH, you could use "inc -file
  146. file".
  147.  
  148. 1.7. Q. Is there a book on Python, or will there be one out soon?
  149.  
  150. A. I am writing one.  Addison-Wesley is interested.  Optimistically,
  151. it will be published by mid-1995.  Other authors are also working on
  152. books...  (Do you guys want your name mentioned here?)
  153.  
  154. 1.8. Q. Are there any published articles about Python that I can quote?
  155.  
  156. A. So far the only refereed and published article that describes
  157. Python in some detail is:
  158.  
  159.     Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
  160.     Servers Using the Python Programming Language", CWI Quarterly, Volume
  161.     4, Issue 4 (December 1991), Amsterdam, pp 283-303.
  162.  
  163. LaTeX source for this paper is available as part of the Python source
  164. distribution.
  165.  
  166. A more recent high-level description of Python is:
  167.  
  168.     Guido van Rossum, "An Introduction to Python for UNIX/C
  169.     Programmers", in the proceedings of the NLUUG najaarsconferentie
  170.     1993 (dutch UNIX users group meeting November 1993).
  171.     
  172. PostScript for this paper and for the slides used for the accompanying
  173. presentation can be found in the ftp directory mentioned a few
  174. questions earlier, with filenames nluug-paper.ps and nluug-slides.ps,
  175. respectively.
  176.  
  177. 1.9. Q. How does the Python version numbering scheme work?
  178.  
  179. A. Python versions are numbered A.B.C.  A is the major version number
  180. -- it is only incremented for major changes in functionality or source
  181. structure.  B is the minor version number, incremented for less
  182. earth-shattering changes to a release.  C is the patchlevel -- it is
  183. incremented for each new release.  Note that in the past, patches have
  184. added significant changes; in fact the changeover from 0.9.9 to 1.0.0
  185. was the first time that either A or B changed!
  186.  
  187. 1.10. Q. Are there other ftp sites that carry Python related material?
  188.  
  189. A. An interesting ftp site for Python users is ftp.markv.com
  190. (192.122.251.1); the directory pub/python contains a growing
  191. collection of interesting Python scripts.  To submit a script for
  192. inclusion, place it together with a readme file (with extension
  193. .readme) in the publicly writable directory /incoming/python.  This
  194. service is maintained by Lance Ellinghouse <lance@markv.com>.
  195.  
  196. 1.11. Q. Are there copyright restrictions on the use of Python?
  197.  
  198. A. Hardly.  You can do anything you want with the source, as long as
  199. you leave the copyrights in, display those copyrights in any
  200. documentation about Python that you produce, don't use the author's
  201. institute's name in publicity without prior written permission, and
  202. don't hold them responsible for anything (read the actual copyright
  203. for a precise legal wording).
  204.  
  205.  
  206. 2. Python in the real world
  207. ===========================
  208.  
  209. 2.1. Q. How many people are using Python?
  210.  
  211. A. I don't know, but the maximum number of simultaneous subscriptions
  212. to the Python mailing list before it was gatewayed into the newsgroup
  213. was about 180 (several of which were local redistribution lists).  I
  214. believe that many active Python users don't bother to subscribe to the
  215. list, and now that there's a newsgroup the mailing list subscription
  216. is even less meaningful.  I see new names on the newsgroup all the
  217. time and my best guess is that there are currently at least several
  218. thousands of users.
  219.  
  220. 2.2. Q. Have any significant projects been done in Python?
  221.  
  222. A. Here at CWI (the home of Python), we have written a 20,000 line
  223. authoring environment for transportable hypermedia presentations, a
  224. 5,000 line multimedia teleconferencing tool, as well as many many
  225. smaller programs.
  226.  
  227. The University of Virginia uses Python to control a virtual reality
  228. engine.  Contact: Matt Conway <conway@virginia.edu>.
  229.  
  230. If you have done a significant project in Python that you'd like to be
  231. included in the list above, send me email!
  232.  
  233. 2.3. Q. Are there any commercial projects going on using Python?
  234.  
  235. A. Several companies have revealed to me that they are planning or
  236. considering to use Python in a future product.
  237.  
  238. The furthest is Sunrise Software, who already have a product out using
  239. Python -- they use Python for a GUI management application and an SNMP
  240. network management application.  Contact: <info@sunrise.com>.
  241.  
  242. Infoseek is using Python to implement their commercial WWW information
  243. retrieval service.  Contact: <info@infoseek.com>.
  244.  
  245. Michael Powers of daVinci Time & Space is "writing tons-o-python for
  246. interactive television entertainment."  Contact: <powers@dvts.com>.
  247.  
  248. Individuals at many other companies are using Python for
  249. internal development (witness their contributions to the Python
  250. mailing list or newsgroup).
  251.  
  252. Python has also been elected as an extension language by MADE, a
  253. consortium supported by the European Committee's ESPRIT program and
  254. consisting of Bull, CWI and some other European companies.  Contact:
  255. Ivan Herman <ivan@cwi.nl>.
  256.  
  257. If you'd like to be included in the list above, send me email!
  258.  
  259. 2.4. Q. How stable is Python?
  260.  
  261. A. Very stable.  While the current version number would suggest it is
  262. in the early stages of development, in fact new, stable releases
  263. (numbered 0.9.x and 1.0.x) have been coming out roughly every 3 to 6
  264. months for the past four years.
  265.  
  266. 2.5. Q. When will the next version be released?
  267.  
  268. A. I am planning to release 1.1 before October 15.  It will contain
  269. tons of changes, including (again) improved portability, especially
  270. better support for DOS, Windows, Windows NT an the Macintosh.  A few
  271. modules will have been converted to the new naming scheme.  A working
  272. signal module will be present.
  273.  
  274. 2.6. Q. What new developments are expected for Python in the future?
  275.  
  276. A.  A proposal is being worked out to change the semantics of operator
  277. overloading (__add__, __mul__ etc.) to make them more useful for
  278. implementing types that don't resemble numbers.  Additions will be
  279. __call__ (to call an instance as if it were a function) and __eq__,
  280. _lt__ etc. (to override individual comparisons).  A (new) pthreads
  281. interface has been submitted which will be integrated in the next
  282. release.  The X11/Motif interface will be improved.  There are ideas
  283. about built-in help using strings placed into function objects, and
  284. possibly a switch statement.
  285.  
  286. There will be better ports to the Mac, DOS, Windows, Windows NT, and
  287. OS/2.  The Windows ports will support dynamically loaded modules using
  288. DLLs.
  289.  
  290. Also planned is improved support for embedding Python in other
  291. applications, e.g. by renaming most global symbols to have a "Py"
  292. prefix and providing more documentation and threading support.
  293.  
  294. 2.7. Q. Is it reasonable to propose incompatible changes to Python?
  295.  
  296. A. In general, no.  There are already millions of lines of Python code
  297. around the world, so any changes in the language that invalidates more
  298. than a very small fraction of existing programs has to be frowned
  299. upon.  Even if you can provide a conversion program, there still is
  300. the problem of updating all documentation.  Providing a gradual
  301. upgrade path is the only way if a feature has to be changed.
  302.  
  303.  
  304. 3. Building Python
  305. ==================
  306.  
  307. 3.1. Q. Is there a test set?
  308.  
  309. A. Yes, simply do "import testall" (or "import autotest" if you aren't
  310. interested in the output).  The standard modules whose name begins
  311. with "test" together comprise the test.  The test set doesn't test
  312. *all* features of Python but it goes a long way to confirm that a new
  313. port is actually working.  The Makefile contains an entry "make test"
  314. which runs the autotest module.
  315.  
  316. 3.2. Q. When running the test set, I get complaints about floating point
  317. operations, but when playing with floating point operations I cannot
  318. find anything wrong with them.
  319.  
  320. A. The test set makes occasional unwarranted assumptions about the
  321. semantics of C floating point operations.  Until someone donates a
  322. better floating point test set, you will have to comment out the
  323. offending floating point tests and execute similar tests manually.
  324.  
  325. 3.3. Q. Link errors building Python with STDWIN 0.9.8. on SGI IRIX.
  326.  
  327. A. Get STDWIN 0.9.9 from ftp://ftp.cwi.nl/pub/stdwin/stdwin0.9.9.tar.gz.
  328.  
  329. 3.4. Q. Link errors building Python with STDWIN 0.9.9.
  330.  
  331. A. Probably routines liek 'tereate', 'tenew' etc.  The STDWIN 0.9.9
  332. distribution requires that you add TWO libraries from stdwin to the
  333. line for stdwin in the Setupfile.  Use something like this (all on one
  334. line!):
  335.  
  336. stdwin stdwinmodule.c -I$(STDWIN)/H $(STDWIN)/Packs/textedit/libtextedit.a $(STDWIN)/Ports/x11/libstdwin.a -lX11
  337.  
  338. 3.5. Q. Link errors after rerunning the configure script.
  339.  
  340. A. It is generally necessary to run "make clean" after a configuration
  341. change.
  342.  
  343. 3.6. Q. The python interpreter complains about options passed to a
  344. script (after the script name).
  345.  
  346. A. You are probably linking with GNU getopt, e.g. through -liberty.
  347. Don't.  The reason for the complaint is that GNU getopt, unlike System
  348. V getopt and other getopt implementations, doesn't consider a
  349. non-option to be the end of the option list.  A quick (and compatible)
  350. fix for scripts is to add "--" to the interpreter, like this:
  351.  
  352.     #! /usr/local/bin/python --
  353.  
  354. You can also use this interactively:
  355.  
  356.     python -- script.py [options]
  357.  
  358. 3.7. Q. When building on the SGI, make tries to run python to create
  359. glmodule.c, but python hasn't been built or installed yet.
  360.  
  361. A. Comment out the line mentioning glmodule.c in Setup and build a
  362. python without gl first; install it or make sure it is in your $PATH,
  363. then edit the Setup file again to turn on the gl module, and make
  364. again.  You don't need to do "make clean"; you do need to run "make
  365. Makefile" in the Modules subdirectory (or just run "make" at the
  366. toplevel).
  367.  
  368. 3.8. Q. Python built with gcc for the DEC Alpha doesn't work.
  369.  
  370. People have reported problems with both gcc 2.5.8 and 2.6.0.  The DEC
  371. OSF/1 cc compiler does not have these problems so it's probably gcc's
  372. fault.  One person reported that the problem went away when using -g
  373. instead of -O so this may be an option if you insist on using gcc.  If
  374. someone tracks it down more completely I'd like to hear about it!
  375.  
  376. 3.9. Q. I use VPATH but some targets are built in the source directory.
  377.  
  378. A. On some systems (e.g. Sun), if the target already exists in the
  379. source directory, it is created there instead of in the build
  380. directory.  This is usually because you have previously built without
  381. VPATH.  Try running "make clobber" in the source directory.
  382.  
  383. 3.10. Q. Trouble building or linking with the GNU readline library.
  384.  
  385. A. Consider using readline 2.0.  From the Python 1.1 README:
  386.  
  387. - You can use the GNU readline library to improve the interactive user
  388. interface: this gives you line editing and command history when
  389. calling python interactively. You need to configure build the GNU
  390. readline library before running the configure script. Its sources are
  391. no longer distributed with Python; you can ftp them from any GNU
  392. mirror site, or from its home site:
  393. ftp://slc2.ins.cwru.edu/pub/dist/readline-2.0.tar.gz (or a higher
  394. version number -- using version 1.x is not recommended). Pass the
  395. Python configure script the option --with-readline=DIRECTORY where
  396. DIRECTORY is the absolute pathname of the directory where you've built
  397. the readline library. Some hints on building and using the readline
  398. library:
  399.  
  400. - On SGI IRIX 5, you may have to add the following
  401. to rldefs.h:
  402.  
  403. #ifndef sigmask
  404. #define sigmask(sig) (1L << ((sig)-1))
  405. #endif
  406.  
  407. - On most systems, you will have to add #include "rldefs.h" to the
  408. top of several source files, and if you use the VPATH feature, you
  409. will have to add dependencies of the form foo.o: foo.c to the
  410. Makefile for several values of foo.
  411.  
  412. - The readline library requires use of the termcap library. A
  413. known problem with this is that it contains entry points which
  414. cause conflicts with the STDWIN and SGI GL libraries. The STDWIN
  415. conflict can be solved (and will be, in the next release of
  416. STDWIN) by adding a line saying '#define werase w_erase' to the
  417. stdwin.h file (in the STDWIN distribution, subdirectory H). The
  418. GL conflict has been solved in the Python configure script by a
  419. hack that forces use of the static version of the termcap library.
  420.  
  421. - Check the newsgroup gnu.bash.bugs for specific problems with the
  422. readline library (I don't get this group here but I've been told
  423. that it is the place for readline bugs.)
  424.  
  425. 3.11. Q. Trouble building Python on Linux.
  426.  
  427. A. There shouldn't be any -- I've seen several complaints but more
  428. reports on successful "out-of-the-box" ports on Linux.  The standard
  429. configure script runs just fine on Linux.
  430.  
  431. 3.12. Q. Trouble with prototypes on Ultrix.
  432.  
  433. A. Ultrix cc seems broken -- use gcc, or edit config.h to #undef
  434. HAVE_PROTOTYPES.
  435.  
  436. 3.13. Q. Trouble with posix.listdir on NeXTSTEP 3.2.
  437.  
  438. A. The problem seems to be that that the NeXT posix library and the
  439. NeXT dynamic loading library are incompatible.  Mike Carlton reports
  440. that the following worked for him (from a clean 1.1 distribution):
  441.  
  442.     1) ./configure
  443.     2) edited config.status and changed 
  444.         OPT='-O'
  445.        to
  446.         OPT='-posix -O'
  447.     3) edited Python/import.c and commented out the section
  448.         #if defined(NeXT) || defined(WITH_RLD) 
  449.         #define DYNAMIC_LINK
  450.         #define USE_RLD
  451.         #endif
  452.        this disables dynamic loading
  453.     4) make
  454.  
  455. 3.14. Q. Other trouble building Python on platform X.
  456.  
  457. A. Please email the details to <guido@cwi.nl> and I'll look into it.
  458.  
  459.  
  460. 4. Programming in Python
  461. ========================
  462.  
  463. 4.1. Q. Is there a source code level debugger with breakpoints, step,
  464. etc.?
  465.  
  466. A. Yes.  Check out module pdb; pdb.help() prints the documentation (or
  467. you can read it as Lib/pdb.doc).  If you use the STDWIN option,
  468. there's also a windowing interface, wdb.  You can write your own
  469. debugger by using the code for pdb or wdb as an example.
  470.  
  471. 4.2. Q. Can I create an object class with some methods implemented in
  472. C and others in Python (e.g. through inheritance)?  (Also phrased as:
  473. Can I use a built-in type as base class?)
  474.  
  475. A. No, but you can easily create a Python class which serves as a
  476. wrapper around a built-in object, e.g. (for dictionaries):
  477.  
  478.     # A user-defined class behaving almost identical
  479.     # to a built-in dictionary.
  480.     class UserDict:
  481.         def __init__(self): self.data = {}
  482.         def __repr__(self): return repr(self.data)
  483.         def __cmp__(self, dict):
  484.             if type(dict) == type(self.data):
  485.                 return cmp(self.data, dict)
  486.             else:
  487.                 return cmp(self.data, dict.data)
  488.         def __len__(self): return len(self.data)
  489.         def __getitem__(self, key): return self.data[key]
  490.         def __setitem__(self, key, item): self.data[key] = item
  491.         def __delitem__(self, key): del self.data[key]
  492.         def keys(self): return self.data.keys()
  493.         def items(self): return self.data.items()
  494.         def values(self): return self.data.values()
  495.         def has_key(self, key): return self.data.has_key(key)
  496.  
  497. 4.3. Q. Is there a curses/termcap package for Python?
  498.  
  499. A. Yes -- Lance Ellinghouse has written a module that interfaces to
  500. System V's "ncurses".  If you know a little curses and some Python,
  501. it's straightforward to use.
  502.  
  503. You could also consider using the "alfa" (== character cell) version
  504. of STDWIN.  (STDWIN == Standard Windows, a portable windowing system
  505. interface by the same author, URL: "ftp://ftp.cwi.nl/pub/stdwin".)  This
  506. will also prepare your program for porting to windowing environments
  507. such as X11 or the Macintosh.
  508.  
  509. 4.4. Q. Is there an equivalent to C's onexit() in Python?
  510.  
  511. A. Yes, if you import sys and assign a function to sys.exitfunc, it
  512. will be called when your program exits, is killed by an unhandled
  513. exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
  514.  
  515. 4.5. Q. When I define a function nested inside another function, the
  516. nested function seemingly can't access the local variables of the
  517. outer function.  What is going on?  How do I pass local data to a
  518. nested function?
  519.  
  520. A. Python does not have arbitrarily nested scopes.  When you need to
  521. create a function that needs to access some data which you have
  522. available locally, create a new class to hold the data and return a
  523. method of an instance of that class, e.g.:
  524.  
  525.     class MultiplierClass:
  526.         def __init__(self, factor):
  527.             self.factor = factor
  528.         def multiplier(self, argument):
  529.             return argument * self.factor
  530.  
  531.     def generate_multiplier(factor):
  532.         return MultiplierClass(factor).multiplier
  533.  
  534.     twice = generate_multiplier(2)
  535.     print twice(10)
  536.     # Output: 20
  537.  
  538. 4.6. Q. How do I iterate over a sequence in reverse order?
  539.  
  540. A. If it is a list, the fastest solution is
  541.  
  542.     list.reverse()
  543.     try:
  544.         for x in list:
  545.             "do something with x"
  546.     finally:
  547.         list.reverse()
  548.  
  549. This has the disadvantage that while you are in the loop, the list
  550. is temporarily reversed.  If you don't like this, you can make a copy.
  551. This appears expensive but is actually faster than other solutions:
  552.  
  553.     rev = list[:]
  554.     rev.reverse()
  555.     for x in rev:
  556.         <do something with x>
  557.  
  558. If it isn't a list, a more general but slower solution is:
  559.  
  560.     i = len(list)
  561.     while i > 0:
  562.         i = i-1
  563.         x = list[i]
  564.         <do something with x>
  565.  
  566. A more elegant solution, is to define a class which acts as a sequence
  567. and yields the elements in reverse order (solution due to Steve
  568. Majewski):
  569.  
  570.     class Rev:
  571.         def __init__(self, seq):
  572.             self.forw = seq
  573.         def __len__(self):
  574.             return len(self.forw)
  575.         def __getitem__(self, i):
  576.             return self.forw[-(i + 1)]
  577.  
  578. You can now simply write:
  579.  
  580.     for x in Rev(list):
  581.         <do something with x>
  582.  
  583. Unfortunately, this solution is slowest of all, due to the method
  584. call overhead...
  585.  
  586. 4.7. Q. My program is too slow.  How do I speed it up?
  587.  
  588. A. That's a tough one, in general.  There are many tricks to speed up
  589. Python code; I would consider rewriting parts in C only as a last
  590. resort.  One thing to notice is that function and (especially) method
  591. calls are rather expensive; if you have designed a purely OO interface
  592. with lots of tiny functions that don't do much more than get or set an
  593. instance variable or call another method, you may consider using a
  594. more direct way, e.g. directly accessing instance variables.  Also see
  595. the standard module "profile" (described in the file
  596. "python/lib/profile.doc") which makes it possible to find out where
  597. your program is spending most of its time (if you have some patience
  598. -- the profiling itself can slow your program down by an order of
  599. magnitude).
  600.  
  601. 4.8. Q. When I have imported a module, then edit it, and import it
  602. again (into the same Python process), the changes don't seem to take
  603. place.  What is going on?
  604.  
  605. A. For efficiency reasons, Python only reads the module file on the
  606. first time a module is imported (otherwise a program consisting of
  607. many modules, each of which imports the same basic module, would read
  608. the basic module over and over again).  To force a changed module
  609. being read again, do this:
  610.  
  611.     import modname
  612.     reload(modname)
  613.  
  614. Warning: this technique is not 100% fool-proof.  In particular,
  615. modules containing statements like
  616.  
  617.     from modname import some_objects
  618.  
  619. will continue to work with the old version of the imported objects.
  620.  
  621. 4.9. Q. How do I find the current module name?
  622.  
  623. A. A module can find out its own module name by looking at the
  624. (predefined) global variable __name__.  If this has the value
  625. '__main__' you are running as a script.  
  626.  
  627. 4.10. Q. I have a module in which I want to execute some extra code when it
  628. is run as a script.  How do I find out whether I am running as a
  629. script?
  630.  
  631. A. See the previous question.  E.g. if you put the following on the
  632. last line of your module, main() is called only when your module is
  633. running as a script:
  634.  
  635.     if __name__ == '__main__': main()
  636.  
  637. 4.11. Q. I try to run a program from the Demo directory but it fails with
  638. ImportError: No module named ...; what gives?
  639.  
  640. A. This is probably an optional module (written in C!) which hasn't
  641. been configured on your system.  This especially happens with modules
  642. like "stdwin", "gl", "Xt" or "Xm".  For STDWIN and many other modules,
  643. see Modules/Setup.in for info on how to add these modules to your
  644. Python, if it is possible at all.  Sometimes you will have to ftp and
  645. build another package first (e.g. STDWIN).  Sometimes the module only
  646. works on specific platforms (e.g. gl only works on SGI machines).
  647.  
  648. For X-related modules (Xt and Xm) you will have to do more work: they
  649. are currently not part of the standard Python distribution.  You will
  650. have to ftp the file "extensions.tar.gz" file from a Python ftp
  651. repository (e.g. ftp.cwi.nl) and follow the instructions there.  Note:
  652. the X related modules are still somewhat flakey, so don't try this
  653. unless you alread know a bit or two about building X applications on
  654. your platform.
  655.  
  656. See also the next question.
  657.  
  658. 4.12. Q. I have successfully built Python with STDWIN but it can't
  659. find some modules (e.g. stdwinevents).
  660.  
  661. A. There's a subdirectory of the library directory named 'stdwin'
  662. which should be in the default module search path.  There's a line in
  663. Modules/Setup(.in) that you have to enable for this purpose --
  664. unfortunately in the latest release it's not near the other
  665. STDWIN-related lines so it's easy to miss it.
  666.  
  667. 4.13. Q. What GUI toolkits exist for Python?
  668.  
  669. A. Depending on what platform(s) you are aiming at, there are several.
  670.  
  671. - There's a neat object-oriented interface to the Tcl/Tk widget set,
  672. called Tkinter.  You can ftp it from ftp.cwi.nl as
  673. pub/python/tkinter.tar.gz.  This is probably the easiest to install
  674. and use, and the most complete widget set.
  675.  
  676. - The standard Python distribution comes with an interface to STDWIN,
  677. a platform-independent low-level windowing interface (you have to ftp
  678. the source for STDWIN separately, e.g. from ftp.cwi.nl in pub/stdwin
  679. or gatekeeper.dec.com in pub/misc/stdwin).  STDWIN runs under X11 or
  680. the Mac; a Windows port has been attempted but I can't seem to get it
  681. working.  Note that STDWIN is really not powerful enough to implement
  682. a modern GUI (no widgets, etc.) and that I don't have the time to
  683. maintain or extend it, so you may be better off using Tkinter or the
  684. Motif interface, unless you require portability to the Mac (which is
  685. also offered by SUIT, by the way -- see below).
  686.  
  687. - For SGI IRIX only, there's an interface to the complete GL (Graphics
  688. Library -- low level but very good 3D capabilities) as well as to
  689. FORMS (a buttons-and-sliders-etc package built on top of GL by Mark
  690. Overmars -- ftp'able from ftp.cs.ruu.nl in pub/SGI/FORMS).
  691.  
  692. - There's an interface to X11, including the Athena and Motif widget
  693. sets (and a few individual widgets, like Mosaic's HTML widget and
  694. SGI's GL widget) in the Extensions set, which is separately ftp'able
  695. from ftp.cwi.nl as pub/python/extensions.tar.gz.
  696.  
  697. - There's an interface to SUIT, the U of Virginia's Simple User
  698. Interface Toolkit; it can be ftp'ed from uvacs.cs.virginia.edu as
  699. pub/suit/python/SUIT_python.tar.Z.  A PC binary of Python 1.0.2
  700. compiled with DJGPP and with SUIT support built-in has been made
  701. available by Antonio Costa on ftp site asterix.inescn.pt, directory
  702. pub/PC/python, file pyt102su.exe (a self-extracting archive).
  703.  
  704. - There's an interface to WAFE, a Tcl interface to the X11 Motif and
  705. Athena widget sets.  Last I heard about it it was included in the
  706. WAFE 1.0 prerelease, ftp'able from ftp.wu-wien.ac.at as
  707. pub/src/X11/wafe/wafe-1.0.tar.gz-prerelease.
  708.  
  709. 4.14. Q. Are there any interfaces to database packages in Python?
  710.  
  711. A. There's an interface to SYBASE by John Redford
  712. <jredford@lehman.com>.
  713.  
  714. There's also an interface to metalbase by Lance Ellinghouse
  715. <lance@markv.com>.
  716.  
  717. Anthony Baxter <anthony.baxter@aaii.oz.au> has written an interface to
  718. mSQL (mini-SQL).  Ftp it from ftp.cwi.nl:/pub/python/PymSQL.tar.gz.
  719.  
  720. 4.15. Q. Is it possible to write obfuscated one-liners in Python?
  721.  
  722. A. Yes.  See the following three examples, due to Ulf Bartelt:
  723.  
  724. # Primes < 1000
  725. print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,\
  726. map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
  727.  
  728. # First 10 Fibonacci numbers
  729. print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),\
  730. range(10))
  731.  
  732. # Mandelbrot set
  733. print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,\
  734. Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,\
  735. Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,\
  736. 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\
  737. >=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(\
  738. 64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy\
  739. ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
  740. #    \___ ___/  \___ ___/  |   |   |__ lines on screen
  741. #        V          V      |   |______ columns on screen
  742. #        |          |      |__________ maximum of "iterations"
  743. #        |          |_________________ range on y axis
  744. #        |____________________________ range on x axis
  745.  
  746. Don't try this at home, kids!
  747.  
  748. 4.16. Q. Is there an equivalent of C's "?:" ternary operator?
  749.  
  750. A. Not directly.  In many cases you can mimic a?b:c with "a and b or
  751. c", but there's a flaw: if b is zero (or empty, or None -- anything
  752. that tests false) then c will be selected instead.  In many cases you
  753. can prove by looking at the code that this can't happen (e.g. because
  754. b is a constant or has a type that can never be false), but in general
  755. this can be a problem.
  756.  
  757. Steve Majewski (or was it Tim Peters?) suggested the following
  758. solution: (a and [b] or [c])[0].  Because [b] is a singleton list it
  759. is never false, so the wrong path is never taken; then applying [0] to
  760. the whole thing gets the b or c that you really wanted.  Ugly, but it
  761. gets you there in the rare cases where it is really inconvenient to
  762. rewrite your code using 'if'.
  763.  
  764. 4.17. Q. My class defines __del__ but it is not called when I delete the
  765. object.
  766.  
  767. A. There are several possible reasons for this.
  768.  
  769. - The del statement does not necessarily call __del__ -- it simply
  770. decrements the object's reference count, and if this reaches zero
  771. __del__ is called.
  772.  
  773. - If your data structures contain circular links (e.g. a tree where
  774. each child has a parent pointer and each parent has a list of
  775. children) the reference counts will never go back to zero.  You'll
  776. have to define an explicit close() method which removes those
  777. pointers.  Please don't ever call __del__ directly -- __del__ should
  778. call close() and close() should make sure that it can be called more
  779. than once for the same object.
  780.  
  781. - If the object has ever been a local variable (or argument, which is
  782. really the same thing) to a function that caught an expression in an
  783. except clause, chances are that a reference to the object still exists
  784. in that function's stack frame as contained in the stack trace.
  785. Normally, deleting (better: assigning None to) sys.exc_traceback will
  786. take care of this.  If you a stack was printed for an unhandled
  787. exception in an interactive interpreter, delete sys.last_traceback
  788. instead.
  789.  
  790. - There is code that deletes all objects when the interpreter exits,
  791. but if your Python has been configured to support threads, it is not
  792. called (because other threads may still be active).  You can define
  793. your own cleanup function using sys.exitfunc (see question 4.4).
  794.  
  795. 4.18. Q. How do I change the shell environment for programs called using
  796. os.popen() or os.system()?  Changing os.environ doesn't work.
  797.  
  798. A. Modifying the environment passed to subshells was left out of the
  799. interpreter because there seemed to be no well-established portable
  800. way to do it.
  801.  
  802. However if all you want is to pass environment variables to the
  803. commands run by os.system() or os.popen(), there's a simple solution:
  804. prefix the command string with a couple of variable assignments and
  805. export statements. I guess the following would be universal for popen
  806. (untested):
  807.  
  808. import os
  809. from commands import mkarg # nifty routine to add shell quoting
  810. def epopen(cmd, mode, env = {}):
  811.     # env is a dictionary of environment variables
  812.     prefix = ''
  813.     for key, value in env.values():
  814.         prefix = prefix + '%s=%s\n' % (key, mkarg(value))
  815.         prefix = prefix + 'export %s\n' % key
  816.     return os.popen(prefix + cmd, mode)
  817.  
  818. 4.19. Q. What is a class?
  819.  
  820. A. A class is the particular object type that is created by executing
  821. a class statement.
  822.  
  823. 4.20. Q. What is a method?
  824.  
  825. A. A method is a function that you normally call as
  826. x.name(arguments...) for some object x.  The word is used for methods
  827. of classes and class instances as well as for methods of built-in
  828. objects.  The latter have a completely different implementation and
  829. only share the way their calls look in Python code.
  830.  
  831. 4.21. Q. What is self?
  832.  
  833. A. Self is merely a conventional name for the first argument of a
  834. method -- i.e. a function defined inside a class definition.  A method
  835. defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for
  836. some instance x of the class in which the definition occurs;
  837. the called method will think it is called as meth(x, a, b, c).
  838.  
  839. 4.22. Q. What is a unbound method?
  840.  
  841. A. An unbound method is a method defined in a class that is not yet
  842. bound to an instance.  You get an unbound method if you ask for a
  843. class attribute that happens to be a function. You get a bound method
  844. if you ask for an instance attribute.  A bound method knows which
  845. instance it belongs to and calling it supplies the instance automatically;
  846. an unbound method only knows which class it wants for its first
  847. argument (a derived class is also OK).  Calling an unbound method
  848. doesn't "magically" derive the first argument from the context -- you
  849. have to provide it explicitly.
  850.  
  851. 4.23. Q. How do I call a method defined in a base class from a derived class
  852. that overrides it?
  853.  
  854. A. If your class definition starts with "class Derived(Base): ..."
  855. then you can call method meth defined in Base (or one of Base's base
  856. classes) as Base.meth(self, arguments...).  Here, Base.meth is an
  857. unbound method (see previous question).
  858.  
  859. 4.24. Q. How do I call a method from a base class without using the name of
  860. the base class?
  861.  
  862. A. DON'T DO THIS.  REALLY.  I MEAN IT.  It appears that you could call
  863. self.__class__.__bases__[0].meth(self, arguments...) but this fails when
  864. a doubly-derived method is derived from your class: for its instances,
  865. self.__class__.__bases__[0] is your class, not its base class -- so
  866. (assuming you are doing this from within Derived.meth) you would start
  867. a recursive call.
  868.  
  869. 4.25. Q. How can I organize my code to make it easier to change the base
  870. class?
  871.  
  872. A. You could define an alias for the base class, assign the real base
  873. class to it before your class definition, and use the alias throughout
  874. your class.  Then all you have to change is the value assigned to the
  875. alias.  Incidentally, this trick is also handy if you want to decide
  876. dynamically (e.g. depending on availability of resources) which base
  877. class to use.  Example:
  878.  
  879. BaseAlias = <real base class>
  880. class Derived(BaseAlias):
  881.     def meth(self):
  882.         BaseAlias.meth(self)
  883.         ...
  884.  
  885. 4.26. Q. How can I find the methods or attributes of an object?
  886.  
  887. A. This depends on the object type.
  888.  
  889. For an instance x of a user-defined class, instance attributes are
  890. found in the dictionary x.__dict__, and methods and attributes defined
  891. by its class are found in x.__class__.__bases__[i].__dict__ (for i in
  892. range(len(x.__class__.__bases__))).  You'll have to walk the tree of
  893. base classes to find *all* class methods and attributes.
  894.  
  895. Many, but not all built-in types define a list of their method names
  896. in x.__methods__, and if they have data attributes, their names may be
  897. found in x.__members__.  However this is only a convention.
  898.  
  899. For more information, read the source of the standard (but
  900. undocumented) module newdir.
  901.  
  902. 4.27. Q. I can't seem to use os.read() on a pipe created with os.popen().
  903.  
  904. A. os.read() is a low-level function which takes a file descriptor (a
  905. small integer).  os.popen() creates a high-level file object -- the
  906. same type used for sys.std{in,out,err} and returned by the builtin
  907. open() function.  Thus, to read n bytes from a pipe p created with
  908. os.popen(), you need to use p.read(n).
  909.  
  910. 4.28. Q. How can I create a stand-alone binary from a Python script?
  911.  
  912. The demo script "Demo/scripts/freeze.py" does what you want.  (It's
  913. actually not a demo but a support tool -- there is some extra code in
  914. the interpreter to accommodate it.)  It requires that you have the
  915. Python build tree handy, complete with all the lib*.a files.
  916.  
  917. This works by scanning your source recursively for import statements
  918. (both forms) and looking for the modules on the standard Python path
  919. as well as in the source directory (for built-in modules).  It then
  920. "compiles" the modules written in Python to C code (array initializers
  921. that can be turned into code objects using the marshal module) and
  922. creates a custom-made config file that only contains those built-in
  923. modules which are actually used in the program.  It then compiles the
  924. generated C code and links it with the rest of the Python interpreter
  925. to form a self-contained binary which acts exactly like your script.
  926.  
  927. Unfortunately, the current version is very platform-specific, because
  928. each platform has its own compilation flags and libraries to link
  929. with.  You will probably have to edit the freeze.py file to point it
  930. to the right directories and tell it about the compilation and link
  931. flags for your platform.  A new version will be released with Python
  932. 1.1 -- if you want a peek write to my colleague <Jack.Jansen@cwi.nl>.
  933.  
  934. 4.29. Q. Is there a special lib for writing CGI scripts in Python?
  935.  
  936. A. There's documentation and code for a cgi.py module by Michael McLay
  937. <mclay@eeel.nist.gov> available from:
  938.  
  939.     http://www.eeel.nist.gov/python/
  940.  
  941. (For the curious: CGI or Common Gateway Interface is the protocol
  942. between HTTP servers (WWW servers) and programs/scripts they run to
  943. perform queries and other tasks that require returning a dynamically
  944. generated document.)
  945.  
  946. 4.30. Q. What other WWW tools are there for Python?
  947.  
  948. A. The standard library has a module urllib, which can retrieve most
  949. commonly used URL types (file, ftp, http, gopher).
  950.  
  951. The Demo2/www directory (Demo2 has to be retrieved separately from the
  952. Python ftp sites) contains some (really old) code to parse HTML and to
  953. display it.
  954.  
  955. Steve Miale <smiale@cs.indiana.edu> has written a modular WWW browser
  956. called Dancer.  An alpha version can be FTP'ed from
  957. ftp.cs.indiana.edu:/pub/smiale/dancer.tar.gz.  (There are a few
  958. articles about Dancer in the (hyper)mail archive.)
  959.  
  960.  
  961. 5. Extending Python
  962. ===================
  963.  
  964. 5.1. Q. Can I create my own functions in C?
  965.  
  966. A. Yes, you can create built-in modules containing functions,
  967. variables, exceptions and even new types in C.  This is explained in
  968. the document "Extending and Embedding the Python Interpreter" (the
  969. LaTeX file Doc/ext.tex).  Also read the chapter on dynamic loading.
  970.  
  971. 5.2. Q. Can I create my own functions in C++?
  972.  
  973. A. Yes, using the C-compatibility features found in C++.  Basically
  974. you place extern "C" { ... } around the Python include files and put
  975. extern "C" before each function that is going to be called by the
  976. Python interpreter.  Global or static C++ objects with constructors
  977. are probably not a good idea.
  978.  
  979. 5.3. Q. How can I execute arbitrary Python statements from C?
  980.  
  981. A. The highest-level function to do this is run_command() which takes
  982. a single string argument which is executed in the context of module
  983. __main__ and returns 0 for success and -1 when an exception occurred
  984. (including SyntaxError).  If you want more control, use run_string();
  985. see the source for run_command() in Python/pythonrun.c.
  986.  
  987. 5.4. Q. How can I evaluate an arbitrary Python expression from C?
  988.  
  989. A. Call the function run_string() from the previous question with the
  990. start symbol eval_input; it then parses an expression, evaluates it
  991. and returns its value.  See exec_eval() in Python/bltinmodule.c.
  992.  
  993. 5.5. Q. How do I extract C values from a Python object?
  994.  
  995. A. That depends on the object's type.  If it's a tuple,
  996. gettuplesize(o) returns its length and gettupleitem(o, i) returns its
  997. i'th item; similar for lists with getlistsize(o) and getlistitem(o,
  998. i).  For strings, getstringsize(o) returns its length and
  999. getstringvalue(o) a pointer to its value (note that Python strings may
  1000. contain null bytes so strlen() is not safe).  To test which type an
  1001. object is, first make sure it isn't NULL, and then use
  1002. is_stringobject(o), is_tupleobject(o), is_listobject(o) etc.
  1003.  
  1004. 5.6. Q. How do I use mkvalue() to create a tuple of arbitrary length?
  1005.  
  1006. A. You can't.  Use t = newtupleobject(n) instead, and fill it with
  1007. objects using settupleitem(t, i, o) -- note that this "eats" a
  1008. reference count of o.  Similar for lists with newlistobject(n) and
  1009. setlistitem(l, i, o).  Note that you *must* set all the tuple items to
  1010. some value before you pass the tuple to Python code --
  1011. newtupleobject(n) initializes them to NULL, which isn't a valid Python
  1012. value.
  1013.  
  1014. 5.7. Q. What happened to mktuple(), featuring in an example in the
  1015. Extensions manual?
  1016.  
  1017. A. It's a typo, I meant newtupleobject() (see previous question).
  1018.  
  1019. 5.8. Q. How do I call an object's method from C?
  1020.  
  1021. A. Here's a function (untested) that might become part of the next
  1022. release in some form.  It uses <stdarg.h> to allow passing the
  1023. argument list on to vmkvalue():
  1024.  
  1025. object *call_method(object *inst, char *methodname, char *format, ...)
  1026. {
  1027.     object *method;
  1028.     object *args;
  1029.     object *result;
  1030.     va_list va;
  1031.     method = getattr(inst, methodname);
  1032.     if (method == NULL) return NULL;
  1033.     va_start(va, format);
  1034.     args = vmkvalue(format, va);
  1035.     va_end(va);
  1036.     if (args == NULL) {
  1037.         DECREF(method);
  1038.         return NULL;
  1039.     }
  1040.     result = call_object(method, args);
  1041.     DECREF(method);
  1042.     DECREF(args);
  1043.     return result;
  1044. }
  1045.  
  1046. This works for any instance that has methods -- whether built-in or
  1047. user-defined.  You are responsible for eventually DECREF'ing the
  1048. return value.
  1049.  
  1050. To call, e.g., a file object's "seek" method with arguments 10, 0
  1051. (assuming the file object pointer is "f"):
  1052.  
  1053. res = call_method(f, "seek", "(OO)", 10, 0);
  1054. if (res == NULL) {
  1055.     ... an exception occurred ...
  1056. }
  1057. else {
  1058.     DECREF(res);
  1059. }
  1060.  
  1061. Note that since call_object() *always* wants a tuple for the argument
  1062. list, to call a function without arguments, pass "()" for the format,
  1063. and to call a function with one argument, surround the argument in
  1064. parentheses, e.g. "(i)".
  1065.  
  1066. 5.9. Q. How do I catch the output from print_error()?
  1067.  
  1068. A. (Due to Mark Hammond):
  1069.  
  1070. * in Python code, define an object that supports the "write()" method.
  1071. FWIW, there seems to be a small problem that requires the 'softspace'
  1072. attribute to be defined too (I can't remember exact details of the
  1073. problem).
  1074.  
  1075. * redirect sys.stdout and sys.stderr to this object.
  1076.  
  1077. * call print_error, or just allow the standard traceback mechanism to
  1078. work.
  1079.  
  1080. Then, the output will go wherever your write() method sends it.
  1081.  
  1082. 5.10. Q. How do I access a module written in Python from C?
  1083.  
  1084. A. You can get a pointer to the module object as follows:
  1085.  
  1086.     module = import_module("<modulename>");
  1087.  
  1088. If the module hasn't been imported yet (i.e. it is not yet present in
  1089. sys.modules), this initializes the module; otherwise it simply returns
  1090. the value of sys.modules["<modulename>"].  Note that it doesn't enter
  1091. the module into any namespace -- it only ensures it has been
  1092. initialized and is stored in sys.modules.
  1093.  
  1094. You can then access the module's attributes (i.e. any name defined in
  1095. the module) as follows:
  1096.  
  1097.     attr = getattr(module, "<attrname>");
  1098.  
  1099. Calling setattr(), to assign to variables in the module, also works.
  1100.  
  1101.  
  1102. 6. Python's design
  1103. ==================
  1104.  
  1105. 6.1. Q. Why isn't there a generic copying operation for objects in
  1106. Python?
  1107.  
  1108. A. Hmm.  Maybe there should be one, but it's difficult to assign a
  1109. useful meaning to copying of open files, sockets and windows, or
  1110. recursive data structures.  As long as you design all your classes
  1111. yourself you are of course free to define a standard base class that
  1112. defines an overridable copying operation for all the objects you care
  1113. about.  (One practical point: it would have to be a built-in function,
  1114. not a standard method name, since not all built-in object types have
  1115. methods; e.g. strings, integers and tuples don't.)
  1116.  
  1117. 6.2. Q. Why isn't there a generic way to implement persistent objects
  1118. in Python?  (Persistent == automatically saved to and restored from
  1119. disk.)
  1120.  
  1121. A. Hmm, hmm.  Basically for the same reasons as why there is no
  1122. generic copying operation.
  1123.  
  1124. However, since there is a real desire to have persistent operations,
  1125. I'm thinking of extending the marshal module to support object sharing
  1126. (and hence recursive objects) and to extend the list of supported
  1127. types considerably.  For user-defined classes, hooks with __*__ names
  1128. will allow the class to modify the way their instances are dumped and
  1129. loaded.  Built-in types (including those defined by new extensions)
  1130. may also define dump/load hooks.  There are several problems still to
  1131. solve, e.g. how do you reliably find the class of which an object is
  1132. an instance at load time -- assuming the class itself is loaded from
  1133. some module, and not part of the dumped data.  It is also necessary to
  1134. separate the functionality of converting a set of objects into a byte
  1135. stream from which they can be reloaded, from the ability to save these
  1136. byte streams as files and being able to reference an object by a
  1137. persistent global name.
  1138.  
  1139. 6.3. Q. Why isn't there a switch or case statement in Python?
  1140.  
  1141. A. You can do this easily enough with a sequence of
  1142. if... elif... elif... else.  There have been some proposals for switch
  1143. statement syntax, but there is no consensus (yet) on whether and how
  1144. to do range tests.
  1145.  
  1146. 6.4. Q. Why does Python use indentation for grouping of statements?
  1147.  
  1148. A. Basically I believe that using indentation for grouping is
  1149. extremely elegant and contributes a lot to the clarity of the average
  1150. Python program.  Most people learn to love this feature after a while.
  1151. Some arguments for it:
  1152.  
  1153. - Since there are no begin/end brackets there cannot be a disagreement
  1154. between grouping perceived by the parser and the human reader.  I
  1155. remember long ago seeing a C fragment like this:
  1156.  
  1157.     if (x <= y)
  1158.         x++;
  1159.         y--;
  1160.     z++;
  1161.  
  1162. and staring a long time at it wondering why y was being decremented
  1163. even for x > y...  (And I wasn't a C newbie then either.)
  1164.  
  1165. - Since there are no begin/end brackets there can be no conflicting
  1166. coding styles.  In C there are loads of different ways to place the
  1167. braces (including the choice whether to place braces around single
  1168. statements in certain cases, for consistency).  If you're used to
  1169. reading (and writing) code that uses one style, you will feel at least
  1170. slightly uneasy when reading (or being required to write) another
  1171. style.
  1172.  
  1173. - Many coding styles place begin/end brackets on a line by themself.
  1174. This makes programs considerably longer and wastes valuable screen
  1175. space, making it harder to get a good overview over a program.
  1176. Ideally, a function should fit on one basic tty screen (say, 20
  1177. lines).  20 lines of Python are worth a LOT more than 20 lines of C.
  1178. This is not solely due to the lack of begin/end brackets (the lack of
  1179. declarations also helps, and the powerful operations of course), but
  1180. it certainly helps!
  1181.  
  1182. 6.5. Q. Why are Python strings immutable?
  1183.  
  1184. A. There are two advantages.  One is performance: knowing that a
  1185. string is immutable makes it easy to lay it out at construction time
  1186. -- fixed and unchanging storage requirements.  (This is also one of
  1187. the reasons for the distinction between tuples and lists.)  The
  1188. other is that strings in Python are considered as "elemental" as
  1189. numbers.  No amount of activity will change the value 8 to anything
  1190. else, and in Python, no amount of activity will change the string
  1191. "eight" to anything else.  (Adapted from Jim Roskind)
  1192.  
  1193. 6.6. Q. Why don't strings have methods like index() or sort(), like
  1194. lists?
  1195.  
  1196. A. Good question.  Strings currently don't have methods at all
  1197. (likewise tuples and numbers).  Long ago, it seemed unnecessary to
  1198. implement any of these functions in C, so a standard library module
  1199. "string" written in Python was created that performs string related
  1200. operations.  Since then, the cry for performance has moved most of
  1201. them into the built-in module strop (this is imported by module
  1202. string, which is still the preferred interface, without loss of
  1203. performance except during initialization).  Some of these functions
  1204. (e.g. index()) could easily be implemented as string methods instead,
  1205. but others (e.g. sort()) can't, since their interface prescribes that
  1206. they modify the object, while strings are immutable (see the previous
  1207. question).
  1208.  
  1209. 6.7. Q. Why does Python use methods for some functionality
  1210. (e.g. list.index()) but functions for other (e.g. len(list))?
  1211.  
  1212. A. Functions are used for those operations that are generic for a
  1213. group of types and which should work even for objects that don't have
  1214. methods at all (e.g. numbers, strings, tuples).  Also, implementing
  1215. len(), max(), min() as a built-in function is actually less code than
  1216. implementing them as methods for each type.  One can quibble about
  1217. individual cases but it's really too late to change such things
  1218. fundamentally now.
  1219.  
  1220. 6.8. Q. Why can't I derive a class from built-in types (e.g. lists or
  1221. files)?
  1222.  
  1223. A. This is caused by the relatively late addition of (user-defined)
  1224. classes to the language -- the implementation framework doesn't easily
  1225. allow it.  See the answer to question 4.2 for a work-around.  This
  1226. *may* be fixed in the (distant) future.
  1227.  
  1228. 6.9. Q. Why must 'self' be declared and used explicitly in method
  1229. definitions and calls?
  1230.  
  1231. A. By asking this question you reveal your C++ background. :-)
  1232. When I added classes, this was (again) the simplest way of
  1233. implementing methods without too many changes to the interpreter.  I
  1234. borrowed the idea from Modula-3.  It turns out to be very useful, for
  1235. a variety of reasons.
  1236.  
  1237. First, it makes it more obvious that you are using a method or
  1238. instance attribute instead of a local variable.  Reading "self.x" or
  1239. "self.meth()" makes it absolutely clear that an instance variable or
  1240. method is used even if you don't know the class definition by heart.
  1241. In C++, you can sort of tell by the lack of a local variable
  1242. declaration (assuming globals are rare or easily recognizable) -- but
  1243. in Python, there are no local variable declarations, so you'd have to
  1244. look up the class definition to be sure.
  1245.  
  1246. Second, it means that no special syntax is necessary if you want to
  1247. explicitly reference or call the method from a particular class.  In
  1248. C++, if you want to use a method from base class that is overridden in
  1249. a derived class, you have to use the :: operator -- in Python you can
  1250. write baseclass.methodname(self, <argument list>).  This is
  1251. particularly useful for __init__() methods, and in general in cases
  1252. where a derived class method wants to extend the base class method of
  1253. the same name and thus has to call the base class method somehow.
  1254.  
  1255. Lastly, for instance variables, it solves a syntactic problem with
  1256. assignment: since local variables in Python are (by definition!) those
  1257. variables to which a value assigned in a function body (and that
  1258. aren't explicitly declared global), there has to be some way to tell
  1259. the interpreter that an assignment was meant to assign to an instance
  1260. variable instead of to a local variable, and it should preferably be
  1261. syntactic (for efficiency reasons).  C++ does this through
  1262. declarations, but Python doesn't have declarations and it would be a
  1263. pity having to introduce them just for this purpose.  Using the
  1264. explicit "self.var" solves this nicely.  Similarly, for using instance
  1265. variables, having to write "self.var" means that references to
  1266. unqualified names inside a method don't have to search the instance's
  1267. directories.
  1268.  
  1269. 6.10. Q. Can't you emulate threads in the interpreter instead of
  1270. relying on an OS-specific thread implementation?
  1271.  
  1272. A. Unfortunately, the interpreter pushes at least one C stack frame
  1273. for each Python stack frame.  Also, extensions can call back into
  1274. Python at almost random moments.  Therefore a complete threads
  1275. implementation requires thread support for C.
  1276.  
  1277. 6.11. Q. Why can't lambda forms contain statements?
  1278.  
  1279. A. Python lambda forms cannot contain statements because Python's
  1280. syntactic framework can't handle statements nested inside functions.
  1281.  
  1282. However, in Python, this is not a serious problem.  Unlike lambda
  1283. forms in other languages, where they add functionality, Python lambdas
  1284. are only a shorthand notation if you're too lazy to define a function.
  1285.  
  1286. Functions are already first class objects in Python, and can be
  1287. declared in a local scope.  Therefore the only advantage of using a
  1288. lambda form instead of a locally-defined function is that you'll have
  1289. to invent a name for the function -- but that's just a local variable
  1290. to which the function object (which is exactly the same type of object
  1291. that a lambda form yields) is assigned!
  1292.  
  1293. 6.12. Q. Why is there no more efficient way of iterating over a dictionary
  1294. than first constructing the list of keys()?
  1295.  
  1296. A. Have you tried it?  I bet it's fast enough for your purposes!  In
  1297. most cases such a list takes only a few percent of the space occupied
  1298. by the dictionary -- it needs only 4 bytes (the size of a pointer) per
  1299. key -- a dictionary costs 8 bytes per key plus between 30 and 70
  1300. percent hash table overhead, plus the space for the keys and values --
  1301. by necessity all keys are unique objects and a string object (the most
  1302. common key type) costs at least 18 bytes plus the length of the
  1303. string.  Add to that the values contained in the dictionary, and you
  1304. see that 4 bytes more per item really isn't that much more memory...
  1305.  
  1306. A call to dict.keys() makes one fast scan over the dictionary
  1307. (internally, the iteration function does exist) copying the pointers
  1308. to the key objects into a pre-allocated list object of the right size.
  1309. The iteration time isn't lost (since you'll have to iterate anyway --
  1310. unless in the majority of cases your loop terminates very prematurely
  1311. (which I doubt since you're getting the keys in random order).
  1312.  
  1313. I don't expose the dictionary iteration operation to Python
  1314. programmers because the dictionary shouldn't be modified during the
  1315. entire iteration -- if it is, there's a very small chance that the
  1316. dictionary is reorganized because the hash table becomes too full, and
  1317. then the iteration may miss some items and see others twice.  Exactly
  1318. because this only occurs rarely, it would lead to hidden bugs in
  1319. programs: it's easy never to have it happen during test runs if you
  1320. only insert or delete a few items per iteration -- but your users will 
  1321. surely hit upon it sooner or later.
  1322.  
  1323.  
  1324. 7. Using Python on non-UNIX platforms
  1325. =====================================
  1326.  
  1327. 7.1. Q. Is there a Mac version of Python?
  1328.  
  1329. A. Yes.  It is on most ftp sites carrying Python as python.sea.hqx --
  1330. this is a self-extracting archive containing the application binary as
  1331. well as the Lib modules.
  1332.  
  1333. 7.2. Q. Is there a DOS version of Python?
  1334.  
  1335. A. Yes.  More than one, actually: 16python.exe runs in standard DOS
  1336. mode on 186 CPUs or higher; 32python.exe uses a DOS extender and only
  1337. runs on a 386 or higher CPUs.  Although 16python.exe does not pass the
  1338. test set because test_grammar is too big for the parser, it actually
  1339. has about 270 kbyte of allocatable heap space, which is sufficient for
  1340. fairly large programs.  32python.exe is distributed as a tar file
  1341. containing the required DOS extended and 387 emulator.  Both are on
  1342. most ftp sites carrying Python.
  1343.  
  1344. The file dosbuild.tar.gz on the standard ftp sites
  1345. (e.g. ftp.cwi.nl:/pub/python/) contains rudimentary Makefiles and
  1346. instructions.
  1347.  
  1348. 7.3. Q. Is there a Windows version of Python?
  1349.  
  1350. A. Yes.  Use qwpython.exe.  The only problem with it: ^C
  1351. unconditionally kills the entire program -- it does not raise
  1352. KeyboardInterrupt.  You can also run 16python.exe or 32python.exe in a
  1353. "DOS box", but qwpython.exe appears to be slightly faster.
  1354.  
  1355. There aren't any Makefiles at this moment.  Sorry.
  1356.  
  1357. Using Win32s (a free NT compatibility package by Microsoft) you can
  1358. also use the NT version by Mark Hammond -- the Win32s package is also
  1359. in that directory (you'll need several MB of disk space to install
  1360. it).  See the next questionYTHONPATH=C:\misc\python\lib
  1361.  
  1362. 7.11. Q. Where's the documentation for the Mac or PC version?
  1363.  
  1364. A. There isn't any.  The documentation for the Unix version also
  1365. applies to the Mac and PC versions.  Where applicable, differences
  1366. are indicated in the text.
  1367.  
  1368. 7.12. Q. The Mac (PC) version doesn't seem to have any facilities for
  1369. creating or editing programs apart from entering it interactively, and
  1370. there seems to be no way to save code that was entered interactively.
  1371. How do I create a Python program on the Mac (PC)?
  1372.  
  1373. A. Use an external editor.  On the Mac, BBEdit seems to be a popular
  1374. no-frills text editor.  I work like this: start the interpreter; edit
  1375. a module file using BBedit; import and test it in the interpreter;
  1376. edit again in BBedit; then use the built-in function reload() to
  1377. re-read the imported module; etc.
  1378.  
  1379. Regarding the same question for the PC, Kurt Wm. Hemr writes: "While
  1380. anyone with a pulse could certainly figure out how to do the same on
  1381. MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows.
  1382. Not only can you easily resave and "reload()" from Python after making
  1383. changes, but since WinNot auto-copies to the clipboard any text you
  1384. select, you can simply select the entire procedure (function) which
  1385. you changed in WinNot, switch to QWPython, and shift-ins to reenter
  1386. the changed program unit."
  1387.