blob: 49b160724a5ea61b30c8b4b64b3d047aa33f307e [file] [log] [blame]
Guido van Rossuma7925f11994-01-26 10:20:16 +00001Subject: FAQ: Python -- an object-oriented language
2Newsgroups: comp.lang.misc,comp.answers,news.answers
3Followup-to: comp.lang.misc
4From: guido@cwi.nl (Guido van Rossum)
5Reply-to: guido@cwi.nl (Guido van Rossum)
6Approved: news-answers-request@MIT.Edu
7
8Archive-name: python-faq/part1
9Version: 1.2
10Last-modified: 24 Jan 1994
11
12This article contains answers to Frequently Asked Questions about
13Python (an object-oriented interpreted programming language -- see
14the answer to question 1.1 for a short overview).
15
16Copyright 1993, 1994 Guido van Rossum. Unchanged electronic
17redistribution of this FAQ is allowed. Printed redistribution only
18with permission of the author. No warranties.
19
20Author's address:
21 Guido van Rossum
22 CWI, dept. CST
23 Kruislaan 413
24 P.O. Box 94079
25 1090 GB Amsterdam
26 The Netherlands
27Email: guido@cwi.nl
28
29The latest version of this FAQ is available by anonymous ftp from
30ftp.cwi.nl [192.16.184.180] in the directory /pub/python, with
31filename python-FAQ. It will also be posted regularly to the
32newsgroups comp.answers and comp.lang.misc.
33
34Many FAQs, including this one, are available by anonymous ftp from
35rtfm.mit.edu [18.70.0.209] in the directory pub/usenet/news.answers.
36The name under which a FAQ is archived appears in the Archive-name line
37at the top of the article. This FAQ is archived as python-faq/part1.
38
39There's a mail server on that machine which will send you files from
40the archive by e-mail if you have no ftp access. You send a e-mail
41message to mail-server@rtfm.mit.edu containing the single word help in
42the message body to receive instructions.
43
44This FAQ is divided in the following chapters:
45
46 1. General information and availability
47 2. Python in the real world
48 3. Building Python
49 4. Programming in Python
50 5. Extending Python
51 6. Python's design
52 7. Using Python on non-UNIX platforms
53
54To find the start of a particular chapter, search for the chapter number
55followed by a dot and a space at the beginning of a line (e.g. to
56find chapter 4 in vi, type /^4\. /).
57
58Here's an overview of the questions per chapter:
59
60 1. General information and availability
61 1.1. Q. What is Python?
62 1.2. Q. Why is it called Python?
63 1.3. Q. How do I obtain a copy of the Python source?
64 1.4. Q. How do I get documentation on Python?
65 1.5. Q. Is there a newsgroup or mailing list devoted to Python?
66 1.6. Q. Is there a book on Python, or will there be one out soon?
67 1.7. Q. Are there any published articles about Python that I can quote?
68
69 2. Python in the real world
70 2.1. Q. How many people are using Python?
71 2.2. Q. Have any significant projects been done in Python?
72 2.3. Q. Are there any commercial projects going on using Python?
73 2.4. Q. What new developments are expected for Python in the future?
74 2.5. Q. How stable is Python?
75 2.6. Q. Any more future plans?
76
77 3. Building Python
78 3.1. Q. I have trouble building the md5 module and/or finding the file
79 md5.c.
80 3.2. Q. Is there a test set?
81 3.3. Q. When running the test set, I get complaints about floating point
82 operations, but when playing with floating point operations I cannot
83 find anything wrong with them.
84 3.4. Q. I get an OverflowError on evaluating 2*2. What is going on?
85 3.5. Q. Trouble building Python 0.9.9 on platform X.
86
87 4. Programming in Python
88 4.1. Q. Can I create an object class with some methods implemented in
89 C and others in Python (e.g. through inheritance)? (Also phrased as:
90 Can I use a built-in type as base class?)
91 4.2. Q. I assign to a variable in a call to exec() but when I try to
92 use it on the next line I get an error. What is going on?
93 4.3. Q. Why does that work?
94 4.4. Q. Is there a curses/termcap package for Python?
95 4.5. Q. Is there an equivalent to C's onexit() in Python?
96 4.6. Q. When I define a function nested inside another function, the
97 nested function seemingly can't access the local variables of the
98 outer function. What is going on? How do I pass local data to a
99 nested function?
100 4.7. Q. How do I iterate over a sequence in reverse order?
101 4.8. Q. My program is too slow. How do I speed it up?
102 4.9. Q. When I have imported a module, then edit it, and import it
103 again (into the same Python process), the changes don't seem to take
104 place. What is going on?
105
106 5. Extending Python
107 5.1. Q. Can I create my own functions in C?
108 5.2. Q. Can I create my own functions in C++?
109
110 6. Python's design
111 6.1. Q. Why isn't there a generic copying operation for objects in
112 Python?
113 6.2. Q. Why isn't there a generic way to implement persistent objects
114 in Python? (Persistent == automatically saved to and restored from
115 disk.)
116 6.3. Q. Why isn't there a switch or case statement in Python?
117
118 7. Using Python on non-UNIX platforms
119 7.1. Q. Where's the DOS version of 0.9.9?
120 7.2. Q. Is there a Windows version of Python?
121 7.3. Q. I have the Mac or DOS version but it appears to be only a binary.
122 Where's the library?
123 7.4. Q. Where's the documentation for the Mac or DOS version?
124 7.5. Q. The Mac version doesn't seem to have any facilities for creating or
125 editing programs apart from entering it interactively, and there seems
126 to be no way to save code that was entered interactively. How do I
127 create a Python program on the Mac?
128
129To find a particular question, search for the question number followed
130by a dot, a space, and a Q at the beginning of a line (e.g. to find
131question 4.2 in vi, type /^4\.2\. Q/).
132
133
1341. General information and availability
135=======================================
136
1371.1. Q. What is Python?
138
139A. Python is an interpreted, interactive, object-oriented programming
140language. It incorporates modules, exceptions, dynamic typing, very
141high level dynamic data types, and classes. Python combines
142remarkable power with very clear syntax. It has interfaces to many
143system calls and libraries, as well as to various window systems, and
144is extensible in C or C++. It is also usable as an extension language
145for applications that need a programmable interface. Finally, Python
146is portable: it runs on many brands of UNIX, on the Mac, and on
147MS-DOS.
148
149To find out more, the best thing to do is to start reading the
150tutorial from the documentation set (see a few questions further
151down).
152
1531.2. Q. Why is it called Python?
154
155A. Apart from being a computer wizard, I'm also a fan of "Monty
156Python's Flying Circus" (a BBC comedy series from the seventies, in
157case you didn't know). It occurred to me one day that I needed a name
158that was short, unique, and slightly mysterious. And I happened to be
159reading some scripts from the series at the time... So then I decided
160to call my language Python. But Python is not a joke. And don't you
161associate it with dangerous reptiles either!
162
1631.3. Q. How do I obtain a copy of the Python source?
164
165A. The latest Python source distribution is always available by
166anonymous ftp from ftp.cwi.nl [192.16.184.180] in the directory
167/pub/python, with filename python<version>.tar.Z. It is a compressed
168tar file containing the complete C source, LaTeX documentation, Python
169library modules, example programs, and several useful pieces of freely
170distributable software. This will compile and run out of the box on
171most UNIX platforms. Currently <version> is 0.9.9. (See section 7
172for non-UNIX information.)
173
1741.4. Q. How do I get documentation on Python?
175
176A. The latest Python documentation set is always available by
177anonymous ftp from ftp.cwi.nl [192.16.184.180] in the directory
178/pub/python, with filename pythondoc-ps<version>.tar.Z. It is a
179compressed tar file containing PostScript files of the reference
180manual, the library manual, and the tutorial. Currently <version> is
1810.9.9. (Note that the library manual is the most important one of the
182set, as much of Python's power stems from the standard or built-in
183types, functions and modules, all of which are described here.)
184PostScript for a high-level description of Python is in the file
185nluug-paper.ps.
186
187The following sites keep mirrors of the Python distribution:
188
189Site IP address Directory
190
191gatekeeper.dec.com 16.1.0.2 /pub/plan/python/cwi
192ftp.uu.net 192.48.96.9 /languages/python
193ftp.wustl.edu 128.252.135.4 /graphics/graphics/sgi-stuff/python
194ftp.funet.fi 128.214.6.100 /pub/languages/python (old?)
195ftp.fu-berlin.de 130.133.4.50 /pub/unix/languages/python (python* only)
196
197Or try archie on e.g. python0.9.9.tar.Z to locate the nearest copy of
198that version...
199
2001.5. Q. Is there a newsgroup or mailing list devoted to Python?
201
202A. There is no Python newsgroup yet; if you want to post to the net
203about Python, use comp.lang.misc. There is a mailing list devoted to
204Python; send e-mail to python-list-request@cwi.nl to (un)subscribe.
205There are plans to start the discussion about creation of
206comp.lang.python as soon as version 1.0.0 has been released.
207
2081.6. Q. Is there a book on Python, or will there be one out soon?
209
210A. Unfortunately, not yet. I would like to write one but my
211obligations at CWI include too much other work to make much progress
212on it. Several parties have expressed interest in sponsoring or
213helping the production of a book or reference manual, but so far there
214are no firm plans. If you volunteer help, by all means drop me a
215note!
216
2171.7. Q. Are there any published articles about Python that I can quote?
218
219A. So far the only refereed and published article that describes
220Python in some detail is:
221
222 Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
223 Servers Using the Python Programming Language", CWI Quarterly, Volume
224 4, Issue 4 (December 1991), Amsterdam, pp 283-303.
225
226LaTeX source for this paper is available as part of the Python source
227distribution.
228
229A more recent high-level description of Python is:
230
231 Guido van Rossum, "An Introduction to Python for UNIX/C
232 Programmers", in the proceedings of the NLUUG najaarsconferentie
233 1993 (dutch UNIX users group meeting november 1993).
234
235PostScript for this paper and for the slides used for the accompanying
236presentation can be found in the ftp directory mentioned a few
237questions earlier, with filenames nluug-paper.ps and nluug-slides.ps,
238respectively.
239
240
2412. Python in the real world
242===========================
243
2442.1. Q. How many people are using Python?
245
246A. I don't know, but at the last count there were at least 130
247addresses on the Python mailing list (several of which are local
248redistribution lists). I suspect that many users don't bother
249to subscribe to the list.
250
2512.2. Q. Have any significant projects been done in Python?
252
253A. Here at CWI (the home of Python), we have written a 20,000 line
254authoring environment for transportable hypermedia presentations, a
255multimedia teleconferencing tool, as well as many smaller programs.
256
257The University of Virginia uses Python to control a virtual reality
258engine. Contact: Matt Conway <conway@virginia.edu>.
259
260See also the next question.
261
2622.3. Q. Are there any commercial projects going on using Python?
263
264A. Several companies have revealed to me that they are planning or
265considering to use Python in a future product. The furthest is
266Sunrise Software, who already have a product out using Python -- they
267use Python for a GUI management application and an SNMP network
268manangement application. Contact: <info@sunrise.com>.
269
270Individuals at many other companies are using Python for
271internal development (witness their contributions to the Python
272mailing list).
273
274Python has also been elected as an extension language by MADE, a
275consortium supported by the European Committee's ESPRIT program and
276consisting of Bull, CWI and some other European companies. Contact:
277Ivan Herman <ivan@cwi.nl>.
278
2792.4. Q. What new developments are expected for Python in the future?
280
281A. I am almost ready to release version 1.0.0 -- it should be out by
282the end of January 1994. It will have some new functionality and
283bugfixes and be portable to more platforms. The directory tree
284structure and build procedure will be radically different -- almost
285all configuration is now done automatically, using GNU autoconf.
286User-visible changes include: double-quoted strings, functional
287programming operations (lambda, map, filter, reduce -- all evaluated
288eagerly), exec becomes a statement, str() is customizable through
289__str__ (used by print). The originally planned grand renaming scheme
290will not be implemented because of lack of time. A beta version can
291be ftp'ed from the usual sites, file python1.0.0beta.tar.Z.
292
2932.5. Q. How stable is Python?
294
295A. Very stable. While the current version number (0.9.9) would
296suggest it is in the early stages of development, in fact new, stable
297releases have been coming out every 3-6 months for the past three years.
298
2992.6. Q. Any more future plans?
300
301A. Without warranty that any of this will actually be realized: I am
302currently thinking about mechanisms for built-in on-line help and a
303switch/case statement. There are also some people (independently)
304working on a windowing interface based on STDWIN but with the power
305and ease of use of the average modern widget set. I still hope to get
306some help in producing a Windows version. It would be nice if there
307were a window-based class browser (Someone at CWI has contributed one
308using Motif but it needs some work).
309
310
3113. Building Python
312==================
313
3143.1. Q. I have trouble building the md5 module and/or finding the file
315md5.c.
316
317A. Apparently the md5 module was based on an older version of RSA's
318md5 implementation. The ftp site rsa.com mentioned in the Makefile
319where this version was found is no longer accessible, and the version
320from RFC 1321 (md5c.c) is slightly different. This will be fixed in
321the 1.0 release; write me if you need the fixes now.
322
3233.2. Q. Is there a test set?
324
325A. Yes, simply do "import testall" (or "import autotest" if you aren't
326interested in the output). The standard modules whose name begins
327with "test" together comprise the test. The test set doesn't test
328*all* features of Python but it goes a long way to confirm that a new
329port is actually working. The Makefile contains an entry "make test"
330which runs the autotest module.
331
3323.3. Q. When running the test set, I get complaints about floating point
333operations, but when playing with floating point operations I cannot
334find anything wrong with them.
335
336A. The test set makes occasional unwarranted assumptions about the
337semantics of C floating point operations. Until someone donates a
338better floating point test set, you will have to comment out the
339offending floating point tests and execute similar tests manually.
340
3413.4. Q. I get an OverflowError on evaluating 2*2. What is going on?
342
343A. Your machine probably has 64 bit long integers (e.g. DEC alpha or
344HP snake architectures). There are some dependencies on word length
345in file intobject.c. This will be corrected in the 1.0 release; until
346then, on a 64 bit machine, just comment out the check for overflow
347from int_mul:
348
349 #if 0
350 if (x > 0x7fffffff || x < (double) (long) 0x80000000)
351 return err_ovf("integer multiplication");
352 #endif
353
354You should also include <limits.h> and replace the constant 32 by
355LONG_BIT in int_[lr]shift.
356
3573.5. Q. Trouble building Python 0.9.9 on platform X.
358
359A. In the bootstrap phase (before you have built the first running
360interpreter), make sure the -D settings in the Makefile are correct
361for your system. In particular you may have to add or delete -DSYSV.
362It may also be necessary to change the flags used to compile
363posixmodule.c and timemodule.c; e.g. on AIX the following are
364necessary:
365 posixmodule.c: -DHAVE_STDLIB -DNOALTTZ -DOLDTZ -Dunix -DSYSV -DDO_TIMES
366 timemodule.c: -DHAVE_STDLIB -DNOALTTZ -DOLDTZ -Uunix -DSYSV -DBSD_TIME
367(Note the -Uunix for timemodule!)
368Those switches for timemodule also require that the
369 #ifdef unix
370 #ifdef BSD_TIME
371just above:
372 static long
373 millitimer()
374( and below the "#endif /* macintosh */" version of millitimer
375be changed to:
376 #if defined(unix) | defined(BSD_TIME)
377 #ifdef BSD_TIME
378
379
3804. Programming in Python
381========================
382
3834.1. Q. Can I create an object class with some methods implemented in
384C and others in Python (e.g. through inheritance)? (Also phrased as:
385Can I use a built-in type as base class?)
386
387A. No, but you can easily create a Python class which serves as a
388wrapper around a built-in object, e.g. (for dictionaries):
389
390 # A user-defined class behaving almost identical
391 # to a built-in dictionary.
392 class UserDict:
393 def __init__(self): self.data = {}
394 def __repr__(self): return repr(self.data)
395 def __cmp__(self, dict):
396 if type(dict) == type(self.data):
397 return cmp(self.data, dict)
398 else:
399 return cmp(self.data, dict.data)
400 def __len__(self): return len(self.data)
401 def __getitem__(self, key): return self.data[key]
402 def __setitem__(self, key, item): self.data[key] = item
403 def __delitem__(self, key): del self.data[key]
404 def keys(self): return self.data.keys()
405 def items(self): return self.data.items()
406 def values(self): return self.data.values()
407 def has_key(self, key): return self.data.has_key(key)
408
4094.2. Q. I assign to a variable in a call to exec() but when I try to
410use it on the next line I get an error. What is going on?
411
412A. The reason why this occurs is too complicated to explain (but see
413the next question). To fix it is easy, however: simply assign None to
414the variable *before* calling exec(). This will be fixed in the 1.0
415release.
416
4174.3. Q. Why does that work?
418
419A. When parsing your program and converting it into internal pseudo
420code, the interpreter does some optimizations to speed up function
421execution: it figures out the names of all the local variables and
422treats them specially. Because your assignment is done by exec(), it
423is not seen initially by the parser and the variable is not recognized
424as a local variable. The default treatment is as a global variable,
425but the exec() statement places it in the local scope, where it is not
426found. This will be fixed in release 1.0 by making exec into a
427statement; the parser will then be able to switch off the
428optimizations for local variables if it encounters an exec statement
429(recognizing calls to built-in functions is not possible for the
430parser, hence the syntax change to a statement).
431
4324.4. Q. Is there a curses/termcap package for Python?
433
434A. No, but you can use the "alfa" (== character cell) version of
435STDWIN. (STDWIN == Standard Windows, a portable windowing system
436interface by the same author, URL ftp://ftp.cwi.nl/pub/stdwin.)
437This will also prepare your program for porting to windowing
438environments such as X11 or the Macintosh.
439
4404.5. Q. Is there an equivalent to C's onexit() in Python?
441
442A. Yes, if you import sys and assign a function to sys.exitfunc, it
443will be called when your program exits, is killed by an unhandled
444exception, or (on UNIX) receives a SIGHUP or SIGTERM signal.
445
4464.6. Q. When I define a function nested inside another function, the
447nested function seemingly can't access the local variables of the
448outer function. What is going on? How do I pass local data to a
449nested function?
450
451A. Python does not have arbitrarily nested scopes. When you need to
452create a function that needs to access some data which you have
453available locally, create a new class to hold the data and return a
454method of an instance of that class, e.g.:
455
456 class MultiplierClass:
457 def __init__(self, factor):
458 self.factor = factor
459 def multiplier(self, argument):
460 return argument * self.factor
461
462 def generate_multiplier(factor):
463 return MultiplierClass(factor).multiplier
464
465 twice = generate_multiplier(2)
466 print twice(10)
467 # Output: 20
468
4694.7. Q. How do I iterate over a sequence in reverse order?
470
471A. If it is a list, the fastest solution is
472
473 list.reverse()
474 try:
475 for x in list:
476 "do something with x"
477 finally:
478 list.reverse()
479
480This has the disadvantage that while you are in the loop, the list
481is temporarily reversed. If you don't like this, you can make a copy.
482This appears expensive but is actually faster than other solutions:
483
484 rev = list[:]
485 rev.reverse()
486 for x in rev:
487 <do something with x>
488
489If it isn't a list, a more general but slower solution is:
490
491 i = len(list)
492 while i > 0:
493 i = i-1
494 x = list[i]
495 <do something with x>
496
497A more elegant solution, is to define a class which acts as a sequence
498and yields the elements in reverse order (solution due to Steve
499Majewski):
500
501 class Rev:
502 def __init__(self, seq):
503 self.forw = seq
504 def __len__(self):
505 return len(self.forw)
506 def __getitem__(self, i):
507 return self.forw[-(i + 1)]
508
509You can now simply write:
510
511 for x in Rev(list):
512 <do something with x>
513
514Unfortunately, this solution is slowest of all, due the the method
515call overhead...
516
5174.8. Q. My program is too slow. How do I speed it up?
518
519A. That's a tough one, in general. There are many tricks to speed up
520Python code; I would consider rewriting parts in C only as a last
521resort. One thing to notice is that function and (especially) method
522calls are rather expensive; if you have designed a purely OO interface
523with lots of tiny functions that don't do much more than get or set an
524instance variable or call another method, you may consider using a
525more direct way, e.g. directly accessing instance variables. Also see
526the standard module "profile" (described in the file
527"python/lib/profile.doc") which makes it possible to find out where
528your program is spending most of its time (if you have some patience
529-- the profiling itself can slow your program down by an order of
530magnitude).
531
5324.9. Q. When I have imported a module, then edit it, and import it
533again (into the same Python process), the changes don't seem to take
534place. What is going on?
535
536A. For efficiency reasons, Python only reads the module file on the
537first time a module is imported (otherwise a program consisting of
538many modules, each of which imports the same basic module, would read
539the basic module over and over again). To force a changed module
540being read again, do this:
541
542 import modname
543 reload(modname)
544
545Warning: this technique is not 100% fool-proof. In particular,
546modules containing statements like
547
548 from modname import some_objects
549
550will continue to work with the old version of the objects imported
551thus.
552
553
5545. Extending Python
555===================
556
5575.1. Q. Can I create my own functions in C?
558
559A. Yes, you can create built-in modules containing functions,
560variables, exceptions and even new types in C. This is all explained
561in the file "python/misc/EXTENDING". Also read the file "DYNLOAD"
562there for hints on how to load such extension modules
563
5645.2. Q. Can I create my own functions in C++?
565
566A. Yes, using the C-compatibility features found in C++. Basically
567you place extern "C" { ... } around the Python include files and put
568extern "C" before each function that is going to be called by the
569Python interpreter. Global or static C++ objects with constructors
570are probably not a good idea.
571
572
5736. Python's design
574==================
575
5766.1. Q. Why isn't there a generic copying operation for objects in
577Python?
578
579A. Hmm. Maybe there should be one, but it's difficult to assign a
580useful meaning to copying of open files, sockets and windows, or
581recursive data structures. As long as you design all your classes
582yourself you are of course free to define a standard base class that
583defines an overridable copying operation for all the objects you care
584about. (One practical point: it would have to be a built-in function,
585not a standard method name, since not all built-in object types have
586methods; e.g. strings, integers and tuples don't.)
587
5886.2. Q. Why isn't there a generic way to implement persistent objects
589in Python? (Persistent == automatically saved to and restored from
590disk.)
591
592A. Hmm, hmm. Basically for the same reasons as why there is no
593generic copying operation.
594
5956.3. Q. Why isn't there a switch or case statement in Python?
596
597A. You can do this easily enough with a sequence of
598if... elif... elif... else. There have been some proposals for switch
599statement syntax, but there is no concensus (yet) on whether and how
600to do range tests.
601
602
6037. Using Python on non-UNIX platforms
604=====================================
605
6067.1. Q. Where's the DOS version of 0.9.9?
607
608A. I hope it will be coming soon. A friend with a DOS machine and a
609compiler has volunteered to build it but he's very busy. Until then,
610you will have to make do with the 0.9.8 version (which isn't so bad,
611actually).
612
6137.2. Q. Is there a Windows version of Python?
614
615A. Not yet. Several Windows hackers with C compilers are working on a
616port though, so maybe we'll have one soon.
617
6187.3. Q. I have the Mac or DOS version but it appears to be only a binary.
619Where's the library?
620
621A. You still need to copy the files from the distribution directory
622"python/lib" to your system. If you don't have the full distribution,
623you can ftp the file pythonlib0.9.9.tar.Z from site ftp.cwi.nl,
624directory /pub/python; this is a subset of the distribution containing
625just those file.
626
6277.4. Q. Where's the documentation for the Mac or DOS version?
628
629A. There isn't any. The documentation for the Unix version also
630applies to the Mac and DOS versions. Where applicable, differences
631are indicated in the text.
632
6337.5. Q. The Mac version doesn't seem to have any facilities for creating or
634editing programs apart from entering it interactively, and there seems
635to be no way to save code that was entered interactively. How do I
636create a Python program on the Mac?
637
638A. Use an external editor. I am quite happy with the Desk Accessory
639called Sigma Edit; this doesn't require Multifinder or System 7. I
640work like this: start the interpreter; edit a module file using Sigma
641Edit; import and test it in the interpreter; edit again in Sigma Edit;
642then use the built-in function reload() to re-read the imported
643module; etc.