blob: 0e1d52483eb20bb0a8becd97b5de20d35761e439 [file] [log] [blame]
Raymond Hettinger72348842003-01-25 21:22:52 +00001 Python 2.3 Quick Reference
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002
Guido van Rossumc8180cc1994-08-05 15:57:31 +00003
Raymond Hettinger72348842003-01-25 21:22:52 +00004 25 Jan 2003 upgraded by Raymond Hettinger for Python 2.3
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00005 16 May 2001 upgraded by Richard Gruet and Simon Brunning for Python 2.0
6 2000/07/18 upgraded by Richard Gruet, rgruet@intraware.com for Python 1.5.2
7from V1.3 ref
81995/10/30, by Chris Hoffmann, choffman@vicorp.com
Guido van Rossumc8180cc1994-08-05 15:57:31 +00009
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000010Based on:
11 Python Bestiary, Author: Ken Manheimer, ken.manheimer@nist.gov
12 Python manuals, Authors: Guido van Rossum and Fred Drake
13 What's new in Python 2.0, Authors: A.M. Kuchling and Moshe Zadka
14 python-mode.el, Author: Tim Peters, tim_one@email.msn.com
15
16 and the readers of comp.lang.python
17
18Python's nest: http://www.python.org Developement: http://
19python.sourceforge.net/ ActivePython : http://www.ActiveState.com/ASPN/
20Python/
21newsgroup: comp.lang.python Help desk: help@python.org
Raymond Hettinger72348842003-01-25 21:22:52 +000022Resources: http://starship.python.net/
23 http://www.vex.net/parnassus/
24 http://aspn.activestate.com/ASPN/Cookbook/Python
25FAQ: http://www.python.org/cgi-bin/faqw.py
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000026Full documentation: http://www.python.org/doc/
Raymond Hettinger72348842003-01-25 21:22:52 +000027Excellent reference books:
28 Python Essential Reference by David Beazley (New Riders)
29 Python Pocket Reference by Mark Lutz (O'Reilly)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000030
31
32Invocation Options
33
34python [-diOStuUvxX?] [-c command | script | - ] [args]
35
36 Invocation Options
37Option Effect
Raymond Hettinger72348842003-01-25 21:22:52 +000038-c cmd program passed in as string (terminates option list)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000039-d Outputs parser debugging information (also PYTHONDEBUG=x)
Raymond Hettinger72348842003-01-25 21:22:52 +000040-E ignore environment variables (such as PYTHONPATH)
41-h print this help message and exit
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000042-i Inspect interactively after running script (also PYTHONINSPECT=x) and
43 force prompts, even if stdin appears not to be a terminal
Raymond Hettinger72348842003-01-25 21:22:52 +000044-O optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)
45-OO remove doc-strings in addition to the -O optimizations
46-Q arg division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000047-S Don't perform 'import site' on initialization
48-t Issue warnings about inconsistent tab usage (-tt: issue errors)
49-u Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x).
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000050-v Verbose (trace import statements) (also PYTHONVERBOSE=x)
Raymond Hettinger72348842003-01-25 21:22:52 +000051-W arg : warning control (arg is action:message:category:module:lineno)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000052-x Skip first line of source, allowing use of non-unix Forms of #!cmd
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000053-? Help!
54-c Specify the command to execute (see next section). This terminates the
55command option list (following options are passed as arguments to the command).
56 the name of a python file (.py) to execute read from stdin.
57script Anything afterward is passed as options to python script or command,
58 not interpreted as an option to interpreter itself.
59args passed to script or command (in sys.argv[1:])
60 If no script or command, Python enters interactive mode.
61
62 * Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin
63 (Windows).
64
65
66
67Environment variables
68
69 Environment variables
70 Variable Effect
71PYTHONHOME Alternate prefix directory (or prefix;exec_prefix). The
72 default module search path uses prefix/lib
73 Augments the default search path for module files. The format
74 is the same as the shell's $PATH: one or more directory
75 pathnames separated by ':' or ';' without spaces around
76 (semi-)colons!
77PYTHONPATH On Windows first search for Registry key HKEY_LOCAL_MACHINE\
78 Software\Python\PythonCore\x.y\PythonPath (default value). You
79 may also define a key named after your application with a
80 default string value giving the root directory path of your
81 app.
82 If this is the name of a readable file, the Python commands in
83PYTHONSTARTUP that file are executed before the first prompt is displayed in
84 interactive mode (no default).
85PYTHONDEBUG If non-empty, same as -d option
86PYTHONINSPECT If non-empty, same as -i option
87PYTHONSUPPRESS If non-empty, same as -s option
88PYTHONUNBUFFERED If non-empty, same as -u option
89PYTHONVERBOSE If non-empty, same as -v option
90PYTHONCASEOK If non-empty, ignore case in file/module names (imports)
91
92
93
94
95Notable lexical entities
96
97Keywords
98
99 and del for is raise
100 assert elif from lambda return
101 break else global not try
102 class except if or while
Raymond Hettinger72348842003-01-25 21:22:52 +0000103 continue exec import pass yield
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000104 def finally in print
105
106 * (list of keywords in std module: keyword)
107 * Illegitimate Tokens (only valid in strings): @ $ ?
108 * A statement must all be on a single line. To break a statement over
109 multiple lines use "\", as with the C preprocessor.
110 Exception: can always break when inside any (), [], or {} pair, or in
111 triple-quoted strings.
112 * More than one statement can appear on a line if they are separated with
113 semicolons (";").
114 * Comments start with "#" and continue to end of line.
115
116Identifiers
117
118 (letter | "_") (letter | digit | "_")*
119
120 * Python identifiers keywords, attributes, etc. are case-sensitive.
121 * Special forms: _ident (not imported by 'from module import *'); __ident__
122 (system defined name);
123 __ident (class-private name mangling)
124
125Strings
126
127 "a string enclosed by double quotes"
128 'another string delimited by single quotes and with a " inside'
129 '''a string containing embedded newlines and quote (') marks, can be
130 delimited with triple quotes.'''
131 """ may also use 3- double quotes as delimiters """
132 u'a unicode string' U"Another unicode string"
133 r'a raw string where \ are kept (literalized): handy for regular
134 expressions and windows paths!'
135 R"another raw string" -- raw strings cannot end with a \
136 ur'a unicode raw string' UR"another raw unicode"
137
138 Use \ at end of line to continue a string on next line.
139 adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as
140 'Monty Python'.
141 u'hello' + ' world' --> u'hello world' (coerced to unicode)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000142
143 String Literal Escapes
144
145 \newline Ignored (escape newline)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000146 \\ Backslash (\) \e Escape (ESC) \v Vertical Tab (VT)
147 \' Single quote (') \f Formfeed (FF) \OOO char with octal value OOO
148 \" Double quote (") \n Linefeed (LF)
149 \a Bell (BEL) \r Carriage Return (CR) \xHH char with hex value HH
150 \b Backspace (BS) \t Horizontal Tab (TAB)
151 \uHHHH unicode char with hex value HHHH, can only be used in unicode string
152 \UHHHHHHHH unicode char with hex value HHHHHHHH, can only be used in unicode string
153 \AnyOtherChar is left as-is
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000154
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000155 * NUL byte (\000) is NOT an end-of-string marker; NULs may be embedded in
156 strings.
157 * Strings (and tuples) are immutable: they cannot be modified.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000158
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000159Numbers
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000160
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000161 Decimal integer: 1234, 1234567890546378940L (or l)
Raymond Hettinger72348842003-01-25 21:22:52 +0000162 Octal integer: 0177, 0177777777777777777 (begin with a 0)
163 Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFF (begin with 0x or 0X)
164 Long integer (unlimited precision): 1234567890123456
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000165 Float (double precision): 3.14e-10, .001, 10., 1E3
166 Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and
167 imaginary parts)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000168
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000169Sequences
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000170
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000171 * String of length 0, 1, 2 (see above)
172 '', '1', "12", 'hello\n'
173 * Tuple of length 0, 1, 2, etc:
174 () (1,) (1,2) # parentheses are optional if len > 0
175 * List of length 0, 1, 2, etc:
176 [] [1] [1,2]
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000177
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000178Indexing is 0-based. Negative indices (usually) mean count backwards from end
179of sequence.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000180
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000181Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to
182'0'; End defaults to 'sequence-length'.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000183
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000184a = (0,1,2,3,4,5,6,7)
185 a[3] ==> 3
186 a[-1] ==> 7
187 a[2:4] ==> (2, 3)
188 a[1:] ==> (1, 2, 3, 4, 5, 6, 7)
189 a[:3] ==> (0, 1, 2)
190 a[:] ==> (0,1,2,3,4,5,6,7) # makes a copy of the sequence.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000191
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000192Dictionaries (Mappings)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000193
Raymond Hettinger72348842003-01-25 21:22:52 +0000194 {} # Zero length empty dictionary
195 {1 : 'first'} # Dictionary with one (key, value) pair
196 {1 : 'first', 'next': 'second'}
197 dict([('one',1),('two',2)]) # Construct a dict from an item list
198 dict('one'=1, 'two'=2) # Construct a dict using keyword args
199 dict.fromkeys(['one', 'keys']) # Construct a dict from a sequence
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000200
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000201Operators and their evaluation order
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000202
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000203 Operators and their evaluation order
204Highest Operator Comment
205 (...) [...] {...} `...` Tuple, list & dict. creation; string
206 conv.
207 s[i] s[i:j] s.attr f(...) indexing & slicing; attributes, fct
208 calls
209 +x, -x, ~x Unary operators
210 x**y Power
211 x*y x/y x%y mult, division, modulo
212 x+y x-y addition, substraction
213 x<<y x>>y Bit shifting
214 x&y Bitwise and
215 x^y Bitwise exclusive or
216 x|y Bitwise or
217 x<y x<=y x>y x>=y x==y x!=y Comparison,
218 x<>y identity,
219 x is y x is not y membership
220 x in s x not in s
221 not x boolean negation
222 x and y boolean and
223 x or y boolean or
224Lowest lambda args: expr anonymous function
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000225
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000226Alternate names are defined in module operator (e.g. __add__ and add for +)
Raymond Hettinger72348842003-01-25 21:22:52 +0000227Most operators are overridable.
228
Raymond Hettinger5a772d32003-01-25 22:35:42 +0000229Many binary operators also support augmented assignment:
Raymond Hettinger72348842003-01-25 21:22:52 +0000230 x += 1 # Same as x = x + 1
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000231
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000232
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000233Basic Types and Their Operations
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000234
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000235Comparisons (defined between *any* types)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000236
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000237 Comparisons
238Comparison Meaning Notes
239< strictly less than (1)
240<= less than or equal to
241> strictly greater than
242>= greater than or equal to
243== equal to
244!= or <> not equal to
245is object identity (2)
246is not negated object identity (2)
247
248Notes :
249 Comparison behavior can be overridden for a given class by defining special
250method __cmp__.
Raymond Hettinger72348842003-01-25 21:22:52 +0000251 The above comparisions return True or False which are of type bool
Raymond Hettinger5a772d32003-01-25 22:35:42 +0000252(a subclass of int) and behave exactly as 1 or 0 except for their type and
Raymond Hettinger72348842003-01-25 21:22:52 +0000253that they print as True or False instead of 1 or 0.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000254 (1) X < Y < Z < W has expected meaning, unlike C
255 (2) Compare object identities (i.e. id(object)), not object values.
256
257Boolean values and operators
258
259 Boolean values and operators
260 Value or Operator Returns Notes
261None, numeric zeros, empty sequences and False
262mappings
263all other values True
264not x True if x is False, else
265 True
266x or y if x is False then y, else (1)
267 x
268x and y if x is False then x, else (1)
269 y
270
271Notes :
272 Truth testing behavior can be overridden for a given class by defining
273special method __nonzero__.
274 (1) Evaluate second arg only if necessary to determine outcome.
275
276None
277
278 None is used as default return value on functions. Built-in single object
279 with type NoneType.
280 Input that evaluates to None does not print when running Python
281 interactively.
282
283Numeric types
284
285Floats, integers and long integers.
286
287 Floats are implemented with C doubles.
288 Integers are implemented with C longs.
289 Long integers have unlimited size (only limit is system resources)
290
291Operators on all numeric types
292
293 Operators on all numeric types
294 Operation Result
295abs(x) the absolute value of x
296int(x) x converted to integer
297long(x) x converted to long integer
298float(x) x converted to floating point
299-x x negated
300+x x unchanged
301x + y the sum of x and y
302x - y difference of x and y
303x * y product of x and y
304x / y quotient of x and y
305x % y remainder of x / y
306divmod(x, y) the tuple (x/y, x%y)
307x ** y x to the power y (the same as pow(x, y))
308
309Bit operators on integers and long integers
310
311 Bit operators
312Operation >Result
313~x the bits of x inverted
314x ^ y bitwise exclusive or of x and y
315x & y bitwise and of x and y
316x | y bitwise or of x and y
317x << n x shifted left by n bits
318x >> n x shifted right by n bits
319
320Complex Numbers
321
322 * represented as a pair of machine-level double precision floating point
323 numbers.
324 * The real and imaginary value of a complex number z can be retrieved through
325 the attributes z.real and z.imag.
326
327Numeric exceptions
328
329TypeError
330 raised on application of arithmetic operation to non-number
331OverflowError
332 numeric bounds exceeded
333ZeroDivisionError
334 raised when zero second argument of div or modulo op
335
336Operations on all sequence types (lists, tuples, strings)
337
338 Operations on all sequence types
339Operation Result Notes
340x in s 1 if an item of s is equal to x, else 0
341x not in s 0 if an item of s is equal to x, else 1
Raymond Hettinger72348842003-01-25 21:22:52 +0000342for x in s: loops over the sequence
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000343s + t the concatenation of s and t
344s * n, n*s n copies of s concatenated
345s[i] i'th item of s, origin 0 (1)
346s[i:j] slice of s from i (included) to j (excluded) (1), (2)
347len(s) length of s
348min(s) smallest item of s
349max(s) largest item of (s)
Raymond Hettinger72348842003-01-25 21:22:52 +0000350iter(s) returns an iterator over s. iterators define __iter__ and next()
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000351
352Notes :
353 (1) if i or j is negative, the index is relative to the end of the string,
354ie len(s)+ i or len(s)+j is
355 substituted. But note that -0 is still 0.
356 (2) The slice of s from i to j is defined as the sequence of items with
357index k such that i <= k < j.
358 If i or j is greater than len(s), use len(s). If i is omitted, use
359len(s). If i is greater than or
360 equal to j, the slice is empty.
361
362Operations on mutable (=modifiable) sequences (lists)
363
364 Operations on mutable sequences
365 Operation Result Notes
366s[i] =x item i of s is replaced by x
367s[i:j] = t slice of s from i to j is replaced by t
368del s[i:j] same as s[i:j] = []
369s.append(x) same as s[len(s) : len(s)] = [x]
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000370s.count(x) return number of i's for which s[i] == x
Raymond Hettinger72348842003-01-25 21:22:52 +0000371s.extend(x) same as s[len(s):len(s)]= x
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000372s.index(x) return smallest i such that s[i] == x (1)
373s.insert(i, x) same as s[i:i] = [x] if i >= 0
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000374s.pop([i]) same as x = s[i]; del s[i]; return x (4)
Raymond Hettinger72348842003-01-25 21:22:52 +0000375s.remove(x) same as del s[s.index(x)] (1)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000376s.reverse() reverse the items of s in place (3)
377s.sort([cmpFct]) sort the items of s in place (2), (3)
378
379Notes :
380 (1) raise a ValueError exception when x is not found in s (i.e. out of
381range).
382 (2) The sort() method takes an optional argument specifying a comparison
383fct of 2 arguments (list items) which should
384 return -1, 0, or 1 depending on whether the 1st argument is
385considered smaller than, equal to, or larger than the 2nd
386 argument. Note that this slows the sorting process down considerably.
387 (3) The sort() and reverse() methods modify the list in place for economy
388of space when sorting or reversing a large list.
389 They don't return the sorted or reversed list to remind you of this
390side effect.
Raymond Hettinger72348842003-01-25 21:22:52 +0000391 (4) [New 1.5.2] The optional argument i defaults to -1, so that by default the last
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000392item is removed and returned.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000393
394
395
396Operations on mappings (dictionaries)
397
398 Operations on mappings
399 Operation Result Notes
400len(d) the number of items in d
401d[k] the item of d with key k (1)
402d[k] = x set d[k] to x
403del d[k] remove d[k] from d (1)
404d.clear() remove all items from d
405d.copy() a shallow copy of d
Raymond Hettinger72348842003-01-25 21:22:52 +0000406d.get(k,defaultval) the item of d with key k (4)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000407d.has_key(k) 1 if d has key k, else 0
408d.items() a copy of d's list of (key, item) pairs (2)
Raymond Hettinger72348842003-01-25 21:22:52 +0000409d.iteritems() an iterator over (key, value) pairs (7)
410d.iterkeys() an iterator over the keys of d (7)
411d.itervalues() an iterator over the values of d (7)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000412d.keys() a copy of d's list of keys (2)
413d1.update(d2) for k, v in d2.items(): d1[k] = v (3)
414d.values() a copy of d's list of values (2)
Raymond Hettinger72348842003-01-25 21:22:52 +0000415d.pop(k) remove d[k] and return its value
416d.popitem() remove and return an arbitrary (6)
417 (key, item) pair
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000418d.setdefault(k,defaultval) the item of d with key k (5)
419
420 Notes :
421 TypeError is raised if key is not acceptable
422 (1) KeyError is raised if key k is not in the map
423 (2) Keys and values are listed in random order
424 (3) d2 must be of the same type as d1
425 (4) Never raises an exception if k is not in the map, instead it returns
426 defaultVal.
427 defaultVal is optional, when not provided and k is not in the map,
428 None is returned.
429 (5) Never raises an exception if k is not in the map, instead it returns
430 defaultVal, and adds k to map with value defaultVal. defaultVal is
431 optional. When not provided and k is not in the map, None is returned and
432 added to map.
Raymond Hettinger72348842003-01-25 21:22:52 +0000433 (6) Raises a KeyError if the dictionary is emtpy.
434 (7) While iterating over a dictionary, the values may be updated but
435 the keys cannot be changed.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000436
437Operations on strings
438
439Note that these string methods largely (but not completely) supersede the
440functions available in the string module.
441
442
443 Operations on strings
444 Operation Result Notes
445s.capitalize() return a copy of s with only its first character
446 capitalized.
447s.center(width) return a copy of s centered in a string of length width (1)
448 .
449s.count(sub[ return the number of occurrences of substring sub in (2)
450,start[,end]]) string s.
Raymond Hettinger72348842003-01-25 21:22:52 +0000451s.decode(([ return a decoded version of s. (3)
452 encoding
453 [,errors]])
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000454s.encode([ return an encoded version of s. Default encoding is the
Raymond Hettinger72348842003-01-25 21:22:52 +0000455 encoding current default string encoding. (3)
456 [,errors]])
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000457s.endswith(suffix return true if s ends with the specified suffix, (2)
Raymond Hettinger72348842003-01-25 21:22:52 +0000458 [,start[,end]]) otherwise return False.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000459s.expandtabs([ return a copy of s where all tab characters are (4)
460tabsize]) expanded using spaces.
461s.find(sub[,start return the lowest index in s where substring sub is (2)
462[,end]]) found. Return -1 if sub is not found.
463s.index(sub[ like find(), but raise ValueError when the substring is (2)
464,start[,end]]) not found.
Raymond Hettinger72348842003-01-25 21:22:52 +0000465s.isalnum() return True if all characters in s are alphanumeric, (5)
466 False otherwise.
467s.isalpha() return True if all characters in s are alphabetic, (5)
468 False otherwise.
469s.isdigit() return True if all characters in s are digit (5)
470 characters, False otherwise.
471s.islower() return True if all characters in s are lowercase, False (6)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000472 otherwise.
Raymond Hettinger72348842003-01-25 21:22:52 +0000473s.isspace() return True if all characters in s are whitespace (5)
474 characters, False otherwise.
475s.istitle() return True if string s is a titlecased string, False (7)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000476 otherwise.
Raymond Hettinger72348842003-01-25 21:22:52 +0000477s.isupper() return True if all characters in s are uppercase, False (6)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000478 otherwise.
479s.join(seq) return a concatenation of the strings in the sequence
480 seq, seperated by 's's.
481s.ljust(width) return s left justified in a string of length width. (1),
482 (8)
483s.lower() return a copy of s converted to lowercase.
484s.lstrip() return a copy of s with leading whitespace removed.
485s.replace(old, return a copy of s with all occurrences of substring (9)
486new[, maxsplit]) old replaced by new.
487s.rfind(sub[ return the highest index in s where substring sub is (2)
488,start[,end]]) found. Return -1 if sub is not found.
489s.rindex(sub[ like rfind(), but raise ValueError when the substring (2)
490,start[,end]]) is not found.
491s.rjust(width) return s right justified in a string of length width. (1),
492 (8)
493s.rstrip() return a copy of s with trailing whitespace removed.
494s.split([sep[ return a list of the words in s, using sep as the (10)
495,maxsplit]]) delimiter string.
496s.splitlines([ return a list of the lines in s, breaking at line (11)
497keepends]) boundaries.
498s.startswith return true if s starts with the specified prefix,
499(prefix[,start[ otherwise return false. (2)
500,end]])
501s.strip() return a copy of s with leading and trailing whitespace
502 removed.
503s.swapcase() return a copy of s with uppercase characters converted
504 to lowercase and vice versa.
505 return a titlecased copy of s, i.e. words start with
506s.title() uppercase characters, all remaining cased characters
507 are lowercase.
508s.translate(table return a copy of s mapped through translation table (12)
509[,deletechars]) table.
510s.upper() return a copy of s converted to uppercase.
Raymond Hettinger5a772d32003-01-25 22:35:42 +0000511s.zfill(width) return a string padded with zeroes on the left side and
Raymond Hettinger72348842003-01-25 21:22:52 +0000512 sliding a minus sign left if necessary. never truncates.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000513
514Notes :
515 (1) Padding is done using spaces.
516 (2) If optional argument start is supplied, substring s[start:] is
517processed. If optional arguments start and end are supplied, substring s[start:
518end] is processed.
519 (3) Optional argument errors may be given to set a different error handling
520scheme. The default for errors is 'strict', meaning that encoding errors raise
521a ValueError. Other possible values are 'ignore' and 'replace'.
522 (4) If optional argument tabsize is not given, a tab size of 8 characters
523is assumed.
524 (5) Returns false if string s does not contain at least one character.
525 (6) Returns false if string s does not contain at least one cased
526character.
527 (7) A titlecased string is a string in which uppercase characters may only
528follow uncased characters and lowercase characters only cased ones.
529 (8) s is returned if width is less than len(s).
530 (9) If the optional argument maxsplit is given, only the first maxsplit
531occurrences are replaced.
532 (10) If sep is not specified or None, any whitespace string is a separator.
533If maxsplit is given, at most maxsplit splits are done.
534 (11) Line breaks are not included in the resulting list unless keepends is
535given and true.
536 (12) table must be a string of length 256. All characters occurring in the
537optional argument deletechars are removed prior to translation.
538
539String formatting with the % operator
540
541formatString % args--> evaluates to a string
542
543 * formatString uses C printf format codes : %, c, s, i, d, u, o, x, X, e, E,
544 f, g, G, r (details below).
545 * Width and precision may be a * to specify that an integer argument gives
546 the actual width or precision.
547 * The flag characters -, +, blank, # and 0 are understood. (details below)
548 * %s will convert any type argument to string (uses str() function)
549 * args may be a single arg or a tuple of args
550
551 '%s has %03d quote types.' % ('Python', 2) # => 'Python has 002 quote types.'
552
553 * Right-hand-side can also be a mapping:
554
555 a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python}
556(vars() function very handy to use on right-hand-side.)
557
558 Format codes
559Conversion Meaning
560d Signed integer decimal.
561i Signed integer decimal.
562o Unsigned octal.
563u Unsigned decimal.
564x Unsigned hexidecimal (lowercase).
565X Unsigned hexidecimal (uppercase).
566e Floating point exponential format (lowercase).
567E Floating point exponential format (uppercase).
568f Floating point decimal format.
569F Floating point decimal format.
570g Same as "e" if exponent is greater than -4 or less than precision,
571 "f" otherwise.
572G Same as "E" if exponent is greater than -4 or less than precision,
573 "F" otherwise.
574c Single character (accepts integer or single character string).
575r String (converts any python object using repr()).
576s String (converts any python object using str()).
577% No argument is converted, results in a "%" character in the result.
578 (The complete specification is %%.)
579
580 Conversion flag characters
581Flag Meaning
582# The value conversion will use the ``alternate form''.
5830 The conversion will be zero padded.
584- The converted value is left adjusted (overrides "-").
585 (a space) A blank should be left before a positive number (or empty
586 string) produced by a signed conversion.
587+ A sign character ("+" or "-") will precede the conversion (overrides a
588 "space" flag).
589
590File Objects
591
592Created with built-in function open; may be created by other modules' functions
593as well.
594
595Operators on file objects
596
597 File operations
598 Operation Result
599f.close() Close file f.
600f.fileno() Get fileno (fd) for file f.
601f.flush() Flush file f's internal buffer.
602f.isatty() 1 if file f is connected to a tty-like dev, else 0.
603f.read([size]) Read at most size bytes from file f and return as a string
604 object. If size omitted, read to EOF.
605f.readline() Read one entire line from file f.
606f.readlines() Read until EOF with readline() and return list of lines read.
607 Set file f's position, like "stdio's fseek()".
608f.seek(offset[, whence == 0 then use absolute indexing.
609whence=0]) whence == 1 then offset relative to current pos.
610 whence == 2 then offset relative to file end.
611f.tell() Return file f's current position (byte offset).
612f.write(str) Write string to file f.
613f.writelines(list Write list of strings to file f.
614)
615
616File Exceptions
617
618 EOFError
619 End-of-file hit when reading (may be raised many times, e.g. if f is a
620 tty).
621 IOError
622 Other I/O-related I/O operation failure
623
624
625 Advanced Types
626
627 -See manuals for more details -
628 + Module objects
629 + Class objects
630 + Class instance objects
631 + Type objects (see module: types)
632 + File objects (see above)
633 + Slice objects
634 + XRange objects
635 + Callable types:
636 o User-defined (written in Python):
637 # User-defined Function objects
638 # User-defined Method objects
639 o Built-in (written in C):
640 # Built-in Function objects
641 # Built-in Method objects
642 + Internal Types:
643 o Code objects (byte-compile executable Python code: bytecode)
644 o Frame objects (execution frames)
645 o Traceback objects (stack trace of an exception)
646
647
648 Statements
649
650 pass -- Null statement
651 del name[,name]* -- Unbind name(s) from object. Object will be indirectly
652 (and automatically) deleted only if no longer referenced.
653 print [>> fileobject,] [s1 [, s2 ]* [,]
654 -- Writes to sys.stdout, or to fileobject if supplied.
655 Puts spaces between arguments. Puts newline at end
656 unless statement ends with comma.
657 Print is not required when running interactively,
658 simply typing an expression will print its value,
659 unless the value is None.
660 exec x [in globals [,locals]]
661 -- Executes x in namespaces provided. Defaults
662 to current namespaces. x can be a string, file
663 object or a function object.
664 callable(value,... [id=value], [*args], [**kw])
665 -- Call function callable with parameters. Parameters can
666 be passed by name or be omitted if function
667 defines default values. E.g. if callable is defined as
668 "def callable(p1=1, p2=2)"
669 "callable()" <=> "callable(1, 2)"
670 "callable(10)" <=> "callable(10, 2)"
671 "callable(p2=99)" <=> "callable(1, 99)"
672 *args is a tuple of positional arguments.
673 **kw is a dictionary of keyword arguments.
674
675 Assignment operators
676
677 Caption
678 Operator Result Notes
679 a = b Basic assignment - assign object b to label a (1)
680 a += b Roughly equivalent to a = a + b (2)
681 a -= b Roughly equivalent to a = a - b (2)
682 a *= b Roughly equivalent to a = a * b (2)
683 a /= b Roughly equivalent to a = a / b (2)
684 a %= b Roughly equivalent to a = a % b (2)
685 a **= b Roughly equivalent to a = a ** b (2)
686 a &= b Roughly equivalent to a = a & b (2)
687 a |= b Roughly equivalent to a = a | b (2)
688 a ^= b Roughly equivalent to a = a ^ b (2)
689 a >>= b Roughly equivalent to a = a >> b (2)
690 a <<= b Roughly equivalent to a = a << b (2)
691
692 Notes :
693 (1) Can unpack tuples, lists, and strings.
694 first, second = a[0:2]; [f, s] = range(2); c1,c2,c3='abc'
695 Tip: x,y = y,x swaps x and y.
696 (2) Not exactly equivalent - a is evaluated only once. Also, where
697 possible, operation performed in-place - a is modified rather than
698 replaced.
699
700 Control Flow
701
702 if condition: suite
703 [elif condition: suite]*
704 [else: suite] -- usual if/else_if/else statement
705 while condition: suite
706 [else: suite]
707 -- usual while statement. "else" suite is executed
708 after loop exits, unless the loop is exited with
709 "break"
710 for element in sequence: suite
711 [else: suite]
712 -- iterates over sequence, assigning each element to element.
713 Use built-in range function to iterate a number of times.
714 "else" suite executed at end unless loop exited
715 with "break"
716 break -- immediately exits "for" or "while" loop
717 continue -- immediately does next iteration of "for" or "while" loop
718 return [result] -- Exits from function (or method) and returns result (use a tuple to
719 return more than one value). If no result given, then returns None.
720
721 Exception Statements
722
723 assert expr[, message]
724 -- expr is evaluated. if false, raises exception AssertionError
725 with message. Inhibited if __debug__ is 0.
726 try: suite1
727 [except [exception [, value]: suite2]+
728 [else: suite3]
729 -- statements in suite1 are executed. If an exception occurs, look
730 in "except" clauses for matching <exception>. If matches or bare
731 "except" execute suite of that clause. If no exception happens
732 suite in "else" clause is executed after suite1.
733 If exception has a value, it is put in value.
734 exception can also be tuple of exceptions, e.g.
735 "except (KeyError, NameError), val: print val"
736 try: suite1
737 finally: suite2
738 -- statements in suite1 are executed. If no
739 exception, execute suite2 (even if suite1 is
740 exited with a "return", "break" or "continue"
741 statement). If exception did occur, executes
742 suite2 and then immediately reraises exception.
743 raise exception [,value [, traceback]]
744 -- raises exception with optional value
745 value. Arg traceback specifies a traceback object to
746 use when printing the exception's backtrace.
747 raise -- a raise statement without arguments re-raises
748 the last exception raised in the current function
749An exception is either a string (object) or a class instance.
750 Can create a new one simply by creating a new string:
751
752 my_exception = 'You did something wrong'
753 try:
754 if bad:
755 raise my_exception, bad
756 except my_exception, value:
757 print 'Oops', value
758
759Exception classes must be derived from the predefined class: Exception, e.g.:
760 class text_exception(Exception): pass
761 try:
762 if bad:
763 raise text_exception()
764 # This is a shorthand for the form
765 # "raise <class>, <instance>"
766 except Exception:
767 print 'Oops'
768 # This will be printed because
769 # text_exception is a subclass of Exception
770When an error message is printed for an unhandled exception which is a
771class, the class name is printed, then a colon and a space, and
772finally the instance converted to a string using the built-in function
773str().
774All built-in exception classes derives from StandardError, itself
775derived from Exception.
776
777Name Space Statements
778
779[1.51: On Mac & Windows, the case of module file names must now match the case
780as used
781 in the import statement]
782Packages (>1.5): a package is a name space which maps to a directory including
783 module(s) and the special initialization module '__init__.py'
784 (possibly empty). Packages/dirs can be nested. You address a
785 module's symbol via '[package.[package...]module.symbol's.
786import module1 [as name1] [, module2]*
787 -- imports modules. Members of module must be
788 referred to by qualifying with [package.]module name:
789 "import sys; print sys.argv:"
790 "import package1.subpackage.module; package1.subpackage.module.foo()"
791 module1 renamed as name1, if supplied.
792from module import name1 [as othername1] [, name2]*
793 -- imports names from module module in current namespace.
794 "from sys import argv; print argv"
795 "from package1 import module; module.foo()"
796 "from package1.module import foo; foo()"
797 name1 renamed as othername1, if supplied.
798from module import *
799 -- imports all names in module, except those starting with "_";
800 *to be used sparsely, beware of name clashes* :
801 "from sys import *; print argv"
802 "from package.module import *; print x'
803 NB: "from package import *" only imports the symbols defined
804 in the package's __init__.py file, not those in the
805 template modules!
806global name1 [, name2]*
807 -- names are from global scope (usually meaning from module)
808 rather than local (usually meaning only in function).
809 -- E.g. in fct without "global" statements, assuming
810 "a" is name that hasn't been used in fct or module
811 so far:
812 -Try to read from "a" -> NameError
813 -Try to write to "a" -> creates "a" local to fcn
814 -If "a" not defined in fct, but is in module, then
815 -Try to read from "a", gets value from module
816 -Try to write to "a", creates "a" local to fct
817 But note "a[0]=3" starts with search for "a",
818 will use to global "a" if no local "a".
819
820Function Definition
821
822def func_id ([param_list]): suite
823 -- Creates a function object & binds it to name func_id.
824
825 param_list ::= [id [, id]*]
826 id ::= value | id = value | *id | **id
827 [Args are passed by value.Thus only args representing a mutable object
828 can be modified (are inout parameters). Use a tuple to return more than
829 one value]
830
831Example:
832 def test (p1, p2 = 1+1, *rest, **keywords):
833 -- Parameters with "=" have default value (v is
834 evaluated when function defined).
835 If list has "*id" then id is assigned a tuple of
836 all remaining args passed to function (like C vararg)
837 If list has "**id" then id is assigned a dictionary of
838 all extra arguments passed as keywords.
839
840Class Definition
841
842class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite>
843 -- Creates a class object and assigns it name <class_id>
844 <suite> may contain local "defs" of class methods and
845 assignments to class attributes.
846Example:
847 class my_class (class1, class_list[3]): ...
848 Creates a class object inheriting from both "class1" and whatever
849 class object "class_list[3]" evaluates to. Assigns new
850 class object to name "my_class".
851 - First arg to class methods is always instance object, called 'self'
852 by convention.
853 - Special method __init__() is called when instance is created.
854 - Special method __del__() called when no more reference to object.
855 - Create instance by "calling" class object, possibly with arg
856 (thus instance=apply(aClassObject, args...) creates an instance!)
857 - In current implementation, can't subclass off built-in
858 classes. But can "wrap" them, see UserDict & UserList modules,
859 and see __getattr__() below.
860Example:
861 class c (c_parent):
862 def __init__(self, name): self.name = name
863 def print_name(self): print "I'm", self.name
864 def call_parent(self): c_parent.print_name(self)
865 instance = c('tom')
866 print instance.name
867 'tom'
868 instance.print_name()
869 "I'm tom"
870 Call parent's super class by accessing parent's method
871 directly and passing "self" explicitly (see "call_parent"
872 in example above).
873 Many other special methods available for implementing
874 arithmetic operators, sequence, mapping indexing, etc.
875
876Documentation Strings
877
878Modules, classes and functions may be documented by placing a string literal by
879itself as the first statement in the suite. The documentation can be retrieved
880by getting the '__doc__' attribute from the module, class or function.
881Example:
882 class C:
883 "A description of C"
884 def __init__(self):
885 "A description of the constructor"
886 # etc.
887Then c.__doc__ == "A description of C".
888Then c.__init__.__doc__ == "A description of the constructor".
889
890Others
891
892lambda [param_list]: returnedExpr
893 -- Creates an anonymous function. returnedExpr must be
894 an expression, not a statement (e.g., not "if xx:...",
895 "print xxx", etc.) and thus can't contain newlines.
896 Used mostly for filter(), map(), reduce() functions, and GUI callbacks..
897List comprehensions
898result = [expression for item1 in sequence1 [if condition1]
899 [for item2 in sequence2 ... for itemN in sequenceN]
900 ]
901is equivalent to:
902result = []
903for item1 in sequence1:
904 for item2 in sequence2:
905 ...
906 for itemN in sequenceN:
907 if (condition1) and furthur conditions:
908 result.append(expression)
909
910
911
912Built-In Functions
913
914 Built-In Functions
915 Function Result
916__import__(name[, Imports module within the given context (see lib ref for
917globals[, locals[, more details)
918fromlist]]])
919abs(x) Return the absolute value of number x.
920apply(f, args[, Calls func/method f with arguments args and optional
921keywords]) keywords.
922callable(x) Returns 1 if x callable, else 0.
923chr(i) Returns one-character string whose ASCII code isinteger i
924cmp(x,y) Returns negative, 0, positive if x <, ==, > to y
925coerce(x,y) Returns a tuple of the two numeric arguments converted to a
926 common type.
927 Compiles string into a code object.filename is used in
928 error message, can be any string. It isusually the file
929compile(string, from which the code was read, or eg. '<string>'if not read
930filename, kind) from file.kind can be 'eval' if string is a single stmt, or
931 'single' which prints the output of expression statements
932 thatevaluate to something else than None, or be 'exec'.
933complex(real[, Builds a complex object (can also be done using J or j
934image]) suffix,e.g. 1+3J)
935delattr(obj, name) deletes attribute named name of object obj <=> del obj.name
936 If no args, returns the list of names in current
937dir([object]) localsymbol table. With a module, class or class
938 instanceobject as arg, returns list of names in its attr.
939 dict.
940divmod(a,b) Returns tuple of (a/b, a%b)
941eval(s[, globals[, Eval string s in (optional) globals, locals contexts.s must
942locals]]) have no NUL's or newlines. s can also be acode object.
943 Example: x = 1; incr_x = eval('x + 1')
944execfile(file[, Executes a file without creating a new module, unlike
945globals[, locals]]) import.
946filter(function, Constructs a list from those elements of sequence for which
947sequence) function returns true. function takes one parameter.
948float(x) Converts a number or a string to floating point.
949getattr(object, [<default> arg added in 1.5.2]Gets attribute called name
950name[, default])) from object,e.g. getattr(x, 'f') <=> x.f). If not found,
951 raisesAttributeError or returns default if specified.
952globals() Returns a dictionary containing current global variables.
953hasattr(object, Returns true if object has attr called name.
954name)
955hash(object) Returns the hash value of the object (if it has one)
956hex(x) Converts a number x to a hexadecimal string.
957id(object) Returns a unique 'identity' integer for an object.
958input([prompt]) Prints prompt if given. Reads input and evaluates it.
959 Converts a number or a string to a plain integer. Optional
960int(x[, base]) base paramenter specifies base from which to convert string
961 values.
962intern(aString) Enters aString in the table of "interned strings"
963 andreturns the string. Interned strings are 'immortals'.
964isinstance(obj, returns true if obj is an instance of class. Ifissubclass
965class) (A,B) then isinstance(x,A) => isinstance(x,B)
966issubclass(class1, returns true if class1 is derived from class2
967class2)
968 Returns the length (the number of items) of an object
969len(obj) (sequence, dictionary, or instance of class implementing
970 __len__).
971list(sequence) Converts sequence into a list. If already a list,returns a
972 copy of it.
973locals() Returns a dictionary containing current local variables.
974 Converts a number or a string to a long integer. Optional
975long(x[, base]) base paramenter specifies base from which to convert string
976 values.
977 Applies function to every item of list and returns a listof
978map(function, list, the results. If additional arguments are passed,function
979...) must take that many arguments and it is givento function on
980 each call.
981max(seq) Returns the largest item of the non-empty sequence seq.
982min(seq) Returns the smallest item of a non-empty sequence seq.
983oct(x) Converts a number to an octal string.
984open(filename [, Returns a new file object. First two args are same asthose
985mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered,
986implementation 1 for line-buffered, negative forsys-default, all else, of
987dependent]]) (about) given size.
988ord(c) Returns integer ASCII value of c (a string of len 1). Works
989 with Unicode char.
990pow(x, y [, z]) Returns x to power y [modulo z]. See also ** operator.
991range(start [,end Returns list of ints from >= start and < end.With 1 arg,
992[, step]]) list from 0..arg-1With 2 args, list from start..end-1With 3
993 args, list from start up to end by step
994raw_input([prompt]) Prints prompt if given, then reads string from stdinput (no
995 trailing \n). See also input().
996reduce(f, list [, Applies the binary function f to the items oflist so as to
997init]) reduce the list to a single value.If init given, it is
998 "prepended" to list.
999 Re-parses and re-initializes an already imported module.
1000 Useful in interactive mode, if you want to reload amodule
1001reload(module) after fixing it. If module was syntacticallycorrect but had
1002 an error in initialization, mustimport it one more time
1003 before calling reload().
1004 Returns a string containing a printable and if possible
1005repr(object) evaluable representation of an object. <=> `object`
1006 (usingbackquotes). Class redefinissable (__repr__). See
1007 also str()
1008round(x, n=0) Returns the floating point value x rounded to n digitsafter
1009 the decimal point.
1010setattr(object, This is the counterpart of getattr().setattr(o, 'foobar',
1011name, value) 3) <=> o.foobar = 3Creates attribute if it doesn't exist!
1012slice([start,] stop Returns a slice object representing a range, with R/
1013[, step]) Oattributes: start, stop, step.
1014 Returns a string containing a nicely
1015str(object) printablerepresentation of an object. Class overridable
1016 (__str__).See also repr().
1017tuple(sequence) Creates a tuple with same elements as sequence. If already
1018 a tuple, return itself (not a copy).
1019 Returns a type object [see module types] representing
1020 thetype of obj. Example: import typesif type(x) ==
1021type(obj) types.StringType: print 'It is a string'NB: it is
1022 recommanded to use the following form:if isinstance(x,
1023 types.StringType): etc...
1024unichr(code) code.
1025unicode(string[, Creates a Unicode string from a 8-bit string, using
1026encoding[, error thegiven encoding name and error treatment ('strict',
1027]]]) 'ignore',or 'replace'}.
1028 Without arguments, returns a dictionary correspondingto the
1029 current local symbol table. With a module,class or class
1030vars([object]) instance object as argumentreturns a dictionary
1031 corresponding to the object'ssymbol table. Useful with "%"
1032 formatting operator.
1033xrange(start [, end Like range(), but doesn't actually store entire listall at
1034[, step]]) once. Good to use in "for" loops when there is abig range
1035 and little memory.
1036zip(seq1[, seq2, Returns a list of tuples where each tuple contains the nth
1037...]) element of each of the argument sequences.
1038
1039
1040
1041
1042Built-In Exceptions
1043
1044Exception>
1045 Root class for all exceptions
1046 SystemExit
1047 On 'sys.exit()'
1048 StandardError
1049 Base class for all built-in exceptions; derived from Exception
1050 root class.
1051 ArithmeticError
1052 Base class for OverflowError, ZeroDivisionError,
1053 FloatingPointError
1054 FloatingPointError
1055 When a floating point operation fails.
1056 OverflowError
1057 On excessively large arithmetic operation
1058 ZeroDivisionError
1059 On division or modulo operation with 0 as 2nd arg
1060 AssertionError
1061 When an assert statement fails.
1062 AttributeError
1063 On attribute reference or assignment failure
1064 EnvironmentError [new in 1.5.2]
1065 On error outside Python; error arg tuple is (errno, errMsg...)
1066 IOError [changed in 1.5.2]
1067 I/O-related operation failure
1068 OSError [new in 1.5.2]
1069 used by the os module's os.error exception.
1070 EOFError
1071 Immediate end-of-file hit by input() or raw_input()
1072 ImportError
1073 On failure of `import' to find module or name
1074 KeyboardInterrupt
1075 On user entry of the interrupt key (often `Control-C')
1076 LookupError
1077 base class for IndexError, KeyError
1078 IndexError
1079 On out-of-range sequence subscript
1080 KeyError
1081 On reference to a non-existent mapping (dict) key
1082 MemoryError
1083 On recoverable memory exhaustion
1084 NameError
1085 On failure to find a local or global (unqualified) name
1086 RuntimeError
1087 Obsolete catch-all; define a suitable error instead
1088 NotImplementedError [new in 1.5.2]
1089 On method not implemented
1090 SyntaxError
1091 On parser encountering a syntax error
1092 IndentationError
1093 On parser encountering an indentation syntax error
1094 TabError
1095 On parser encountering an indentation syntax error
1096 SystemError
1097 On non-fatal interpreter error - bug - report it
1098 TypeError
1099 On passing inappropriate type to built-in op or func
1100 ValueError
1101 On arg error not covered by TypeError or more precise
1102
1103
1104
1105Standard methods & operators redefinition in classes
1106
1107Standard methods & operators map to special '__methods__' and thus may be
1108 redefined (mostly in in user-defined classes), e.g.:
1109 class x:
1110 def __init__(self, v): self.value = v
1111 def __add__(self, r): return self.value + r
1112 a = x(3) # sort of like calling x.__init__(a, 3)
1113 a + 4 # is equivalent to a.__add__(4)
1114
1115Special methods for any class
1116
1117(s: self, o: other)
1118 __init__(s, args) instance initialization (on construction)
1119 __del__(s) called on object demise (refcount becomes 0)
1120 __repr__(s) repr() and `...` conversions
1121 __str__(s) str() and 'print' statement
1122 __cmp__(s, o) Compares s to o and returns <0, 0, or >0.
1123 Implements >, <, == etc...
1124 __hash__(s) Compute a 32 bit hash code; hash() and dictionary ops
1125 __nonzero__(s) Returns 0 or 1 for truth value testing
1126 __getattr__(s, name) called when attr lookup doesn't find <name>
1127 __setattr__(s, name, val) called when setting an attr
1128 (inside, don't use "self.name = value"
1129 use "self.__dict__[name] = val")
1130 __delattr__(s, name) called to delete attr <name>
1131 __call__(self, *args) called when an instance is called as function.
1132
1133Operators
1134
1135 See list in the operator module. Operator function names are provided with
1136 2 variants, with or without
1137 ading & trailing '__' (eg. __add__ or add).
1138
1139 Numeric operations special methods
1140 (s: self, o: other)
1141
1142 s+o = __add__(s,o) s-o = __sub__(s,o)
1143 s*o = __mul__(s,o) s/o = __div__(s,o)
1144 s%o = __mod__(s,o) divmod(s,o) = __divmod__(s,o)
1145 s**o = __pow__(s,o)
1146 s&o = __and__(s,o)
1147 s^o = __xor__(s,o) s|o = __or__(s,o)
1148 s<<o = __lshift__(s,o) s>>o = __rshift__(s,o)
1149 nonzero(s) = __nonzero__(s) (used in boolean testing)
1150 -s = __neg__(s) +s = __pos__(s)
1151 abs(s) = __abs__(s) ~s = __invert__(s) (bitwise)
1152 s+=o = __iadd__(s,o) s-=o = __isub__(s,o)
1153 s*=o = __imul__(s,o) s/=o = __idiv__(s,o)
1154 s%=o = __imod__(s,o)
1155 s**=o = __ipow__(s,o)
1156 s&=o = __iand__(s,o)
1157 s^=o = __ixor__(s,o) s|=o = __ior__(s,o)
1158 s<<=o = __ilshift__(s,o) s>>=o = __irshift__(s,o)
1159 Conversions
1160 int(s) = __int__(s) long(s) = __long__(s)
1161 float(s) = __float__(s) complex(s) = __complex__(s)
1162 oct(s) = __oct__(s) hex(s) = __hex__(s)
1163 coerce(s,o) = __coerce__(s,o)
1164 Right-hand-side equivalents for all binary operators exist;
1165 are called when class instance is on r-h-s of operator:
1166 a + 3 calls __add__(a, 3)
1167 3 + a calls __radd__(a, 3)
1168
1169 All seqs and maps, general operations plus:
1170 (s: self, i: index or key)
1171
1172 len(s) = __len__(s) length of object, >= 0. Length 0 == false
1173 s[i] = __getitem__(s,i) Element at index/key i, origin 0
1174
1175 Sequences, general methods, plus:
1176 s[i]=v = __setitem__(s,i,v)
1177 del s[i] = __delitem__(s,i)
1178 s[i:j] = __getslice__(s,i,j)
1179 s[i:j]=seq = __setslice__(s,i,j,seq)
1180 del s[i:j] = __delslice__(s,i,j) == s[i:j] = []
1181 seq * n = __repeat__(seq, n)
1182 s1 + s2 = __concat__(s1, s2)
1183 i in s = __contains__(s, i)
1184 Mappings, general methods, plus
1185 hash(s) = __hash__(s) - hash value for dictionary references
1186 s[k]=v = __setitem__(s,k,v)
1187 del s[k] = __delitem__(s,k)
1188
1189Special informative state attributes for some types:
1190
1191 Lists & Dictionaries:
1192 __methods__ (list, R/O): list of method names of the object
1193
1194 Modules:
1195 __doc__ (string/None, R/O): doc string (<=> __dict__['__doc__'])
1196 __name__(string, R/O): module name (also in __dict__['__name__'])
1197 __dict__ (dict, R/O): module's name space
1198 __file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for
1199 modules statically linked to the interpreter)
1200 __path__(string/undefined, R/O): fully qualified package name when applies.
1201
1202 Classes: [in bold: writable since 1.5.2]
1203 __doc__ (string/None, R/W): doc string (<=> __dict__['__doc__'])
1204 __name__(string, R/W): class name (also in __dict__['__name__'])
1205 __bases__ (tuple, R/W): parent classes
1206 __dict__ (dict, R/W): attributes (class name space)
1207
1208 Instances:
1209 __class__ (class, R/W): instance's class
1210 __dict__ (dict, R/W): attributes
1211 User-defined functions: [bold: writable since 1.5.2]
1212 __doc__ (string/None, R/W): doc string
1213 __name__(string, R/O): function name
1214 func_doc (R/W): same as __doc__
1215 func_name (R/O): same as __name__
1216 func_defaults (tuple/None, R/W): default args values if any
1217 func_code (code, R/W): code object representing the compiled function body
1218 func_globals (dict, R/O): ref to dictionary of func global variables
1219
1220 User-defined Methods:
1221 __doc__ (string/None, R/O): doc string
1222 __name__(string, R/O): method name (same as im_func.__name__)
1223 im_class (class, R/O): class defining the method (may be a base class)
1224 im_self (instance/None, R/O): target instance object (None if unbound)
1225 im_func (function, R/O): function object
1226 Built-in Functions & methods:
1227 __doc__ (string/None, R/O): doc string
1228 __name__ (string, R/O): function name
1229 __self__ : [methods only] target object
1230 __members__ = list of attr names: ['__doc__','__name__','__self__'])
1231 Codes:
1232 co_name (string, R/O): function name
1233 co_argcount (int, R/0): number of positional args
1234 co_nlocals (int, R/O): number of local vars (including args)
1235 co_varnames (tuple, R/O): names of local vars (starting with args)
1236 co_code (string, R/O): sequence of bytecode instructions
1237 co_consts (tuple, R/O): litterals used by the bytecode, 1st one is
1238 fct doc (or None)
1239 co_names (tuple, R/O): names used by the bytecode
1240 co_filename (string, R/O): filename from which the code was compiled
1241 co_firstlineno (int, R/O): first line number of the function
1242 co_lnotab (string, R/O): string encoding bytecode offsets to line numbers.
1243 co_stacksize (int, R/O): required stack size (including local vars)
1244 co_firstlineno (int, R/O): first line number of the function
1245 co_flags (int, R/O): flags for the interpreter
1246 bit 2 set if fct uses "*arg" syntax
1247 bit 3 set if fct uses '**keywords' syntax
1248 Frames:
1249 f_back (frame/None, R/O): previous stack frame (toward the caller)
1250 f_code (code, R/O): code object being executed in this frame
1251 f_locals (dict, R/O): local vars
1252 f_globals (dict, R/O): global vars
1253 f_builtins (dict, R/O): built-in (intrinsic) names
1254 f_restricted (int, R/O): flag indicating whether fct is executed in
1255 restricted mode
1256 f_lineno (int, R/O): current line number
1257 f_lasti (int, R/O): precise instruction (index into bytecode)
1258 f_trace (function/None, R/W): debug hook called at start of each source line
1259 f_exc_type (Type/None, R/W): Most recent exception type
1260 f_exc_value (any, R/W): Most recent exception value
1261 f_exc_traceback (traceback/None, R/W): Most recent exception traceback
1262 Tracebacks:
1263 tb_next (frame/None, R/O): next level in stack trace (toward the frame where
1264 the exception occurred)
1265 tb_frame (frame, R/O): execution frame of the current level
1266 tb_lineno (int, R/O): line number where the exception occured
1267 tb_lasti (int, R/O): precise instruction (index into bytecode)
1268
1269 Slices:
1270 start (any/None, R/O): lowerbound
1271 stop (any/None, R/O): upperbound
1272 step (any/None, R/O): step value
1273
1274 Complex numbers:
1275 real (float, R/O): real part
1276 imag (float, R/O): imaginary part
1277 XRanges:
1278 tolist (Built-in method, R/O): ?
1279
1280
1281Important Modules
1282
1283 sys
1284
1285 Some sys variables
1286 Variable Content
1287argv The list of command line arguments passed to aPython
1288 script. sys.argv[0] is the script name.
1289builtin_module_names A list of strings giving the names of all moduleswritten
1290 in C that are linked into this interpreter.
1291check_interval How often to check for thread switches or signals(measured
1292 in number of virtual machine instructions)
1293exc_type, exc_value, Deprecated since release 1.5. Use exc_info() instead.
1294exc_traceback
1295exitfunc User can set to a parameterless fcn. It will getcalled
1296 before interpreter exits.
1297last_type, Set only when an exception not handled andinterpreter
1298last_value, prints an error. Used by debuggers.
1299last_traceback
1300maxint maximum positive value for integers
1301modules Dictionary of modules that have already been loaded.
1302path Search path for external modules. Can be modifiedby
1303 program. sys.path[0] == dir of script executing
1304platform The current platform, e.g. "sunos5", "win32"
1305ps1, ps2 prompts to use in interactive mode.
1306 File objects used for I/O. One can redirect byassigning a
1307stdin, stdout, new file object to them (or any object:.with a method
1308stderr write(string) for stdout/stderr,.with a method readline()
1309 for stdin)
1310version string containing version info about Python interpreter.
1311 (and also: copyright, dllhandle, exec_prefix, prefix)
1312version_info tuple containing Python version info - (major, minor,
1313 micro, level, serial).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001314
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001315 Some sys functions
1316 Function Result
1317exit(n) Exits with status n. Raises SystemExit exception.(Hence can
1318 be caught and ignored by program)
1319getrefcount(object Returns the reference count of the object. Generally 1
1320) higherthan you might expect, because of object arg temp
1321 reference.
1322setcheckinterval( Sets the interpreter's thread switching interval (in number
1323interval) ofvirtualcode instructions, default:10).
1324settrace(func) Sets a trace function: called before each line ofcode is
1325 exited.
1326setprofile(func) Sets a profile function for performance profiling.
1327 Info on exception currently being handled; this is atuple
1328 (exc_type, exc_value, exc_traceback).Warning: assigning the
1329exc_info() traceback return value to a loca variable in a
1330 functionhandling an exception will cause a circular
1331 reference.
1332setdefaultencoding Change default Unicode encoding - defaults to 7-bit ASCII.
1333(encoding)
1334getrecursionlimit Retrieve maximum recursion depth.
1335()
1336setrecursionlimit Set maximum recursion depth. (Defaults to 1000.)
1337()
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001338
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001339
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001340
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001341 os
1342"synonym" for whatever O/S-specific module is proper for current environment.
1343this module uses posix whenever possible.
1344(see also M.A. Lemburg's utility http://www.lemburg.com/files/python/
1345platform.py)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001346
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001347 Some os variables
1348 Variable Meaning
1349name name of O/S-specific module (e.g. "posix", "mac", "nt")
1350path O/S-specific module for path manipulations.
1351 On Unix, os.path.split() <=> posixpath.split()
1352curdir string used to represent current directory ('.')
1353pardir string used to represent parent directory ('..')
1354sep string used to separate directories ('/' or '\'). Tip: use
1355 os.path.join() to build portable paths.
1356altsep Alternate sep
1357if applicable (None
1358otherwise)
1359pathsep character used to separate search path components (as in
1360 $PATH), eg. ';' for windows.
1361linesep line separator as used in binary files, ie '\n' on Unix, '\
1362 r\n' on Dos/Win, '\r'
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001363
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001364 Some os functions
1365 Function Result
1366makedirs(path[, Recursive directory creation (create required intermediary
1367mode=0777]) dirs); os.error if fails.
1368removedirs(path) Recursive directory delete (delete intermediary empty
1369 dirs); if fails.
1370renames(old, new) Recursive directory or file renaming; os.error if fails.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001371
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001372
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001373
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001374 posix
1375don't import this module directly, import os instead !
1376(see also module: shutil for file copy & remove fcts)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001377
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001378 posix Variables
1379Variable Meaning
1380environ dictionary of environment variables, e.g.posix.environ['HOME'].
1381error exception raised on POSIX-related error.
1382 Corresponding value is tuple of errno code and perror() string.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001383
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001384 Some posix functions
1385 Function Result
1386chdir(path) Changes current directory to path.
1387chmod(path, Changes the mode of path to the numeric mode
1388mode)
1389close(fd) Closes file descriptor fd opened with posix.open.
1390_exit(n) Immediate exit, with no cleanups, no SystemExit,etc. Should use
1391 this to exit a child process.
1392execv(p, args) "Become" executable p with args args
1393getcwd() Returns a string representing the current working directory
1394getpid() Returns the current process id
1395fork() Like C's fork(). Returns 0 to child, child pid to parent.[Not
1396 on Windows]
1397kill(pid, Like C's kill [Not on Windows]
1398signal)
1399listdir(path) Lists (base)names of entries in directory path, excluding '.'
1400 and '..'
1401lseek(fd, pos, Sets current position in file fd to position pos, expressedas
1402how) an offset relative to beginning of file (how=0), tocurrent
1403 position (how=1), or to end of file (how=2)
1404mkdir(path[, Creates a directory named path with numeric mode (default 0777)
1405mode])
1406open(file, Like C's open(). Returns file descriptor. Use file object
1407flags, mode) fctsrather than this low level ones.
1408pipe() Creates a pipe. Returns pair of file descriptors (r, w) [Not on
1409 Windows].
1410popen(command, Opens a pipe to or from command. Result is a file object to
1411mode='r', read to orwrite from, as indicated by mode being 'r' or 'w'.
1412bufSize=0) Use it to catch acommand output ('r' mode) or to feed it ('w'
1413 mode).
1414remove(path) See unlink.
1415rename(src, dst Renames/moves the file or directory src to dst. [error iftarget
1416) name already exists]
1417rmdir(path) Removes the empty directory path
1418read(fd, n) Reads n bytes from file descriptor fd and return as string.
1419 Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid,
1420stat(path) st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid
1421 are dummy on Windows]
1422system(command) Executes string command in a subshell. Returns exitstatus of
1423 subshell (usually 0 means OK).
1424 Returns accumulated CPU times in sec (user, system, children's
1425times() user,children's sys, elapsed real time). [3 last not on
1426 Windows]
1427unlink(path) Unlinks ("deletes") the file (not dir!) path. same as: remove
1428utime(path, ( Sets the access & modified time of the file to the given tuple
1429aTime, mTime)) of values.
1430wait() Waits for child process completion. Returns tuple ofpid,
1431 exit_status [Not on Windows]
1432waitpid(pid, Waits for process pid to complete. Returns tuple ofpid,
1433options) exit_status [Not on Windows]
1434write(fd, str) Writes str to file fd. Returns nb of bytes written.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001435
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001436
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001437
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001438 posixpath
1439Do not import this module directly, import os instead and refer to this module
1440as os.path. (e.g. os.path.exists(p)) !
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001441
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001442 Some posixpath functions
1443 Function Result
1444abspath(p) Returns absolute path for path p, taking current working dir in
1445 account.
1446dirname/
1447basename(p directory and name parts of the path p. See also split.
1448)
1449exists(p) True if string p is an existing path (file or directory)
1450expanduser Returns string that is (a copy of) p with "~" expansion done.
1451(p)
1452expandvars Returns string that is (a copy of) p with environment vars expanded.
1453(p) [Windows: case significant; must use Unix: $var notation, not %var%]
1454getsize( return the size in bytes of filename. raise os.error.
1455filename)
1456getmtime( return last modification time of filename (integer nb of seconds
1457filename) since epoch).
1458getatime( return last access time of filename (integer nb of seconds since
1459filename) epoch).
1460isabs(p) True if string p is an absolute path.
1461isdir(p) True if string p is a directory.
1462islink(p) True if string p is a symbolic link.
1463ismount(p) True if string p is a mount point [true for all dirs on Windows].
1464join(p[,q Joins one or more path components intelligently.
1465[,...]])
1466 Splits p into (head, tail) where tail is lastpathname component and
1467split(p) <head> is everything leadingup to that. <=> (dirname(p), basename
1468 (p))
1469splitdrive Splits path p in a pair ('drive:', tail) [Windows]
1470(p)
1471splitext(p Splits into (root, ext) where last comp of root contains no periods
1472) and ext is empty or startswith a period.
1473 Calls the function visit with arguments(arg, dirname, names) for
1474 each directory recursively inthe directory tree rooted at p
1475walk(p, (including p itself if it's a dir)The argument dirname specifies the
1476visit, arg visited directory, the argumentnames lists the files in the
1477) directory. The visit function maymodify names to influence the set
1478 of directories visited belowdirname, e.g., to avoid visiting certain
1479 parts of the tree.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001480
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001481
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001482
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001483 shutil
1484high-level file operations (copying, deleting).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001485
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001486 Main shutil functions
1487 Function Result
1488copy(src, dst) Copies the contents of file src to file dst, retaining file
1489 permissions.
1490copytree(src, dst Recursively copies an entire directory tree rooted at src
1491[, symlinks]) into dst (which should not already exist). If symlinks is
1492 true, links insrc are kept as such in dst.
1493rmtree(path[, Deletes an entire directory tree, ignoring errors if
1494ignore_errors[, ignore_errors true,or calling onerror(func, path,
1495onerror]]) sys.exc_info()) if supplied with
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001496
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001497(and also: copyfile, copymode, copystat, copy2)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001498
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001499time
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001500
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001501 Variables
1502Variable Meaning
1503altzone signed offset of local DST timezone in sec west of the 0th meridian.
1504daylight nonzero if a DST timezone is specified
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001505
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001506 Functions
1507 Function Result
1508time() return a float representing UTC time in seconds since the epoch.
1509gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day
1510localtime( (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is
1511secs) monday), Julian day(1-366), daylight flag(-1,0 or 1))
1512asctime(
1513timeTuple),
1514strftime(
1515format, return a formated string representing time.
1516timeTuple)
1517mktime(tuple) inverse of localtime(). Return a float.
1518strptime( parse a formated string representing time, return tuple as in
1519string[, gmtime().
1520format])
1521sleep(secs) Suspend execution for <secs> seconds. <secs> can be a float.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001522
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001523and also: clock, ctime.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001524
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001525 string
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001526
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001527As of Python 2.0, much (though not all) of the functionality provided by the
1528string module have been superseded by built-in string methods - see Operations
1529on strings for details.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001530
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001531 Some string variables
1532 Variable Meaning
1533digits The string '0123456789'
1534hexdigits, octdigits legal hexadecimal & octal digits
1535letters, uppercase, lowercase, Strings containing the appropriate
1536whitespace characters
1537index_error Exception raised by index() if substr not
1538 found.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001539
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001540 Some string functions
1541 Function Result
1542expandtabs(s, returns a copy of string <s> with tabs expanded.
1543tabSize)
1544find/rfind(s, sub Return the lowest/highest index in <s> where the substring
1545[, start=0[, end= <sub> is found such that <sub> is wholly contained ins
15460]) [start:end]. Return -1 if <sub> not found.
1547ljust/rjust/center Return a copy of string <s> left/right justified/centerd in
1548(s, width) afield of given width, padded with spaces. <s> is
1549 nevertruncated.
1550lower/upper(s) Return a string that is (a copy of) <s> in lowercase/
1551 uppercase
1552split(s[, sep= Return a list containing the words of the string <s>,using
1553whitespace[, the string <sep> as a separator.
1554maxsplit=0]])
1555join(words[, sep=' Concatenate a list or tuple of words with
1556']) interveningseparators; inverse of split.
1557replace(s, old, Returns a copy of string <s> with all occurences of
1558new[, maxsplit=0] substring<old> replaced by <new>. Limits to <maxsplit>
1559 firstsubstitutions if specified.
1560strip(s) Return a string that is (a copy of) <s> without leadingand
1561 trailing whitespace. see also lstrip, rstrip.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001562
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001563
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001564
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001565 re (sre)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001566
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001567Handles Unicode strings. Implemented in new module sre, re now a mere front-end
1568for compatibility.
1569Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to
1570litteralize backslashes.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001571
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001572
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001573 Regular expression syntax
1574 Form Description
1575. matches any character (including newline if DOTALL flag specified)
1576^ matches start of the string (of every line in MULTILINE mode)
1577$ matches end of the string (of every line in MULTILINE mode)
1578* 0 or more of preceding regular expression (as many as possible)
1579+ 1 or more of preceding regular expression (as many as possible)
1580? 0 or 1 occurence of preceding regular expression
1581*?, +?, ?? Same as *, + and ? but matches as few characters as possible
1582{m,n} matches from m to n repetitions of preceding RE
1583{m,n}? idem, attempting to match as few repetitions as possible
1584[ ] defines character set: e.g. '[a-zA-Z]' to match all letters(see also
1585 \w \S)
1586[^ ] defines complemented character set: matches if char is NOT in set
1587 escapes special chars '*?+&$|()' and introduces special sequences
1588\ (see below). Due to Python string rules, write as '\\' orr'\' in the
1589 pattern string.
1590\\ matches a litteral '\'; due to Python string rules, write as '\\\\
1591 'in pattern string, or better using raw string: r'\\'.
1592| specifies alternative: 'foo|bar' matches 'foo' or 'bar'
1593(...) matches any RE inside (), and delimits a group.
1594(?:...) idem but doesn't delimit a group.
1595 matches if ... matches next, but doesn't consume any of the string
1596(?=...) e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by
1597 'Asimov'.
1598(?!...) matches if ... doesn't match next. Negative of (?=...)
1599(?P<name matches any RE inside (), and delimits a named group. (e.g. r'(?P
1600>...) <id>[a-zA-Z_]\w*)' defines a group named id)
1601(?P=name) matches whatever text was matched by the earlier group named name.
1602(?#...) A comment; ignored.
1603(?letter) letter is one of 'i','L', 'm', 's', 'x'. Set the corresponding flags
1604 (re.I, re.L, re.M, re.S, re.X) for the entire RE.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001605
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001606 Special sequences
1607Sequence Description
1608number matches content of the group of the same number; groups are numbered
1609 starting from 1
1610\A matches only at the start of the string
1611\b empty str at beg or end of word: '\bis\b' matches 'is', but not 'his'
1612\B empty str NOT at beginning or end of word
1613\d any decimal digit (<=> [0-9])
1614\D any non-decimal digit char (<=> [^O-9])
1615\s any whitespace char (<=> [ \t\n\r\f\v])
1616\S any non-whitespace char (<=> [^ \t\n\r\f\v])
1617\w any alphaNumeric char (depends on LOCALE flag)
1618\W any non-alphaNumeric char (depends on LOCALE flag)
1619\Z matches only at the end of the string
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001620
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001621 Variables
1622Variable Meaning
1623error Exception when pattern string isn't a valid regexp.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001624
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001625 Functions
1626 Function Result
1627 Compile a RE pattern string into a regular expression object.
1628 Flags (combinable by |):
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001629
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001630 I or IGNORECASE or (?i)
1631 case insensitive matching
1632compile( L or LOCALE or (?L)
1633pattern[, make \w, \W, \b, \B dependent on thecurrent locale
1634flags=0]) M or MULTILINE or (?m)
1635 matches every new line and not onlystart/end of the whole
1636 string
1637 S or DOTALL or (?s)
1638 '.' matches ALL chars, including newline
1639 X or VERBOSE or (?x)
1640 Ignores whitespace outside character sets
1641escape(string) return (a copy of) string with all non-alphanumerics
1642 backslashed.
1643match(pattern, if 0 or more chars at beginning of <string> match the RE pattern
1644string[, flags string,return a corresponding MatchObject instance, or None if
1645]) no match.
1646search(pattern scan thru <string> for a location matching <pattern>, return
1647, string[, acorresponding MatchObject instance, or None if no match.
1648flags])
1649split(pattern, split <string> by occurrences of <pattern>. If capturing () are
1650string[, used inpattern, then occurrences of patterns or subpatterns are
1651maxsplit=0]) also returned.
1652findall( return a list of non-overlapping matches in <pattern>, either a
1653pattern, list ofgroups or a list of tuples if the pattern has more than 1
1654string) group.
1655 return string obtained by replacing the (<count> first) lefmost
1656sub(pattern, non-overlapping occurrences of <pattern> (a string or a RE
1657repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct
1658count=0]) called with a single MatchObj arg, which must return the
1659 replacement string.
1660subn(pattern,
1661repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade)
1662count=0])
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001663
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001664Regular Expression Objects
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001665
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001666
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001667(RE objects are returned by the compile fct)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001668
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001669 re object attributes
1670Attribute Descrition
1671flags flags arg used when RE obj was compiled, or 0 if none provided
1672groupindex dictionary of {group name: group number} in pattern
1673pattern pattern string from which RE obj was compiled
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001674
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001675 re object methods
1676 Method Result
1677 If zero or more characters at the beginning of string match this
1678 regular expression, return a corresponding MatchObject instance.
1679 Return None if the string does not match the pattern; note that
1680 this is different from a zero-length match.
1681 The optional second parameter pos gives an index in the string
1682match( where the search is to start; it defaults to 0. This is not
1683string[, completely equivalent to slicing the string; the '' pattern
1684pos][, character matches at the real beginning of the string and at
1685endpos]) positions just after a newline, but not necessarily at the index
1686 where the search is to start.
1687 The optional parameter endpos limits how far the string will be
1688 searched; it will be as if the string is endpos characters long, so
1689 only the characters from pos to endpos will be searched for a
1690 match.
1691 Scan through string looking for a location where this regular
1692search( expression produces a match, and return a corresponding MatchObject
1693string[, instance. Return None if no position in the string matches the
1694pos][, pattern; note that this is different from finding a zero-length
1695endpos]) match at some point in the string.
1696 The optional pos and endpos parameters have the same meaning as for
1697 the match() method.
1698split(
1699string[, Identical to the split() function, using the compiled pattern.
1700maxsplit=
17010])
1702findall( Identical to the findall() function, using the compiled pattern.
1703string)
1704sub(repl,
1705string[, Identical to the sub() function, using the compiled pattern.
1706count=0])
1707subn(repl,
1708string[, Identical to the subn() function, using the compiled pattern.
1709count=0])
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001710
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001711Match Objects
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001712
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001713
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001714(Match objects are returned by the match & search functions)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001715
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001716 Match object attributes
1717Attribute Description
1718pos value of pos passed to search or match functions; index intostring at
1719 which RE engine started search.
1720endpos value of endpos passed to search or match functions; index intostring
1721 beyond which RE engine won't go.
1722re RE object whose match or search fct produced this MatchObj instance
1723string string passed to match() or search()
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001724
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001725 Match object functions
1726Function Result
1727 returns one or more groups of the match. If one arg, result is a
1728group([g1 string;if multiple args, result is a tuple with one item per arg. If
1729, g2, gi is 0,return value is entire matching string; if 1 <= gi <= 99,
1730...]) returnstring matching group #gi (or None if no such group); gi may
1731 also bea group name.
1732 returns a tuple of all groups of the match; groups not
1733groups() participatingto the match have a value of None. Returns a string
1734 instead of tupleif len(tuple)=1
1735start(
1736group), returns indices of start & end of substring matched by group (or
1737end(group Noneif group exists but doesn't contribute to the match)
1738)
1739span( returns the 2-tuple (start(group), end(group)); can be (None, None)if
1740group) group didn't contibute to the match.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001741
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001742
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001743
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001744 math
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001745
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001746Variables:
1747pi
1748e
1749Functions (see ordinary C man pages for info):
1750acos(x)
1751asin(x)
1752atan(x)
1753atan2(x, y)
1754ceil(x)
1755cos(x)
1756cosh(x)
1757exp(x)
1758fabs(x)
1759floor(x)
1760fmod(x, y)
1761frexp(x) -- Unlike C: (float, int) = frexp(float)
1762ldexp(x, y)
1763log(x)
1764log10(x)
1765modf(x) -- Unlike C: (float, float) = modf(float)
1766pow(x, y)
1767sin(x)
1768sinh(x)
1769sqrt(x)
1770tan(x)
1771tanh(x)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001772
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001773 getopt
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001774
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001775Functions:
1776getopt(list, optstr) -- Similar to C. <optstr> is option
1777 letters to look for. Put ':' after letter
1778 if option takes arg. E.g.
1779 # invocation was "python test.py -c hi -a arg1 arg2"
1780 opts, args = getopt.getopt(sys.argv[1:], 'ab:c:')
1781 # opts would be
1782 [('-c', 'hi'), ('-a', '')]
1783 # args would be
1784 ['arg1', 'arg2']
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001785
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001786
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001787List of modules and packages in base distribution
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001788
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001789(built-ins and content of python Lib directory)
1790(Python NT distribution, may be slightly different in other distributions)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001791
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001792 Standard library modules
1793 Operation Result
1794aifc Stuff to parse AIFF-C and AIFF files.
1795anydbm Generic interface to all dbm clones. (dbhash, gdbm,
1796 dbm,dumbdbm)
1797asynchat Support for 'chat' style protocols
1798asyncore Asynchronous File I/O (in select style)
1799atexit Register functions to be called at exit of Python interpreter.
1800audiodev Audio support for a few platforms.
1801base64 Conversions to/from base64 RFC-MIME transport encoding .
1802BaseHTTPServer Base class forhttp services.
1803Bastion "Bastionification" utility (control access to instance vars)
1804bdb A generic Python debugger base class.
1805binhex Macintosh binhex compression/decompression.
1806bisect List bisection algorithms.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001807bz2 Support for bz2 compression/decompression.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001808calendar Calendar printing functions.
1809cgi Wraps the WWW Forms Common Gateway Interface (CGI).
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001810cgitb Utility for handling CGI tracebacks.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001811CGIHTTPServer CGI http services.
1812cmd A generic class to build line-oriented command interpreters.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001813datetime Basic date and time types.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001814code Utilities needed to emulate Python's interactive interpreter
1815codecs Lookup existing Unicode encodings and register new ones.
1816colorsys Conversion functions between RGB and other color systems.
1817commands Tools for executing UNIX commands .
1818compileall Force "compilation" of all .py files in a directory.
1819ConfigParser Configuration file parser (much like windows .ini files)
1820copy Generic shallow and deep copying operations.
1821copy_reg Helper to provide extensibility for pickle/cPickle.
1822dbhash (g)dbm-compatible interface to bsdhash.hashopen.
1823dircache Sorted list of files in a dir, using a cache.
1824[DEL:dircmp:DEL] [DEL:Defines a class to build directory diff tools on.:DEL]
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001825difflib Tool for creating delta between sequences.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001826dis Bytecode disassembler.
1827distutils Package installation system.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001828doctest Tool for running and verifying tests inside doc strings.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001829dospath Common operations on DOS pathnames.
1830dumbdbm A dumb and slow but simple dbm clone.
1831[DEL:dump:DEL] [DEL:Print python code that reconstructs a variable.:DEL]
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001832email Comprehensive support for internet email.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001833exceptions Class based built-in exception hierarchy.
1834filecmp File comparison.
1835fileinput Helper class to quickly write a loop over all standard input
1836 files.
1837[DEL:find:DEL] [DEL:Find files directory hierarchy matching a pattern.:DEL]
1838fnmatch Filename matching with shell patterns.
1839formatter A test formatter.
1840fpformat General floating point formatting functions.
1841ftplib An FTP client class. Based on RFC 959.
1842gc Perform garbacge collection, obtain GC debug stats, and tune
1843 GC parameters.
1844getopt Standard command line processing. See also ftp://
1845 www.pauahtun.org/pub/getargspy.zip
1846getpass Utilities to get a password and/or the current user name.
1847glob filename globbing.
1848gopherlib Gopher protocol client interface.
1849[DEL:grep:DEL] [DEL:'grep' utilities.:DEL]
1850gzip Read & write gzipped files.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001851heapq Priority queue implemented using lists organized as heaps.
1852HMAC Keyed-Hashing for Message Authentication -- RFC 2104.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001853htmlentitydefs Proposed entity definitions for HTML.
1854htmllib HTML parsing utilities.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001855HTMLParser A parser for HTML and XHTML.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001856httplib HTTP client class.
1857ihooks Hooks into the "import" mechanism.
1858imaplib IMAP4 client.Based on RFC 2060.
1859imghdr Recognizing image files based on their first few bytes.
1860imputil Privides a way of writing customised import hooks.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001861inspect Tool for probing live Python objects.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001862keyword List of Python keywords.
1863knee A Python re-implementation of hierarchical module import.
1864linecache Cache lines from files.
1865linuxaudiodev Lunix /dev/audio support.
1866locale Support for number formatting using the current locale
1867 settings.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001868logging Python logging facility.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001869macpath Pathname (or related) operations for the Macintosh.
1870macurl2path Mac specific module for conversion between pathnames and URLs.
1871mailbox A class to handle a unix-style or mmdf-style mailbox.
1872mailcap Mailcap file handling (RFC 1524).
1873mhlib MH (mailbox) interface.
1874mimetools Various tools used by MIME-reading or MIME-writing programs.
1875mimetypes Guess the MIME type of a file.
1876MimeWriter Generic MIME writer.
1877mimify Mimification and unmimification of mail messages.
1878mmap Interface to memory-mapped files - they behave like mutable
1879 strings./font>
1880multifile Class to make multi-file messages easier to handle.
1881mutex Mutual exclusion -- for use with module sched.
1882netrc
1883nntplib An NNTP client class. Based on RFC 977.
1884ntpath Common operations on DOS pathnames.
1885nturl2path Mac specific module for conversion between pathnames and URLs.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001886optparse A comprehensive tool for processing command line options.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001887os Either mac, dos or posix depending system.
1888[DEL:packmail: [DEL:Create a self-unpacking shell archive.:DEL]
1889DEL]
1890pdb A Python debugger.
1891pickle Pickling (save and restore) of Python objects (a faster
1892 Cimplementation exists in built-in module: cPickle).
1893pipes Conversion pipeline templates.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001894pkgunil Utilities for working with Python packages.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001895popen2 variations on pipe open.
1896poplib A POP3 client class. Based on the J. Myers POP3 draft.
1897posixfile Extended (posix) file operations.
1898posixpath Common operations on POSIX pathnames.
1899pprint Support to pretty-print lists, tuples, & dictionaries
1900 recursively.
1901profile Class for profiling python code.
1902pstats Class for printing reports on profiled python code.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001903pydoc Utility for generating documentation from source files.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001904pty Pseudo terminal utilities.
1905pyexpat Interface to the Expay XML parser.
1906py_compile Routine to "compile" a .py file to a .pyc file.
1907pyclbr Parse a Python file and retrieve classes and methods.
1908Queue A multi-producer, multi-consumer queue.
1909quopri Conversions to/from quoted-printable transport encoding.
1910rand Don't use unless you want compatibility with C's rand().
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001911random Random variable generators
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001912re Regular Expressions.
1913reconvert Convert old ("regex") regular expressions to new syntax
1914 ("re").
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001915repr Redo repr() but with limits on most sizes.
1916rexec Restricted execution facilities ("safe" exec, eval, etc).
1917rfc822 RFC-822 message manipulation class.
1918rlcompleter Word completion for GNU readline 2.0.
1919robotparser Parse robot.txt files, useful for web spiders.
1920sched A generally useful event scheduler class.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001921sets Module for a set datatype.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001922sgmllib A parser for SGML.
1923shelve Manage shelves of pickled objects.
1924shlex Lexical analyzer class for simple shell-like syntaxes.
1925shutil Utility functions usable in a shell-like program.
1926SimpleHTTPServer Simple extension to base http class
1927site Append module search paths for third-party packages to
1928 sys.path.
1929smtplib SMTP Client class (RFC 821)
1930sndhdr Several routines that help recognizing sound.
1931SocketServer Generic socket server classes.
1932stat Constants and functions for interpreting stat/lstat struct.
1933statcache Maintain a cache of file stats.
1934statvfs Constants for interpreting statvfs struct as returned by
1935 os.statvfs()and os.fstatvfs() (if they exist).
1936string A collection of string operations.
1937StringIO File-like objects that read/write a string buffer (a fasterC
1938 implementation exists in built-in module: cStringIO).
1939sunau Stuff to parse Sun and NeXT audio files.
1940sunaudio Interpret sun audio headers.
1941symbol Non-terminal symbols of Python grammar (from "graminit.h").
1942tabnanny,/font> Check Python source for ambiguous indentation.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001943tarfile Facility for reading and writing to the *nix tarfile format.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001944telnetlib TELNET client class. Based on RFC 854.
1945tempfile Temporary file name allocation.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001946textwrap Object for wrapping and filling text.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001947threading Proposed new higher-level threading interfaces
1948threading_api (doc of the threading module)
1949toaiff Convert "arbitrary" sound files to AIFF files .
1950token Tokens (from "token.h").
1951tokenize Compiles a regular expression that recognizes Python tokens.
1952traceback Format and print Python stack traces.
1953tty Terminal utilities.
1954turtle LogoMation-like turtle graphics
1955types Define names for all type symbols in the std interpreter.
1956tzparse Parse a timezone specification.
1957unicodedata Interface to unicode properties.
1958urllib Open an arbitrary URL.
1959urlparse Parse URLs according to latest draft of standard.
1960user Hook to allow user-specified customization code to run.
1961UserDict A wrapper to allow subclassing of built-in dict class.
1962UserList A wrapper to allow subclassing of built-in list class.
1963UserString A wrapper to allow subclassing of built-in string class.
1964[DEL:util:DEL] [DEL:some useful functions that don't fit elsewhere !!:DEL]
1965uu UUencode/UUdecode.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001966unittest Utilities for implementing unit testing.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001967wave Stuff to parse WAVE files.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001968weakref Tools for creating and managing weakly referenced objects.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001969webbrowser Platform independent URL launcher.
1970[DEL:whatsound: [DEL:Several routines that help recognizing sound files.:DEL]
1971DEL]
1972whichdb Guess which db package to use to open a db file.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001973xdrlib Implements (a subset of) Sun XDR (eXternal Data
1974 Representation)
1975xmllib A parser for XML, using the derived class as static DTD.
1976xml.dom Classes for processing XML using the Document Object Model.
1977xml.sax Classes for processing XML using the SAX API.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001978xmlrpclib Support for remote procedure calls using XML.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001979zipfile Read & write PK zipped files.
1980[DEL:zmod:DEL] [DEL:Demonstration of abstruse mathematical concepts.:DEL]
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001981
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001982
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001983
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001984(following list not revised)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001985
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001986* Built-ins *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001987
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001988 sys Interpreter state vars and functions
1989 __built-in__ Access to all built-in python identifiers
1990 __main__ Scope of the interpreters main program, script or stdin
1991 array Obj efficiently representing arrays of basic values
1992 math Math functions of C standard
1993 time Time-related functions
1994 regex Regular expression matching operations
1995 marshal Read and write some python values in binary format
1996 struct Convert between python values and C structs
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001997
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001998* Standard *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001999
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002000 getopt Parse cmd line args in sys.argv. A la UNIX 'getopt'.
2001 os A more portable interface to OS dependent functionality
2002 re Functions useful for working with regular expressions
2003 string Useful string and characters functions and exceptions
2004 whrandom Wichmann-Hill pseudo-random number generator
2005 thread Low-level primitives for working with process threads
2006 threading idem, new recommanded interface.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002007
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002008* Unix/Posix *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002009
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002010 dbm Interface to Unix ndbm database library
2011 grp Interface to Unix group database
2012 posix OS functionality standardized by C and POSIX standards
2013 posixpath POSIX pathname functions
2014 pwd Access to the Unix password database
2015 select Access to Unix select multiplex file synchronization
2016 socket Access to BSD socket interface
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002017
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002018* Tk User-interface Toolkit *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002019
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002020 tkinter Main interface to Tk
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002021
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002022* Multimedia *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002023
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002024 audioop Useful operations on sound fragments
2025 imageop Useful operations on images
2026 jpeg Access to jpeg image compressor and decompressor
2027 rgbimg Access SGI imglib image files
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002028
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002029* Cryptographic Extensions *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002030
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002031 md5 Interface to RSA's MD5 message digest algorithm
2032 mpz Interface to int part of GNU multiple precision library
2033 rotor Implementation of a rotor-based encryption algorithm
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002034
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002035* Stdwin * Standard Window System
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002036
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002037 stdwin Standard Window System interface
2038 stdwinevents Stdwin event, command, and selection constants
2039 rect Rectangle manipulation operations
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002040
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002041* SGI IRIX * (4 & 5)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002042
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002043 al SGI audio facilities
2044 AL al constants
2045 fl Interface to FORMS library
2046 FL fl constants
2047 flp Functions for form designer
2048 fm Access to font manager library
2049 gl Access to graphics library
2050 GL Constants for gl
2051 DEVICE More constants for gl
2052 imgfile Imglib image file interface
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002053
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002054* Suns *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002055
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002056 sunaudiodev Access to sun audio interface
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002057
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002058
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002059Workspace exploration and idiom hints
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002060
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002061 dir(<module>) list functions, variables in <module>
2062 dir() get object keys, defaults to local name space
2063 X.__methods__ list of methods supported by X (if any)
2064 X.__members__ List of X's data attributes
2065 if __name__ == '__main__': main() invoke main if running as script
2066 map(None, lst1, lst2, ...) merge lists
2067 b = a[:] create copy of seq structure
2068 _ in interactive mode, is last value printed
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002069
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002070
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002071
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002072
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002073
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002074
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002075
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002076Python Mode for Emacs
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002077
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002078(Not revised, possibly not up to date)
2079Type C-c ? when in python-mode for extensive help.
2080INDENTATION
2081Primarily for entering new code:
2082 TAB indent line appropriately
2083 LFD insert newline, then indent
2084 DEL reduce indentation, or delete single character
2085Primarily for reindenting existing code:
2086 C-c : guess py-indent-offset from file content; change locally
2087 C-u C-c : ditto, but change globally
2088 C-c TAB reindent region to match its context
2089 C-c < shift region left by py-indent-offset
2090 C-c > shift region right by py-indent-offset
2091MARKING & MANIPULATING REGIONS OF CODE
2092C-c C-b mark block of lines
2093M-C-h mark smallest enclosing def
2094C-u M-C-h mark smallest enclosing class
2095C-c # comment out region of code
2096C-u C-c # uncomment region of code
2097MOVING POINT
2098C-c C-p move to statement preceding point
2099C-c C-n move to statement following point
2100C-c C-u move up to start of current block
2101M-C-a move to start of def
2102C-u M-C-a move to start of class
2103M-C-e move to end of def
2104C-u M-C-e move to end of class
2105EXECUTING PYTHON CODE
2106C-c C-c sends the entire buffer to the Python interpreter
2107C-c | sends the current region
2108C-c ! starts a Python interpreter window; this will be used by
2109 subsequent C-c C-c or C-c | commands
2110VARIABLES
2111py-indent-offset indentation increment
2112py-block-comment-prefix comment string used by py-comment-region
2113py-python-command shell command to invoke Python interpreter
2114py-scroll-process-buffer t means always scroll Python process buffer
2115py-temp-directory directory used for temp files (if needed)
2116py-beep-if-tab-change ring the bell if tab-width is changed
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002117
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002118
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002119The Python Debugger
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002120
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002121(Not revised, possibly not up to date, see 1.5.2 Library Ref section 9.1; in 1.5.2, you may also use debugger integrated in IDLE)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002122
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002123Accessing
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002124
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002125import pdb (it's a module written in Python)
2126 -- defines functions :
2127 run(statement[,globals[, locals]])
2128 -- execute statement string under debugger control, with optional
2129 global & local environment.
2130 runeval(expression[,globals[, locals]])
2131 -- same as run, but evaluate expression and return value.
2132 runcall(function[, argument, ...])
2133 -- run function object with given arg(s)
2134 pm() -- run postmortem on last exception (like debugging a core file)
2135 post_mortem(t)
2136 -- run postmortem on traceback object <t>
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002137
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002138 -- defines class Pdb :
2139 use Pdb to create reusable debugger objects. Object
2140 preserves state (i.e. break points) between calls.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002141
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002142 runs until a breakpoint hit, exception, or end of program
2143 If exception, variable '__exception__' holds (exception,value).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002144
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002145Commands
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002146
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002147h, help
2148 brief reminder of commands
2149b, break [<arg>]
2150 if <arg> numeric, break at line <arg> in current file
2151 if <arg> is function object, break on entry to fcn <arg>
2152 if no arg, list breakpoints
2153cl, clear [<arg>]
2154 if <arg> numeric, clear breakpoint at <arg> in current file
2155 if no arg, clear all breakpoints after confirmation
2156w, where
2157 print current call stack
2158u, up
2159 move up one stack frame (to top-level caller)
2160d, down
2161 move down one stack frame
2162s, step
2163 advance one line in the program, stepping into calls
2164n, next
2165 advance one line, stepping over calls
2166r, return
2167 continue execution until current function returns
2168 (return value is saved in variable "__return__", which
2169 can be printed or manipulated from debugger)
2170c, continue
2171 continue until next breakpoint
2172a, args
2173 print args to current function
2174rv, retval
2175 prints return value from last function that returned
2176p, print <arg>
2177 prints value of <arg> in current stack frame
2178l, list [<first> [, <last>]]
2179 List source code for the current file.
2180 Without arguments, list 11 lines around the current line
2181 or continue the previous listing.
2182 With one argument, list 11 lines starting at that line.
2183 With two arguments, list the given range;
2184 if the second argument is less than the first, it is a count.
2185whatis <arg>
2186 prints type of <arg>
2187!
2188 executes rest of line as a Python statement in the current stack frame
2189q quit
2190 immediately stop execution and leave debugger
2191<return>
2192 executes last command again
2193Any input debugger doesn't recognize as a command is assumed to be a
2194Python statement to execute in the current stack frame, the same way
2195the exclamation mark ("!") command does.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002196
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002197Example
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002198
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002199(1394) python
2200Python 1.0.3 (Sep 26 1994)
2201Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
2202>>> import rm
2203>>> rm.run()
2204Traceback (innermost last):
2205 File "<stdin>", line 1
2206 File "./rm.py", line 7
2207 x = div(3)
2208 File "./rm.py", line 2
2209 return a / r
2210ZeroDivisionError: integer division or modulo
2211>>> import pdb
2212>>> pdb.pm()
2213> ./rm.py(2)div: return a / r
2214(Pdb) list
2215 1 def div(a):
2216 2 -> return a / r
2217 3
2218 4 def run():
2219 5 global r
2220 6 r = 0
2221 7 x = div(3)
2222 8 print x
2223[EOF]
2224(Pdb) print r
22250
2226(Pdb) q
2227>>> pdb.runcall(rm.run)
2228etc.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002229
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002230Quirks
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002231
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002232Breakpoints are stored as filename, line number tuples. If a module is reloaded
2233after editing, any remembered breakpoints are likely to be wrong.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002234
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002235Always single-steps through top-most stack frame. That is, "c" acts like "n".
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002236
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002237