From a7925f18ded087c10d2a0f971e320e5f89380288 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Wed, 26 Jan 1994 10:20:16 +0000 Subject: Initial revision --- Misc/ACKS | 64 ++ Misc/AIX-NOTES | 61 ++ Misc/BLURB | 45 ++ Misc/BLURB.LUTZ | 122 ++++ Misc/COPYRIGHT | 20 + Misc/FAQ | 643 +++++++++++++++++++ Misc/Fixcprt.py | 69 ++ Misc/HISTORY | 1400 +++++++++++++++++++++++++++++++++++++++++ Misc/Makefile | 10 + Misc/README | 20 + Misc/RFD | 114 ++++ Misc/fixfuncptrs.sh | 47 ++ Misc/python-mode-old.el | 1601 +++++++++++++++++++++++++++++++++++++++++++++++ Misc/python.gif | Bin 0 -> 7380 bytes Misc/python.man | 247 ++++++++ Misc/renumber.py | 108 ++++ 16 files changed, 4571 insertions(+) create mode 100644 Misc/ACKS create mode 100644 Misc/AIX-NOTES create mode 100644 Misc/BLURB create mode 100644 Misc/BLURB.LUTZ create mode 100644 Misc/COPYRIGHT create mode 100644 Misc/FAQ create mode 100755 Misc/Fixcprt.py create mode 100644 Misc/HISTORY create mode 100644 Misc/Makefile create mode 100644 Misc/README create mode 100644 Misc/RFD create mode 100755 Misc/fixfuncptrs.sh create mode 100644 Misc/python-mode-old.el create mode 100644 Misc/python.gif create mode 100644 Misc/python.man create mode 100755 Misc/renumber.py diff --git a/Misc/ACKS b/Misc/ACKS new file mode 100644 index 0000000..fc922b7 --- /dev/null +++ b/Misc/ACKS @@ -0,0 +1,64 @@ +Acknowledgements +---------------- + +This list is not complete and not in any useful order, but I would +like to thank everybody who contributed in any way, with code, hints, +bug reports, ideas, moral support, endorsement, or even complaints.... +Without you I would've stopped working on Python long ago! + + --Guido + +Amrit +Mark Anacker +Anthony Baxter +Donald Beaudry +Eric Beser +Stephen Bevan +Peter Bosch +Terrence Brannon +Erik de Bueger +Jan-Hein B"uhrman +Dick Bulterman +David Chaum +Jonathan Dasteel +John DeGood +Roger Dev +Lance Ellinghouse +Stoffel Erasmus +Niels Ferguson +Michael Guravage +Paul ten Hagen +Lynda Hardman +Ivan Herman +Chris Hoffman +Philip Homburg +Jack Jansen +Bill Janssen +Drew Jenkins +Lou Kates +Robert van Liere +Steve Majewski +Lambert Meertens +Steven Miale +Doug Moen +Sape Mullender +Sjoerd Mullender +George Neville-Neil +Randy Pausch +Marcel van der Peijl +Steven Pemberton +Tim Peters +John Redford +Timothy Roscoe +Kevin Samborn +Fred Sells +Denis Severson +Michael Shiplett +Paul Sijben +Dirk Soede +Per Spilling +Quentin Stafford-Fraser +Tracy Tims +Bennett Todd +Jaap Vermeulen +Dik Winter diff --git a/Misc/AIX-NOTES b/Misc/AIX-NOTES new file mode 100644 index 0000000..97c0944 --- /dev/null +++ b/Misc/AIX-NOTES @@ -0,0 +1,61 @@ +[Excerpt from an email describing how to build Python on AIX.] + + +Subject: Re: Python 1.0.0 BETA 5 -- also for Macintosh! +From: se@MI.Uni-Koeln.DE (Stefan Esser) +To: Guido.van.Rossum@cwi.nl +Date: Fri, 7 Jan 1994 17:40:43 +0100 + +[...] + +The following are [...] Instructions +to get a clean compile using gcc and xlc +under AIX 3.2.4. + +Since I wanted to make sure that Python compiles +using both compilers and several sets of options +(ANSI and traditional C, optimize on/off) I didn't +try to include bash readline or other optional +modules. + +'make test' succeeded using Python compiled with +the AIX C-compiler invoked as 'cc' and with options +'-o -qMEMMAX=4000' and compiled with 'gcc' and +options '-O -Wall'. + +There were some problems trying to compile python +using 'gcc -ansi' (because of _AIX no longer being +defined), but I didn't have time to look into this. + + + +Regards, + +Stefan Esser + + + + +REQUIRED: +--------- + +1) AIX compilers don't like the LANG env + varaiable set to european locales. + This makes the compiler generate floating + point constants using "," as the decimal + seperator, which the assembler doesnt't + understand (or was it the other way around, + with the assembler expecting "," in float + numbers ???). + Anyway: "LANG=C; export LANG" solves the + problem, as does "LANG=C $(MAKE) ..." in + the master Makefile. + +OPTIONAL: +--------- + +2) The xlc compiler considers "Python/ceval.c" + too complex to optimize, except when invoked + with "-qMEMMAX=4000". + +[...] diff --git a/Misc/BLURB b/Misc/BLURB new file mode 100644 index 0000000..53cf55b --- /dev/null +++ b/Misc/BLURB @@ -0,0 +1,45 @@ +What is Python? +--------------- + +Python is an interpreted, interactive, object-oriented programming +language. It incorporates modules, exceptions, dynamic typing, very +high level dynamic data types, and classes. Python combines +remarkable power with very clear syntax. It has interfaces to many +system calls and libraries, as well as to various window systems, and +is extensible in C or C++. It is also usable as an extension language +for applications that need a programmable interface. Finally, Python +is portable: it runs on many brands of UNIX, on the Mac, and on +MS-DOS. + +As a short example of what Python looks like, here's a script to +print prime numbers (not blazingly fast, but readable!). When this +file is made executable, it is callable directly from the UNIX shell +(if your system supports #! in scripts and the python interpreter is +installed at the indicated place). + +#!/usr/local/bin/python + +# Print prime numbers in a given range + +def main(): + import sys + min, max = 2, 0x7fffffff + if sys.argv[1:]: + min = int(eval(sys.argv[1])) + if sys.argv[2:]: + max = int(eval(sys.argv[2])) + primes(min, max) + +def primes(min, max): + if 2 >= min: print 2 + primes = [2] + i = 3 + while i <= max: + for p in primes: + if i%p == 0 or p*p > i: break + if i%p <> 0: + primes.append(i) + if i >= min: print i + i = i+2 + +main() diff --git a/Misc/BLURB.LUTZ b/Misc/BLURB.LUTZ new file mode 100644 index 0000000..e508207 --- /dev/null +++ b/Misc/BLURB.LUTZ @@ -0,0 +1,122 @@ +Newsgroups: comp.lang.perl,comp.lang.tcl +From: lutz@xvt.com (Mark Lutz) +Subject: Python (was Re: Has anyone done a tk addition to perl?) +Organization: XVT Software Inc. +Date: Thu, 14 Oct 1993 17:10:37 GMT +X-Disclaimer: The views expressed in this message are those of an + individual at XVT Software Inc., and do not necessarily + reflect those of the company. + + +I've gotten a number of requests for information about Python, +since my post here earlier this week. Since this appears to be +of general interest, and since there's no python news group yet, +I'm posting a description here. I'm not the best authority on +the language, but here's my take on it. + +[TCL/Perl zealots: this is informational only; I'm not trying to +'convert' anybody, and don't have time for a language war :-) +There is a paper comparing TCL/Perl/Python/Emacs-Lisp, which is +referenced in the comp.lang.misc faq, I beleive.] + + +What is Python?... + +Python is a relatively new very-high-level language developed +in Amsterdam. Python is a simple, procedural language, with +features taken from ABC, Icon, Modula-3, and C/C++. + +It's central goal is to provide the best of both worlds: +the dynamic nature of scripting languages like Perl/TCL/REXX, +but also support for general programming found in the more +traditional languages like Icon, C, Modula,... + +As such, it can function as a scripting/extension language, +as a rapid prototyping language, and as a serious software +development language. Python is suitable for fast development +of large programs, but also does well at throw-away shell coding. + +Python resembles other scripting languages a number of ways: + - dynamic, interpretive, interactive nature + - no explicit compile or link steps needed + - no type declarations (it's dynamically typed) + - high-level operators ('in', concatenation, etc) + - automatic memory allocation/deallocation (no 'pointers') + - high level objects: lists, tuples, strings, associative arrays + - programs can construct and execute program code using strings + - very fast edit/compile/run cycle; no static linking + - well-defined interface to and from C functions and data + - well-defined ways to add C modules to the system and language + +Python's features that make it useful for serious programming: + - it's object-oriented; it has a simplified subset of + C++'s 'class' facility, made more useful by python's + dynamic typing; the language is object-oriented from + the ground up (rather than being an add-on, as in C++) + + - it supports modules (imported packages, as in Modula-3); + modules replace C's 'include' files and linking, and allow + for multiple-module systems, code sharing, etc.; + + - it has a good exception handling system (a 'try' statement, + and a 'raise' statement, with user-defined exceptions); + + - it's orthogonal; everything is a first-class object in the + language (functions, modules, classes, class instance methods...) + and can be assigned/passed and used generically; + + - it's fairly run-time secure; it does many run-time checks + like index-out-of-bounds, etc., that C usually doesn't; + + - it has general data structuring support; Python lists are + heterogeneous, variable length, nestable, support slicing, + concatenation, etc., and come into existance and are reclaimed + automatically; strings and dictionaries are similarly general; + + - it's got a symbolic debugger and profiler (written in python, + of course..), and an interactive command-line interface; + as in Lisp, you can enter code and test functions in isolation, + from the interactive command line (even linked C functions); + + - it has a large library of built-in modules; it has support + for sockets, regular expressions, posix bindings, etc. + + - it supports dynamic loading of C modules on many platforms; + + - it has a _readable_ syntax; python code looks like normal + programming languages; tcl and perl can be very unreadable + (IMHO; what was that joke about Perl looking the same after + rot13..); python's syntax is simple, and statement based; + + +Of course, Python isn't perfect, but it's a good compromise betweem +scripting languages and traditional ones, and so is widely applicable. +'Perfect' languages aren't always useful for real-world tasks (Prolog, +for example), and languages at either extreme are not useful in the other +domain (C is poor for shell coding and prototyping, and awk is useless +for large systems design; Python does both well). + +For example, I've used Python successfully for a 4K line expert system +shell project; it would have been at least twice as large in C, and would +have been very difficult in TCL or Perl. + +Python uses an indentation-based syntax which may seem unusual at first +to C coders, but after using it I have found it to be _very_ handy, since +there's less to type. [I now forget to type '}' in my C code, and am +busy calculating how much time I wasted typing all those '}', 'END', etc., +just to pander to 'brain-dead' C/Pascal compilers :-)]. + +Python's currently at release 0.9.9. It seems suprisingly stable. +The first 'official' 1.0 release is due out by the end of this year. +Python runs on most popular machines/systems (mac, dos, unix, etc.) +It's public domain and distributable, and can be had via ftp. The +distribution includes examples, tutorials, and documentation. The +latest ftp address I have (I got it on a cd-rom): + pub/python/* at ftp.cwi.nl + pub/? at wuarchive.wustl.edu (in america) + +There's a python mailing list maintained by the language's creator. +Mail 'python-list-request@cwi.nl' to get on it. + +Mark Lutz +lutz@xvt.com diff --git a/Misc/COPYRIGHT b/Misc/COPYRIGHT new file mode 100644 index 0000000..38ad364 --- /dev/null +++ b/Misc/COPYRIGHT @@ -0,0 +1,20 @@ +Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum, +Amsterdam, The Netherlands. + + All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the names of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/Misc/FAQ b/Misc/FAQ new file mode 100644 index 0000000..49b1607 --- /dev/null +++ b/Misc/FAQ @@ -0,0 +1,643 @@ +Subject: FAQ: Python -- an object-oriented language +Newsgroups: comp.lang.misc,comp.answers,news.answers +Followup-to: comp.lang.misc +From: guido@cwi.nl (Guido van Rossum) +Reply-to: guido@cwi.nl (Guido van Rossum) +Approved: news-answers-request@MIT.Edu + +Archive-name: python-faq/part1 +Version: 1.2 +Last-modified: 24 Jan 1994 + +This article contains answers to Frequently Asked Questions about +Python (an object-oriented interpreted programming language -- see +the answer to question 1.1 for a short overview). + +Copyright 1993, 1994 Guido van Rossum. Unchanged electronic +redistribution of this FAQ is allowed. Printed redistribution only +with permission of the author. No warranties. + +Author's address: + Guido van Rossum + CWI, dept. CST + Kruislaan 413 + P.O. Box 94079 + 1090 GB Amsterdam + The Netherlands +Email: guido@cwi.nl + +The latest version of this FAQ is available by anonymous ftp from +ftp.cwi.nl [192.16.184.180] in the directory /pub/python, with +filename python-FAQ. It will also be posted regularly to the +newsgroups comp.answers and comp.lang.misc. + +Many FAQs, including this one, are available by anonymous ftp from +rtfm.mit.edu [18.70.0.209] in the directory pub/usenet/news.answers. +The name under which a FAQ is archived appears in the Archive-name line +at the top of the article. This FAQ is archived as python-faq/part1. + +There's a mail server on that machine which will send you files from +the archive by e-mail if you have no ftp access. You send a e-mail +message to mail-server@rtfm.mit.edu containing the single word help in +the message body to receive instructions. + +This FAQ is divided in the following chapters: + + 1. General information and availability + 2. Python in the real world + 3. Building Python + 4. Programming in Python + 5. Extending Python + 6. Python's design + 7. Using Python on non-UNIX platforms + +To find the start of a particular chapter, search for the chapter number +followed by a dot and a space at the beginning of a line (e.g. to +find chapter 4 in vi, type /^4\. /). + +Here's an overview of the questions per chapter: + + 1. General information and availability + 1.1. Q. What is Python? + 1.2. Q. Why is it called Python? + 1.3. Q. How do I obtain a copy of the Python source? + 1.4. Q. How do I get documentation on Python? + 1.5. Q. Is there a newsgroup or mailing list devoted to Python? + 1.6. Q. Is there a book on Python, or will there be one out soon? + 1.7. Q. Are there any published articles about Python that I can quote? + + 2. Python in the real world + 2.1. Q. How many people are using Python? + 2.2. Q. Have any significant projects been done in Python? + 2.3. Q. Are there any commercial projects going on using Python? + 2.4. Q. What new developments are expected for Python in the future? + 2.5. Q. How stable is Python? + 2.6. Q. Any more future plans? + + 3. Building Python + 3.1. Q. I have trouble building the md5 module and/or finding the file + md5.c. + 3.2. Q. Is there a test set? + 3.3. Q. When running the test set, I get complaints about floating point + operations, but when playing with floating point operations I cannot + find anything wrong with them. + 3.4. Q. I get an OverflowError on evaluating 2*2. What is going on? + 3.5. Q. Trouble building Python 0.9.9 on platform X. + + 4. Programming in Python + 4.1. Q. Can I create an object class with some methods implemented in + C and others in Python (e.g. through inheritance)? (Also phrased as: + Can I use a built-in type as base class?) + 4.2. Q. I assign to a variable in a call to exec() but when I try to + use it on the next line I get an error. What is going on? + 4.3. Q. Why does that work? + 4.4. Q. Is there a curses/termcap package for Python? + 4.5. Q. Is there an equivalent to C's onexit() in Python? + 4.6. Q. When I define a function nested inside another function, the + nested function seemingly can't access the local variables of the + outer function. What is going on? How do I pass local data to a + nested function? + 4.7. Q. How do I iterate over a sequence in reverse order? + 4.8. Q. My program is too slow. How do I speed it up? + 4.9. Q. When I have imported a module, then edit it, and import it + again (into the same Python process), the changes don't seem to take + place. What is going on? + + 5. Extending Python + 5.1. Q. Can I create my own functions in C? + 5.2. Q. Can I create my own functions in C++? + + 6. Python's design + 6.1. Q. Why isn't there a generic copying operation for objects in + Python? + 6.2. Q. Why isn't there a generic way to implement persistent objects + in Python? (Persistent == automatically saved to and restored from + disk.) + 6.3. Q. Why isn't there a switch or case statement in Python? + + 7. Using Python on non-UNIX platforms + 7.1. Q. Where's the DOS version of 0.9.9? + 7.2. Q. Is there a Windows version of Python? + 7.3. Q. I have the Mac or DOS version but it appears to be only a binary. + Where's the library? + 7.4. Q. Where's the documentation for the Mac or DOS version? + 7.5. Q. The Mac version doesn't seem to have any facilities for creating or + editing programs apart from entering it interactively, and there seems + to be no way to save code that was entered interactively. How do I + create a Python program on the Mac? + +To find a particular question, search for the question number followed +by a dot, a space, and a Q at the beginning of a line (e.g. to find +question 4.2 in vi, type /^4\.2\. Q/). + + +1. General information and availability +======================================= + +1.1. Q. What is Python? + +A. Python is an interpreted, interactive, object-oriented programming +language. It incorporates modules, exceptions, dynamic typing, very +high level dynamic data types, and classes. Python combines +remarkable power with very clear syntax. It has interfaces to many +system calls and libraries, as well as to various window systems, and +is extensible in C or C++. It is also usable as an extension language +for applications that need a programmable interface. Finally, Python +is portable: it runs on many brands of UNIX, on the Mac, and on +MS-DOS. + +To find out more, the best thing to do is to start reading the +tutorial from the documentation set (see a few questions further +down). + +1.2. Q. Why is it called Python? + +A. Apart from being a computer wizard, I'm also a fan of "Monty +Python's Flying Circus" (a BBC comedy series from the seventies, in +case you didn't know). It occurred to me one day that I needed a name +that was short, unique, and slightly mysterious. And I happened to be +reading some scripts from the series at the time... So then I decided +to call my language Python. But Python is not a joke. And don't you +associate it with dangerous reptiles either! + +1.3. Q. How do I obtain a copy of the Python source? + +A. The latest Python source distribution is always available by +anonymous ftp from ftp.cwi.nl [192.16.184.180] in the directory +/pub/python, with filename python.tar.Z. It is a compressed +tar file containing the complete C source, LaTeX documentation, Python +library modules, example programs, and several useful pieces of freely +distributable software. This will compile and run out of the box on +most UNIX platforms. Currently is 0.9.9. (See section 7 +for non-UNIX information.) + +1.4. Q. How do I get documentation on Python? + +A. The latest Python documentation set is always available by +anonymous ftp from ftp.cwi.nl [192.16.184.180] in the directory +/pub/python, with filename pythondoc-ps.tar.Z. It is a +compressed tar file containing PostScript files of the reference +manual, the library manual, and the tutorial. Currently is +0.9.9. (Note that the library manual is the most important one of the +set, as much of Python's power stems from the standard or built-in +types, functions and modules, all of which are described here.) +PostScript for a high-level description of Python is in the file +nluug-paper.ps. + +The following sites keep mirrors of the Python distribution: + +Site IP address Directory + +gatekeeper.dec.com 16.1.0.2 /pub/plan/python/cwi +ftp.uu.net 192.48.96.9 /languages/python +ftp.wustl.edu 128.252.135.4 /graphics/graphics/sgi-stuff/python +ftp.funet.fi 128.214.6.100 /pub/languages/python (old?) +ftp.fu-berlin.de 130.133.4.50 /pub/unix/languages/python (python* only) + +Or try archie on e.g. python0.9.9.tar.Z to locate the nearest copy of +that version... + +1.5. Q. Is there a newsgroup or mailing list devoted to Python? + +A. There is no Python newsgroup yet; if you want to post to the net +about Python, use comp.lang.misc. There is a mailing list devoted to +Python; send e-mail to python-list-request@cwi.nl to (un)subscribe. +There are plans to start the discussion about creation of +comp.lang.python as soon as version 1.0.0 has been released. + +1.6. Q. Is there a book on Python, or will there be one out soon? + +A. Unfortunately, not yet. I would like to write one but my +obligations at CWI include too much other work to make much progress +on it. Several parties have expressed interest in sponsoring or +helping the production of a book or reference manual, but so far there +are no firm plans. If you volunteer help, by all means drop me a +note! + +1.7. Q. Are there any published articles about Python that I can quote? + +A. So far the only refereed and published article that describes +Python in some detail is: + + Guido van Rossum and Jelke de Boer, "Interactively Testing Remote + Servers Using the Python Programming Language", CWI Quarterly, Volume + 4, Issue 4 (December 1991), Amsterdam, pp 283-303. + +LaTeX source for this paper is available as part of the Python source +distribution. + +A more recent high-level description of Python is: + + Guido van Rossum, "An Introduction to Python for UNIX/C + Programmers", in the proceedings of the NLUUG najaarsconferentie + 1993 (dutch UNIX users group meeting november 1993). + +PostScript for this paper and for the slides used for the accompanying +presentation can be found in the ftp directory mentioned a few +questions earlier, with filenames nluug-paper.ps and nluug-slides.ps, +respectively. + + +2. Python in the real world +=========================== + +2.1. Q. How many people are using Python? + +A. I don't know, but at the last count there were at least 130 +addresses on the Python mailing list (several of which are local +redistribution lists). I suspect that many users don't bother +to subscribe to the list. + +2.2. Q. Have any significant projects been done in Python? + +A. Here at CWI (the home of Python), we have written a 20,000 line +authoring environment for transportable hypermedia presentations, a +multimedia teleconferencing tool, as well as many smaller programs. + +The University of Virginia uses Python to control a virtual reality +engine. Contact: Matt Conway . + +See also the next question. + +2.3. Q. Are there any commercial projects going on using Python? + +A. Several companies have revealed to me that they are planning or +considering to use Python in a future product. The furthest is +Sunrise Software, who already have a product out using Python -- they +use Python for a GUI management application and an SNMP network +manangement application. Contact: . + +Individuals at many other companies are using Python for +internal development (witness their contributions to the Python +mailing list). + +Python has also been elected as an extension language by MADE, a +consortium supported by the European Committee's ESPRIT program and +consisting of Bull, CWI and some other European companies. Contact: +Ivan Herman . + +2.4. Q. What new developments are expected for Python in the future? + +A. I am almost ready to release version 1.0.0 -- it should be out by +the end of January 1994. It will have some new functionality and +bugfixes and be portable to more platforms. The directory tree +structure and build procedure will be radically different -- almost +all configuration is now done automatically, using GNU autoconf. +User-visible changes include: double-quoted strings, functional +programming operations (lambda, map, filter, reduce -- all evaluated +eagerly), exec becomes a statement, str() is customizable through +__str__ (used by print). The originally planned grand renaming scheme +will not be implemented because of lack of time. A beta version can +be ftp'ed from the usual sites, file python1.0.0beta.tar.Z. + +2.5. Q. How stable is Python? + +A. Very stable. While the current version number (0.9.9) would +suggest it is in the early stages of development, in fact new, stable +releases have been coming out every 3-6 months for the past three years. + +2.6. Q. Any more future plans? + +A. Without warranty that any of this will actually be realized: I am +currently thinking about mechanisms for built-in on-line help and a +switch/case statement. There are also some people (independently) +working on a windowing interface based on STDWIN but with the power +and ease of use of the average modern widget set. I still hope to get +some help in producing a Windows version. It would be nice if there +were a window-based class browser (Someone at CWI has contributed one +using Motif but it needs some work). + + +3. Building Python +================== + +3.1. Q. I have trouble building the md5 module and/or finding the file +md5.c. + +A. Apparently the md5 module was based on an older version of RSA's +md5 implementation. The ftp site rsa.com mentioned in the Makefile +where this version was found is no longer accessible, and the version +from RFC 1321 (md5c.c) is slightly different. This will be fixed in +the 1.0 release; write me if you need the fixes now. + +3.2. Q. Is there a test set? + +A. Yes, simply do "import testall" (or "import autotest" if you aren't +interested in the output). The standard modules whose name begins +with "test" together comprise the test. The test set doesn't test +*all* features of Python but it goes a long way to confirm that a new +port is actually working. The Makefile contains an entry "make test" +which runs the autotest module. + +3.3. Q. When running the test set, I get complaints about floating point +operations, but when playing with floating point operations I cannot +find anything wrong with them. + +A. The test set makes occasional unwarranted assumptions about the +semantics of C floating point operations. Until someone donates a +better floating point test set, you will have to comment out the +offending floating point tests and execute similar tests manually. + +3.4. Q. I get an OverflowError on evaluating 2*2. What is going on? + +A. Your machine probably has 64 bit long integers (e.g. DEC alpha or +HP snake architectures). There are some dependencies on word length +in file intobject.c. This will be corrected in the 1.0 release; until +then, on a 64 bit machine, just comment out the check for overflow +from int_mul: + + #if 0 + if (x > 0x7fffffff || x < (double) (long) 0x80000000) + return err_ovf("integer multiplication"); + #endif + +You should also include and replace the constant 32 by +LONG_BIT in int_[lr]shift. + +3.5. Q. Trouble building Python 0.9.9 on platform X. + +A. In the bootstrap phase (before you have built the first running +interpreter), make sure the -D settings in the Makefile are correct +for your system. In particular you may have to add or delete -DSYSV. +It may also be necessary to change the flags used to compile +posixmodule.c and timemodule.c; e.g. on AIX the following are +necessary: + posixmodule.c: -DHAVE_STDLIB -DNOALTTZ -DOLDTZ -Dunix -DSYSV -DDO_TIMES + timemodule.c: -DHAVE_STDLIB -DNOALTTZ -DOLDTZ -Uunix -DSYSV -DBSD_TIME +(Note the -Uunix for timemodule!) +Those switches for timemodule also require that the + #ifdef unix + #ifdef BSD_TIME +just above: + static long + millitimer() +( and below the "#endif /* macintosh */" version of millitimer +be changed to: + #if defined(unix) | defined(BSD_TIME) + #ifdef BSD_TIME + + +4. Programming in Python +======================== + +4.1. Q. Can I create an object class with some methods implemented in +C and others in Python (e.g. through inheritance)? (Also phrased as: +Can I use a built-in type as base class?) + +A. No, but you can easily create a Python class which serves as a +wrapper around a built-in object, e.g. (for dictionaries): + + # A user-defined class behaving almost identical + # to a built-in dictionary. + class UserDict: + def __init__(self): self.data = {} + def __repr__(self): return repr(self.data) + def __cmp__(self, dict): + if type(dict) == type(self.data): + return cmp(self.data, dict) + else: + return cmp(self.data, dict.data) + def __len__(self): return len(self.data) + def __getitem__(self, key): return self.data[key] + def __setitem__(self, key, item): self.data[key] = item + def __delitem__(self, key): del self.data[key] + def keys(self): return self.data.keys() + def items(self): return self.data.items() + def values(self): return self.data.values() + def has_key(self, key): return self.data.has_key(key) + +4.2. Q. I assign to a variable in a call to exec() but when I try to +use it on the next line I get an error. What is going on? + +A. The reason why this occurs is too complicated to explain (but see +the next question). To fix it is easy, however: simply assign None to +the variable *before* calling exec(). This will be fixed in the 1.0 +release. + +4.3. Q. Why does that work? + +A. When parsing your program and converting it into internal pseudo +code, the interpreter does some optimizations to speed up function +execution: it figures out the names of all the local variables and +treats them specially. Because your assignment is done by exec(), it +is not seen initially by the parser and the variable is not recognized +as a local variable. The default treatment is as a global variable, +but the exec() statement places it in the local scope, where it is not +found. This will be fixed in release 1.0 by making exec into a +statement; the parser will then be able to switch off the +optimizations for local variables if it encounters an exec statement +(recognizing calls to built-in functions is not possible for the +parser, hence the syntax change to a statement). + +4.4. Q. Is there a curses/termcap package for Python? + +A. No, but you can use the "alfa" (== character cell) version of +STDWIN. (STDWIN == Standard Windows, a portable windowing system +interface by the same author, URL ftp://ftp.cwi.nl/pub/stdwin.) +This will also prepare your program for porting to windowing +environments such as X11 or the Macintosh. + +4.5. Q. Is there an equivalent to C's onexit() in Python? + +A. Yes, if you import sys and assign a function to sys.exitfunc, it +will be called when your program exits, is killed by an unhandled +exception, or (on UNIX) receives a SIGHUP or SIGTERM signal. + +4.6. Q. When I define a function nested inside another function, the +nested function seemingly can't access the local variables of the +outer function. What is going on? How do I pass local data to a +nested function? + +A. Python does not have arbitrarily nested scopes. When you need to +create a function that needs to access some data which you have +available locally, create a new class to hold the data and return a +method of an instance of that class, e.g.: + + class MultiplierClass: + def __init__(self, factor): + self.factor = factor + def multiplier(self, argument): + return argument * self.factor + + def generate_multiplier(factor): + return MultiplierClass(factor).multiplier + + twice = generate_multiplier(2) + print twice(10) + # Output: 20 + +4.7. Q. How do I iterate over a sequence in reverse order? + +A. If it is a list, the fastest solution is + + list.reverse() + try: + for x in list: + "do something with x" + finally: + list.reverse() + +This has the disadvantage that while you are in the loop, the list +is temporarily reversed. If you don't like this, you can make a copy. +This appears expensive but is actually faster than other solutions: + + rev = list[:] + rev.reverse() + for x in rev: + + +If it isn't a list, a more general but slower solution is: + + i = len(list) + while i > 0: + i = i-1 + x = list[i] + + +A more elegant solution, is to define a class which acts as a sequence +and yields the elements in reverse order (solution due to Steve +Majewski): + + class Rev: + def __init__(self, seq): + self.forw = seq + def __len__(self): + return len(self.forw) + def __getitem__(self, i): + return self.forw[-(i + 1)] + +You can now simply write: + + for x in Rev(list): + + +Unfortunately, this solution is slowest of all, due the the method +call overhead... + +4.8. Q. My program is too slow. How do I speed it up? + +A. That's a tough one, in general. There are many tricks to speed up +Python code; I would consider rewriting parts in C only as a last +resort. One thing to notice is that function and (especially) method +calls are rather expensive; if you have designed a purely OO interface +with lots of tiny functions that don't do much more than get or set an +instance variable or call another method, you may consider using a +more direct way, e.g. directly accessing instance variables. Also see +the standard module "profile" (described in the file +"python/lib/profile.doc") which makes it possible to find out where +your program is spending most of its time (if you have some patience +-- the profiling itself can slow your program down by an order of +magnitude). + +4.9. Q. When I have imported a module, then edit it, and import it +again (into the same Python process), the changes don't seem to take +place. What is going on? + +A. For efficiency reasons, Python only reads the module file on the +first time a module is imported (otherwise a program consisting of +many modules, each of which imports the same basic module, would read +the basic module over and over again). To force a changed module +being read again, do this: + + import modname + reload(modname) + +Warning: this technique is not 100% fool-proof. In particular, +modules containing statements like + + from modname import some_objects + +will continue to work with the old version of the objects imported +thus. + + +5. Extending Python +=================== + +5.1. Q. Can I create my own functions in C? + +A. Yes, you can create built-in modules containing functions, +variables, exceptions and even new types in C. This is all explained +in the file "python/misc/EXTENDING". Also read the file "DYNLOAD" +there for hints on how to load such extension modules + +5.2. Q. Can I create my own functions in C++? + +A. Yes, using the C-compatibility features found in C++. Basically +you place extern "C" { ... } around the Python include files and put +extern "C" before each function that is going to be called by the +Python interpreter. Global or static C++ objects with constructors +are probably not a good idea. + + +6. Python's design +================== + +6.1. Q. Why isn't there a generic copying operation for objects in +Python? + +A. Hmm. Maybe there should be one, but it's difficult to assign a +useful meaning to copying of open files, sockets and windows, or +recursive data structures. As long as you design all your classes +yourself you are of course free to define a standard base class that +defines an overridable copying operation for all the objects you care +about. (One practical point: it would have to be a built-in function, +not a standard method name, since not all built-in object types have +methods; e.g. strings, integers and tuples don't.) + +6.2. Q. Why isn't there a generic way to implement persistent objects +in Python? (Persistent == automatically saved to and restored from +disk.) + +A. Hmm, hmm. Basically for the same reasons as why there is no +generic copying operation. + +6.3. Q. Why isn't there a switch or case statement in Python? + +A. You can do this easily enough with a sequence of +if... elif... elif... else. There have been some proposals for switch +statement syntax, but there is no concensus (yet) on whether and how +to do range tests. + + +7. Using Python on non-UNIX platforms +===================================== + +7.1. Q. Where's the DOS version of 0.9.9? + +A. I hope it will be coming soon. A friend with a DOS machine and a +compiler has volunteered to build it but he's very busy. Until then, +you will have to make do with the 0.9.8 version (which isn't so bad, +actually). + +7.2. Q. Is there a Windows version of Python? + +A. Not yet. Several Windows hackers with C compilers are working on a +port though, so maybe we'll have one soon. + +7.3. Q. I have the Mac or DOS version but it appears to be only a binary. +Where's the library? + +A. You still need to copy the files from the distribution directory +"python/lib" to your system. If you don't have the full distribution, +you can ftp the file pythonlib0.9.9.tar.Z from site ftp.cwi.nl, +directory /pub/python; this is a subset of the distribution containing +just those file. + +7.4. Q. Where's the documentation for the Mac or DOS version? + +A. There isn't any. The documentation for the Unix version also +applies to the Mac and DOS versions. Where applicable, differences +are indicated in the text. + +7.5. Q. The Mac version doesn't seem to have any facilities for creating or +editing programs apart from entering it interactively, and there seems +to be no way to save code that was entered interactively. How do I +create a Python program on the Mac? + +A. Use an external editor. I am quite happy with the Desk Accessory +called Sigma Edit; this doesn't require Multifinder or System 7. I +work like this: start the interpreter; edit a module file using Sigma +Edit; import and test it in the interpreter; edit again in Sigma Edit; +then use the built-in function reload() to re-read the imported +module; etc. diff --git a/Misc/Fixcprt.py b/Misc/Fixcprt.py new file mode 100755 index 0000000..7b447fb --- /dev/null +++ b/Misc/Fixcprt.py @@ -0,0 +1,69 @@ +#! /usr/local/bin/python + +import regex +import regsub +import glob +import sys +import os +import stat +import getopt + +oldcprt = 'Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.' +newcprt = 'Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.' + +oldprog = regex.compile(oldcprt) +newprog = regex.compile(newcprt) + +def main(): + opts, args = getopt.getopt(sys.argv[1:], 'y:') + agelimit = 0L + for opt, arg in opts: + if opt == '-y': + agelimit = os.stat(arg)[stat.ST_MTIME] + if not args: + args = glob.glob('*.[ch]') + for file in args: + try: + age = os.stat(file)[stat.ST_MTIME] + except os.error, msg: + print file, ': stat failed :', msg + continue + if age <= agelimit: + print file, ': too old, skipped' + continue + try: + f = open(file, 'r') + except IOError, msg: + print file, ': open failed :', msg + continue + head = f.read(1024) + if oldprog.search(head) < 0: + if newprog.search(head) < 0: + print file, ': NO COPYRIGHT FOUND' + else: + print file, ': (new copyright already there)' + f.close() + continue + newhead = regsub.sub(oldcprt, newcprt, head) + data = newhead + f.read() + f.close() + try: + f = open(file + '.new', 'w') + except IOError, msg: + print file, ': creat failed :', msg + continue + f.write(data) + f.close() + try: + os.rename(file, file + '~') + except IOError, msg: + print file, ': rename to backup failed :', msg + continue + try: + os.rename(file + '.new', file) + except IOError, msg: + print file, ': rename from .new failed :', msg + continue + print file, ': copyright changed.' + +main() diff --git a/Misc/HISTORY b/Misc/HISTORY new file mode 100644 index 0000000..82c4b31 --- /dev/null +++ b/Misc/HISTORY @@ -0,0 +1,1400 @@ +Python history +-------------- + +This file contains the release messages for previous Python releases +(slightly edited to adapt them to the format of this file). As you +read on you go back to the dark ages of Python's history. + +=================================== +==> Release 0.9.9 (29 Jul 1993) <== +=================================== + +I *believe* these are the main user-visible changes in this release, +but there may be others. SGI users may scan the {src,lib}/ChangeLog +files for improvements of some SGI specific modules, e.g. aifc and +cl. Developers of extension modules should also read src/ChangeLog. + + +Naming of C symbols used by the Python interpreter +-------------------------------------------------- + +* This is the last release using the current naming conventions. New +naming conventions are explained in the file misc/NAMING. +Summarizing, all externally visible symbols get (at least) a "Py" +prefix, and most functions are renamed to the standard form +PyModule_FunctionName. + +* Writers of extensions are urged to start using the new naming +conventions. The next release will use the new naming conventions +throughout (it will also have a different source directory +structure). + +* As a result of the preliminary work for the great renaming, many +functions that were accidentally global have been made static. + + +BETA X11 support +---------------- + +* There are now modules interfacing to the X11 Toolkit Intrinsics, the +Athena widgets, and the Motif 1.1 widget set. These are not yet +documented except through the examples and README file in the demo/x11 +directory. It is expected that this interface will be replaced by a +more powerful and correct one in the future, which may or may not be +backward compatible. In other words, this part of the code is at most +BETA level software! (Note: the rest of Python is rock solid as ever!) + +* I understand that the above may be a bit of a disappointment, +however my current schedule does not allow me to change this situation +before putting the release out of the door. By releasing it +undocumented and buggy, at least some of the (working!) demo programs, +like itr (my Internet Talk Radio browser) become available to a larger +audience. + +* There are also modules interfacing to SGI's "Glx" widget (a GL +window wrapped in a widget) and to NCSA's "HTML" widget (which can +format HyperText Markup Language, the document format used by the +World Wide Web). + +* I've experienced some problems when building the X11 support. In +particular, the Xm and Xaw widget sets don't go together, and it +appears that using X11R5 is better than using X11R4. Also the threads +module and its link time options may spoil things. My own strategy is +to build two Python binaries: one for use with X11 and one without +it, which can contain a richer set of built-in modules. Don't even +*think* of loading the X11 modules dynamically... + + +Environmental changes +--------------------- + +* Compiled files (*.pyc files) created by this Python version are +incompatible with those created by the previous version. Both +versions detect this and silently create a correct version, but it +means that it is not a good idea to use the same library directory for +an old and a new interpreter, since they will start to "fight" over +the *.pyc files... + +* When a stack trace is printed, the exception is printed last instead +of first. This means that if the beginning of the stack trace +scrolled out of your window you can still see what exception caused +it. + +* Sometimes interrupting a Python operation does not work because it +hangs in a blocking system call. You can now kill the interpreter by +interrupting it three times. The second time you interrupt it, a +message will be printed telling you that the third interrupt will kill +the interpreter. The "sys.exitfunc" feature still makes limited +clean-up possible in this case. + + +Changes to the command line interface +------------------------------------- + +* The python usage message is now much more informative. + +* New option -i enters interactive mode after executing a script -- +useful for debugging. + +* New option -k raises an exception when an expression statement +yields a value other than None. + +* For each option there is now also a corresponding environment +variable. + + +Using Python as an embedded language +------------------------------------ + +* The distribution now contains (some) documentation on the use of +Python as an "embedded language" in other applications, as well as a +simple example. See the file misc/EMBEDDING and the directory embed/. + + +Speed improvements +------------------ + +* Function local variables are now generally stored in an array and +accessed using an integer indexing operation, instead of through a +dictionary lookup. (This compensates the somewhat slower dictionary +lookup caused by the generalization of the dictionary module.) + + +Changes to the syntax +--------------------- + +* Continuation lines can now *sometimes* be written without a +backslash: if the continuation is contained within nesting (), [] or +{} brackets the \ may be omitted. There's a much improved +python-mode.el in the misc directory which knows about this as well. + +* You can no longer use an empty set of parentheses to define a class +without base classes. That is, you no longer write this: + + class Foo(): # syntax error + ... + +You must write this instead: + + class Foo: + ... + +This was already the preferred syntax in release 0.9.8 but many +people seemed not to have picked it up. There's a Python script that +fixes old code: demo/scripts/classfix.py. + +* There's a new reserved word: "access". The syntax and semantics are +still subject of of research and debate (as well as undocumented), but +the parser knows about the keyword so you must not use it as a +variable, function, or attribute name. + + +Changes to the semantics of the language proper +----------------------------------------------- + +* The following compatibility hack is removed: if a function was +defined with two or more arguments, and called with a single argument +that was a tuple with just as many arguments, the items of this tuple +would be used as the arguments. This is no longer supported. + + +Changes to the semantics of classes and instances +------------------------------------------------- + +* Class variables are now also accessible as instance variables for +reading (assignment creates an instance variable which overrides the +class variable of the same name though). + +* If a class attribute is a user-defined function, a new kind of +object is returned: an "unbound method". This contains a pointer to +the class and can only be called with a first argument which is a +member of that class (or a derived class). + +* If a class defines a method __init__(self, arg1, ...) then this +method is called when a class instance is created by the classname() +construct. Arguments passed to classname() are passed to the +__init__() method. The __init__() methods of base classes are not +automatically called; the derived __init__() method must call these if +necessary (this was done so the derived __init__() method can choose +the call order and arguments for the base __init__() methods). + +* If a class defines a method __del__(self) then this method is called +when an instance of the class is about to be destroyed. This makes it +possible to implement clean-up of external resources attached to the +instance. As with __init__(), the __del__() methods of base classes +are not automatically called. If __del__ manages to store a reference +to the object somewhere, its destruction is postponed; when the object +is again about to be destroyed its __del__() method will be called +again. + +* Classes may define a method __hash__(self) to allow their instances +to be used as dictionary keys. This must return a 32-bit integer. + + +Minor improvements +------------------ + +* Function and class objects now know their name (the name given in +the 'def' or 'class' statement that created them). + +* Class instances now know their class name. + + +Additions to built-in operations +-------------------------------- + +* The % operator with a string left argument implements formatting +similar to sprintf() in C. The right argument is either a single +value or a tuple of values. All features of Standard C sprintf() are +supported except %p. + +* Dictionaries now support almost any key type, instead of just +strings. (The key type must be an immutable type or must be a class +instance where the class defines a method __hash__(), in order to +avoid losing track of keys whose value may change.) + +* Built-in methods are now compared properly: when comparing x.meth1 +and y.meth2, if x is equal to y and the methods are defined by the +same function, x.meth1 compares equal to y.meth2. + + +Additions to built-in functions +------------------------------- + +* str(x) returns a string version of its argument. If the argument is +a string it is returned unchanged, otherwise it returns `x`. + +* repr(x) returns the same as `x`. (Some users found it easier to +have this as a function.) + +* round(x) returns the floating point number x rounded to an whole +number, represented as a floating point number. round(x, n) returns x +rounded to n digits. + +* hasattr(x, name) returns true when x has an attribute with the given +name. + +* hash(x) returns a hash code (32-bit integer) of an arbitrary +immutable object's value. + +* id(x) returns a unique identifier (32-bit integer) of an arbitrary +object. + +* compile() compiles a string to a Python code object. + +* exec() and eval() now support execution of code objects. + + +Changes to the documented part of the library (standard modules) +---------------------------------------------------------------- + +* os.path.normpath() (a.k.a. posixpath.normpath()) has been fixed so +the border case '/foo/..' returns '/' instead of ''. + +* A new function string.find() is added with similar semantics to +string.index(); however when it does not find the given substring it +returns -1 instead of raising string.index_error. + + +Changes to built-in modules +--------------------------- + +* New optional module 'array' implements operations on sequences of +integers or floating point numbers of a particular size. This is +useful to manipulate large numerical arrays or to read and write +binary files consisting of numerical data. + +* Regular expression objects created by module regex now support a new +method named group(), which returns one or more \(...\) groups by number. +The number of groups is increased from 10 to 100. + +* Function compile() in module regex now supports an optional mapping +argument; a variable casefold is added to the module which can be used +as a standard uppercase to lowercase mapping. + +* Module time now supports many routines that are defined in the +Standard C time interface (): gmtime(), localtime(), +asctime(), ctime(), mktime(), as well as these variables (taken from +System V): timezone, altzone, daylight and tzname. (The corresponding +functions in the undocumented module calendar have been removed; the +undocumented and unfinished module tzparse is now obsolete and will +disappear in a future release.) + +* Module strop (the fast built-in version of standard module string) +now uses C's definition of whitespace instead of fixing it to space, +tab and newline; in practice this usually means that vertical tab, +form feed and return are now also considered whitespace. It exports +the string of characters that are considered whitespace as well as the +characters that are considered lowercase or uppercase. + +* Module sys now defines the variable builtin_module_names, a list of +names of modules built into the current interpreter (including not +yet imported, but excluding two special modules that always have to be +defined -- sys and builtin). + +* Objects created by module sunaudiodev now also support flush() and +close() methods. + +* Socket objects created by module socket now support an optional +flags argument for their methods sendto() and recvfrom(). + +* Module marshal now supports dumping to and loading from strings, +through the functions dumps() and loads(). + +* Module stdwin now supports some new functionality. You may have to +ftp the latest version: ftp.cwi.nl:/pub/stdwin/stdwinforviews.tar.Z.) + + +Bugs fixed +---------- + +* Fixed comparison of negative long integers. + +* The tokenizer no longer botches input lines longer than BUFSIZ. + +* Fixed several severe memory leaks in module select. + +* Fixed memory leaks in modules socket and sv. + +* Fixed memory leak in divmod() for long integers. + +* Problems with definition of floatsleep() on Suns fixed. + +* Many portability bugs fixed (and undoubtedly new ones added :-). + + +Changes to the build procedure +------------------------------ + +* The Makefile supports some new targets: "make default" and "make +all". Both are by normally equivalent to "make python". + +* The Makefile no longer uses $> since it's not supported by all +versions of Make. + +* The header files now all contain #ifdef constructs designed to make +it safe to include the same header file twice, as well as support for +inclusion from C++ programs (automatic extern "C" { ... } added). + + +Freezing Python scripts +----------------------- + +* There is now some support for "freezing" a Python script as a +stand-alone executable binary file. See the script +demo/scripts/freeze.py. It will require some site-specific tailoring +of the script to get this working, but is quite worthwhile if you write +Python code for other who may not have built and installed Python. + + +MS-DOS +------ + +* A new MS-DOS port has been done, using MSC 6.0 (I believe). Thanks, +Marcel van der Peijl! This requires fewer compatibility hacks in +posixmodule.c. The executable is not yet available but will be soon +(check the mailing list). + +* The default PYTHONPATH has changed. + + +Changes for developers of extension modules +------------------------------------------- + +* Read src/ChangeLog for full details. + + +SGI specific changes +-------------------- + +* Read src/ChangeLog for full details. + +================================== +==> Release 0.9.8 (9 Jan 1993) <== +================================== + +I claim no completeness here, but I've tried my best to scan the log +files throughout my source tree for interesting bits of news. A more +complete account of the changes is to be found in the various +ChangeLog files. See also "News for release 0.9.7beta" below if you're +still using release 0.9.6, and the file HISTORY if you have an even +older release. + + --Guido + + +Changes to the language proper +------------------------------ + +There's only one big change: the conformance checking for function +argument lists (of user-defined functions only) is stricter. Earlier, +you could get away with the following: + + (a) define a function of one argument and call it with any + number of arguments; if the actual argument count wasn't + one, the function would receive a tuple containing the + arguments arguments (an empty tuple if there were none). + + (b) define a function of two arguments, and call it with more + than two arguments; if there were more than two arguments, + the second argument would be passed as a tuple containing + the second and further actual arguments. + +(Note that an argument (formal or actual) that is a tuple is counted as +one; these rules don't apply inside such tuples, only at the top level +of the argument list.) + +Case (a) was needed to accommodate variable-length argument lists; +there is now an explicit "varargs" feature (precede the last argument +with a '*'). Case (b) was needed for compatibility with old class +definitions: up to release 0.9.4 a method with more than one argument +had to be declared as "def meth(self, (arg1, arg2, ...)): ...". +Version 0.9.6 provide better ways to handle both casees, bot provided +backward compatibility; version 0.9.8 retracts the compatibility hacks +since they also cause confusing behavior if a function is called with +the wrong number of arguments. + +There's a script that helps converting classes that still rely on (b), +provided their methods' first argument is called "self": +demo/scripts/methfix.py. + +If this change breaks lots of code you have developed locally, try +#defining COMPAT_HACKS in ceval.c. + +(There's a third compatibility hack, which is the reverse of (a): if a +function is defined with two or more arguments, and called with a +single argument that is a tuple with just as many arguments, the items +of this tuple will be used as the arguments. Although this can (and +should!) be done using the built-in function apply() instead, it isn't +withdrawn yet.) + + +One minor change: comparing instance methods works like expected, so +that if x is an instance of a user-defined class and has a method m, +then (x.m==x.m) yields 1. + + +The following was already present in 0.9.7beta, but not explicitly +mentioned in the NEWS file: user-defined classes can now define types +that behave in almost allrespects like numbers. See +demo/classes/Rat.py for a simple example. + + +Changes to the build process +---------------------------- + +The Configure.py script and the Makefile has been made somewhat more +bullet-proof, after reports of (minor) trouble on certain platforms. + +There is now a script to patch Makefile and config.c to add a new +optional built-in module: Addmodule.sh. Read the script before using! + +Useing Addmodule.sh, all optional modules can now be configured at +compile time using Configure.py, so there are no modules left that +require dynamic loading. + +The Makefile has been fixed to make it easier to use with the VPATH +feature of some Make versions (e.g. SunOS). + + +Changes affecting portability +----------------------------- + +Several minor portability problems have been solved, e.g. "malloc.h" +has been renamed to "mymalloc.h", "strdup.c" is no longer used, and +the system now tolerates malloc(0) returning 0. + +For dynamic loading on the SGI, Jack Jansen's dl 1.6 is now +distributed with Python. This solves several minor problems, in +particular scripts invoked using #! can now use dynamic loading. + + +Changes to the interpreter interface +------------------------------------ + +On popular demand, there's finally a "profile" feature for interactive +use of the interpreter. If the environment variable $PYTHONSTARTUP is +set to the name of an existing file, Python statements in this file +are executed when the interpreter is started in interactive mode. + +There is a new clean-up mechanism, complementing try...finally: if you +assign a function object to sys.exitfunc, it will be called when +Python exits or receives a SIGTERM or SIGHUP signal. + +The interpreter is now generally assumed to live in +/usr/local/bin/python (as opposed to /usr/local/python). The script +demo/scripts/fixps.py will update old scripts in place (you can easily +modify it to do other similar changes). + +Most I/O that uses sys.stdin/stdout/stderr will now use any object +assigned to those names as long as the object supports readline() or +write() methods. + +The parser stack has been increased to 500 to accommodate more +complicated expressions (7 levels used to be the practical maximum, +it's now about 38). + +The limit on the size of the *run-time* stack has completely been +removed -- this means that tuple or list displays can contain any +number of elements (formerly more than 50 would crash the +interpreter). + + +Changes to existing built-in functions and methods +-------------------------------------------------- + +The built-in functions int(), long(), float(), oct() and hex() now +also apply to class instalces that define corresponding methods +(__int__ etc.). + + +New built-in functions +---------------------- + +The new functions str() and repr() convert any object to a string. +The function repr(x) is in all respects equivalent to `x` -- some +people prefer a function for this. The function str(x) does the same +except if x is already a string -- then it returns x unchanged +(repr(x) adds quotes and escapes "funny" characters as octal escapes). + +The new function cmp(x, y) returns -1 if xy. + + +Changes to general built-in modules +----------------------------------- + +The time module's functions are more general: time() returns a +floating point number and sleep() accepts one. Their accuracies +depends on the precision of the system clock. Millisleep is no longer +needed (although it still exists for now), but millitimer is still +needed since on some systems wall clock time is only available with +seconds precision, while a source of more precise time exists that +isn't synchronized with the wall clock. (On UNIX systems that support +the BSD gettimeofday() function, time.time() is as time.millitimer().) + +The string representation of a file object now includes an address: +'' where ###### is a hex number +(the object's address) to make it unique. + +New functions added to posix: nice(), setpgrp(), and if your system +supports them: setsid(), setpgid(), tcgetpgrp(), tcsetpgrp(). + +Improvements to the socket module: socket objects have new methods +getpeername() and getsockname(), and the {get,set}sockopt methods can +now get/set any kind of option using strings built with the new struct +module. And there's a new function fromfd() which creates a socket +object given a file descriptor (useful for servers started by inetd, +which have a socket connected to stdin and stdout). + + +Changes to SGI-specific built-in modules +---------------------------------------- + +The FORMS library interface (fl) now requires FORMS 2.1a. Some new +functions have been added and some bugs have been fixed. + +Additions to al (audio library interface): added getname(), +getdefault() and getminmax(). + +The gl modules doesn't call "foreground()" when initialized (this +caused some problems) like it dit in 0.9.7beta (but not before). +There's a new gl function 'gversion() which returns a version string. + +The interface to sv (Indigo video interface) has totally changed. +(Sorry, still no documentation, but see the examples in +demo/sgi/{sv,video}.) + + +Changes to standard library modules +----------------------------------- + +Most functions in module string are now much faster: they're actually +implemented in C. The module containing the C versions is called +"strop" but you should still import "string" since strop doesn't +provide all the interfaces defined in string (and strop may be renamed +to string when it is complete in a future release). + +string.index() now accepts an optional third argument giving an index +where to start searching in the first argument, so you can find second +and further occurrences (this is similar to the regular expression +functions in regex). + +The definition of what string.splitfields(anything, '') should return +is changed for the last time: it returns a singleton list containing +its whole first argument unchanged. This is compatible with +regsub.split() which also ignores empty delimiter matches. + +posixpath, macpath: added dirname() and normpath() (and basename() to +macpath). + +The mainloop module (for use with stdwin) can now demultiplex input +from other sources, as long as they can be polled with select(). + + +New built-in modules +-------------------- + +Module struct defines functions to pack/unpack values to/from strings +representing binary values in native byte order. + +Module strop implements C versions of many functions from string (see +above). + +Optional module fcntl defines interfaces to fcntl() and ioctl() -- +UNIX only. (Not yet properly documented -- see however src/fcntl.doc.) + +Optional module mpz defines an interface to an altaernative long +integer implementation, the GNU MPZ library. + +Optional module md5 uses the GNU MPZ library to calculate MD5 +signatures of strings. + +There are also optional new modules specific to SGI machines: imageop +defines some simple operations to images represented as strings; sv +interfaces to the Indigo video board; cl interfaces to the (yet +unreleased) compression library. + + +New standard library modules +---------------------------- + +(Unfortunately the following modules are not all documented; read the +sources to find out more about them!) + +autotest: run testall without showing any output unless it differs +from the expected output + +bisect: use bisection to insert or find an item in a sorted list + +colorsys: defines conversions between various color systems (e.g. RGB +<-> YUV) + +nntplib: a client interface to NNTP servers + +pipes: utility to construct pipeline from templates, e.g. for +conversion from one file format to another using several utilities. + +regsub: contains three functions that are more or less compatible with +awk functions of the same name: sub() and gsub() do string +substitution, split() splits a string using a regular expression to +define how separators are define. + +test_types: test operations on the built-in types of Python + +toaiff: convert various audio file formats to AIFF format + +tzparse: parse the TZ environment parameter (this may be less general +than it could be, let me know if you fix it). + +(Note that the obsolete module "path" no longer exists.) + + +New SGI-specific library modules +-------------------------------- + +CL: constants for use with the built-in compression library interface (cl) + +Queue: a multi-producer, multi-consumer queue class implemented for +use with the built-in thread module + +SOCKET: constants for use with built-in module socket, e.g. to set/get +socket options. This is SGI-specific because the constants to be +passed are system-dependent. You can generate a version for your own +system by running the script demo/scripts/h2py.py with +/usr/include/sys/socket.h as input. + +cddb: interface to the database used the the CD player + +torgb: convert various image file types to rgb format (requires pbmplus) + + +New demos +--------- + +There's an experimental interface to define Sun RPC clients and +servers in demo/rpc. + +There's a collection of interfaces to WWW, WAIS and Gopher (both +Python classes and program providing a user interface) in demo/www. +This includes a program texi2html.py which converts texinfo files to +HTML files (the format used hy WWW). + +The ibrowse demo has moved from demo/stdwin/ibrowse to demo/ibrowse. + +For SGI systems, there's a whole collection of programs and classes +that make use of the Indigo video board in demo/sgi/{sv,video}. This +represents a significant amount of work that we're giving away! + +There are demos "rsa" and "md5test" that exercise the mpz and md5 +modules, respectively. The rsa demo is a complete implementation of +the RSA public-key cryptosystem! + +A bunch of games and examples submitted by Stoffel Erasmus have been +included in demo/stoffel. + +There are miscellaneous new files in some existing demo +subdirectories: classes/bitvec.py, scripts/{fixps,methfix}.py, +sgi/al/cmpaf.py, sockets/{mcast,gopher}.py. + +There are also many minor changes to existing files, but I'm too lazy +to run a diff and note the differences -- you can do this yourself if +you save the old distribution's demos. One highlight: the +stdwin/python.py demo is much improved! + + +Changes to the documentation +---------------------------- + +The LaTeX source for the library uses different macros to enable it to +be converted to texinfo, and from there to INFO or HTML format so it +can be browsed as a hypertext. The net result is that you can now +read the Python library documentation in Emacs info mode! + + +Changes to the source code that affect C extension writers +---------------------------------------------------------- + +The function strdup() no longer exists (it was used only in one places +and is somewhat of a a portability problem sice some systems have the +same function in their C library. + +The functions NEW() and RENEW() allocate one spare byte to guard +against a NULL return from malloc(0) being taken for an error, but +this should not be relied upon. + + +========================= +==> Release 0.9.7beta <== +========================= + + +Changes to the language proper +------------------------------ + +User-defined classes can now implement operations invoked through +special syntax, such as x[i] or `x` by defining methods named +__getitem__(self, i) or __repr__(self), etc. + + +Changes to the build process +---------------------------- + +Instead of extensive manual editing of the Makefile to select +compile-time options, you can now run a Configure.py script. +The Makefile as distributed builds a minimal interpreter sufficient to +run Configure.py. See also misc/BUILD + +The Makefile now includes more "utility" targets, e.g. install and +tags/TAGS + +Using the provided strtod.c and strtol.c are now separate options, as +on the Sun the provided strtod.c dumps core :-( + +The regex module is now an option chosen by the Makefile, since some +(old) C compilers choke on regexpr.c + + +Changes affecting portability +----------------------------- + +You need STDWIN version 0.9.7 (released 30 June 1992) for the stdwin +interface + +Dynamic loading is now supported for Sun (and other non-COFF systems) +throug dld-3.2.3, as well as for SGI (a new version of Jack Jansen's +DL is out, 1.4) + +The system-dependent code for the use of the select() system call is +moved to one file: myselect.h + +Thanks to Jaap Vermeulen, the code should now port cleanly to the +SEQUENT + + +Changes to the interpreter interface +------------------------------------ + +The interpretation of $PYTHONPATH in the environment is different: it +is inserted in front of the default path instead of overriding it + + +Changes to existing built-in functions and methods +-------------------------------------------------- + +List objects now support an optional argument to their sort() method, +which is a comparison function similar to qsort(3) in C + +File objects now have a method fileno(), used by the new select module +(see below) + + +New built-in function +--------------------- + +coerce(x, y): take two numbers and return a tuple containing them +both converted to a common type + + +Changes to built-in modules +--------------------------- + +sys: fixed core dumps in settrace() and setprofile() + +socket: added socket methods setsockopt() and getsockopt(); and +fileno(), used by the new select module (see below) + +stdwin: added fileno() == connectionnumber(), in support of new module +select (see below) + +posix: added get{eg,eu,g,u}id(); waitpid() is now a separate function. + +gl: added qgetfd() + +fl: added several new functions, fixed several obscure bugs, adapted +to FORMS 2.1 + + +Changes to standard modules +--------------------------- + +posixpath: changed implementation of ismount() + +string: atoi() no longer mistakes leading zero for octal number + +... + + +New built-in modules +-------------------- + +Modules marked "dynamic only" are not configured at compile time but +can be loaded dynamically. You need to turn on the DL or DLD option in +the Makefile for support dynamic loading of modules (this requires +external code). + +select: interfaces to the BSD select() system call + +dbm: interfaces to the (new) dbm library (dynamic only) + +nis: interfaces to some NIS functions (aka yellow pages) + +thread: limited form of multiple threads (sgi only) + +audioop: operations useful for audio programs, e.g. u-LAW and ADPCM +coding (dynamic only) + +cd: interface to Indigo SCSI CDROM player audio library (sgi only) + +jpeg: read files in JPEG format (dynamic only, sgi only; needs +external code) + +imgfile: read SGI image files (dynamic only, sgi only) + +sunaudiodev: interface to sun's /dev/audio (dynamic only, sun only) + +sv: interface to Indigo video library (sgi only) + +pc: a minimal set of MS-DOS interfaces (MS-DOS only) + +rotor: encryption, by Lance Ellinghouse (dynamic only) + + +New standard modules +-------------------- + +Not all these modules are documented. Read the source: +lib/.py. Sometimes a file lib/.doc contains +additional documentation. + +imghdr: recognizes image file headers + +sndhdr: recognizes sound file headers + +profile: print run-time statistics of Python code + +readcd, cdplayer: companion modules for built-in module cd (sgi only) + +emacs: interface to Emacs using py-connect.el (see below). + +SOCKET: symbolic constant definitions for socket options + +SUNAUDIODEV: symbolic constant definitions for sunaudiodef (sun only) + +SV: symbolic constat definitions for sv (sgi only) + +CD: symbolic constat definitions for cd (sgi only) + + +New demos +--------- + +scripts/pp.py: execute Python as a filter with a Perl-like command +line interface + +classes/: examples using the new class features + +threads/: examples using the new thread module + +sgi/cd/: examples using the new cd module + + +Changes to the documentation +---------------------------- + +The last-minute syntax changes of release 0.9.6 are now reflected +everywhere in the manuals + +The reference manual has a new section (3.2) on implementing new kinds +of numbers, sequences or mappings with user classes + +Classes are now treated extensively in the tutorial (chapter 9) + +Slightly restructured the system-dependent chapters of the library +manual + +The file misc/EXTENDING incorporates documentation for mkvalue() and +a new section on error handling + +The files misc/CLASSES and misc/ERRORS are no longer necessary + +The doc/Makefile now creates PostScript files automatically + + +Miscellaneous changes +--------------------- + +Incorporated Tim Peters' changes to python-mode.el, it's now version +1.06 + +A python/Emacs bridge (provided by Terrence M. Brannon) lets a Python +program running in an Emacs buffer execute Emacs lisp code. The +necessary Python code is in lib/emacs.py. The Emacs code is +misc/py-connect.el (it needs some external Emacs lisp code) + + +Changes to the source code that affect C extension writers +---------------------------------------------------------- + +New service function mkvalue() to construct a Python object from C +values according to a "format" string a la getargs() + +Most functions from pythonmain.c moved to new pythonrun.c which is +in libpython.a. This should make embedded versions of Python easier + +ceval.h is split in eval.h (which needs compile.h and only declares +eval_code) and ceval.h (which doesn't need compile.hand declares the +rest) + +ceval.h defines macros BGN_SAVE / END_SAVE for use with threads (to +improve the parallellism of multi-threaded programs by letting other +Python code run when a blocking system call or something similar is +made) + +In structmember.[ch], new member types BYTE, CHAR and unsigned +variants have been added + +New file xxmodule.c is a template for new extension modules. + +================================== +==> RELEASE 0.9.6 (6 Apr 1992) <== +================================== + +Misc news in 0.9.6: +- Restructured the misc subdirectory +- Reference manual completed, library manual much extended (with indexes!) +- the GNU Readline library is now distributed standard with Python +- the script "../demo/scripts/classfix.py" fixes Python modules using old + class syntax +- Emacs python-mode.el (was python.el) vastly improved (thanks, Tim!) +- Because of the GNU copyleft business I am not using the GNU regular + expression implementation but a free re-implementation by Tatu Ylonen + that recently appeared in comp.sources.misc (Bravo, Tatu!) + +New features in 0.9.6: +- stricter try stmt syntax: cannot mix except and finally clauses on 1 try +- New module 'os' supplants modules 'mac' and 'posix' for most cases; + module 'path' is replaced by 'os.path' +- os.path.split() return value differs from that of old path.split() +- sys.exc_type, sys.exc_value, sys.exc_traceback are set to the exception + currently being handled +- sys.last_type, sys.last_value, sys.last_traceback remember last unhandled + exception +- New function string.expandtabs() expands tabs in a string +- Added times() interface to posix (user & sys time of process & children) +- Added uname() interface to posix (returns OS type, hostname, etc.) +- New built-in function execfile() is like exec() but from a file +- Functions exec() and eval() are less picky about whitespace/newlines +- New built-in functions getattr() and setattr() access arbitrary attributes +- More generic argument handling in built-in functions (see "./EXTENDING") +- Dynamic loading of modules written in C or C++ (see "./DYNLOAD") +- Division and modulo for long and plain integers with negative operands + have changed; a/b is now floor(float(a)/float(b)) and a%b is defined + as a-(a/b)*b. So now the outcome of divmod(a,b) is the same as + (a/b, a%b) for integers. For floats, % is also changed, but of course + / is unchanged, and divmod(x,y) does not yield (x/y, x%y)... +- A function with explicit variable-length argument list can be declared + like this: def f(*args): ...; or even like this: def f(a, b, *rest): ... +- Code tracing and profiling features have been added, and two source + code debuggers are provided in the library (pdb.py, tty-oriented, + and wdb, window-oriented); you can now step through Python programs! + See sys.settrace() and sys.setprofile(), and "../lib/pdb.doc" +- '==' is now the only equality operator; "../demo/scripts/eqfix.py" is + a script that fixes old Python modules +- Plain integer right shift now uses sign extension +- Long integer shift/mask operations now simulate 2's complement + to give more useful results for negative operands +- Changed/added range checks for long/plain integer shifts +- Options found after "-c command" are now passed to the command in sys.argv + (note subtle incompatiblity with "python -c command -- -options"!) +- Module stdwin is better protected against touching objects after they've + been closed; menus can now also be closed explicitly +- Stdwin now uses its own exception (stdwin.error) + +New features in 0.9.5 (released as Macintosh application only, 2 Jan 1992): +- dictionary objects can now be compared properly; e.g., {}=={} is true +- new exception SystemExit causes termination if not caught; + it is raised by sys.exit() so that 'finally' clauses can clean up, + and it may even be caught. It does work interactively! +- new module "regex" implements GNU Emacs style regular expressions; + module "regexp" is rewritten in Python for backward compatibility +- formal parameter lists may contain trailing commas + +Bugs fixed in 0.9.6: +- assigning to or deleting a list item with a negative index dumped core +- divmod(-10L,5L) returned (-3L, 5L) instead of (-2L, 0L) + +Bugs fixed in 0.9.5: +- masking operations involving negative long integers gave wrong results + + +=================================== +==> RELEASE 0.9.4 (24 Dec 1991) <== +=================================== + +- new function argument handling (see below) +- built-in apply(func, args) means func(args[0], args[1], ...) +- new, more refined exceptions +- new exception string values (NameError = 'NameError' etc.) +- better checking for math exceptions +- for sequences (string/tuple/list), x[-i] is now equivalent to x[len(x)-i] +- fixed list assignment bug: "a[1:1] = a" now works correctly +- new class syntax, without extraneous parentheses +- new 'global' statement to assign global variables from within a function + + +New class syntax +---------------- + +You can now declare a base class as follows: + + class B: # Was: class B(): + def some_method(self): ... + ... + +and a derived class thusly: + + class D(B): # Was: class D() = B(): + def another_method(self, arg): ... + +Multiple inheritance looks like this: + + class M(B, D): # Was: class M() = B(), D(): + def this_or_that_method(self, arg): ... + +The old syntax is still accepted by Python 0.9.4, but will disappear +in Python 1.0 (to be posted to comp.sources). + + +New 'global' statement +---------------------- + +Every now and then you have a global variable in a module that you +want to change from within a function in that module -- say, a count +of calls to a function, or an option flag, etc. Until now this was +not directly possible. While several kludges are known that +circumvent the problem, and often the need for a global variable can +be avoided by rewriting the module as a class, this does not always +lead to clearer code. + +The 'global' statement solves this dilemma. Its occurrence in a +function body means that, for the duration of that function, the +names listed there refer to global variables. For instance: + + total = 0.0 + count = 0 + + def add_to_total(amount): + global total, count + total = total + amount + count = count + 1 + +'global' must be repeated in each function where it is needed. The +names listed in a 'global' statement must not be used in the function +before the statement is reached. + +Remember that you don't need to use 'global' if you only want to *use* +a global variable in a function; nor do you need ot for assignments to +parts of global variables (e.g., list or dictionary items or +attributes of class instances). This has not changed; in fact +assignment to part of a global variable was the standard workaround. + + +New exceptions +-------------- + +Several new exceptions have been defined, to distinguish more clearly +between different types of errors. + +name meaning was + +AttributeError reference to non-existing attribute NameError +IOError unexpected I/O error RuntimeError +ImportError import of non-existing module or name NameError +IndexError invalid string, tuple or list index RuntimeError +KeyError key not in dictionary RuntimeError +OverflowError numeric overflow RuntimeError +SyntaxError invalid syntax RuntimeError +ValueError invalid argument value RuntimeError +ZeroDivisionError division by zero RuntimeError + +The string value of each exception is now its name -- this makes it +easier to experimentally find out which operations raise which +exceptions; e.g.: + + >>> KeyboardInterrupt + 'KeyboardInterrupt' + >>> + + +New argument passing semantics +------------------------------ + +Off-line discussions with Steve Majewski and Daniel LaLiberte have +convinced me that Python's parameter mechanism could be changed in a +way that made both of them happy (I hope), kept me happy, fixed a +number of outstanding problems, and, given some backward compatibility +provisions, would only break a very small amount of existing code -- +probably all mine anyway. In fact I suspect that most Python users +will hardly notice the difference. And yet it has cost me at least +one sleepless night to decide to make the change... + +Philosophically, the change is quite radical (to me, anyway): a +function is no longer called with either zero or one argument, which +is a tuple if there appear to be more arguments. Every function now +has an argument list containing 0, 1 or more arguments. This list is +always implemented as a tuple, and it is a (run-time) error if a +function is called with a different number of arguments than expected. + +What's the difference? you may ask. The answer is, very little unless +you want to write variadic functions -- functions that may be called +with a variable number of arguments. Formerly, you could write a +function that accepted one or more arguments with little trouble, but +writing a function that could be called with either 0 or 1 argument +(or more) was next to impossible. This is now a piece of cake: you +can simply declare an argument that receives the entire argument +tuple, and check its length -- it will be of size 0 if there are no +arguments. + +Another anomaly of the old system was the way multi-argument methods +(in classes) had to be declared, e.g.: + + class Point(): + def init(self, (x, y, color)): ... + def setcolor(self, color): ... + dev moveto(self, (x, y)): ... + def draw(self): ... + +Using the new scheme there is no need to enclose the method arguments +in an extra set of parentheses, so the above class could become: + + class Point: + def init(self, x, y, color): ... + def setcolor(self, color): ... + dev moveto(self, x, y): ... + def draw(self): ... + +That is, the equivalence rule between methods and functions has +changed so that now p.moveto(x,y) is equivalent to Point.moveto(p,x,y) +while formerly it was equivalent to Point.moveto(p,(x,y)). + +A special backward compatibility rule makes that the old version also +still works: whenever a function with exactly two arguments (at the top +level) is called with more than two arguments, the second and further +arguments are packed into a tuple and passed as the second argument. +This rule is invoked independently of whether the function is actually a +method, so there is a slight chance that some erroneous calls of +functions expecting two arguments with more than that number of +arguments go undetected at first -- when the function tries to use the +second argument it may find it is a tuple instead of what was expected. +Note that this rule will be removed from future versions of the +language; it is a backward compatibility provision *only*. + +Two other rules and a new built-in function handle conversion between +tuples and argument lists: + +Rule (a): when a function with more than one argument is called with a +single argument that is a tuple of the right size, the tuple's items +are used as arguments. + +Rule (b): when a function with exactly one argument receives no +arguments or more than one, that one argument will receive a tuple +containing the arguments (the tuple will be empty if there were no +arguments). + + +A new built-in function, apply(), was added to support functions that +need to call other functions with a constructed argument list. The call + + apply(function, tuple) + +is equivalent to + + function(tuple[0], tuple[1], ..., tuple[len(tuple)-1]) + + +While no new argument syntax was added in this phase, it would now be +quite sensible to add explicit syntax to Python for default argument +values (as in C++ or Modula-3), or a "rest" argument to receive the +remaining arguments of a variable-length argument list. + + +======================================================== +==> Release 0.9.3 (never made available outside CWI) <== +======================================================== + +- string sys.version shows current version (also printed on interactive entry) +- more detailed exceptions, e.g., IOError, ZeroDivisionError, etc. +- 'global' statement to declare module-global variables assigned in functions. +- new class declaration syntax: class C(Base1, Base2, ...): suite + (the old syntax is still accepted -- be sure to convert your classes now!) +- C shifting and masking operators: << >> ~ & ^ | (for ints and longs). +- C comparison operators: == != (the old = and <> remain valid). +- floating point numbers may now start with a period (e.g., .14). +- definition of integer division tightened (always truncates towards zero). +- new builtins hex(x), oct(x) return hex/octal string from (long) integer. +- new list method l.count(x) returns the number of occurrences of x in l. +- new SGI module: al (Indigo and 4D/35 audio library). +- the FORMS interface (modules fl and FL) now uses FORMS 2.0 +- module gl: added lrect{read,write}, rectzoom and pixmode; + added (non-GL) functions (un)packrect. +- new socket method: s.allowbroadcast(flag). +- many objects support __dict__, __methods__ or __members__. +- dir() lists anything that has __dict__. +- class attributes are no longer read-only. +- classes support __bases__, instances support __class__ (and __dict__). +- divmod() now also works for floats. +- fixed obscure bug in eval('1 '). + + +=================================== +==> Release 0.9.2 (Autumn 1991) <== +=================================== + +Highlights +---------- + +- tutorial now (almost) complete; library reference reorganized +- new syntax: continue statement; semicolons; dictionary constructors; + restrictions on blank lines in source files removed +- dramatically improved module load time through precompiled modules +- arbitrary precision integers: compute 2 to the power 1000 and more... +- arithmetic operators now accept mixed type operands, e.g., 3.14/4 +- more operations on list: remove, index, reverse; repetition +- improved/new file operations: readlines, seek, tell, flush, ... +- process management added to the posix module: fork/exec/wait/kill etc. +- BSD socket operations (with example servers and clients!) +- many new STDWIN features (color, fonts, polygons, ...) +- new SGI modules: font manager and FORMS library interface + + +Extended list of changes in 0.9.2 +--------------------------------- + +Here is a summary of the most important user-visible changes in 0.9.2, +in somewhat arbitrary order. Changes in later versions are listed in +the "highlights" section above. + + +1. Changes to the interpreter proper + +- Simple statements can now be separated by semicolons. + If you write "if t: s1; s2", both s1 and s2 are executed + conditionally. +- The 'continue' statement was added, with semantics as in C. +- Dictionary displays are now allowed on input: {key: value, ...}. +- Blank lines and lines bearing only a comment no longer need to + be indented properly. (A completely empty line still ends a multi- + line statement interactively.) +- Mixed arithmetic is supported, 1 compares equal to 1.0, etc. +- Option "-c command" to execute statements from the command line +- Compiled versions of modules are cached in ".pyc" files, giving a + dramatic improvement of start-up time +- Other, smaller speed improvements, e.g., extracting characters from + strings, looking up single-character keys, and looking up global + variables +- Interrupting a print operation raises KeyboardInterrupt instead of + only cancelling the print operation +- Fixed various portability problems (it now passes gcc with only + warnings -- more Standard C compatibility will be provided in later + versions) +- Source is prepared for porting to MS-DOS +- Numeric constants are now checked for overflow (this requires + standard-conforming strtol() and strtod() functions; a correct + strtol() implementation is provided, but the strtod() provided + relies on atof() for everything, including error checking + + +2. Changes to the built-in types, functions and modules + +- New module socket: interface to BSD socket primitives +- New modules pwd and grp: access the UNIX password and group databases +- (SGI only:) New module "fm" interfaces to the SGI IRIX Font Manager +- (SGI only:) New module "fl" interfaces to Mark Overmars' FORMS library +- New numeric type: long integer, for unlimited precision + - integer constants suffixed with 'L' or 'l' are long integers + - new built-in function long(x) converts int or float to long + - int() and float() now also convert from long integers +- New built-in function: + - pow(x, y) returns x to the power y +- New operation and methods for lists: + - l*n returns a new list consisting of n concatenated copies of l + - l.remove(x) removes the first occurrence of the value x from l + - l.index(x) returns the index of the first occurrence of x in l + - l.reverse() reverses l in place +- New operation for tuples: + - t*n returns a tuple consisting of n concatenated copies of t +- Improved file handling: + - f.readline() no longer restricts the line length, is faster, + and isn't confused by null bytes; same for raw_input() + - f.read() without arguments reads the entire (rest of the) file + - mixing of print and sys.stdout.write() has different effect +- New methods for files: + - f.readlines() returns a list containing the lines of the file, + as read with f.readline() + - f.flush(), f.tell(), f.seek() call their stdio counterparts + - f.isatty() tests for "tty-ness" +- New posix functions: + - _exit(), exec(), fork(), getpid(), getppid(), kill(), wait() + - popen() returns a file object connected to a pipe + - utime() replaces utimes() (the latter is not a POSIX name) +- New stdwin features, including: + - font handling + - color drawing + - scroll bars made optional + - polygons + - filled and xor shapes + - text editing objects now have a 'settext' method + + +3. Changes to the standard library + +- Name change: the functions path.cat and macpath.cat are now called + path.join and macpath.join +- Added new modules: formatter, mutex, persist, sched, mainloop +- Added some modules and functionality to the "widget set" (which is + still under development, so please bear with me): + DirList, FormSplit, TextEdit, WindowSched +- Fixed module testall to work non-interactively +- Module string: + - added functions join() and joinfields() + - fixed center() to work correct and make it "transitive" +- Obsolete modules were removed: util, minmax +- Some modules were moved to the demo directory + + +4. Changes to the demonstration programs + +- Added new useful scipts: byteyears, eptags, fact, from, lfact, + objgraph, pdeps, pi, primes, ptags, which +- Added a bunch of socket demos +- Doubled the speed of ptags +- Added new stdwin demos: microedit, miniedit +- Added a windowing interface to the Python interpreter: python (most + useful on the Mac) +- Added a browser for Emacs info files: demo/stdwin/ibrowse + (yes, I plan to put all STDWIN and Python documentation in texinfo + form in the future) + + +5. Other changes to the distribution + +- An Emacs Lisp file "python.el" is provided to facilitate editing + Python programs in GNU Emacs (slightly improved since posted to + gnu.emacs.sources) +- Some info on writing an extension in C is provided +- Some info on building Python on non-UNIX platforms is provided + + +===================================== +==> Release 0.9.1 (February 1991) <== +===================================== + +- Micro changes only +- Added file "patchlevel.h" + + +===================================== +==> Release 0.9.0 (February 1991) <== +===================================== + +Original posting to alt.sources. diff --git a/Misc/Makefile b/Misc/Makefile new file mode 100644 index 0000000..9df7110 --- /dev/null +++ b/Misc/Makefile @@ -0,0 +1,10 @@ +all: + @echo Nothing to make in this directory. + +clean: + find . '(' -name '*.pyc' -o -name core -o -name '*~' \ + -o -name '[@,#]*' -o -name '*.old' \ + -o -name '*.orig' -o -name '*.rej' ')' \ + -print -exec rm -f {} ';' + +clobber: clean diff --git a/Misc/README b/Misc/README new file mode 100644 index 0000000..d466919 --- /dev/null +++ b/Misc/README @@ -0,0 +1,20 @@ +Python Misc subdirectory +======================== + +This directory contains files that wouldn't fit in elsewhere, in +particular the UNIX manual page, an Emacs mode for Python source code, +and a list of Frequently Asked Questions (and their answers). + +Files found here +---------------- + +BLURB A quick description of Python for newcomers +BLURB.LUTZ A very good blurb to show to TCL/Perl hackers +COPYING The GNU GENERAL PUBLIC LICENCE (needed because of autoconf) +COPYRIGHT The Python copyright notice +FAQ Frequently Asked Questions about Python (and answers) +Fixcprt.py Fix the copyright message (a yearly chore :-) +README The file you're reading now +fixfuncptrs.sh Shell script to fix function pointer initializers +python-mode.el Emacs mode for editing Python programs (thanks again, Tim!) +python.man UNIX man page for the python interpreter diff --git a/Misc/RFD b/Misc/RFD new file mode 100644 index 0000000..fd278c4 --- /dev/null +++ b/Misc/RFD @@ -0,0 +1,114 @@ +To: python-list +Subject: comp.lang.python RFD again +From: Guido.van.Rossum@cwi.nl + +I've followed the recent discussion and trimmed the blurb RFD down a bit +(and added the word "object-oriented" to the blurb). + +I don't think it's too early to *try* to create the newsgroup -- +whether we will succeed may depend on how many Python supporters there +are outside the mailing list. + +I'm personally not worried about moderation, and anyway I haven't +heard from any volunteers for moderation (and I won't volunteer +myself) so I suggest that we'll continue to ask for one unmoderated +newsgroup. + +My next action will be to post an updated FAQ (which will hint at the +upcoming RFD) to comp.lang.misc; then finalize the 1.0.0 release and +put it on the ftp site. I'll also try to get it into +comp.sources.unix or .misc. And all this before the end of January! + +--Guido van Rossum, CWI, Amsterdam +URL: + +====================================================================== + +These are the steps required (in case you don't know about the +newsgroup creation process): + +First, we need to draw up an RFD (Request For Discussion). This is a +document that tells what the purpose of the group is, and gives a case +for its creation. We post this to relevant groups (comp.lang.misc, +the mailing list, news.groups, etc.) Discussion is held on +news.groups. + +Then, after a few weeks, we run the official CFV (Call For Votes). +The votes are then collected over a period of weeks. We need 100 more +yes votes than no votes, and a 2/3 majority, to get the group. + +There are some restrictions on the vote taker: [s]he cannot actively +campaign for/against the group during the vote process. So the main +benefit to Steve instead of me running the vote is that I will be free +to campaign for its creation! + +The following is our current draft for the RFD. + +====================================================================== + +Request For Discussion: comp.lang.python + + +Purpose +------- + +The newsgroup will be for discussion on the Python computer language. +Possible topics include requests for information, general programming, +development, and bug reports. The group will be unmoderated. + + +What is Python? +--------------- + +Python is a relatively new very-high-level language developed in +Amsterdam. Python is a simple, object-oriented procedural language, +with features taken from ABC, Icon, Modula-3, and C/C++. + +Its central goal is to provide the best of both worlds: the dynamic +nature of scripting languages like Perl/TCL/REXX, but also support for +general programming found in the more traditional languages like Icon, +C, Modula,... + +Python may be FTP'd from the following sites: + + ftp.cwi.nl in directory /pub/python (its "home site", also has a FAQ) + ftp.uu.net in directory /languages/python + gatekeeper.dec.com in directory /pub/plan/python/cwi + + +Rationale +--------- + +Currently there is a mailing list with over 130 subscribers. +The activity of this list is high, and to make handling the +traffic more reasonable, a newsgroup is being proposed. We +also feel that comp.lang.misc would not be a suitable forum +for this volume of discussion on a particular language. + + +Charter +------- + +Comp.lang.python is an unmoderated newsgroup which will serve +as a forum for discussing the Python computer language. The +group will serve both those who just program in Python and +those who work on developing the language. Topics that +may be discussed include: + + - announcements of new versions of the language and + applications written in Python. + + - discussion on the internals of the Python language. + + - general information about the language. + + - discussion on programming in Python. + + +Discussion +---------- + +Any objections to this RFD will be considered and, if determined +to be appropriate, will be incorporated. The discussion period +will be for a period of 21 days after which the first CFV will be +issued. diff --git a/Misc/fixfuncptrs.sh b/Misc/fixfuncptrs.sh new file mode 100755 index 0000000..f05809e --- /dev/null +++ b/Misc/fixfuncptrs.sh @@ -0,0 +1,47 @@ +prog=' +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_dealloc\*/\)$|\1(destructor)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_print\*/\)$|\1(printfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_getattr\*/\)$|\1(getattrfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_setattr\*/\)$|\1(setattrfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_compare\*/\)$|\1(cmpfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_repr\*/\)$|\1(reprfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*tp_hash\*/\)$|\1(hashfunc)\2 \3| + +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_length\*/\)$|\1(inquiry)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_concat\*/\)$|\1(binaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_repeat\*/\)$|\1(intargfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_item\*/\)$|\1(intargfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_slice\*/\)$|\1(intintargfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_ass_item\*/\)$|\1(intobjargproc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*sq_ass_slice\*/\)$|\1(intintobjargproc)\2 \3| + +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*mp_length\*/\)$|\1(inquiry)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*mp_subscript\*/\)$|\1(binaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*mp_ass_subscript\*/\)$|\1(objobjargproc)\2 \3| + +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_nonzero*\*/\)$|\1(inquiry)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_coerce*\*/\)$|\1(coercion)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_negative*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_positive*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_absolute*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_invert*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_int*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_long*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_float*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_oct*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_hex*\*/\)$|\1(unaryfunc)\2 \3| +s|^\([ ]*\)\([a-z_]*,\)[ ]*\(/\*nb_[a-z]*\*/\)$|\1(binaryfunc)\2 \3| + +' +for file +do + sed -e "$prog" $file >$file.new || break + if cmp -s $file $file.new + then + echo $file unchanged; rm $file.new + else + echo $file UPDATED + mv $file $file~ + mv $file.new $file + fi +done diff --git a/Misc/python-mode-old.el b/Misc/python-mode-old.el new file mode 100644 index 0000000..e748ca3 --- /dev/null +++ b/Misc/python-mode-old.el @@ -0,0 +1,1601 @@ +;;; Major mode for editing Python programs, version 1.08a +;; by: Tim Peters +;; after an original idea by: Michael A. Guravage +;; +;; Copyright (c) 1992,1993,1994 Tim Peters +;; +;; This software is provided as-is, without express or implied warranty. +;; Permission to use, copy, modify, distribute or sell this software, +;; without fee, for any purpose and by any individual or organization, is +;; hereby granted, provided that the above copyright notice and this +;; paragraph appear in all copies. +;; +;; +;; The following statements, placed in your .emacs file or site-init.el, +;; will cause this file to be autoloaded, and python-mode invoked, when +;; visiting .py files (assuming the file is in your load-path): +;; +;; (autoload 'python-mode "python-mode" "" t) +;; (setq auto-mode-alist +;; (cons '("\\.py$" . python-mode) auto-mode-alist)) + +(provide 'python-mode) + +;;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. +;;; This seems to be the standard way of checking this. + +(setq py-this-is-lucid-emacs-p (string-match "Lucid" emacs-version)) +(setq py-this-is-emacs-19-p + (and + (not py-this-is-lucid-emacs-p) + (string-match "^19\\." emacs-version))) + +;;; Constants and variables + +(defvar py-python-command "python" + "*Shell command used to start Python interpreter.") + +(defvar py-indent-offset 8 ; argue with Guido + "*Indentation increment. +Note that `\\[py-guess-indent-offset]' can usually guess a good value when you're +editing someone else's Python code.") + +(defvar py-continuation-offset 2 + "*Indentation (in addition to py-indent-offset) for continued lines. +The additional indentation given to the first continuation line in a +multi-line statement. Each subsequent continuation line in the +statement inherits its indentation from the line that precedes it, so if +you don't like the default indentation given to the first continuation +line, change it to something you do like and Python-mode will +automatically use that for the remaining continuation lines (or, until +you change the indentation again).") + +(defvar py-block-comment-prefix "##" + "*String used by py-comment-region to comment out a block of code. +This should follow the convention for non-indenting comment lines so +that the indentation commands won't get confused (i.e., the string +should be of the form `#x...' where `x' is not a blank or a tab, and +`...' is arbitrary).") + +(defvar py-scroll-process-buffer t + "*Scroll Python process buffer as output arrives. +If nil, the Python process buffer acts, with respect to scrolling, like +Shell-mode buffers normally act. This is surprisingly complicated and +so won't be explained here; in fact, you can't get the whole story +without studying the Emacs C code. + +If non-nil, the behavior is different in two respects (which are +slightly inaccurate in the interest of brevity): + + - If the buffer is in a window, and you left point at its end, the + window will scroll as new output arrives, and point will move to the + buffer's end, even if the window is not the selected window (that + being the one the cursor is in). The usual behavior for shell-mode + windows is not to scroll, and to leave point where it was, if the + buffer is in a window other than the selected window. + + - If the buffer is not visible in any window, and you left point at + its end, the buffer will be popped into a window as soon as more + output arrives. This is handy if you have a long-running + computation and don't want to tie up screen area waiting for the + output. The usual behavior for a shell-mode buffer is to stay + invisible until you explicitly visit it. + +Note the `and if you left point at its end' clauses in both of the +above: you can `turn off' the special behaviors while output is in +progress, by visiting the Python buffer and moving point to anywhere +besides the end. Then the buffer won't scroll, point will remain where +you leave it, and if you hide the buffer it will stay hidden until you +visit it again. You can enable and disable the special behaviors as +often as you like, while output is in progress, by (respectively) moving +point to, or away from, the end of the buffer. + +Warning: If you expect a large amount of output, you'll probably be +happier setting this option to nil. + +Obscure: `End of buffer' above should really say `at or beyond the +process mark', but if you know what that means you didn't need to be +told .") + +(defvar py-temp-directory + (let ( (ok '(lambda (x) + (and x + (setq x (expand-file-name x)) ; always true + (file-directory-p x) + (file-writable-p x) + x)))) + (or (funcall ok (getenv "TMPDIR")) + (funcall ok "/usr/tmp") + (funcall ok "/tmp") + (funcall ok ".") + (error + "Couldn't find a usable temp directory -- set py-temp-directory"))) + "*Directory used for temp files created by a *Python* process. +By default, the first directory from this list that exists and that you +can write into: the value (if any) of the environment variable TMPDIR, +/usr/tmp, /tmp, or the current directory.") + +;; have to bind py-file-queue before installing the kill-emacs hook +(defvar py-file-queue nil + "Queue of Python temp files awaiting execution. +Currently-active file is at the head of the list.") + +;; define a mode-specific abbrev table for those who use such things +(defvar python-mode-abbrev-table nil + "Abbrev table in use in python-mode buffers.") +(define-abbrev-table 'python-mode-abbrev-table nil) + +;; arrange to kill temp files no matter what +(if py-this-is-emacs-19-p + (add-hook 'kill-emacs-hook 'py-kill-emacs-hook) + ;; have to trust that other people are as respectful of our hook + ;; fiddling as we are of theirs + (if (boundp 'py-inherited-kill-emacs-hook) + ;; we were loaded before -- trust others not to have screwed us + ;; in the meantime (no choice, really) + nil + ;; else arrange for our hook to run theirs + (setq py-inherited-kill-emacs-hook kill-emacs-hook) + (setq kill-emacs-hook 'py-kill-emacs-hook))) + +(defvar py-beep-if-tab-change t + "*Ring the bell if tab-width is changed. +If a comment of the form +\t# vi:set tabsize=: +is found before the first code line when the file is entered, and +the current value of (the general Emacs variable) tab-width does not +equal , tab-width is set to , a message saying so is +displayed in the echo area, and if py-beep-if-tab-change is non-nil the +Emacs bell is also rung as a warning.") + +(defvar py-mode-map nil "Keymap used in Python mode buffers.") +(if py-mode-map + () + (setq py-mode-map (make-sparse-keymap)) + + ;; shadow global bindings for newline-and-indent w/ the py- version + (mapcar (function (lambda (key) + (define-key + py-mode-map key 'py-newline-and-indent))) + (where-is-internal 'newline-and-indent)) + + (mapcar (function + (lambda (x) + (define-key py-mode-map (car x) (cdr x)))) + '( ("\C-c\C-c" . py-execute-buffer) + ("\C-c|" . py-execute-region) + ("\C-c!" . py-shell) + ("\177" . py-delete-char) + ("\n" . py-newline-and-indent) + ("\C-c:" . py-guess-indent-offset) + ("\C-c\t" . py-indent-region) + ("\C-c<" . py-shift-region-left) + ("\C-c>" . py-shift-region-right) + ("\C-c\C-n" . py-next-statement) + ("\C-c\C-p" . py-previous-statement) + ("\C-c\C-u" . py-goto-block-up) + ("\C-c\C-b" . py-mark-block) + ("\C-c#" . py-comment-region) + ("\C-c?" . py-describe-mode) + ("\C-c\C-hm" . py-describe-mode) + ("\e\C-a" . beginning-of-python-def-or-class) + ("\e\C-e" . end-of-python-def-or-class) + ( "\e\C-h" . mark-python-def-or-class)))) + +(defvar py-mode-syntax-table nil "Python mode syntax table") +(if py-mode-syntax-table + () + (setq py-mode-syntax-table (make-syntax-table)) + (mapcar (function + (lambda (x) (modify-syntax-entry + (car x) (cdr x) py-mode-syntax-table))) + '(( ?\( . "()" ) ( ?\) . ")(" ) + ( ?\[ . "(]" ) ( ?\] . ")[" ) + ( ?\{ . "(}" ) ( ?\} . "){" ) + ;; fix operator symbols misassigned in the std table + ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." ) + ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." ) + ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." ) + ( ?\> . "." ) ( ?\| . "." ) + ( ?\_ . "w" ) ; underscore is legit in names + ( ?\' . "\"") ; single quote is string quote + ( ?\" . "\"" ) ; double quote is string quote too + ( ?\` . "$") ; backquote is open and close paren + ( ?\# . "<") ; hash starts comment + ( ?\n . ">")))) ; newline ends comment + +(defconst py-stringlit-re "'\\([^'\n\\]\\|\\\\.\\)*'" + "regexp matching a Python string literal") + +;; this is tricky because a trailing backslash does not mean +;; continuation if it's in a comment +(defconst py-continued-re + (concat + "\\(" "[^#'\n\\]" "\\|" py-stringlit-re "\\)*" + "\\\\$") + "regexp matching Python lines that are continued") + +(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)" + "regexp matching blank or comment lines") + +;;; General Functions + +(defun python-mode () + "Major mode for editing Python files. +Do `\\[py-describe-mode]' for detailed documentation. +Knows about Python indentation, tokens, comments and continuation lines. +Paragraphs are separated by blank lines only. + +COMMANDS +\\{py-mode-map} +VARIABLES + +py-indent-offset\tindentation increment +py-continuation-offset\textra indentation given to continuation lines +py-block-comment-prefix\tcomment string used by py-comment-region +py-python-command\tshell command to invoke Python interpreter +py-scroll-process-buffer\talways scroll Python process buffer +py-temp-directory\tdirectory used for temp files (if needed) +py-beep-if-tab-change\tring the bell if tab-width is changed" + (interactive) + (kill-all-local-variables) + (setq major-mode 'python-mode + mode-name "Python" + local-abbrev-table python-mode-abbrev-table) + (use-local-map py-mode-map) + (set-syntax-table py-mode-syntax-table) + + (mapcar (function (lambda (x) + (make-local-variable (car x)) + (set (car x) (cdr x)))) + '( (paragraph-separate . "^[ \t]*$") + (paragraph-start . "^[ \t]*$") + (require-final-newline . t) + (comment-start . "# ") + (comment-start-skip . "# *") + (comment-column . 40) + (indent-line-function . py-indent-line))) + + ;; hack to allow overriding the tabsize in the file (see tokenizer.c) + + ;; not sure where the magic comment has to be; to save time searching + ;; for a rarity, we give up if it's not found prior to the first + ;; executable statement + (let ( (case-fold-search nil) + (start (point)) + new-tab-width) + (if (re-search-forward + "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):" + (prog2 (py-next-statement 1) (point) (goto-char 1)) + t) + (progn + (setq new-tab-width + (string-to-int + (buffer-substring (match-beginning 1) (match-end 1)))) + (if (= tab-width new-tab-width) + nil + (setq tab-width new-tab-width) + (message "Caution: tab-width changed to %d" new-tab-width) + (if py-beep-if-tab-change (beep))))) + (goto-char start)) + + (run-hooks 'py-mode-hook)) + +;;; Functions that execute Python commands in a subprocess + +(defun py-shell () + "Start an interactive Python interpreter in another window. +This is like Shell mode, except that Python is running in the window +instead of a shell. See the `Interactive Shell' and `Shell Mode' +sections of the Emacs manual for details, especially for the key +bindings active in the `*Python*' buffer. + +See the docs for variable py-scroll-buffer for info on scrolling +behavior in the process window. + +Warning: Don't use an interactive Python if you change sys.ps1 or +sys.ps2 from their default values, or if you're running code that prints +`>>> ' or `... ' at the start of a line. Python mode can't distinguish +your output from Python's output, and assumes that `>>> ' at the start +of a line is a prompt from Python. Similarly, the Emacs Shell mode code +assumes that both `>>> ' and `... ' at the start of a line are Python +prompts. Bad things can happen if you fool either mode. + +Warning: If you do any editing *in* the process buffer *while* the +buffer is accepting output from Python, do NOT attempt to `undo' the +changes. Some of the output (nowhere near the parts you changed!) may +be lost if you do. This appears to be an Emacs bug, an unfortunate +interaction between undo and process filters; the same problem exists in +non-Python process buffers using the default (Emacs-supplied) process +filter." + (interactive) + (if py-this-is-emacs-19-p + (progn + (require 'comint) + (switch-to-buffer-other-window + (make-comint "Python" py-python-command))) + (progn + (require 'shell) + (switch-to-buffer-other-window + (make-shell "Python" py-python-command)))) + (make-local-variable 'shell-prompt-pattern) + (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ") + (set-process-filter (get-buffer-process (current-buffer)) + 'py-process-filter) + (set-syntax-table py-mode-syntax-table)) + +(defun py-execute-region (start end) + "Send the region between START and END to a Python interpreter. +If there is a *Python* process it is used. + +Hint: If you want to execute part of a Python file several times (e.g., +perhaps you're developing a function and want to flesh it out a bit at a +time), use `\\[narrow-to-region]' to restrict the buffer to the region of interest, +and send the code to a *Python* process via `\\[py-execute-buffer]' instead. + +Following are subtleties to note when using a *Python* process: + +If a *Python* process is used, the region is copied into a temp file (in +directory py-temp-directory), and an `execfile' command is sent to +Python naming that file. If you send regions faster than Python can +execute them, Python mode will save them into distinct temp files, and +execute the next one in the queue the next time it sees a `>>> ' prompt +from Python. Each time this happens, the process buffer is popped into +a window (if it's not already in some window) so you can see it, and a +comment of the form + +\t## working on region in file ... + +is inserted at the end. + +Caution: No more than 26 regions can be pending at any given time. This +limit is (indirectly) inherited from libc's mktemp(3). Python mode does +not try to protect you from exceeding the limit. It's extremely +unlikely that you'll get anywhere close to the limit in practice, unless +you're trying to be a jerk . + +See the `\\[py-shell]' docs for additional warnings." + (interactive "r") + (or (< start end) (error "Region is empty")) + (let ( (pyproc (get-process "Python")) + fname) + (if (null pyproc) + (shell-command-on-region start end py-python-command) + ;; else feed it thru a temp file + (setq fname (py-make-temp-name)) + (write-region start end fname nil 'no-msg) + (setq py-file-queue (append py-file-queue (list fname))) + (if (cdr py-file-queue) + (message "File %s queued for execution" fname) + ;; else + (py-execute-file pyproc fname))))) + +(defun py-execute-file (pyproc fname) + (py-append-to-process-buffer + pyproc + (format "## working on region in file %s ...\n" fname)) + (process-send-string pyproc (format "execfile('%s')\n" fname))) + +(defun py-process-filter (pyproc string) + (let ( (curbuf (current-buffer)) + (pbuf (process-buffer pyproc)) + (pmark (process-mark pyproc)) + file-finished) + + ;; make sure we switch to a different buffer at least once. if we + ;; *don't* do this, then if the process buffer is in the selected + ;; window, and point is before the end, and lots of output is coming + ;; at a fast pace, then (a) simple cursor-movement commands like + ;; C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time to have + ;; a visible effect (the window just doesn't get updated, sometimes + ;; for minutes(!)), and (b) it takes about 5x longer to get all the + ;; process output (until the next python prompt). + ;; + ;; #b makes no sense to me at all. #a almost makes sense: unless we + ;; actually change buffers, set_buffer_internal in buffer.c doesn't + ;; set windows_or_buffers_changed to 1, & that in turn seems to make + ;; the Emacs command loop reluctant to update the display. Perhaps + ;; the default process filter in process.c's read_process_output has + ;; update_mode_lines++ for a similar reason? beats me ... + (if (eq curbuf pbuf) ; mysterious ugly hack + (set-buffer (get-buffer-create "*scratch*"))) + + (set-buffer pbuf) + (let* ( (start (point)) + (goback (< start pmark)) + (buffer-read-only nil)) + (goto-char pmark) + (insert string) + (move-marker pmark (point)) + (setq file-finished + (and py-file-queue + (equal ">>> " + (buffer-substring + (prog2 (beginning-of-line) (point) + (goto-char pmark)) + (point))))) + (if goback (goto-char start) + ;; else + (if py-scroll-process-buffer + (let* ( (pop-up-windows t) + (pwin (display-buffer pbuf))) + (set-window-point pwin (point)))))) + (set-buffer curbuf) + (if file-finished + (progn + (py-delete-file-silently (car py-file-queue)) + (setq py-file-queue (cdr py-file-queue)) + (if py-file-queue + (py-execute-file pyproc (car py-file-queue))))))) + +(defun py-execute-buffer () + "Send the contents of the buffer to a Python interpreter. +If there is a *Python* process buffer it is used. If a clipping +restriction is in effect, only the accessible portion of the buffer is +sent. A trailing newline will be supplied if needed. + +See the `\\[py-execute-region]' docs for an account of some subtleties." + (interactive) + (py-execute-region (point-min) (point-max))) + + +;;; Functions for Python style indentation + +(defun py-delete-char () + "Reduce indentation or delete character. +If point is at the leftmost column, deletes the preceding newline. + +Else if point is at the leftmost non-blank character of a line that is +neither a continuation line nor a non-indenting comment line, or if +point is at the end of a blank line, reduces the indentation to match +that of the line that opened the current block of code. The line that +opened the block is displayed in the echo area to help you keep track of +where you are. + +Else the preceding character is deleted, converting a tab to spaces if +needed so that only a single column position is deleted." + (interactive "*") + (if (or (/= (current-indentation) (current-column)) + (bolp) + (py-continuation-line-p) + (looking-at "#[^ \t\n]")) ; non-indenting # + (backward-delete-char-untabify 1) + ;; else indent the same as the colon line that opened the block + + ;; force non-blank so py-goto-block-up doesn't ignore it + (insert-char ?* 1) + (backward-char) + (let ( (base-indent 0) ; indentation of base line + (base-text "") ; and text of base line + (base-found-p nil)) + (condition-case nil ; in case no enclosing block + (save-excursion + (py-goto-block-up 'no-mark) + (setq base-indent (current-indentation) + base-text (py-suck-up-leading-text) + base-found-p t)) + (error nil)) + (delete-char 1) ; toss the dummy character + (delete-horizontal-space) + (indent-to base-indent) + (if base-found-p + (message "Closes block: %s" base-text))))) + +(defun py-indent-line () + "Fix the indentation of the current line according to Python rules." + (interactive) + (let* ( (ci (current-indentation)) + (move-to-indentation-p (<= (current-column) ci)) + (need (py-compute-indentation)) ) + (if (/= ci need) + (save-excursion + (beginning-of-line) + (delete-horizontal-space) + (indent-to need))) + (if move-to-indentation-p (back-to-indentation)))) + +(defun py-newline-and-indent () + "Strives to act like the Emacs newline-and-indent. +This is just `strives to' because correct indentation can't be computed +from scratch for Python code. In general, deletes the whitespace before +point, inserts a newline, and takes an educated guess as to how you want +the new line indented." + (interactive) + (let ( (ci (current-indentation)) ) + (if (< ci (current-column)) ; if point beyond indentation + (newline-and-indent) + ;; else try to act like newline-and-indent "normally" acts + (beginning-of-line) + (insert-char ?\n 1) + (move-to-column ci)))) + +(defun py-compute-indentation () + (save-excursion + (beginning-of-line) + (cond + ;; are we on a continuation line? + ( (py-continuation-line-p) + (forward-line -1) + (if (py-continuation-line-p) ; on at least 3rd line in block + (current-indentation) ; so just continue the pattern + ;; else on 2nd line in block, so indent more + (+ (current-indentation) py-indent-offset + py-continuation-offset))) + ;; not on a continuation line + + ;; if at start of restriction, or on a non-indenting comment line, + ;; assume they intended whatever's there + ( (or (bobp) (looking-at "[ \t]*#[^ \t\n]")) + (current-indentation) ) + + ;; else indentation based on that of the statement that precedes + ;; us; use the first line of that statement to establish the base, + ;; in case the user forced a non-std indentation for the + ;; continuation lines (if any) + ( t + ;; skip back over blank & non-indenting comment lines + ;; note: will skip a blank or non-indenting comment line that + ;; happens to be a continuation line too + (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" + nil 'move) + (py-goto-initial-line) + (if (py-statement-opens-block-p) + (+ (current-indentation) py-indent-offset) + (current-indentation)))))) + +(defun py-guess-indent-offset (&optional global) + "Guess a good value for, and change, py-indent-offset. +By default (without a prefix arg), makes a buffer-local copy of +py-indent-offset with the new value. This will not affect any other +Python buffers. With a prefix arg, changes the global value of +py-indent-offset. This affects all Python buffers (that don't have +their own buffer-local copy), both those currently existing and those +created later in the Emacs session. + +Some people use a different value for py-indent-offset than you use. +There's no excuse for such foolishness, but sometimes you have to deal +with their ugly code anyway. This function examines the file and sets +py-indent-offset to what it thinks it was when they created the mess. + +Specifically, it searches forward from the statement containing point, +looking for a line that opens a block of code. py-indent-offset is set +to the difference in indentation between that line and the Python +statement following it. If the search doesn't succeed going forward, +it's tried again going backward." + (interactive "P") ; raw prefix arg + (let ( new-value + (start (point)) + restart + (found nil) + colon-indent) + (py-goto-initial-line) + (while (not (or found (eobp))) + (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) + (progn + (setq restart (point)) + (py-goto-initial-line) + (if (py-statement-opens-block-p) + (setq found t) + (goto-char restart))))) + (if found + () + (goto-char start) + (py-goto-initial-line) + (while (not (or found (bobp))) + (setq found + (and + (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) + (or (py-goto-initial-line) t) ; always true -- side effect + (py-statement-opens-block-p))))) + (setq colon-indent (current-indentation) + found (and found (zerop (py-next-statement 1))) + new-value (- (current-indentation) colon-indent)) + (goto-char start) + (if found + (progn + (funcall (if global 'kill-local-variable 'make-local-variable) + 'py-indent-offset) + (setq py-indent-offset new-value) + (message "%s value of py-indent-offset set to %d" + (if global "Global" "Local") + py-indent-offset)) + (error "Sorry, couldn't guess a value for py-indent-offset")))) + +(defun py-shift-region (start end count) + (save-excursion + (goto-char end) (beginning-of-line) (setq end (point)) + (goto-char start) (beginning-of-line) (setq start (point)) + (indent-rigidly start end count))) + +(defun py-shift-region-left (start end &optional count) + "Shift region of Python code to the left. +The lines from the line containing the start of the current region up +to (but not including) the line containing the end of the region are +shifted to the left, by py-indent-offset columns. + +If a prefix argument is given, the region is instead shifted by that +many columns." + (interactive "*r\nP") ; region; raw prefix arg + (py-shift-region start end + (- (prefix-numeric-value + (or count py-indent-offset))))) + +(defun py-shift-region-right (start end &optional count) + "Shift region of Python code to the right. +The lines from the line containing the start of the current region up +to (but not including) the line containing the end of the region are +shifted to the right, by py-indent-offset columns. + +If a prefix argument is given, the region is instead shifted by that +many columns." + (interactive "*r\nP") ; region; raw prefix arg + (py-shift-region start end (prefix-numeric-value + (or count py-indent-offset)))) + +(defun py-indent-region (start end &optional indent-offset) + "Reindent a region of Python code. +The lines from the line containing the start of the current region up +to (but not including) the line containing the end of the region are +reindented. If the first line of the region has a non-whitespace +character in the first column, the first line is left alone and the rest +of the region is reindented with respect to it. Else the entire region +is reindented with respect to the (closest code or indenting-comment) +statement immediately preceding the region. + +This is useful when code blocks are moved or yanked, when enclosing +control structures are introduced or removed, or to reformat code using +a new value for the indentation offset. + +If a numeric prefix argument is given, it will be used as the value of +the indentation offset. Else the value of py-indent-offset will be +used. + +Warning: The region must be consistently indented before this function +is called! This function does not compute proper indentation from +scratch (that's impossible in Python), it merely adjusts the existing +indentation to be correct in context. + +Warning: This function really has no idea what to do with non-indenting +comment lines, and shifts them as if they were indenting comment lines. +Fixing this appears to require telepathy. + +Special cases: whitespace is deleted from blank lines; continuation +lines are shifted by the same amount their initial line was shifted, in +order to preserve their relative indentation with respect to their +initial line; and comment lines beginning in column 1 are ignored." + + (interactive "*r\nP") ; region; raw prefix arg + (save-excursion + (goto-char end) (beginning-of-line) (setq end (point-marker)) + (goto-char start) (beginning-of-line) + (let ( (py-indent-offset (prefix-numeric-value + (or indent-offset py-indent-offset))) + (indents '(-1)) ; stack of active indent levels + (target-column 0) ; column to which to indent + (base-shifted-by 0) ; amount last base line was shifted + (indent-base (if (looking-at "[ \t\n]") + (py-compute-indentation) + 0)) + ci) + (while (< (point) end) + (setq ci (current-indentation)) + ;; figure out appropriate target column + (cond + ( (or (eq (following-char) ?#) ; comment in column 1 + (looking-at "[ \t]*$")) ; entirely blank + (setq target-column 0)) + ( (py-continuation-line-p) ; shift relative to base line + (setq target-column (+ ci base-shifted-by))) + (t ; new base line + (if (> ci (car indents)) ; going deeper; push it + (setq indents (cons ci indents)) + ;; else we should have seen this indent before + (setq indents (memq ci indents)) ; pop deeper indents + (if (null indents) + (error "Bad indentation in region, at line %d" + (save-restriction + (widen) + (1+ (count-lines 1 (point))))))) + (setq target-column (+ indent-base + (* py-indent-offset + (- (length indents) 2)))) + (setq base-shifted-by (- target-column ci)))) + ;; shift as needed + (if (/= ci target-column) + (progn + (delete-horizontal-space) + (indent-to target-column))) + (forward-line 1)))) + (set-marker end nil)) + +;;; Functions for moving point + +(defun py-previous-statement (count) + "Go to the start of previous Python statement. +If the statement at point is the i'th Python statement, goes to the +start of statement i-COUNT. If there is no such statement, goes to the +first statement. Returns count of statements left to move. +`Statements' do not include blank, comment, or continuation lines." + (interactive "p") ; numeric prefix arg + (if (< count 0) (py-next-statement (- count)) + (py-goto-initial-line) + (let ( start ) + (while (and + (setq start (point)) ; always true -- side effect + (> count 0) + (zerop (forward-line -1)) + (py-goto-statement-at-or-above)) + (setq count (1- count))) + (if (> count 0) (goto-char start))) + count)) + +(defun py-next-statement (count) + "Go to the start of next Python statement. +If the statement at point is the i'th Python statement, goes to the +start of statement i+COUNT. If there is no such statement, goes to the +last statement. Returns count of statements left to move. `Statements' +do not include blank, comment, or continuation lines." + (interactive "p") ; numeric prefix arg + (if (< count 0) (py-previous-statement (- count)) + (beginning-of-line) + (let ( start ) + (while (and + (setq start (point)) ; always true -- side effect + (> count 0) + (py-goto-statement-below)) + (setq count (1- count))) + (if (> count 0) (goto-char start))) + count)) + +(defun py-goto-block-up (&optional nomark) + "Move up to start of current block. +Go to the statement that starts the smallest enclosing block; roughly +speaking, this will be the closest preceding statement that ends with a +colon and is indented less than the statement you started on. If +successful, also sets the mark to the starting point. + +`\\[py-mark-block]' can be used afterward to mark the whole code block, if desired. + +If called from a program, the mark will not be set if optional argument +NOMARK is not nil." + (interactive) + (let ( (start (point)) + (found nil) + initial-indent) + (py-goto-initial-line) + ;; if on blank or non-indenting comment line, use the preceding stmt + (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") + (progn + (py-goto-statement-at-or-above) + (setq found (py-statement-opens-block-p)))) + ;; search back for colon line indented less + (setq initial-indent (current-indentation)) + (if (zerop initial-indent) + ;; force fast exit + (goto-char (point-min))) + (while (not (or found (bobp))) + (setq found + (and + (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) + (or (py-goto-initial-line) t) ; always true -- side effect + (< (current-indentation) initial-indent) + (py-statement-opens-block-p)))) + (if found + (progn + (or nomark (push-mark start)) + (back-to-indentation)) + (goto-char start) + (error "Enclosing block not found")))) + +(defun beginning-of-python-def-or-class (&optional class) + "Move point to start of def (or class, with prefix arg). + +Searches back for the closest preceding `def'. If you supply a prefix +arg, looks for a `class' instead. The docs assume the `def' case; just +substitute `class' for `def' for the other case. + +If point is in a def statement already, and after the `d', simply moves +point to the start of the statement. + +Else (point is not in a def statement, or at or before the `d' of a def +statement), searches for the closest preceding def statement, and leaves +point at its start. If no such statement can be found, leaves point at +the start of the buffer. + +Returns t iff a def statement is found by these rules. + +Note that doing this command repeatedly will take you closer to the start +of the buffer each time. + +If you want to mark the current def/class, see `\\[mark-python-def-or-class]'." + (interactive "P") ; raw prefix arg + (let ( (at-or-before-p (<= (current-column) (current-indentation))) + (start-of-line (progn (beginning-of-line) (point))) + (start-of-stmt (progn (py-goto-initial-line) (point)))) + (if (or (/= start-of-stmt start-of-line) + (not at-or-before-p)) + (end-of-line)) ; OK to match on this line + (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>") + nil 'move))) + +(defun end-of-python-def-or-class (&optional class) + "Move point beyond end of def (or class, with prefix arg) body. + +By default, looks for an appropriate `def'. If you supply a prefix arg, +looks for a `class' instead. The docs assume the `def' case; just +substitute `class' for `def' for the other case. + +If point is in a def statement already, this is the def we use. + +Else if the def found by `\\[beginning-of-python-def-or-class]' contains the statement you +started on, that's the def we use. + +Else we search forward for the closest following def, and use that. + +If a def can be found by these rules, point is moved to the start of the +line immediately following the def block, and the position of the start +of the def is returned. + +Else point is moved to the end of the buffer, and nil is returned. + +Note that doing this command repeatedly will take you closer to the end +of the buffer each time. + +If you want to mark the current def/class, see `\\[mark-python-def-or-class]'." + (interactive "P") ; raw prefix arg + (let ( (start (progn (py-goto-initial-line) (point))) + (which (if class "class" "def")) + (state 'not-found)) + ;; move point to start of appropriate def/class + (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one + (setq state 'at-beginning) + ;; else see if beginning-of-python-def-or-class hits container + (if (and (beginning-of-python-def-or-class class) + (progn (py-goto-beyond-block) + (> (point) start))) + (setq state 'at-end) + ;; else search forward + (goto-char start) + (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move) + (progn (setq state 'at-beginning) + (beginning-of-line))))) + (cond + ((eq state 'at-beginning) (py-goto-beyond-block) t) + ((eq state 'at-end) t) + ((eq state 'not-found) nil) + (t (error "internal error in end-of-python-def-or-class"))))) + +;;; Functions for marking regions + +(defun py-mark-block (&optional extend just-move) + "Mark following block of lines. With prefix arg, mark structure. +Easier to use than explain. It sets the region to an `interesting' +block of succeeding lines. If point is on a blank line, it goes down to +the next non-blank line. That will be the start of the region. The end +of the region depends on the kind of line at the start: + + - If a comment, the region will include all succeeding comment lines up + to (but not including) the next non-comment line (if any). + + - Else if a prefix arg is given, and the line begins one of these + structures: +\tif elif else try except finally for while def class + the region will be set to the body of the structure, including + following blocks that `belong' to it, but excluding trailing blank + and comment lines. E.g., if on a `try' statement, the `try' block + and all (if any) of the following `except' and `finally' blocks that + belong to the `try' structure will be in the region. Ditto for + if/elif/else, for/else and while/else structures, and (a bit + degenerate, since they're always one-block structures) def and class + blocks. + + - Else if no prefix argument is given, and the line begins a Python + block (see list above), and the block is not a `one-liner' (i.e., the + statement ends with a colon, not with code), the region will include + all succeeding lines up to (but not including) the next code + statement (if any) that's indented no more than the starting line, + except that trailing blank and comment lines are excluded. E.g., if + the starting line begins a multi-statement `def' structure, the + region will be set to the full function definition, but without any + trailing `noise' lines. + + - Else the region will include all succeeding lines up to (but not + including) the next blank line, or code or indenting-comment line + indented strictly less than the starting line. Trailing indenting + comment lines are included in this case, but not trailing blank + lines. + +A msg identifying the location of the mark is displayed in the echo +area; or do `\\[exchange-point-and-mark]' to flip down to the end. + +If called from a program, optional argument EXTEND plays the role of the +prefix arg, and if optional argument JUST-MOVE is not nil, just moves to +the end of the block (& does not set mark or display a msg)." + + (interactive "P") ; raw prefix arg + (py-goto-initial-line) + ;; skip over blank lines + (while (and + (looking-at "[ \t]*$") ; while blank line + (not (eobp))) ; & somewhere to go + (forward-line 1)) + (if (eobp) + (error "Hit end of buffer without finding a non-blank stmt")) + (let ( (initial-pos (point)) + (initial-indent (current-indentation)) + last-pos ; position of last stmt in region + (followers + '( (if elif else) (elif elif else) (else) + (try except finally) (except except) (finally) + (for else) (while else) + (def) (class) ) ) + first-symbol next-symbol) + + (cond + ;; if comment line, suck up the following comment lines + ((looking-at "[ \t]*#") + (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment + (re-search-backward "^[ \t]*#") ; and back to last comment in block + (setq last-pos (point))) + + ;; else if line is a block line and EXTEND given, suck up + ;; the whole structure + ((and extend + (setq first-symbol (py-suck-up-first-keyword) ) + (assq first-symbol followers)) + (while (and + (or (py-goto-beyond-block) t) ; side effect + (forward-line -1) ; side effect + (setq last-pos (point)) ; side effect + (py-goto-statement-below) + (= (current-indentation) initial-indent) + (setq next-symbol (py-suck-up-first-keyword)) + (memq next-symbol (cdr (assq first-symbol followers)))) + (setq first-symbol next-symbol))) + + ;; else if line *opens* a block, search for next stmt indented <= + ((py-statement-opens-block-p) + (while (and + (setq last-pos (point)) ; always true -- side effect + (py-goto-statement-below) + (> (current-indentation) initial-indent)) + nil)) + + ;; else plain code line; stop at next blank line, or stmt or + ;; indenting comment line indented < + (t + (while (and + (setq last-pos (point)) ; always true -- side effect + (or (py-goto-beyond-final-line) t) + (not (looking-at "[ \t]*$")) ; stop at blank line + (or + (>= (current-indentation) initial-indent) + (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting # + nil))) + + ;; skip to end of last stmt + (goto-char last-pos) + (py-goto-beyond-final-line) + + ;; set mark & display + (if just-move + () ; just return + (push-mark (point) 'no-msg) + (forward-line -1) + (message "Mark set after: %s" (py-suck-up-leading-text)) + (goto-char initial-pos)))) + +(defun mark-python-def-or-class (&optional class) + "Set region to body of def (or class, with prefix arg) enclosing point. +Pushes the current mark, then point, on the mark ring (all language +modes do this, but although it's handy it's never documented ...). + +In most Emacs language modes, this function bears at least a +hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and `\\[beginning-of-python-def-or-class]'. + +And in earlier versions of Python mode, all 3 were tightly connected. +Turned out that was more confusing than useful: the `goto start' and +`goto end' commands are usually used to search through a file, and people +expect them to act a lot like `search backward' and `search forward' +string-search commands. But because Python `def' and `class' can nest to +arbitrary levels, finding the smallest def containing point cannot be +done via a simple backward search: the def containing point may not be +the closest preceding def, or even the closest preceding def that's +indented less. The fancy algorithm required is appropriate for the usual +uses of this `mark' command, but not for the `goto' variations. + +So the def marked by this command may not be the one either of the `goto' +commands find: If point is on a blank or non-indenting comment line, +moves back to start of the closest preceding code statement or indenting +comment line. If this is a `def' statement, that's the def we use. Else +searches for the smallest enclosing `def' block and uses that. Else +signals an error. + +When an enclosing def is found: The mark is left immediately beyond the +last line of the def block. Point is left at the start of the def, +except that: if the def is preceded by a number of comment lines +followed by (at most) one optional blank line, point is left at the start +of the comments; else if the def is preceded by a blank line, point is +left at its start. + +The intent is to mark the containing def/class and its associated +documentation, to make moving and duplicating functions and classes +pleasant." + (interactive "P") ; raw prefix arg + (let ( (start (point)) + (which (if class "class" "def"))) + (push-mark start) + (if (not (py-go-up-tree-to-keyword which)) + (progn (goto-char start) + (error "Enclosing %s not found" which)) + ;; else enclosing def/class found + (setq start (point)) + (py-goto-beyond-block) + (push-mark (point)) + (goto-char start) + (if (zerop (forward-line -1)) ; if there is a preceding line + (progn + (if (looking-at "[ \t]*$") ; it's blank + (setq start (point)) ; so reset start point + (goto-char start)) ; else try again + (if (zerop (forward-line -1)) + (if (looking-at "[ \t]*#") ; a comment + ;; look back for non-comment line + ;; tricky: note that the regexp matches a blank + ;; line, cuz \n is in the 2nd character class + (and + (re-search-backward "^[ \t]*[^ \t#]" nil 'move) + (forward-line 1)) + ;; no comment, so go back + (goto-char start)))))))) + +(defun py-comment-region (start end &optional uncomment-p) + "Comment out region of code; with prefix arg, uncomment region. +The lines from the line containing the start of the current region up +to (but not including) the line containing the end of the region are +commented out, by inserting the string py-block-comment-prefix at the +start of each line. With a prefix arg, removes py-block-comment-prefix +from the start of each line instead." + (interactive "*r\nP") ; region; raw prefix arg + (goto-char end) (beginning-of-line) (setq end (point)) + (goto-char start) (beginning-of-line) (setq start (point)) + (let ( (prefix-len (length py-block-comment-prefix)) ) + (save-excursion + (save-restriction + (narrow-to-region start end) + (while (not (eobp)) + (if uncomment-p + (and (string= py-block-comment-prefix + (buffer-substring + (point) (+ (point) prefix-len))) + (delete-char prefix-len)) + (insert py-block-comment-prefix)) + (forward-line 1)))))) + +;;; Documentation functions + +;; dump the long form of the mode blurb; does the usual doc escapes, +;; plus lines of the form ^[vc]:name$ to suck variable & command +;; docs out of the right places, along with the keys they're on & +;; current values +(defun py-dump-help-string (str) + (with-output-to-temp-buffer "*Help*" + (let ( (locals (buffer-local-variables)) + funckind funcname func funcdoc + (start 0) mstart end + keys ) + (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start) + (setq mstart (match-beginning 0) end (match-end 0) + funckind (substring str (match-beginning 1) (match-end 1)) + funcname (substring str (match-beginning 2) (match-end 2)) + func (intern funcname)) + (princ (substitute-command-keys (substring str start mstart))) + (cond + ( (equal funckind "c") ; command + (setq funcdoc (documentation func) + keys (concat + "Key(s): " + (mapconcat 'key-description + (where-is-internal func py-mode-map) + ", ")))) + ( (equal funckind "v") ; variable + (setq funcdoc (substitute-command-keys + (get func 'variable-documentation)) + keys (if (assq func locals) + (concat + "Local/Global values: " + (prin1-to-string (symbol-value func)) + " / " + (prin1-to-string (default-value func))) + (concat + "Value: " + (prin1-to-string (symbol-value func)))))) + ( t ; unexpected + (error "Error in py-dump-help-string, tag `%s'" funckind))) + (princ (format "\n-> %s:\t%s\t%s\n\n" + (if (equal funckind "c") "Command" "Variable") + funcname keys)) + (princ funcdoc) + (terpri) + (setq start end)) + (princ (substitute-command-keys (substring str start)))) + (print-help-return-message))) + +(defun py-describe-mode () + "Dump long form of Python-mode docs." + (interactive) + (py-dump-help-string "Major mode for editing Python files. +Knows about Python indentation, tokens, comments and continuation lines. +Paragraphs are separated by blank lines only. + +Major sections below begin with the string `@'; specific function and +variable docs begin with `->'. + +@EXECUTING PYTHON CODE + +\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter +\\[py-execute-region]\tsends the current region +\\[py-shell]\tstarts a Python interpreter window; this will be used by +\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands +%c:py-execute-buffer +%c:py-execute-region +%c:py-shell + +@VARIABLES + +py-indent-offset\tindentation increment +py-continuation-offset\textra indentation given to continuation lines +py-block-comment-prefix\tcomment string used by py-comment-region + +py-python-command\tshell command to invoke Python interpreter +py-scroll-process-buffer\talways scroll Python process buffer +py-temp-directory\tdirectory used for temp files (if needed) + +py-beep-if-tab-change\tring the bell if tab-width is changed +%v:py-indent-offset +%v:py-continuation-offset +%v:py-block-comment-prefix +%v:py-python-command +%v:py-scroll-process-buffer +%v:py-temp-directory +%v:py-beep-if-tab-change + +@KINDS OF LINES + +Each physical line in the file is either a `continuation line' (the +preceding line ends with a backslash that's not part of a comment, or the +paren/bracket/brace nesting level at the start of the line is non-zero, +or both) or an `initial line' (everything else). + +An initial line is in turn a `blank line' (contains nothing except +possibly blanks or tabs), a `comment line' (leftmost non-blank character +is `#'), or a `code line' (everything else). + +Comment Lines + +Although all comment lines are treated alike by Python, Python mode +recognizes two kinds that act differently with respect to indentation. + +An `indenting comment line' is a comment line with a blank, tab or +nothing after the initial `#'. The indentation commands (see below) +treat these exactly as if they were code lines: a line following an +indenting comment line will be indented like the comment line. All +other comment lines (those with a non-whitespace character immediately +following the initial `#') are `non-indenting comment lines', and their +indentation is ignored by the indentation commands. + +Indenting comment lines are by far the usual case, and should be used +whenever possible. Non-indenting comment lines are useful in cases like +these: + +\ta = b # a very wordy single-line comment that ends up being +\t #... continued onto another line + +\tif a == b: +##\t\tprint 'panic!' # old code we've `commented out' +\t\treturn a + +Since the `#...' and `##' comment lines have a non-whitespace character +following the initial `#', Python mode ignores them when computing the +proper indentation for the next line. + +Continuation Lines and Statements + +The Python-mode commands generally work on statements instead of on +individual lines, where a `statement' is a comment or blank line, or a +code line and all of its following continuation lines (if any) +considered as a single logical unit. The commands in this mode +generally (when it makes sense) automatically move to the start of the +statement containing point, even if point happens to be in the middle of +some continuation line. + +A Bad Idea + +Always put something on the initial line of a multi-line statement +besides the backslash! E.g., don't do this: + +\t\\ +\ta = b # what's the indentation of this stmt? + +While that's legal Python, it's silly & would be very expensive for +Python mode to handle correctly. + +@INDENTATION + +Primarily for entering new code: +\t\\[indent-for-tab-command]\t indent line appropriately +\t\\[py-newline-and-indent]\t insert newline, then indent +\t\\[py-delete-char]\t reduce indentation, or delete single character + +Primarily for reindenting existing code: +\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally +\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally + +\t\\[py-indent-region]\t reindent region to match its context +\t\\[py-shift-region-left]\t shift region left by py-indent-offset +\t\\[py-shift-region-right]\t shift region right by py-indent-offset + +Unlike most programming languages, Python uses indentation, and only +indentation, to specify block structure. Hence the indentation supplied +automatically by Python-mode is just an educated guess: only you know +the block structure you intend, so only you can supply correct +indentation. + +The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on +the indentation of preceding statements. E.g., assuming +py-indent-offset is 4, after you enter +\tif a > 0: \\[py-newline-and-indent] +the cursor will be moved to the position of the `_' (_ is not a +character in the file, it's just used here to indicate the location of +the cursor): +\tif a > 0: +\t _ +If you then enter `c = d' \\[py-newline-and-indent], the cursor will move +to +\tif a > 0: +\t c = d +\t _ +Python-mode cannot know whether that's what you intended, or whether +\tif a > 0: +\t c = d +\t_ +was your intent. In general, Python-mode either reproduces the +indentation of the (closest code or indenting-comment) preceding +statement, or adds an extra py-indent-offset blanks if the preceding +statement has `:' as its last significant (non-whitespace and non- +comment) character. If the suggested indentation is too much, use +\\[py-delete-char] to reduce it. + +Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command] +repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block +structure you intend. +%c:indent-for-tab-command +%c:py-newline-and-indent +%c:py-delete-char + + +The next function may be handy when editing code you didn't write: +%c:py-guess-indent-offset + + +The remaining `indent' functions apply to a region of Python code. They +assume the block structure (equals indentation, in Python) of the region +is correct, and alter the indentation in various ways while preserving +the block structure: +%c:py-indent-region +%c:py-shift-region-left +%c:py-shift-region-right + +@MARKING & MANIPULATING REGIONS OF CODE + +\\[py-mark-block]\t mark block of lines +\\[mark-python-def-or-class]\t mark smallest enclosing def +\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class +\\[py-comment-region]\t comment out region of code +\\[universal-argument] \\[py-comment-region]\t uncomment region of code +%c:py-mark-block +%c:mark-python-def-or-class +%c:py-comment-region + +@MOVING POINT + +\\[py-previous-statement]\t move to statement preceding point +\\[py-next-statement]\t move to statement following point +\\[py-goto-block-up]\t move up to start of current block +\\[beginning-of-python-def-or-class]\t move to start of def +\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class +\\[end-of-python-def-or-class]\t move to end of def +\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class + +The first two move to one statement beyond the statement that contains +point. A numeric prefix argument tells them to move that many +statements instead. Blank lines, comment lines, and continuation lines +do not count as `statements' for these commands. So, e.g., you can go +to the first code statement in a file by entering +\t\\[beginning-of-buffer]\t to move to the top of the file +\t\\[py-next-statement]\t to skip over initial comments and blank lines +Or do `\\[py-previous-statement]' with a huge prefix argument. +%c:py-previous-statement +%c:py-next-statement +%c:py-goto-block-up +%c:beginning-of-python-def-or-class +%c:end-of-python-def-or-class + +@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE + +`\\[indent-new-comment-line]' is handy for entering a multi-line comment. + +`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the +overall class and def structure of a module. + +`\\[back-to-indentation]' moves point to a line's first non-blank character. + +`\\[indent-relative]' is handy for creating odd indentation. + +@OTHER EMACS HINTS + +If you don't like the default value of a variable, change its value to +whatever you do like by putting a `setq' line in your .emacs file. +E.g., to set the indentation increment to 4, put this line in your +.emacs: +\t(setq py-indent-offset 4) +To see the value of a variable, do `\\[describe-variable]' and enter the variable +name at the prompt. + +When entering a key sequence like `C-c C-n', it is not necessary to +release the CONTROL key after doing the `C-c' part -- it suffices to +press the CONTROL key, press and release `c' (while still holding down +CONTROL), press and release `n' (while still holding down CONTROL), & +then release CONTROL. + +Entering Python mode calls with no arguments the value of the variable +`py-mode-hook', if that value exists and is not nil; see the `Hooks' +section of the Elisp manual for details. + +Obscure: When python-mode is first loaded, it looks for all bindings +to newline-and-indent in the global keymap, and shadows them with +local bindings to py-newline-and-indent.")) + +;;; Helper functions + +(defvar py-parse-state-re + (concat + "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>" + "\\|" + "^[^ #\t\n]")) +;; returns the parse state at point (see parse-partial-sexp docs) +(defun py-parse-state () + (save-excursion + (let ( (here (point)) ) + ;; back up to the first preceding line (if any; else start of + ;; buffer) that begins with a popular Python keyword, or a non- + ;; whitespace and non-comment character. These are good places to + ;; start parsing to see whether where we started is at a non-zero + ;; nesting level. It may be slow for people who write huge code + ;; blocks or huge lists ... tough beans. + (re-search-backward py-parse-state-re nil 'move) + (beginning-of-line) + (parse-partial-sexp (point) here)))) + +;; if point is at a non-zero nesting level, returns the number of the +;; character that opens the smallest enclosing unclosed list; else +;; returns nil. +(defun py-nesting-level () + (let ( (status (py-parse-state)) ) + (if (zerop (car status)) + nil ; not in a nest + (car (cdr status))))) ; char# of open bracket + +;; t iff preceding line ends with backslash that's not in a comment +(defun py-backslash-continuation-line-p () + (save-excursion + (beginning-of-line) + (and + ;; use a cheap test first to avoid the regexp if possible + ;; use 'eq' because char-after may return nil + (eq (char-after (- (point) 2)) ?\\ ) + ;; make sure; since eq test passed, there is a preceding line + (forward-line -1) ; always true -- side effect + (looking-at py-continued-re)))) + +;; t iff current line is a continuation line +(defun py-continuation-line-p () + (save-excursion + (beginning-of-line) + (or (py-backslash-continuation-line-p) + (py-nesting-level)))) + +;; go to initial line of current statement; usually this is the +;; line we're on, but if we're on the 2nd or following lines of a +;; continuation block, we need to go up to the first line of the block. +;; +;; Tricky: We want to avoid quadratic-time behavior for long continued +;; blocks, whether of the backslash or open-bracket varieties, or a mix +;; of the two. The following manages to do that in the usual cases. +(defun py-goto-initial-line () + (let ( open-bracket-pos ) + (while (py-continuation-line-p) + (beginning-of-line) + (if (py-backslash-continuation-line-p) + (while (py-backslash-continuation-line-p) + (forward-line -1)) + ;; else zip out of nested brackets/braces/parens + (while (setq open-bracket-pos (py-nesting-level)) + (goto-char open-bracket-pos))))) + (beginning-of-line)) + +;; go to point right beyond final line of current statement; usually +;; this is the start of the next line, but if this is a multi-line +;; statement we need to skip over the continuation lines. +;; Tricky: Again we need to be clever to avoid quadratic time behavior. +(defun py-goto-beyond-final-line () + (forward-line 1) + (let ( state ) + (while (and (py-continuation-line-p) + (not (eobp))) + ;; skip over the backslash flavor + (while (and (py-backslash-continuation-line-p) + (not (eobp))) + (forward-line 1)) + ;; if in nest, zip to the end of the nest + (setq state (py-parse-state)) + (if (and (not (zerop (car state))) + (not (eobp))) + (progn + ;; BUG ALERT: I could swear, from reading the docs, that + ;; the 3rd argument should be plain 0 + (parse-partial-sexp (point) (point-max) (- 0 (car state)) + nil state) + (forward-line 1)))))) + +;; t iff statement opens a block == iff it ends with a colon that's +;; not in a comment +;; point should be at the start of a statement +(defun py-statement-opens-block-p () + (save-excursion + (let ( (start (point)) + (finish (progn (py-goto-beyond-final-line) (1- (point)))) + (searching t) + (answer nil) + state) + (goto-char start) + (while searching + ;; look for a colon with nothing after it except whitespace, and + ;; maybe a comment + (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$" + finish t) + (if (eq (point) finish) ; note: no `else' clause; just + ; keep searching if we're not at + ; the end yet + ;; sure looks like it opens a block -- but it might + ;; be in a comment + (progn + (setq searching nil) ; search is done either way + (setq state (parse-partial-sexp start + (match-beginning 0))) + (setq answer (not (nth 4 state))))) + ;; search failed: couldn't find another interesting colon + (setq searching nil))) + answer))) + +;; go to point right beyond final line of block begun by the current +;; line. This is the same as where py-goto-beyond-final-line goes +;; unless we're on colon line, in which case we go to the end of the +;; block. +;; assumes point is at bolp +(defun py-goto-beyond-block () + (if (py-statement-opens-block-p) + (py-mark-block nil 'just-move) + (py-goto-beyond-final-line))) + +;; go to start of first statement (not blank or comment or continuation +;; line) at or preceding point +;; returns t if there is one, else nil +(defun py-goto-statement-at-or-above () + (py-goto-initial-line) + (if (looking-at py-blank-or-comment-re) + ;; skip back over blank & comment lines + ;; note: will skip a blank or comment line that happens to be + ;; a continuation line too + (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t) + (progn (py-goto-initial-line) t) + nil) + t)) + +;; go to start of first statement (not blank or comment or continuation +;; line) following the statement containing point +;; returns t if there is one, else nil +(defun py-goto-statement-below () + (beginning-of-line) + (let ( (start (point)) ) + (py-goto-beyond-final-line) + (while (and + (looking-at py-blank-or-comment-re) + (not (eobp))) + (forward-line 1)) + (if (eobp) + (progn (goto-char start) nil) + t))) + +;; go to start of statement, at or preceding point, starting with keyword +;; KEY. Skips blank lines and non-indenting comments upward first. If +;; that statement starts with KEY, done, else go back to first enclosing +;; block starting with KEY. +;; If successful, leaves point at the start of the KEY line & returns t. +;; Else leaves point at an undefined place & returns nil. +(defun py-go-up-tree-to-keyword (key) + ;; skip blanks and non-indenting # + (py-goto-initial-line) + (while (and + (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") + (zerop (forward-line -1))) ; go back + nil) + (py-goto-initial-line) + (let* ( (re (concat "[ \t]*" key "\\b")) + (case-fold-search nil) ; let* so looking-at sees this + (found (looking-at re)) + (dead nil)) + (while (not (or found dead)) + (condition-case nil ; in case no enclosing block + (py-goto-block-up 'no-mark) + (error (setq dead t))) + (or dead (setq found (looking-at re)))) + (beginning-of-line) + found)) + +;; return string in buffer from start of indentation to end of line; +;; prefix "..." if leading whitespace was skipped +(defun py-suck-up-leading-text () + (save-excursion + (back-to-indentation) + (concat + (if (bolp) "" "...") + (buffer-substring (point) (progn (end-of-line) (point)))))) + +;; assuming point at bolp, return first keyword ([a-z]+) on the line, +;; as a Lisp symbol; return nil if none +(defun py-suck-up-first-keyword () + (let ( (case-fold-search nil) ) + (if (looking-at "[ \t]*\\([a-z]+\\)\\b") + (intern (buffer-substring (match-beginning 1) (match-end 1))) + nil))) + +(defun py-make-temp-name () + (make-temp-name + (concat (file-name-as-directory py-temp-directory) "python"))) + +(defun py-delete-file-silently (fname) + (condition-case nil + (delete-file fname) + (error nil))) + +(defun py-kill-emacs-hook () + ;; delete our temp files + (while py-file-queue + (py-delete-file-silently (car py-file-queue)) + (setq py-file-queue (cdr py-file-queue))) + (if (not py-this-is-emacs-19-p) + ;; run the hook we inherited, if any + (and py-inherited-kill-emacs-hook + (funcall py-inherited-kill-emacs-hook)))) + +;; make PROCESS's buffer visible, append STRING to it, and force display; +;; also make shell-mode believe the user typed this string, so that +;; kill-output-from-shell and show-output-from-shell work "right" +(defun py-append-to-process-buffer (process string) + (let ( (cbuf (current-buffer)) + (pbuf (process-buffer process)) + (py-scroll-process-buffer t)) + (set-buffer pbuf) + (goto-char (point-max)) + (move-marker (process-mark process) (point)) + (if (not py-this-is-emacs-19-p) + (move-marker last-input-start (point))) ; muck w/ shell-mode + (funcall (process-filter process) process string) + (if (not py-this-is-emacs-19-p) + (move-marker last-input-end (point))) ; muck w/ shell-mode + (set-buffer cbuf)) + (sit-for 0)) + +;; To do: +;; - support for ptags diff --git a/Misc/python.gif b/Misc/python.gif new file mode 100644 index 0000000..4c94b3d Binary files /dev/null and b/Misc/python.gif differ diff --git a/Misc/python.man b/Misc/python.man new file mode 100644 index 0000000..206f8ba --- /dev/null +++ b/Misc/python.man @@ -0,0 +1,247 @@ +.TH PYTHON "3 January 1994" +.SH NAME +python \- an interpreted, interactive, object-oriented programming language +.SH SYNOPSIS +.B python +[ +.I X11-options +] +[ +.B \-d +] +[ +.B \-i +] +[ +.B \-k +] +[ +.B \-v +] +[ +.B \-c +.I command +| +.I script +| +\- +] +[ +.I arguments +] +.SH DESCRIPTION +Python is an interpreted, interactive, object-oriented programming +language that combines remarkable power with very clear syntax. +For an introduction to programming in Python you are referred to the +Python Tutorial. +The Python Library Reference documents built-in and standard types, +constants, functions and modules. +Finally, the Python Reference Manual describes the syntax and +semantics of the core language in (perhaps too) much detail. +.PP +Python's basic power can be extended with your own modules written in +C or C++. +On some (most?) systems such modules may be dynamically loaded. +Python is also adaptable as an extension language for existing +applications. +See the internal documentation for hints. +.SH COMMAND LINE OPTIONS +.TP +.TP +.B \-d +Turn on parser debugging output (for wizards only, depending on +compilation options). +.B \-i +When a script is passed as first argument or the \fB\-c\fP option is +used, enter interactive mode after executing the script or the +command. This can be useful to inspect global variables or a stack +trace when a script raises an exception. +.TP +.B \-i +When executing a program from a file, this option enters interactive +mode after the program has completed. It does not read the +$PYTHONSTARTUP file. +.TP +.B \-k +This hack, eh, feature is intended to help you to find expression +statements that print a value. Although a feature of the language, it +can sometimes be annoying that when a function is called which returns +a value that is not +.IR None , +the value is printed to standard output, and it is not always easy to +find which statement is the cause of an unwanted `1', for instance. +When this option is set, if an expression statement prints its value, +the exception +.I RuntimeError +is raised. The resulting stack trace will help you to track down the +culprit. +.TP +.B \-v +Print a message each time a module is initialized, showing the place +(filename or built-in module) from which it is loaded. +.TP +.BI "\-c " command +Specify the command to execute (see next section). +This terminates the option list (following options are passed as +arguments to the command). +.PP +When the interpreter is configured to contain the +.I stdwin +built-in module for use with the X window system, additional command +line options common to most X applications are recognized (by STDWIN), +e.g. +.B \-display +.I displayname +and +.B \-geometry +.I widthxheight+x+y. +The complete set of options is described in the STDWIN documentation. +.SH INTERPRETER INTERFACE +The interpreter interface resembles that of the UNIX shell: when +called with standard input connected to a tty device, it prompts for +commands and executes them until an EOF is read; when called with a +file name argument or with a file as standard input, it reads and +executes a +.I script +from that file; +when called with +.B \-c +.I command, +it executes the Python statement(s) given as +.I command. +Here +.I command +may contain multiple statements separated by newlines. +Leading whitespace is significant in Python statements! +In non-interactive mode, the entire input is parsed befored it is +executed. +.PP +If available, the script name and additional arguments thereafter are +passed to the script in the Python variable +.I sys.argv , +which is a list of strings (you must first +.I import sys +to be able to access it). +If no script name is given, +.I sys.argv +is empty; if +.B \-c +is used, +.I sys.argv[0] +contains the string +.I '-c'. +Note that options interpreter by the Python interpreter or by STDWIN +are not placed in +.I sys.argv. +.PP +In interactive mode, the primary prompt is `>>>'; the second prompt +(which appears when a command is not complete) is `...'. +The prompts can be changed by assignment to +.I sys.ps1 +or +.I sys.ps2. +The interpreter quits when it reads an EOF at a prompt. +When an unhandled exception occurs, a stack trace is printed and +control returns to the primary prompt; in non-interactive mode, the +interpreter exits after printing the stack trace. +The interrupt signal raises the +.I Keyboard\%Interrupt +exception; other UNIX signals are not caught (except that SIGPIPE is +sometimes ignored, in favor of the +.I IOError +exception). Error messages are written to stderr. +.SH FILES AND DIRECTORIES +These are subject to difference depending on local installation +conventions: +.IP /usr/local/bin/python +Recommended location of the interpreter. +.IP /usr/local/lib/python +Recommended location of the directory containing the standard modules. +.SH ENVIRONMENT VARIABLES +.IP PYTHONPATH +Augments the default search path for module files. +The format is the same as the shell's $PATH: one or more directory +pathnames separated by colons. +Non-existant directories are silently ignored. +The default search path is installation dependent, but always begins +with `.', (for example, +.I .:/usr/local/lib/python ). +The default search path is appended to $PYTHONPATH. +The search path can be manipulated from within a Python program as the +variable +.I sys.path . +.IP PYTHONSTARTUP +If this is the name of a readable file, the Python commands in that +file are executed before the first prompt is displayed in interactive +mode. +The file is executed in the same name space where interactive commands +are executed so that objects defined or imported in it can be used +without qualification in the interactive session. +You can also change the prompts +.I sys.ps1 +and +.I sys.ps2 +in this file. +.IP PYTHONDEBUG +If this is set to a non-empty string it is equivalent to specifying +the \fB\-d\fP option. +.IP PYTHONINSPECT +If this is set to a non-empty string it is equivalent to specifying +the \fB\-i\fP option. +.IP PYTHONKILLPRINT +If this is set to a non-empty string it is equivalent to specifying +the \fB\-k\fP option. +.IP PYTHONVERBOSE +If this is set to a non-empty string it is equivalent to specifying +the \fB\-v\fP option. +.SH SEE ALSO +Python Tutorial +.br +Python Library Reference +.br +Python Reference Manual +.br +STDWIN under X11 +.SH BUGS AND CAVEATS +The first time +.I stdwin +is imported, it initializes the STDWIN library. +If this initialization fails, e.g. because the display connection +fails, the interpreter aborts immediately. +.SH AUTHOR +.nf +Guido van Rossum +CWI (Centrum voor Wiskunde en Informatica) +P.O. Box 4079 +1009 AB Amsterdam +The Netherlands +.PP +E-mail: Guido.van.Rossum@cwi.nl +.fi +.SH MAILING LIST +There is a mailing list devoted to Python programming, bugs and +design. +To subscribe, send mail containing your real name and e-mail address +in Internet form to +.I python-list-request@cwi.nl. +.SH COPYRIGHT +Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum, +Amsterdam, The Netherlands. +.IP " " +All Rights Reserved +.PP +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the names of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/Misc/renumber.py b/Misc/renumber.py new file mode 100755 index 0000000..a62257c --- /dev/null +++ b/Misc/renumber.py @@ -0,0 +1,108 @@ +#! /usr/local/bin/python + +# Renumber the Python FAQ + +import string +import regex +import sys +import os + +FAQ = 'FAQ' + +chapterprog = regex.compile('^\([1-9][0-9]*\)\. ') +questionprog = regex.compile('^\([1-9][0-9]*\)\.\([1-9][0-9]*\)\. ') +newquestionprog = regex.compile('^Q\. ') +blankprog = regex.compile('^[ \t]*$') +indentedorblankprog = regex.compile('^\([ \t]+\|[ \t]*$\)') + +def main(): + print 'Reading lines...' + lines = open(FAQ, 'r').readlines() + print 'Renumbering in memory...' + oldlines = lines[:] + after_blank = 1 + chapter = 0 + question = 0 + chapters = ['\n'] + questions = [] + for i in range(len(lines)): + line = lines[i] + if after_blank: + n = chapterprog.match(line) + if n >= 0: + chapter = chapter + 1 + question = 0 + line = `chapter` + '. ' + line[n:] + lines[i] = line + chapters.append(' ' + line) + questions.append('\n') + questions.append(' ' + line) + afterblank = 0 + continue + n = questionprog.match(line) + if n < 0: n = newquestionprog.match(line) - 3 + if n >= 0: + question = question + 1 + line = '%d.%d. '%(chapter, question) + line[n:] + lines[i] = line + questions.append(' ' + line) + # Add up to 4 continuations of the question + for j in range(i+1, i+5): + if blankprog.match(lines[j]) >= 0: + break + questions.append(' '*(n+2) + lines[j]) + afterblank = 0 + continue + afterblank = (blankprog.match(line) >= 0) + print 'Inserting list of chapters...' + chapters.append('\n') + for i in range(len(lines)): + line = lines[i] + if regex.match( + '^This FAQ is divided in the following chapters', + line) >= 0: + i = i+1 + while 1: + line = lines[i] + if indentedorblankprog.match(line) < 0: + break + del lines[i] + lines[i:i] = chapters + break + else: + print '*** Can\'t find header for list of chapters' + print '*** Chapters found:' + for line in chapters: print line, + print 'Inserting list of questions...' + questions.append('\n') + for i in range(len(lines)): + line = lines[i] + if regex.match('^Here.s an overview of the questions', + line) >= 0: + i = i+1 + while 1: + line = lines[i] + if indentedorblankprog.match(line) < 0: + break + del lines[i] + lines[i:i] = questions + break + else: + print '*** Can\'t find header for list of questions' + print '*** Questions found:' + for line in questions: print line, + if lines == oldlines: + print 'No changes.' + return + print 'Writing new file...' + f = open(FAQ + '.new', 'w') + for line in lines: + f.write(line) + f.close() + print 'Making backup...' + os.rename(FAQ, FAQ + '~') + print 'Moving new file...' + os.rename(FAQ + '.new', FAQ) + print 'Done.' + +main() -- cgit v0.12