blob: ebbf1d457d1db2129b2d7083b76704a50f65e900 [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
Guido van Rossume7ba4952007-06-06 23:52:48 +000044-m mod run library module as a script (terminates option list
Raymond Hettinger72348842003-01-25 21:22:52 +000045-O optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)
46-OO remove doc-strings in addition to the -O optimizations
47-Q arg division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000048-S Don't perform 'import site' on initialization
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000049-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
Raymond Hettingere685f942003-01-26 03:29:15 +0000211 x*y x/y x%y x//y mult, division, modulo, floor division
Georg Brandlf33d01d2005-08-22 19:35:18 +0000212 x+y x-y addition, subtraction
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000213 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,
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000218 x is y x is not y membership
219 x in s x not in s
220 not x boolean negation
221 x and y boolean and
222 x or y boolean or
223Lowest lambda args: expr anonymous function
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000224
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000225Alternate names are defined in module operator (e.g. __add__ and add for +)
Raymond Hettinger72348842003-01-25 21:22:52 +0000226Most operators are overridable.
227
Raymond Hettinger5a772d32003-01-25 22:35:42 +0000228Many binary operators also support augmented assignment:
Raymond Hettinger72348842003-01-25 21:22:52 +0000229 x += 1 # Same as x = x + 1
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000230
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000231
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000232Basic Types and Their Operations
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000233
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000234Comparisons (defined between *any* types)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000235
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000236 Comparisons
237Comparison Meaning Notes
238< strictly less than (1)
239<= less than or equal to
240> strictly greater than
241>= greater than or equal to
242== equal to
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000243!= not equal to
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000244is object identity (2)
245is not negated object identity (2)
246
247Notes :
248 Comparison behavior can be overridden for a given class by defining special
249method __cmp__.
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +0000250 The above comparisons return True or False which are of type bool
Raymond Hettinger5a772d32003-01-25 22:35:42 +0000251(a subclass of int) and behave exactly as 1 or 0 except for their type and
Raymond Hettinger72348842003-01-25 21:22:52 +0000252that they print as True or False instead of 1 or 0.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000253 (1) X < Y < Z < W has expected meaning, unlike C
254 (2) Compare object identities (i.e. id(object)), not object values.
255
256Boolean values and operators
257
258 Boolean values and operators
259 Value or Operator Returns Notes
260None, numeric zeros, empty sequences and False
261mappings
262all other values True
263not x True if x is False, else
264 True
265x or y if x is False then y, else (1)
266 x
267x and y if x is False then x, else (1)
268 y
269
270Notes :
271 Truth testing behavior can be overridden for a given class by defining
Jack Diederich62971282006-11-30 20:50:23 +0000272special method __bool__.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000273 (1) Evaluate second arg only if necessary to determine outcome.
274
275None
276
277 None is used as default return value on functions. Built-in single object
278 with type NoneType.
279 Input that evaluates to None does not print when running Python
280 interactively.
281
282Numeric types
283
Neal Norwitz01688022007-08-12 00:43:29 +0000284Floats and integers.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000285
286 Floats are implemented with C doubles.
Neal Norwitz01688022007-08-12 00:43:29 +0000287 Integers have unlimited size (only limit is system resources)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000288
289Operators on all numeric types
290
291 Operators on all numeric types
292 Operation Result
293abs(x) the absolute value of x
294int(x) x converted to integer
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000295float(x) x converted to floating point
296-x x negated
297+x x unchanged
298x + y the sum of x and y
299x - y difference of x and y
300x * y product of x and y
301x / y quotient of x and y
302x % y remainder of x / y
303divmod(x, y) the tuple (x/y, x%y)
304x ** y x to the power y (the same as pow(x, y))
305
Neal Norwitz01688022007-08-12 00:43:29 +0000306Bit operators on integers
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000307
308 Bit operators
309Operation >Result
310~x the bits of x inverted
311x ^ y bitwise exclusive or of x and y
312x & y bitwise and of x and y
313x | y bitwise or of x and y
314x << n x shifted left by n bits
315x >> n x shifted right by n bits
316
317Complex Numbers
318
319 * represented as a pair of machine-level double precision floating point
320 numbers.
321 * The real and imaginary value of a complex number z can be retrieved through
322 the attributes z.real and z.imag.
323
324Numeric exceptions
325
326TypeError
327 raised on application of arithmetic operation to non-number
328OverflowError
329 numeric bounds exceeded
330ZeroDivisionError
331 raised when zero second argument of div or modulo op
Raymond Hettingere685f942003-01-26 03:29:15 +0000332FloatingPointError
333 raised when a floating point operation fails
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000334
335Operations on all sequence types (lists, tuples, strings)
336
337 Operations on all sequence types
338Operation Result Notes
Raymond Hettingere685f942003-01-26 03:29:15 +0000339x in s True if an item of s is equal to x, else False
340x not in s False if an item of s is equal to x, else True
Raymond Hettinger72348842003-01-25 21:22:52 +0000341for x in s: loops over the sequence
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000342s + t the concatenation of s and t
343s * n, n*s n copies of s concatenated
344s[i] i'th item of s, origin 0 (1)
345s[i:j] slice of s from i (included) to j (excluded) (1), (2)
346len(s) length of s
347min(s) smallest item of s
348max(s) largest item of (s)
Raymond Hettinger72348842003-01-25 21:22:52 +0000349iter(s) returns an iterator over s. iterators define __iter__ and next()
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000350
351Notes :
352 (1) if i or j is negative, the index is relative to the end of the string,
353ie len(s)+ i or len(s)+j is
354 substituted. But note that -0 is still 0.
355 (2) The slice of s from i to j is defined as the sequence of items with
356index k such that i <= k < j.
357 If i or j is greater than len(s), use len(s). If i is omitted, use
358len(s). If i is greater than or
359 equal to j, the slice is empty.
360
361Operations on mutable (=modifiable) sequences (lists)
362
363 Operations on mutable sequences
364 Operation Result Notes
365s[i] =x item i of s is replaced by x
366s[i:j] = t slice of s from i to j is replaced by t
367del s[i:j] same as s[i:j] = []
368s.append(x) same as s[len(s) : len(s)] = [x]
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000369s.count(x) return number of i's for which s[i] == x
Raymond Hettingere685f942003-01-26 03:29:15 +0000370s.extend(x) same as s[len(s):len(s)]= x
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000371s.index(x) return smallest i such that s[i] == x (1)
372s.insert(i, x) same as s[i:i] = [x] if i >= 0
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000373s.pop([i]) same as x = s[i]; del s[i]; return x (4)
Raymond Hettinger72348842003-01-25 21:22:52 +0000374s.remove(x) same as del s[s.index(x)] (1)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000375s.reverse() reverse the items of s in place (3)
376s.sort([cmpFct]) sort the items of s in place (2), (3)
377
378Notes :
379 (1) raise a ValueError exception when x is not found in s (i.e. out of
380range).
381 (2) The sort() method takes an optional argument specifying a comparison
382fct of 2 arguments (list items) which should
383 return -1, 0, or 1 depending on whether the 1st argument is
384considered smaller than, equal to, or larger than the 2nd
385 argument. Note that this slows the sorting process down considerably.
386 (3) The sort() and reverse() methods modify the list in place for economy
387of space when sorting or reversing a large list.
388 They don't return the sorted or reversed list to remind you of this
389side effect.
Raymond Hettinger72348842003-01-25 21:22:52 +0000390 (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 +0000391item is removed and returned.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000392
393
394
395Operations on mappings (dictionaries)
396
397 Operations on mappings
398 Operation Result Notes
399len(d) the number of items in d
400d[k] the item of d with key k (1)
401d[k] = x set d[k] to x
402del d[k] remove d[k] from d (1)
403d.clear() remove all items from d
404d.copy() a shallow copy of d
Raymond Hettinger72348842003-01-25 21:22:52 +0000405d.get(k,defaultval) the item of d with key k (4)
Raymond Hettingere685f942003-01-26 03:29:15 +0000406d.has_key(k) True if d has key k, else False
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000407d.items() a copy of d's list of (key, item) pairs (2)
Raymond Hettinger72348842003-01-25 21:22:52 +0000408d.iteritems() an iterator over (key, value) pairs (7)
409d.iterkeys() an iterator over the keys of d (7)
410d.itervalues() an iterator over the values of d (7)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000411d.keys() a copy of d's list of keys (2)
412d1.update(d2) for k, v in d2.items(): d1[k] = v (3)
413d.values() a copy of d's list of values (2)
Raymond Hettinger72348842003-01-25 21:22:52 +0000414d.pop(k) remove d[k] and return its value
415d.popitem() remove and return an arbitrary (6)
416 (key, item) pair
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000417d.setdefault(k,defaultval) the item of d with key k (5)
418
419 Notes :
420 TypeError is raised if key is not acceptable
421 (1) KeyError is raised if key k is not in the map
422 (2) Keys and values are listed in random order
423 (3) d2 must be of the same type as d1
424 (4) Never raises an exception if k is not in the map, instead it returns
425 defaultVal.
426 defaultVal is optional, when not provided and k is not in the map,
427 None is returned.
428 (5) Never raises an exception if k is not in the map, instead it returns
429 defaultVal, and adds k to map with value defaultVal. defaultVal is
430 optional. When not provided and k is not in the map, None is returned and
431 added to map.
Raymond Hettinger72348842003-01-25 21:22:52 +0000432 (6) Raises a KeyError if the dictionary is emtpy.
433 (7) While iterating over a dictionary, the values may be updated but
434 the keys cannot be changed.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000435
436Operations on strings
437
438Note that these string methods largely (but not completely) supersede the
439functions available in the string module.
440
441
442 Operations on strings
443 Operation Result Notes
444s.capitalize() return a copy of s with only its first character
445 capitalized.
446s.center(width) return a copy of s centered in a string of length width (1)
447 .
448s.count(sub[ return the number of occurrences of substring sub in (2)
449,start[,end]]) string s.
Raymond Hettinger72348842003-01-25 21:22:52 +0000450s.decode(([ return a decoded version of s. (3)
451 encoding
452 [,errors]])
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000453s.encode([ return an encoded version of s. Default encoding is the
Raymond Hettinger72348842003-01-25 21:22:52 +0000454 encoding current default string encoding. (3)
455 [,errors]])
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000456s.endswith(suffix return true if s ends with the specified suffix, (2)
Raymond Hettinger72348842003-01-25 21:22:52 +0000457 [,start[,end]]) otherwise return False.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000458s.expandtabs([ return a copy of s where all tab characters are (4)
459tabsize]) expanded using spaces.
460s.find(sub[,start return the lowest index in s where substring sub is (2)
461[,end]]) found. Return -1 if sub is not found.
462s.index(sub[ like find(), but raise ValueError when the substring is (2)
463,start[,end]]) not found.
Raymond Hettinger72348842003-01-25 21:22:52 +0000464s.isalnum() return True if all characters in s are alphanumeric, (5)
465 False otherwise.
466s.isalpha() return True if all characters in s are alphabetic, (5)
467 False otherwise.
468s.isdigit() return True if all characters in s are digit (5)
469 characters, False otherwise.
470s.islower() return True if all characters in s are lowercase, False (6)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000471 otherwise.
Raymond Hettinger72348842003-01-25 21:22:52 +0000472s.isspace() return True if all characters in s are whitespace (5)
473 characters, False otherwise.
474s.istitle() return True if string s is a titlecased string, False (7)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000475 otherwise.
Raymond Hettinger72348842003-01-25 21:22:52 +0000476s.isupper() return True if all characters in s are uppercase, False (6)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000477 otherwise.
478s.join(seq) return a concatenation of the strings in the sequence
Mark Dickinson934896d2009-02-21 20:59:32 +0000479 seq, separated by 's's.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000480s.ljust(width) return s left justified in a string of length width. (1),
481 (8)
482s.lower() return a copy of s converted to lowercase.
483s.lstrip() return a copy of s with leading whitespace removed.
484s.replace(old, return a copy of s with all occurrences of substring (9)
485new[, maxsplit]) old replaced by new.
486s.rfind(sub[ return the highest index in s where substring sub is (2)
487,start[,end]]) found. Return -1 if sub is not found.
488s.rindex(sub[ like rfind(), but raise ValueError when the substring (2)
489,start[,end]]) is not found.
490s.rjust(width) return s right justified in a string of length width. (1),
491 (8)
492s.rstrip() return a copy of s with trailing whitespace removed.
493s.split([sep[ return a list of the words in s, using sep as the (10)
494,maxsplit]]) delimiter string.
495s.splitlines([ return a list of the lines in s, breaking at line (11)
496keepends]) boundaries.
497s.startswith return true if s starts with the specified prefix,
498(prefix[,start[ otherwise return false. (2)
499,end]])
500s.strip() return a copy of s with leading and trailing whitespace
501 removed.
502s.swapcase() return a copy of s with uppercase characters converted
503 to lowercase and vice versa.
504 return a titlecased copy of s, i.e. words start with
505s.title() uppercase characters, all remaining cased characters
506 are lowercase.
507s.translate(table return a copy of s mapped through translation table (12)
508[,deletechars]) table.
509s.upper() return a copy of s converted to uppercase.
Raymond Hettinger5a772d32003-01-25 22:35:42 +0000510s.zfill(width) return a string padded with zeroes on the left side and
Raymond Hettinger72348842003-01-25 21:22:52 +0000511 sliding a minus sign left if necessary. never truncates.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000512
513Notes :
514 (1) Padding is done using spaces.
515 (2) If optional argument start is supplied, substring s[start:] is
516processed. If optional arguments start and end are supplied, substring s[start:
517end] is processed.
518 (3) Optional argument errors may be given to set a different error handling
519scheme. The default for errors is 'strict', meaning that encoding errors raise
520a ValueError. Other possible values are 'ignore' and 'replace'.
521 (4) If optional argument tabsize is not given, a tab size of 8 characters
522is assumed.
523 (5) Returns false if string s does not contain at least one character.
524 (6) Returns false if string s does not contain at least one cased
525character.
526 (7) A titlecased string is a string in which uppercase characters may only
527follow uncased characters and lowercase characters only cased ones.
528 (8) s is returned if width is less than len(s).
529 (9) If the optional argument maxsplit is given, only the first maxsplit
530occurrences are replaced.
531 (10) If sep is not specified or None, any whitespace string is a separator.
532If maxsplit is given, at most maxsplit splits are done.
533 (11) Line breaks are not included in the resulting list unless keepends is
534given and true.
535 (12) table must be a string of length 256. All characters occurring in the
536optional argument deletechars are removed prior to translation.
537
538String formatting with the % operator
539
540formatString % args--> evaluates to a string
541
542 * formatString uses C printf format codes : %, c, s, i, d, u, o, x, X, e, E,
543 f, g, G, r (details below).
544 * Width and precision may be a * to specify that an integer argument gives
545 the actual width or precision.
546 * The flag characters -, +, blank, # and 0 are understood. (details below)
547 * %s will convert any type argument to string (uses str() function)
548 * args may be a single arg or a tuple of args
549
550 '%s has %03d quote types.' % ('Python', 2) # => 'Python has 002 quote types.'
551
552 * Right-hand-side can also be a mapping:
553
554 a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python}
555(vars() function very handy to use on right-hand-side.)
556
557 Format codes
558Conversion Meaning
559d Signed integer decimal.
560i Signed integer decimal.
561o Unsigned octal.
562u Unsigned decimal.
Christian Heimesa612dc02008-02-24 13:08:18 +0000563x Unsigned hexadecimal (lowercase).
564X Unsigned hexadecimal (uppercase).
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000565e Floating point exponential format (lowercase).
566E Floating point exponential format (uppercase).
567f Floating point decimal format.
568F Floating point decimal format.
569g Same as "e" if exponent is greater than -4 or less than precision,
570 "f" otherwise.
571G Same as "E" if exponent is greater than -4 or less than precision,
572 "F" otherwise.
573c Single character (accepts integer or single character string).
574r String (converts any python object using repr()).
575s String (converts any python object using str()).
576% No argument is converted, results in a "%" character in the result.
577 (The complete specification is %%.)
578
579 Conversion flag characters
580Flag Meaning
581# The value conversion will use the ``alternate form''.
5820 The conversion will be zero padded.
583- The converted value is left adjusted (overrides "-").
584 (a space) A blank should be left before a positive number (or empty
585 string) produced by a signed conversion.
586+ A sign character ("+" or "-") will precede the conversion (overrides a
587 "space" flag).
588
589File Objects
590
591Created with built-in function open; may be created by other modules' functions
592as well.
593
594Operators on file objects
595
596 File operations
597 Operation Result
598f.close() Close file f.
599f.fileno() Get fileno (fd) for file f.
600f.flush() Flush file f's internal buffer.
Raymond Hettingere685f942003-01-26 03:29:15 +0000601f.isatty() True if file f is connected to a tty-like dev, else False.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000602f.read([size]) Read at most size bytes from file f and return as a string
603 object. If size omitted, read to EOF.
604f.readline() Read one entire line from file f.
605f.readlines() Read until EOF with readline() and return list of lines read.
606 Set file f's position, like "stdio's fseek()".
607f.seek(offset[, whence == 0 then use absolute indexing.
608whence=0]) whence == 1 then offset relative to current pos.
609 whence == 2 then offset relative to file end.
610f.tell() Return file f's current position (byte offset).
611f.write(str) Write string to file f.
612f.writelines(list Write list of strings to file f.
613)
614
615File Exceptions
616
617 EOFError
618 End-of-file hit when reading (may be raised many times, e.g. if f is a
619 tty).
620 IOError
Raymond Hettingere685f942003-01-26 03:29:15 +0000621 Other I/O-related I/O operation failure.
622 OSError
623 OS system call failed.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000624
625
626 Advanced Types
627
628 -See manuals for more details -
629 + Module objects
630 + Class objects
631 + Class instance objects
632 + Type objects (see module: types)
633 + File objects (see above)
634 + Slice objects
635 + XRange objects
636 + Callable types:
637 o User-defined (written in Python):
638 # User-defined Function objects
639 # User-defined Method objects
640 o Built-in (written in C):
641 # Built-in Function objects
642 # Built-in Method objects
643 + Internal Types:
644 o Code objects (byte-compile executable Python code: bytecode)
645 o Frame objects (execution frames)
646 o Traceback objects (stack trace of an exception)
647
648
649 Statements
650
651 pass -- Null statement
652 del name[,name]* -- Unbind name(s) from object. Object will be indirectly
653 (and automatically) deleted only if no longer referenced.
654 print [>> fileobject,] [s1 [, s2 ]* [,]
655 -- Writes to sys.stdout, or to fileobject if supplied.
656 Puts spaces between arguments. Puts newline at end
657 unless statement ends with comma.
658 Print is not required when running interactively,
659 simply typing an expression will print its value,
660 unless the value is None.
661 exec x [in globals [,locals]]
662 -- Executes x in namespaces provided. Defaults
663 to current namespaces. x can be a string, file
664 object or a function object.
665 callable(value,... [id=value], [*args], [**kw])
666 -- Call function callable with parameters. Parameters can
667 be passed by name or be omitted if function
668 defines default values. E.g. if callable is defined as
669 "def callable(p1=1, p2=2)"
670 "callable()" <=> "callable(1, 2)"
671 "callable(10)" <=> "callable(10, 2)"
672 "callable(p2=99)" <=> "callable(1, 99)"
673 *args is a tuple of positional arguments.
674 **kw is a dictionary of keyword arguments.
675
676 Assignment operators
677
678 Caption
679 Operator Result Notes
680 a = b Basic assignment - assign object b to label a (1)
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 a <<= b Roughly equivalent to a = a << b (2)
692
693 Notes :
694 (1) Can unpack tuples, lists, and strings.
695 first, second = a[0:2]; [f, s] = range(2); c1,c2,c3='abc'
696 Tip: x,y = y,x swaps x and y.
697 (2) Not exactly equivalent - a is evaluated only once. Also, where
698 possible, operation performed in-place - a is modified rather than
699 replaced.
700
701 Control Flow
702
703 if condition: suite
704 [elif condition: suite]*
705 [else: suite] -- usual if/else_if/else statement
706 while condition: suite
707 [else: suite]
708 -- usual while statement. "else" suite is executed
709 after loop exits, unless the loop is exited with
710 "break"
711 for element in sequence: suite
712 [else: suite]
713 -- iterates over sequence, assigning each element to element.
714 Use built-in range function to iterate a number of times.
715 "else" suite executed at end unless loop exited
716 with "break"
717 break -- immediately exits "for" or "while" loop
718 continue -- immediately does next iteration of "for" or "while" loop
719 return [result] -- Exits from function (or method) and returns result (use a tuple to
720 return more than one value). If no result given, then returns None.
Raymond Hettingere685f942003-01-26 03:29:15 +0000721 yield result -- Freezes the execution frame of a generator and returns the result
Georg Brandla18af4e2007-04-21 15:47:16 +0000722 to the iterator's .__next__() method. Upon the next call to __next__(),
Raymond Hettingere685f942003-01-26 03:29:15 +0000723 resumes execution at the frozen point with all of the local variables
724 still intact.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000725
726 Exception Statements
727
728 assert expr[, message]
729 -- expr is evaluated. if false, raises exception AssertionError
730 with message. Inhibited if __debug__ is 0.
731 try: suite1
732 [except [exception [, value]: suite2]+
733 [else: suite3]
734 -- statements in suite1 are executed. If an exception occurs, look
735 in "except" clauses for matching <exception>. If matches or bare
736 "except" execute suite of that clause. If no exception happens
737 suite in "else" clause is executed after suite1.
738 If exception has a value, it is put in value.
739 exception can also be tuple of exceptions, e.g.
740 "except (KeyError, NameError), val: print val"
741 try: suite1
742 finally: suite2
743 -- statements in suite1 are executed. If no
744 exception, execute suite2 (even if suite1 is
745 exited with a "return", "break" or "continue"
746 statement). If exception did occur, executes
747 suite2 and then immediately reraises exception.
748 raise exception [,value [, traceback]]
749 -- raises exception with optional value
750 value. Arg traceback specifies a traceback object to
751 use when printing the exception's backtrace.
752 raise -- a raise statement without arguments re-raises
753 the last exception raised in the current function
754An exception is either a string (object) or a class instance.
755 Can create a new one simply by creating a new string:
756
757 my_exception = 'You did something wrong'
758 try:
759 if bad:
760 raise my_exception, bad
761 except my_exception, value:
762 print 'Oops', value
763
764Exception classes must be derived from the predefined class: Exception, e.g.:
765 class text_exception(Exception): pass
766 try:
767 if bad:
768 raise text_exception()
769 # This is a shorthand for the form
770 # "raise <class>, <instance>"
771 except Exception:
772 print 'Oops'
773 # This will be printed because
774 # text_exception is a subclass of Exception
775When an error message is printed for an unhandled exception which is a
776class, the class name is printed, then a colon and a space, and
777finally the instance converted to a string using the built-in function
778str().
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000779All built-in exception classes derives from Exception, itself
780derived from BaseException.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000781
782Name Space Statements
783
784[1.51: On Mac & Windows, the case of module file names must now match the case
785as used
786 in the import statement]
787Packages (>1.5): a package is a name space which maps to a directory including
788 module(s) and the special initialization module '__init__.py'
789 (possibly empty). Packages/dirs can be nested. You address a
790 module's symbol via '[package.[package...]module.symbol's.
791import module1 [as name1] [, module2]*
792 -- imports modules. Members of module must be
793 referred to by qualifying with [package.]module name:
794 "import sys; print sys.argv:"
795 "import package1.subpackage.module; package1.subpackage.module.foo()"
796 module1 renamed as name1, if supplied.
797from module import name1 [as othername1] [, name2]*
798 -- imports names from module module in current namespace.
799 "from sys import argv; print argv"
800 "from package1 import module; module.foo()"
801 "from package1.module import foo; foo()"
802 name1 renamed as othername1, if supplied.
803from module import *
804 -- imports all names in module, except those starting with "_";
805 *to be used sparsely, beware of name clashes* :
806 "from sys import *; print argv"
807 "from package.module import *; print x'
808 NB: "from package import *" only imports the symbols defined
809 in the package's __init__.py file, not those in the
810 template modules!
811global name1 [, name2]*
812 -- names are from global scope (usually meaning from module)
813 rather than local (usually meaning only in function).
814 -- E.g. in fct without "global" statements, assuming
815 "a" is name that hasn't been used in fct or module
816 so far:
817 -Try to read from "a" -> NameError
818 -Try to write to "a" -> creates "a" local to fcn
819 -If "a" not defined in fct, but is in module, then
820 -Try to read from "a", gets value from module
821 -Try to write to "a", creates "a" local to fct
822 But note "a[0]=3" starts with search for "a",
823 will use to global "a" if no local "a".
824
825Function Definition
826
827def func_id ([param_list]): suite
828 -- Creates a function object & binds it to name func_id.
829
830 param_list ::= [id [, id]*]
831 id ::= value | id = value | *id | **id
832 [Args are passed by value.Thus only args representing a mutable object
833 can be modified (are inout parameters). Use a tuple to return more than
834 one value]
835
836Example:
837 def test (p1, p2 = 1+1, *rest, **keywords):
838 -- Parameters with "=" have default value (v is
839 evaluated when function defined).
840 If list has "*id" then id is assigned a tuple of
841 all remaining args passed to function (like C vararg)
842 If list has "**id" then id is assigned a dictionary of
843 all extra arguments passed as keywords.
844
845Class Definition
846
847class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite>
848 -- Creates a class object and assigns it name <class_id>
849 <suite> may contain local "defs" of class methods and
850 assignments to class attributes.
851Example:
852 class my_class (class1, class_list[3]): ...
853 Creates a class object inheriting from both "class1" and whatever
854 class object "class_list[3]" evaluates to. Assigns new
855 class object to name "my_class".
856 - First arg to class methods is always instance object, called 'self'
857 by convention.
858 - Special method __init__() is called when instance is created.
859 - Special method __del__() called when no more reference to object.
860 - Create instance by "calling" class object, possibly with arg
861 (thus instance=apply(aClassObject, args...) creates an instance!)
862 - In current implementation, can't subclass off built-in
863 classes. But can "wrap" them, see UserDict & UserList modules,
864 and see __getattr__() below.
865Example:
866 class c (c_parent):
867 def __init__(self, name): self.name = name
868 def print_name(self): print "I'm", self.name
869 def call_parent(self): c_parent.print_name(self)
870 instance = c('tom')
871 print instance.name
872 'tom'
873 instance.print_name()
874 "I'm tom"
875 Call parent's super class by accessing parent's method
876 directly and passing "self" explicitly (see "call_parent"
877 in example above).
878 Many other special methods available for implementing
879 arithmetic operators, sequence, mapping indexing, etc.
880
881Documentation Strings
882
883Modules, classes and functions may be documented by placing a string literal by
884itself as the first statement in the suite. The documentation can be retrieved
885by getting the '__doc__' attribute from the module, class or function.
886Example:
887 class C:
888 "A description of C"
889 def __init__(self):
890 "A description of the constructor"
891 # etc.
892Then c.__doc__ == "A description of C".
893Then c.__init__.__doc__ == "A description of the constructor".
894
895Others
896
897lambda [param_list]: returnedExpr
898 -- Creates an anonymous function. returnedExpr must be
899 an expression, not a statement (e.g., not "if xx:...",
900 "print xxx", etc.) and thus can't contain newlines.
Guido van Rossum0919a1a2006-08-26 20:49:04 +0000901 Used mostly for filter(), map() functions, and GUI callbacks..
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000902List comprehensions
903result = [expression for item1 in sequence1 [if condition1]
904 [for item2 in sequence2 ... for itemN in sequenceN]
905 ]
906is equivalent to:
907result = []
908for item1 in sequence1:
909 for item2 in sequence2:
910 ...
911 for itemN in sequenceN:
912 if (condition1) and furthur conditions:
913 result.append(expression)
914
915
916
917Built-In Functions
918
919 Built-In Functions
920 Function Result
921__import__(name[, Imports module within the given context (see lib ref for
922globals[, locals[, more details)
923fromlist]]])
924abs(x) Return the absolute value of number x.
Raymond Hettingere685f942003-01-26 03:29:15 +0000925bool(x) Returns True when the argument x is true and False otherwise.
926buffer(obj) Creates a buffer reference to an object.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000927chr(i) Returns one-character string whose ASCII code isinteger i
Raymond Hettingere685f942003-01-26 03:29:15 +0000928classmethod(f) Converts a function f, into a method with the class as the
929 first argument. Useful for creating alternative constructors.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000930cmp(x,y) Returns negative, 0, positive if x <, ==, > to y
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000931compile(string, from which the code was read, or eg. '<string>'if not read
932filename, kind) from file.kind can be 'eval' if string is a single stmt, or
933 'single' which prints the output of expression statements
Guido van Rossume7ba4952007-06-06 23:52:48 +0000934 that evaluate to something else than None, or be 'exec'.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000935complex(real[, Builds a complex object (can also be done using J or j
936image]) suffix,e.g. 1+3J)
937delattr(obj, name) deletes attribute named name of object obj <=> del obj.name
938 If no args, returns the list of names in current
Raymond Hettingere685f942003-01-26 03:29:15 +0000939dict([items]) Create a new dictionary from the specified item list.
Guido van Rossume7ba4952007-06-06 23:52:48 +0000940dir([object]) local symbol table. With a module, class or class
941 instance object as arg, returns list of names in its attr.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000942 dict.
943divmod(a,b) Returns tuple of (a/b, a%b)
Raymond Hettingere685f942003-01-26 03:29:15 +0000944enumerate(seq) Return a iterator giving: (0, seq[0]), (1, seq[1]), ...
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000945eval(s[, globals[, Eval string s in (optional) globals, locals contexts.s must
946locals]]) have no NUL's or newlines. s can also be acode object.
947 Example: x = 1; incr_x = eval('x + 1')
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000948filter(function, Constructs a list from those elements of sequence for which
949sequence) function returns true. function takes one parameter.
950float(x) Converts a number or a string to floating point.
951getattr(object, [<default> arg added in 1.5.2]Gets attribute called name
952name[, default])) from object,e.g. getattr(x, 'f') <=> x.f). If not found,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000953 raises AttributeError or returns default if specified.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000954globals() Returns a dictionary containing current global variables.
955hasattr(object, Returns true if object has attr called name.
956name)
957hash(object) Returns the hash value of the object (if it has one)
Raymond Hettingere685f942003-01-26 03:29:15 +0000958help(f) Display documentation on object f.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000959hex(x) Converts a number x to a hexadecimal string.
960id(object) Returns a unique 'identity' integer for an object.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000961int(x[, base]) base paramenter specifies base from which to convert string
962 values.
Guido van Rossume7ba4952007-06-06 23:52:48 +0000963isinstance(obj, Returns true if obj is an instance of class. Ifissubclass
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000964class) (A,B) then isinstance(x,A) => isinstance(x,B)
965issubclass(class1, returns true if class1 is derived from class2
966class2)
967 Returns the length (the number of items) of an object
Raymond Hettingere685f942003-01-26 03:29:15 +0000968iter(collection) Returns an iterator over the collection.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000969len(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.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000974 Applies function to every item of list and returns a listof
975map(function, list, the results. If additional arguments are passed,function
976...) must take that many arguments and it is givento function on
977 each call.
978max(seq) Returns the largest item of the non-empty sequence seq.
979min(seq) Returns the smallest item of a non-empty sequence seq.
980oct(x) Converts a number to an octal string.
981open(filename [, Returns a new file object. First two args are same asthose
982mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered,
983implementation 1 for line-buffered, negative forsys-default, all else, of
984dependent]]) (about) given size.
985ord(c) Returns integer ASCII value of c (a string of len 1). Works
986 with Unicode char.
Raymond Hettingere685f942003-01-26 03:29:15 +0000987object() Create a base type. Used as a superclass for new-style objects.
988open(name Open a file.
989 [, mode
990 [, buffering]])
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000991pow(x, y [, z]) Returns x to power y [modulo z]. See also ** operator.
Raymond Hettingere685f942003-01-26 03:29:15 +0000992property() Created a property with access controlled by functions.
Guido van Rossume7ba4952007-06-06 23:52:48 +0000993range(start [,end Returns list of ints from >= start and < end. With 1 arg,
994[, step]]) list from 0..arg-1. With 2 args, list from start..end-1.
995 With 3 args, list from start up to end by step
996 after fixing it.
997repr(object) Returns a string containing a printable and if possible
998 evaluable representation of an object.
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000999 Class redefinable (__repr__). See also str().
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001000round(x, n=0) Returns the floating point value x rounded to n digitsafter
1001 the decimal point.
Guido van Rossume7ba4952007-06-06 23:52:48 +00001002setattr(object, This is the counterpart of getattr(). setattr(o, 'foobar',
1003name, value) 3) <=> o.foobar = 3. Creates attribute if it doesn't exist!
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001004slice([start,] stop Returns a slice object representing a range, with R/
Guido van Rossume7ba4952007-06-06 23:52:48 +00001005[, step]) O attributes: start, stop, step.
Raymond Hettingere685f942003-01-26 03:29:15 +00001006staticmethod() Convert a function to method with no self or class
1007 argument. Useful for methods associated with a class that
1008 do not need access to an object's internal state.
Guido van Rossume7ba4952007-06-06 23:52:48 +00001009str(object) Returns a string containing a nicely
1010 printable representation of an object. Class overridable
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001011 (__str__).See also repr().
Raymond Hettingere685f942003-01-26 03:29:15 +00001012super(type) Create an unbound super object. Used to call cooperative
1013 superclass methods.
Raymond Hettingerca60cac2003-07-12 23:55:57 +00001014sum(sequence, Add the values in the sequence and return the sum.
1015 [start])
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001016tuple(sequence) Creates a tuple with same elements as sequence. If already
1017 a tuple, return itself (not a copy).
1018 Returns a type object [see module types] representing
1019 thetype of obj. Example: import typesif type(x) ==
1020type(obj) types.StringType: print 'It is a string'NB: it is
1021 recommanded to use the following form:if isinstance(x,
1022 types.StringType): etc...
1023unichr(code) code.
1024unicode(string[, Creates a Unicode string from a 8-bit string, using
1025encoding[, error thegiven encoding name and error treatment ('strict',
1026]]]) 'ignore',or 'replace'}.
1027 Without arguments, returns a dictionary correspondingto the
1028 current local symbol table. With a module,class or class
1029vars([object]) instance object as argumentreturns a dictionary
1030 corresponding to the object'ssymbol table. Useful with "%"
1031 formatting operator.
Guido van Rossume7ba4952007-06-06 23:52:48 +00001032zip(seq1[, seq2, Returns an iterator of tuples where each tuple contains
1033...]) the nth element of each of the argument sequences.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001034
1035
1036
1037Built-In Exceptions
1038
1039Exception>
1040 Root class for all exceptions
1041 SystemExit
1042 On 'sys.exit()'
Raymond Hettingere685f942003-01-26 03:29:15 +00001043 StopIteration
Georg Brandla18af4e2007-04-21 15:47:16 +00001044 Signal the end from iterator.__next__()
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001045 ArithmeticError
1046 Base class for OverflowError, ZeroDivisionError,
1047 FloatingPointError
1048 FloatingPointError
1049 When a floating point operation fails.
1050 OverflowError
1051 On excessively large arithmetic operation
1052 ZeroDivisionError
1053 On division or modulo operation with 0 as 2nd arg
1054 AssertionError
1055 When an assert statement fails.
1056 AttributeError
1057 On attribute reference or assignment failure
1058 EnvironmentError [new in 1.5.2]
1059 On error outside Python; error arg tuple is (errno, errMsg...)
1060 IOError [changed in 1.5.2]
1061 I/O-related operation failure
1062 OSError [new in 1.5.2]
1063 used by the os module's os.error exception.
1064 EOFError
1065 Immediate end-of-file hit by input() or raw_input()
1066 ImportError
1067 On failure of `import' to find module or name
1068 KeyboardInterrupt
1069 On user entry of the interrupt key (often `Control-C')
1070 LookupError
1071 base class for IndexError, KeyError
1072 IndexError
1073 On out-of-range sequence subscript
1074 KeyError
1075 On reference to a non-existent mapping (dict) key
1076 MemoryError
1077 On recoverable memory exhaustion
1078 NameError
1079 On failure to find a local or global (unqualified) name
1080 RuntimeError
1081 Obsolete catch-all; define a suitable error instead
1082 NotImplementedError [new in 1.5.2]
1083 On method not implemented
1084 SyntaxError
1085 On parser encountering a syntax error
1086 IndentationError
1087 On parser encountering an indentation syntax error
1088 TabError
1089 On parser encountering an indentation syntax error
1090 SystemError
1091 On non-fatal interpreter error - bug - report it
1092 TypeError
1093 On passing inappropriate type to built-in op or func
1094 ValueError
1095 On arg error not covered by TypeError or more precise
Raymond Hettingere685f942003-01-26 03:29:15 +00001096 Warning
1097 UserWarning
1098 DeprecationWarning
1099 PendingDeprecationWarning
1100 SyntaxWarning
Raymond Hettingere685f942003-01-26 03:29:15 +00001101 RuntimeWarning
1102 FutureWarning
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001103
1104
1105
1106Standard methods & operators redefinition in classes
1107
1108Standard methods & operators map to special '__methods__' and thus may be
Georg Brandleeb575f2009-06-24 06:42:05 +00001109 redefined (mostly in user-defined classes), e.g.:
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001110 class x:
1111 def __init__(self, v): self.value = v
1112 def __add__(self, r): return self.value + r
1113 a = x(3) # sort of like calling x.__init__(a, 3)
1114 a + 4 # is equivalent to a.__add__(4)
1115
1116Special methods for any class
1117
1118(s: self, o: other)
1119 __init__(s, args) instance initialization (on construction)
1120 __del__(s) called on object demise (refcount becomes 0)
1121 __repr__(s) repr() and `...` conversions
1122 __str__(s) str() and 'print' statement
1123 __cmp__(s, o) Compares s to o and returns <0, 0, or >0.
1124 Implements >, <, == etc...
1125 __hash__(s) Compute a 32 bit hash code; hash() and dictionary ops
Jack Diederich62971282006-11-30 20:50:23 +00001126 __bool__(s) Returns False or True for truth value testing
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001127 __getattr__(s, name) called when attr lookup doesn't find <name>
1128 __setattr__(s, name, val) called when setting an attr
1129 (inside, don't use "self.name = value"
1130 use "self.__dict__[name] = val")
1131 __delattr__(s, name) called to delete attr <name>
1132 __call__(self, *args) called when an instance is called as function.
1133
1134Operators
1135
1136 See list in the operator module. Operator function names are provided with
1137 2 variants, with or without
1138 ading & trailing '__' (eg. __add__ or add).
1139
1140 Numeric operations special methods
1141 (s: self, o: other)
1142
1143 s+o = __add__(s,o) s-o = __sub__(s,o)
1144 s*o = __mul__(s,o) s/o = __div__(s,o)
1145 s%o = __mod__(s,o) divmod(s,o) = __divmod__(s,o)
1146 s**o = __pow__(s,o)
1147 s&o = __and__(s,o)
1148 s^o = __xor__(s,o) s|o = __or__(s,o)
1149 s<<o = __lshift__(s,o) s>>o = __rshift__(s,o)
Jack Diederich62971282006-11-30 20:50:23 +00001150 bool(s) = __bool__(s) (used in boolean testing)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001151 -s = __neg__(s) +s = __pos__(s)
1152 abs(s) = __abs__(s) ~s = __invert__(s) (bitwise)
1153 s+=o = __iadd__(s,o) s-=o = __isub__(s,o)
1154 s*=o = __imul__(s,o) s/=o = __idiv__(s,o)
1155 s%=o = __imod__(s,o)
1156 s**=o = __ipow__(s,o)
1157 s&=o = __iand__(s,o)
1158 s^=o = __ixor__(s,o) s|=o = __ior__(s,o)
1159 s<<=o = __ilshift__(s,o) s>>=o = __irshift__(s,o)
1160 Conversions
Neal Norwitz01688022007-08-12 00:43:29 +00001161 int(s) = __int__(s)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001162 float(s) = __float__(s) complex(s) = __complex__(s)
1163 oct(s) = __oct__(s) hex(s) = __hex__(s)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001164 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
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001191 Modules:
1192 __doc__ (string/None, R/O): doc string (<=> __dict__['__doc__'])
1193 __name__(string, R/O): module name (also in __dict__['__name__'])
1194 __dict__ (dict, R/O): module's name space
1195 __file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for
1196 modules statically linked to the interpreter)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001197
1198 Classes: [in bold: writable since 1.5.2]
1199 __doc__ (string/None, R/W): doc string (<=> __dict__['__doc__'])
Raymond Hettingere685f942003-01-26 03:29:15 +00001200 __module__ is the module name in which the class was defined
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001201 __name__(string, R/W): class name (also in __dict__['__name__'])
1202 __bases__ (tuple, R/W): parent classes
1203 __dict__ (dict, R/W): attributes (class name space)
1204
1205 Instances:
1206 __class__ (class, R/W): instance's class
1207 __dict__ (dict, R/W): attributes
Raymond Hettingere685f942003-01-26 03:29:15 +00001208
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001209 User-defined functions: [bold: writable since 1.5.2]
1210 __doc__ (string/None, R/W): doc string
1211 __name__(string, R/O): function name
1212 func_doc (R/W): same as __doc__
1213 func_name (R/O): same as __name__
1214 func_defaults (tuple/None, R/W): default args values if any
1215 func_code (code, R/W): code object representing the compiled function body
1216 func_globals (dict, R/O): ref to dictionary of func global variables
Raymond Hettingere685f942003-01-26 03:29:15 +00001217 func_dict (dict, R/W): same as __dict__ contains the namespace supporting
1218 arbitrary function attributes
1219 func_closure (R/O): None or a tuple of cells that contain bindings
1220 for the function's free variables.
1221
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001222
1223 User-defined Methods:
1224 __doc__ (string/None, R/O): doc string
1225 __name__(string, R/O): method name (same as im_func.__name__)
1226 im_class (class, R/O): class defining the method (may be a base class)
1227 im_self (instance/None, R/O): target instance object (None if unbound)
1228 im_func (function, R/O): function object
Raymond Hettingere685f942003-01-26 03:29:15 +00001229
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001230 Built-in Functions & methods:
1231 __doc__ (string/None, R/O): doc string
1232 __name__ (string, R/O): function name
1233 __self__ : [methods only] target object
Raymond Hettingere685f942003-01-26 03:29:15 +00001234
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001235 Codes:
1236 co_name (string, R/O): function name
1237 co_argcount (int, R/0): number of positional args
1238 co_nlocals (int, R/O): number of local vars (including args)
1239 co_varnames (tuple, R/O): names of local vars (starting with args)
Raymond Hettingere685f942003-01-26 03:29:15 +00001240 co_cellvars (tuple, R/O)) the names of local variables referenced by
1241 nested functions
1242 co_freevars (tuple, R/O)) names of free variables
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001243 co_code (string, R/O): sequence of bytecode instructions
1244 co_consts (tuple, R/O): litterals used by the bytecode, 1st one is
1245 fct doc (or None)
1246 co_names (tuple, R/O): names used by the bytecode
1247 co_filename (string, R/O): filename from which the code was compiled
1248 co_firstlineno (int, R/O): first line number of the function
1249 co_lnotab (string, R/O): string encoding bytecode offsets to line numbers.
1250 co_stacksize (int, R/O): required stack size (including local vars)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001251 co_flags (int, R/O): flags for the interpreter
1252 bit 2 set if fct uses "*arg" syntax
1253 bit 3 set if fct uses '**keywords' syntax
1254 Frames:
1255 f_back (frame/None, R/O): previous stack frame (toward the caller)
1256 f_code (code, R/O): code object being executed in this frame
1257 f_locals (dict, R/O): local vars
1258 f_globals (dict, R/O): global vars
1259 f_builtins (dict, R/O): built-in (intrinsic) names
1260 f_restricted (int, R/O): flag indicating whether fct is executed in
1261 restricted mode
1262 f_lineno (int, R/O): current line number
1263 f_lasti (int, R/O): precise instruction (index into bytecode)
1264 f_trace (function/None, R/W): debug hook called at start of each source line
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001265 Tracebacks:
1266 tb_next (frame/None, R/O): next level in stack trace (toward the frame where
1267 the exception occurred)
1268 tb_frame (frame, R/O): execution frame of the current level
Fred Drakedb390c12005-10-28 14:39:47 +00001269 tb_lineno (int, R/O): line number where the exception occurred
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001270 tb_lasti (int, R/O): precise instruction (index into bytecode)
1271
1272 Slices:
1273 start (any/None, R/O): lowerbound
1274 stop (any/None, R/O): upperbound
1275 step (any/None, R/O): step value
1276
1277 Complex numbers:
1278 real (float, R/O): real part
1279 imag (float, R/O): imaginary part
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001280
1281
1282Important Modules
1283
1284 sys
1285
1286 Some sys variables
1287 Variable Content
1288argv The list of command line arguments passed to aPython
1289 script. sys.argv[0] is the script name.
1290builtin_module_names A list of strings giving the names of all moduleswritten
1291 in C that are linked into this interpreter.
1292check_interval How often to check for thread switches or signals(measured
1293 in number of virtual machine instructions)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001294last_type, Set only when an exception not handled andinterpreter
1295last_value, prints an error. Used by debuggers.
1296last_traceback
1297maxint maximum positive value for integers
1298modules Dictionary of modules that have already been loaded.
1299path Search path for external modules. Can be modifiedby
1300 program. sys.path[0] == dir of script executing
1301platform The current platform, e.g. "sunos5", "win32"
1302ps1, ps2 prompts to use in interactive mode.
1303 File objects used for I/O. One can redirect byassigning a
1304stdin, stdout, new file object to them (or any object:.with a method
1305stderr write(string) for stdout/stderr,.with a method readline()
1306 for stdin)
1307version string containing version info about Python interpreter.
1308 (and also: copyright, dllhandle, exec_prefix, prefix)
1309version_info tuple containing Python version info - (major, minor,
1310 micro, level, serial).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001311
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001312 Some sys functions
1313 Function Result
1314exit(n) Exits with status n. Raises SystemExit exception.(Hence can
1315 be caught and ignored by program)
Raymond Hettingere685f942003-01-26 03:29:15 +00001316getrefcount(object Returns the reference count of the object. Generally one
1317) higher than you might expect, because of object arg temp
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001318 reference.
1319setcheckinterval( Sets the interpreter's thread switching interval (in number
Skip Montanaroeec26f92003-07-02 21:38:34 +00001320interval) of virtual code instructions, default:100).
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001321settrace(func) Sets a trace function: called before each line ofcode is
1322 exited.
1323setprofile(func) Sets a profile function for performance profiling.
1324 Info on exception currently being handled; this is atuple
1325 (exc_type, exc_value, exc_traceback).Warning: assigning the
Guido van Rossume7ba4952007-06-06 23:52:48 +00001326exc_info() traceback return value to a local variable in a
Raymond Hettingere685f942003-01-26 03:29:15 +00001327 function handling an exception will cause a circular
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001328 reference.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001329getrecursionlimit Retrieve maximum recursion depth.
1330()
1331setrecursionlimit Set maximum recursion depth. (Defaults to 1000.)
1332()
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001333
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001334
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001335
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001336 os
1337"synonym" for whatever O/S-specific module is proper for current environment.
1338this module uses posix whenever possible.
1339(see also M.A. Lemburg's utility http://www.lemburg.com/files/python/
1340platform.py)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001341
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001342 Some os variables
1343 Variable Meaning
1344name name of O/S-specific module (e.g. "posix", "mac", "nt")
1345path O/S-specific module for path manipulations.
1346 On Unix, os.path.split() <=> posixpath.split()
1347curdir string used to represent current directory ('.')
1348pardir string used to represent parent directory ('..')
1349sep string used to separate directories ('/' or '\'). Tip: use
1350 os.path.join() to build portable paths.
1351altsep Alternate sep
1352if applicable (None
1353otherwise)
1354pathsep character used to separate search path components (as in
1355 $PATH), eg. ';' for windows.
1356linesep line separator as used in binary files, ie '\n' on Unix, '\
1357 r\n' on Dos/Win, '\r'
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001358
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001359 Some os functions
1360 Function Result
1361makedirs(path[, Recursive directory creation (create required intermediary
1362mode=0777]) dirs); os.error if fails.
1363removedirs(path) Recursive directory delete (delete intermediary empty
1364 dirs); if fails.
1365renames(old, new) Recursive directory or file renaming; os.error if fails.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001366
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001367
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001368
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001369 posix
1370don't import this module directly, import os instead !
1371(see also module: shutil for file copy & remove fcts)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001372
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001373 posix Variables
1374Variable Meaning
1375environ dictionary of environment variables, e.g.posix.environ['HOME'].
1376error exception raised on POSIX-related error.
1377 Corresponding value is tuple of errno code and perror() string.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001378
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001379 Some posix functions
1380 Function Result
1381chdir(path) Changes current directory to path.
1382chmod(path, Changes the mode of path to the numeric mode
1383mode)
1384close(fd) Closes file descriptor fd opened with posix.open.
1385_exit(n) Immediate exit, with no cleanups, no SystemExit,etc. Should use
1386 this to exit a child process.
1387execv(p, args) "Become" executable p with args args
1388getcwd() Returns a string representing the current working directory
1389getpid() Returns the current process id
1390fork() Like C's fork(). Returns 0 to child, child pid to parent.[Not
1391 on Windows]
1392kill(pid, Like C's kill [Not on Windows]
1393signal)
1394listdir(path) Lists (base)names of entries in directory path, excluding '.'
1395 and '..'
1396lseek(fd, pos, Sets current position in file fd to position pos, expressedas
1397how) an offset relative to beginning of file (how=0), tocurrent
1398 position (how=1), or to end of file (how=2)
1399mkdir(path[, Creates a directory named path with numeric mode (default 0777)
1400mode])
1401open(file, Like C's open(). Returns file descriptor. Use file object
1402flags, mode) fctsrather than this low level ones.
1403pipe() Creates a pipe. Returns pair of file descriptors (r, w) [Not on
1404 Windows].
1405popen(command, Opens a pipe to or from command. Result is a file object to
1406mode='r', read to orwrite from, as indicated by mode being 'r' or 'w'.
1407bufSize=0) Use it to catch acommand output ('r' mode) or to feed it ('w'
1408 mode).
1409remove(path) See unlink.
1410rename(src, dst Renames/moves the file or directory src to dst. [error iftarget
1411) name already exists]
1412rmdir(path) Removes the empty directory path
1413read(fd, n) Reads n bytes from file descriptor fd and return as string.
1414 Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid,
1415stat(path) st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid
1416 are dummy on Windows]
1417system(command) Executes string command in a subshell. Returns exitstatus of
1418 subshell (usually 0 means OK).
1419 Returns accumulated CPU times in sec (user, system, children's
1420times() user,children's sys, elapsed real time). [3 last not on
1421 Windows]
1422unlink(path) Unlinks ("deletes") the file (not dir!) path. same as: remove
1423utime(path, ( Sets the access & modified time of the file to the given tuple
1424aTime, mTime)) of values.
1425wait() Waits for child process completion. Returns tuple ofpid,
1426 exit_status [Not on Windows]
1427waitpid(pid, Waits for process pid to complete. Returns tuple ofpid,
1428options) exit_status [Not on Windows]
1429write(fd, str) Writes str to file fd. Returns nb of bytes written.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001430
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001431
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001432
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001433 posixpath
1434Do not import this module directly, import os instead and refer to this module
1435as os.path. (e.g. os.path.exists(p)) !
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001436
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001437 Some posixpath functions
1438 Function Result
1439abspath(p) Returns absolute path for path p, taking current working dir in
1440 account.
1441dirname/
1442basename(p directory and name parts of the path p. See also split.
1443)
1444exists(p) True if string p is an existing path (file or directory)
1445expanduser Returns string that is (a copy of) p with "~" expansion done.
1446(p)
1447expandvars Returns string that is (a copy of) p with environment vars expanded.
1448(p) [Windows: case significant; must use Unix: $var notation, not %var%]
1449getsize( return the size in bytes of filename. raise os.error.
1450filename)
1451getmtime( return last modification time of filename (integer nb of seconds
1452filename) since epoch).
1453getatime( return last access time of filename (integer nb of seconds since
1454filename) epoch).
1455isabs(p) True if string p is an absolute path.
1456isdir(p) True if string p is a directory.
1457islink(p) True if string p is a symbolic link.
1458ismount(p) True if string p is a mount point [true for all dirs on Windows].
1459join(p[,q Joins one or more path components intelligently.
1460[,...]])
1461 Splits p into (head, tail) where tail is lastpathname component and
1462split(p) <head> is everything leadingup to that. <=> (dirname(p), basename
1463 (p))
1464splitdrive Splits path p in a pair ('drive:', tail) [Windows]
1465(p)
1466splitext(p Splits into (root, ext) where last comp of root contains no periods
1467) and ext is empty or startswith a period.
1468 Calls the function visit with arguments(arg, dirname, names) for
1469 each directory recursively inthe directory tree rooted at p
1470walk(p, (including p itself if it's a dir)The argument dirname specifies the
1471visit, arg visited directory, the argumentnames lists the files in the
1472) directory. The visit function maymodify names to influence the set
1473 of directories visited belowdirname, e.g., to avoid visiting certain
1474 parts of the tree.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001475
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001476
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001477
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001478 shutil
1479high-level file operations (copying, deleting).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001480
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001481 Main shutil functions
1482 Function Result
1483copy(src, dst) Copies the contents of file src to file dst, retaining file
1484 permissions.
1485copytree(src, dst Recursively copies an entire directory tree rooted at src
1486[, symlinks]) into dst (which should not already exist). If symlinks is
1487 true, links insrc are kept as such in dst.
1488rmtree(path[, Deletes an entire directory tree, ignoring errors if
1489ignore_errors[, ignore_errors true,or calling onerror(func, path,
1490onerror]]) sys.exc_info()) if supplied with
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001491
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001492(and also: copyfile, copymode, copystat, copy2)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001493
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001494time
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001495
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001496 Variables
1497Variable Meaning
1498altzone signed offset of local DST timezone in sec west of the 0th meridian.
1499daylight nonzero if a DST timezone is specified
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001500
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001501 Functions
1502 Function Result
1503time() return a float representing UTC time in seconds since the epoch.
1504gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day
1505localtime( (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is
1506secs) monday), Julian day(1-366), daylight flag(-1,0 or 1))
1507asctime(
1508timeTuple),
1509strftime(
Mark Dickinson934896d2009-02-21 20:59:32 +00001510format, return a formatted string representing time.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001511timeTuple)
1512mktime(tuple) inverse of localtime(). Return a float.
Mark Dickinson934896d2009-02-21 20:59:32 +00001513strptime( parse a formatted string representing time, return tuple as in
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001514string[, gmtime().
1515format])
1516sleep(secs) Suspend execution for <secs> seconds. <secs> can be a float.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001517
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001518and also: clock, ctime.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001519
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001520 string
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001521
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001522As of Python 2.0, much (though not all) of the functionality provided by the
1523string module have been superseded by built-in string methods - see Operations
1524on strings for details.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001525
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001526 Some string variables
1527 Variable Meaning
1528digits The string '0123456789'
1529hexdigits, octdigits legal hexadecimal & octal digits
1530letters, uppercase, lowercase, Strings containing the appropriate
1531whitespace characters
1532index_error Exception raised by index() if substr not
1533 found.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001534
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001535 Some string functions
1536 Function Result
1537expandtabs(s, returns a copy of string <s> with tabs expanded.
1538tabSize)
1539find/rfind(s, sub Return the lowest/highest index in <s> where the substring
1540[, start=0[, end= <sub> is found such that <sub> is wholly contained ins
15410]) [start:end]. Return -1 if <sub> not found.
1542ljust/rjust/center Return a copy of string <s> left/right justified/centerd in
1543(s, width) afield of given width, padded with spaces. <s> is
1544 nevertruncated.
1545lower/upper(s) Return a string that is (a copy of) <s> in lowercase/
1546 uppercase
1547split(s[, sep= Return a list containing the words of the string <s>,using
1548whitespace[, the string <sep> as a separator.
1549maxsplit=0]])
1550join(words[, sep=' Concatenate a list or tuple of words with
1551']) interveningseparators; inverse of split.
Fred Drakedb390c12005-10-28 14:39:47 +00001552replace(s, old, Returns a copy of string <s> with all occurrences of
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001553new[, maxsplit=0] substring<old> replaced by <new>. Limits to <maxsplit>
1554 firstsubstitutions if specified.
1555strip(s) Return a string that is (a copy of) <s> without leadingand
1556 trailing whitespace. see also lstrip, rstrip.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001557
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001558
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001559
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001560 re (sre)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001561
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001562Handles Unicode strings. Implemented in new module sre, re now a mere front-end
1563for compatibility.
1564Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to
1565litteralize backslashes.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001566
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001567
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001568 Regular expression syntax
1569 Form Description
1570. matches any character (including newline if DOTALL flag specified)
1571^ matches start of the string (of every line in MULTILINE mode)
1572$ matches end of the string (of every line in MULTILINE mode)
1573* 0 or more of preceding regular expression (as many as possible)
1574+ 1 or more of preceding regular expression (as many as possible)
Fred Drakedb390c12005-10-28 14:39:47 +00001575? 0 or 1 occurrence of preceding regular expression
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001576*?, +?, ?? Same as *, + and ? but matches as few characters as possible
1577{m,n} matches from m to n repetitions of preceding RE
1578{m,n}? idem, attempting to match as few repetitions as possible
1579[ ] defines character set: e.g. '[a-zA-Z]' to match all letters(see also
1580 \w \S)
1581[^ ] defines complemented character set: matches if char is NOT in set
1582 escapes special chars '*?+&$|()' and introduces special sequences
1583\ (see below). Due to Python string rules, write as '\\' orr'\' in the
1584 pattern string.
1585\\ matches a litteral '\'; due to Python string rules, write as '\\\\
1586 'in pattern string, or better using raw string: r'\\'.
1587| specifies alternative: 'foo|bar' matches 'foo' or 'bar'
1588(...) matches any RE inside (), and delimits a group.
1589(?:...) idem but doesn't delimit a group.
1590 matches if ... matches next, but doesn't consume any of the string
1591(?=...) e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by
1592 'Asimov'.
1593(?!...) matches if ... doesn't match next. Negative of (?=...)
1594(?P<name matches any RE inside (), and delimits a named group. (e.g. r'(?P
1595>...) <id>[a-zA-Z_]\w*)' defines a group named id)
1596(?P=name) matches whatever text was matched by the earlier group named name.
1597(?#...) A comment; ignored.
1598(?letter) letter is one of 'i','L', 'm', 's', 'x'. Set the corresponding flags
1599 (re.I, re.L, re.M, re.S, re.X) for the entire RE.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001600
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001601 Special sequences
1602Sequence Description
1603number matches content of the group of the same number; groups are numbered
1604 starting from 1
1605\A matches only at the start of the string
1606\b empty str at beg or end of word: '\bis\b' matches 'is', but not 'his'
1607\B empty str NOT at beginning or end of word
1608\d any decimal digit (<=> [0-9])
1609\D any non-decimal digit char (<=> [^O-9])
1610\s any whitespace char (<=> [ \t\n\r\f\v])
1611\S any non-whitespace char (<=> [^ \t\n\r\f\v])
1612\w any alphaNumeric char (depends on LOCALE flag)
1613\W any non-alphaNumeric char (depends on LOCALE flag)
1614\Z matches only at the end of the string
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001615
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001616 Variables
1617Variable Meaning
1618error Exception when pattern string isn't a valid regexp.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001619
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001620 Functions
1621 Function Result
1622 Compile a RE pattern string into a regular expression object.
1623 Flags (combinable by |):
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001624
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001625 I or IGNORECASE or (?i)
1626 case insensitive matching
1627compile( L or LOCALE or (?L)
1628pattern[, make \w, \W, \b, \B dependent on thecurrent locale
1629flags=0]) M or MULTILINE or (?m)
1630 matches every new line and not onlystart/end of the whole
1631 string
1632 S or DOTALL or (?s)
1633 '.' matches ALL chars, including newline
1634 X or VERBOSE or (?x)
1635 Ignores whitespace outside character sets
1636escape(string) return (a copy of) string with all non-alphanumerics
1637 backslashed.
1638match(pattern, if 0 or more chars at beginning of <string> match the RE pattern
1639string[, flags string,return a corresponding MatchObject instance, or None if
1640]) no match.
1641search(pattern scan thru <string> for a location matching <pattern>, return
1642, string[, acorresponding MatchObject instance, or None if no match.
1643flags])
1644split(pattern, split <string> by occurrences of <pattern>. If capturing () are
1645string[, used inpattern, then occurrences of patterns or subpatterns are
1646maxsplit=0]) also returned.
1647findall( return a list of non-overlapping matches in <pattern>, either a
1648pattern, list ofgroups or a list of tuples if the pattern has more than 1
1649string) group.
1650 return string obtained by replacing the (<count> first) lefmost
1651sub(pattern, non-overlapping occurrences of <pattern> (a string or a RE
1652repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct
1653count=0]) called with a single MatchObj arg, which must return the
1654 replacement string.
1655subn(pattern,
1656repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade)
1657count=0])
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001658
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001659Regular Expression Objects
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001660
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001661
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001662(RE objects are returned by the compile fct)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001663
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001664 re object attributes
1665Attribute Descrition
1666flags flags arg used when RE obj was compiled, or 0 if none provided
1667groupindex dictionary of {group name: group number} in pattern
1668pattern pattern string from which RE obj was compiled
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001669
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001670 re object methods
1671 Method Result
1672 If zero or more characters at the beginning of string match this
1673 regular expression, return a corresponding MatchObject instance.
1674 Return None if the string does not match the pattern; note that
1675 this is different from a zero-length match.
1676 The optional second parameter pos gives an index in the string
1677match( where the search is to start; it defaults to 0. This is not
1678string[, completely equivalent to slicing the string; the '' pattern
1679pos][, character matches at the real beginning of the string and at
1680endpos]) positions just after a newline, but not necessarily at the index
1681 where the search is to start.
1682 The optional parameter endpos limits how far the string will be
1683 searched; it will be as if the string is endpos characters long, so
1684 only the characters from pos to endpos will be searched for a
1685 match.
1686 Scan through string looking for a location where this regular
1687search( expression produces a match, and return a corresponding MatchObject
1688string[, instance. Return None if no position in the string matches the
1689pos][, pattern; note that this is different from finding a zero-length
1690endpos]) match at some point in the string.
1691 The optional pos and endpos parameters have the same meaning as for
1692 the match() method.
1693split(
1694string[, Identical to the split() function, using the compiled pattern.
1695maxsplit=
16960])
1697findall( Identical to the findall() function, using the compiled pattern.
1698string)
1699sub(repl,
1700string[, Identical to the sub() function, using the compiled pattern.
1701count=0])
1702subn(repl,
1703string[, Identical to the subn() function, using the compiled pattern.
1704count=0])
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001705
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001706Match Objects
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001707
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001708
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001709(Match objects are returned by the match & search functions)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001710
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001711 Match object attributes
1712Attribute Description
1713pos value of pos passed to search or match functions; index intostring at
1714 which RE engine started search.
1715endpos value of endpos passed to search or match functions; index intostring
1716 beyond which RE engine won't go.
1717re RE object whose match or search fct produced this MatchObj instance
1718string string passed to match() or search()
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001719
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001720 Match object functions
1721Function Result
1722 returns one or more groups of the match. If one arg, result is a
1723group([g1 string;if multiple args, result is a tuple with one item per arg. If
1724, g2, gi is 0,return value is entire matching string; if 1 <= gi <= 99,
1725...]) returnstring matching group #gi (or None if no such group); gi may
1726 also bea group name.
1727 returns a tuple of all groups of the match; groups not
1728groups() participatingto the match have a value of None. Returns a string
1729 instead of tupleif len(tuple)=1
1730start(
1731group), returns indices of start & end of substring matched by group (or
1732end(group Noneif group exists but doesn't contribute to the match)
1733)
1734span( returns the 2-tuple (start(group), end(group)); can be (None, None)if
1735group) group didn't contibute to the match.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001736
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001737
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001738
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001739 math
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001740
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001741Variables:
1742pi
1743e
1744Functions (see ordinary C man pages for info):
1745acos(x)
1746asin(x)
1747atan(x)
1748atan2(x, y)
1749ceil(x)
1750cos(x)
1751cosh(x)
Raymond Hettingere685f942003-01-26 03:29:15 +00001752degrees(x)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001753exp(x)
1754fabs(x)
1755floor(x)
1756fmod(x, y)
1757frexp(x) -- Unlike C: (float, int) = frexp(float)
1758ldexp(x, y)
Raymond Hettingere685f942003-01-26 03:29:15 +00001759log(x [,base])
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001760log10(x)
1761modf(x) -- Unlike C: (float, float) = modf(float)
1762pow(x, y)
Raymond Hettingere685f942003-01-26 03:29:15 +00001763radians(x)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001764sin(x)
1765sinh(x)
1766sqrt(x)
1767tan(x)
1768tanh(x)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001769
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001770 getopt
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001771
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001772Functions:
1773getopt(list, optstr) -- Similar to C. <optstr> is option
1774 letters to look for. Put ':' after letter
1775 if option takes arg. E.g.
1776 # invocation was "python test.py -c hi -a arg1 arg2"
1777 opts, args = getopt.getopt(sys.argv[1:], 'ab:c:')
1778 # opts would be
1779 [('-c', 'hi'), ('-a', '')]
1780 # args would be
1781 ['arg1', 'arg2']
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001782
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001783
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001784List of modules and packages in base distribution
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001785
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001786(built-ins and content of python Lib directory)
1787(Python NT distribution, may be slightly different in other distributions)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001788
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001789 Standard library modules
1790 Operation Result
1791aifc Stuff to parse AIFF-C and AIFF files.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001792asynchat Support for 'chat' style protocols
1793asyncore Asynchronous File I/O (in select style)
1794atexit Register functions to be called at exit of Python interpreter.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001795base64 Conversions to/from base64 RFC-MIME transport encoding .
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001796bdb A generic Python debugger base class.
1797binhex Macintosh binhex compression/decompression.
1798bisect List bisection algorithms.
Raymond Hettingere685f942003-01-26 03:29:15 +00001799bz2 Support for bz2 compression/decompression.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001800calendar Calendar printing functions.
1801cgi Wraps the WWW Forms Common Gateway Interface (CGI).
Raymond Hettingere685f942003-01-26 03:29:15 +00001802cgitb Utility for handling CGI tracebacks.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001803cmd A generic class to build line-oriented command interpreters.
Raymond Hettingere685f942003-01-26 03:29:15 +00001804datetime Basic date and time types.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001805code Utilities needed to emulate Python's interactive interpreter
1806codecs Lookup existing Unicode encodings and register new ones.
1807colorsys Conversion functions between RGB and other color systems.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001808compileall Force "compilation" of all .py files in a directory.
Georg Brandl24420152008-05-26 16:32:26 +00001809configparser Configuration file parser (much like windows .ini files)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001810copy Generic shallow and deep copying operations.
Georg Brandl24420152008-05-26 16:32:26 +00001811copyreg Helper to provide extensibility for pickle/cPickle.
Raymond Hettingerca60cac2003-07-12 23:55:57 +00001812csv Read and write files with comma separated values.
Georg Brandl24420152008-05-26 16:32:26 +00001813dbm Generic interface to all dbm clones (dbm.bsd, dbm.gnu,
1814 dbm.ndbm, dbm.dumb).
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001815dircache Sorted list of files in a dir, using a cache.
Raymond Hettingere685f942003-01-26 03:29:15 +00001816difflib Tool for creating delta between sequences.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001817dis Bytecode disassembler.
1818distutils Package installation system.
Raymond Hettingere685f942003-01-26 03:29:15 +00001819doctest Tool for running and verifying tests inside doc strings.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001820dospath Common operations on DOS pathnames.
Raymond Hettingere685f942003-01-26 03:29:15 +00001821email Comprehensive support for internet email.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001822filecmp File comparison.
1823fileinput Helper class to quickly write a loop over all standard input
1824 files.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001825fnmatch Filename matching with shell patterns.
1826formatter A test formatter.
1827fpformat General floating point formatting functions.
1828ftplib An FTP client class. Based on RFC 959.
1829gc Perform garbacge collection, obtain GC debug stats, and tune
1830 GC parameters.
1831getopt Standard command line processing. See also ftp://
1832 www.pauahtun.org/pub/getargspy.zip
1833getpass Utilities to get a password and/or the current user name.
1834glob filename globbing.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001835gzip Read & write gzipped files.
Raymond Hettingere685f942003-01-26 03:29:15 +00001836heapq Priority queue implemented using lists organized as heaps.
Georg Brandl24420152008-05-26 16:32:26 +00001837hmac Keyed-Hashing for Message Authentication -- RFC 2104.
1838html.entities HTML entity definitions.
1839html.parser A parser for HTML and XHTML.
1840http.client HTTP client class.
1841http.server HTTP server services.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001842ihooks Hooks into the "import" mechanism.
1843imaplib IMAP4 client.Based on RFC 2060.
1844imghdr Recognizing image files based on their first few bytes.
1845imputil Privides a way of writing customised import hooks.
Raymond Hettingere685f942003-01-26 03:29:15 +00001846inspect Tool for probing live Python objects.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001847keyword List of Python keywords.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001848linecache Cache lines from files.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001849locale Support for number formatting using the current locale
1850 settings.
Raymond Hettingere685f942003-01-26 03:29:15 +00001851logging Python logging facility.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001852macpath Pathname (or related) operations for the Macintosh.
1853macurl2path Mac specific module for conversion between pathnames and URLs.
1854mailbox A class to handle a unix-style or mmdf-style mailbox.
1855mailcap Mailcap file handling (RFC 1524).
1856mhlib MH (mailbox) interface.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001857mimetypes Guess the MIME type of a file.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001858mmap Interface to memory-mapped files - they behave like mutable
1859 strings./font>
1860multifile Class to make multi-file messages easier to handle.
1861mutex Mutual exclusion -- for use with module sched.
1862netrc
1863nntplib An NNTP client class. Based on RFC 977.
1864ntpath Common operations on DOS pathnames.
1865nturl2path Mac specific module for conversion between pathnames and URLs.
Raymond Hettingere685f942003-01-26 03:29:15 +00001866optparse A comprehensive tool for processing command line options.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001867os Either mac, dos or posix depending system.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001868pdb A Python debugger.
1869pickle Pickling (save and restore) of Python objects (a faster
1870 Cimplementation exists in built-in module: cPickle).
1871pipes Conversion pipeline templates.
Raymond Hettingere685f942003-01-26 03:29:15 +00001872pkgunil Utilities for working with Python packages.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001873poplib A POP3 client class. Based on the J. Myers POP3 draft.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001874posixpath Common operations on POSIX pathnames.
1875pprint Support to pretty-print lists, tuples, & dictionaries
1876 recursively.
1877profile Class for profiling python code.
1878pstats Class for printing reports on profiled python code.
Raymond Hettingere685f942003-01-26 03:29:15 +00001879pydoc Utility for generating documentation from source files.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001880pty Pseudo terminal utilities.
1881pyexpat Interface to the Expay XML parser.
1882py_compile Routine to "compile" a .py file to a .pyc file.
1883pyclbr Parse a Python file and retrieve classes and methods.
Georg Brandl24420152008-05-26 16:32:26 +00001884queue A multi-producer, multi-consumer queue.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001885quopri Conversions to/from quoted-printable transport encoding.
Raymond Hettinger5a772d32003-01-25 22:35:42 +00001886random Random variable generators
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001887re Regular Expressions.
Georg Brandl24420152008-05-26 16:32:26 +00001888reprlib Redo repr() but with limits on most sizes.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001889rlcompleter Word completion for GNU readline 2.0.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001890sched A generally useful event scheduler class.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001891shelve Manage shelves of pickled objects.
1892shlex Lexical analyzer class for simple shell-like syntaxes.
1893shutil Utility functions usable in a shell-like program.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001894site Append module search paths for third-party packages to
1895 sys.path.
1896smtplib SMTP Client class (RFC 821)
1897sndhdr Several routines that help recognizing sound.
Alexandre Vassalottice261952008-05-12 02:31:37 +00001898socketserver Generic socket server classes.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001899stat Constants and functions for interpreting stat/lstat struct.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001900statvfs Constants for interpreting statvfs struct as returned by
1901 os.statvfs()and os.fstatvfs() (if they exist).
1902string A collection of string operations.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001903sunau Stuff to parse Sun and NeXT audio files.
1904sunaudio Interpret sun audio headers.
1905symbol Non-terminal symbols of Python grammar (from "graminit.h").
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00001906tabnanny Check Python source for ambiguous indentation.
Raymond Hettingere685f942003-01-26 03:29:15 +00001907tarfile Facility for reading and writing to the *nix tarfile format.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001908telnetlib TELNET client class. Based on RFC 854.
1909tempfile Temporary file name allocation.
Raymond Hettingere685f942003-01-26 03:29:15 +00001910textwrap Object for wrapping and filling text.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001911threading Proposed new higher-level threading interfaces
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001912token Tokens (from "token.h").
1913tokenize Compiles a regular expression that recognizes Python tokens.
1914traceback Format and print Python stack traces.
1915tty Terminal utilities.
1916turtle LogoMation-like turtle graphics
1917types Define names for all type symbols in the std interpreter.
1918tzparse Parse a timezone specification.
1919unicodedata Interface to unicode properties.
Georg Brandl029986a2008-06-23 11:44:14 +00001920urllib.parse Parse URLs according to latest draft of standard.
1921urllib.request Open an arbitrary URL.
1922urllib.robotparser Parse robots.txt files, useful for web spiders.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001923user Hook to allow user-specified customization code to run.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001924uu UUencode/UUdecode.
Raymond Hettingere685f942003-01-26 03:29:15 +00001925unittest Utilities for implementing unit testing.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001926wave Stuff to parse WAVE files.
Raymond Hettingere685f942003-01-26 03:29:15 +00001927weakref Tools for creating and managing weakly referenced objects.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001928webbrowser Platform independent URL launcher.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001929xdrlib Implements (a subset of) Sun XDR (eXternal Data
Georg Brandl24420152008-05-26 16:32:26 +00001930 Representation).
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001931xml.dom Classes for processing XML using the Document Object Model.
1932xml.sax Classes for processing XML using the SAX API.
Georg Brandl38eceaa2008-05-26 11:14:17 +00001933xmlrpc.client Support for remote procedure calls using XML.
1934xmlrpc.server Create XMLRPC servers.
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001935zipfile Read & write PK zipped files.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001936
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001937
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001938
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001939* Built-ins *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001940
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001941 sys Interpreter state vars and functions
1942 __built-in__ Access to all built-in python identifiers
1943 __main__ Scope of the interpreters main program, script or stdin
1944 array Obj efficiently representing arrays of basic values
1945 math Math functions of C standard
Raymond Hettingere685f942003-01-26 03:29:15 +00001946 time Time-related functions (also the newer datetime module)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001947 marshal Read and write some python values in binary format
1948 struct Convert between python values and C structs
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001949
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001950* Standard *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001951
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001952 getopt Parse cmd line args in sys.argv. A la UNIX 'getopt'.
1953 os A more portable interface to OS dependent functionality
1954 re Functions useful for working with regular expressions
1955 string Useful string and characters functions and exceptions
Raymond Hettingere685f942003-01-26 03:29:15 +00001956 random Mersenne Twister pseudo-random number generator
Georg Brandl2067bfd2008-05-25 13:05:15 +00001957 _thread Low-level primitives for working with process threads
1958 threading idem, new recommended interface.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001959
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001960* Unix/Posix *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001961
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00001962 dbm Interface to Unix dbm databases
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001963 grp Interface to Unix group database
1964 posix OS functionality standardized by C and POSIX standards
1965 posixpath POSIX pathname functions
1966 pwd Access to the Unix password database
1967 select Access to Unix select multiplex file synchronization
1968 socket Access to BSD socket interface
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001969
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001970* Tk User-interface Toolkit *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001971
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001972 tkinter Main interface to Tk
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001973
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001974* Multimedia *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001975
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001976 audioop Useful operations on sound fragments
1977 imageop Useful operations on images
1978 jpeg Access to jpeg image compressor and decompressor
1979 rgbimg Access SGI imglib image files
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001980
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001981* Cryptographic Extensions *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001982
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001983 md5 Interface to RSA's MD5 message digest algorithm
Andrew M. Kuchling5a9618e2004-08-31 13:43:19 +00001984 sha Interface to the SHA message digest algorithm
Raymond Hettingere685f942003-01-26 03:29:15 +00001985 HMAC Keyed-Hashing for Message Authentication -- RFC 2104.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001986
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001987* SGI IRIX * (4 & 5)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001988
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001989 al SGI audio facilities
1990 AL al constants
1991 fl Interface to FORMS library
1992 FL fl constants
1993 flp Functions for form designer
1994 fm Access to font manager library
1995 gl Access to graphics library
1996 GL Constants for gl
1997 DEVICE More constants for gl
1998 imgfile Imglib image file interface
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001999
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002000
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002001Workspace exploration and idiom hints
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002002
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002003 dir(<module>) list functions, variables in <module>
2004 dir() get object keys, defaults to local name space
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002005 if __name__ == '__main__': main() invoke main if running as script
2006 map(None, lst1, lst2, ...) merge lists
2007 b = a[:] create copy of seq structure
2008 _ in interactive mode, is last value printed
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002009
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002010
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002011
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002012
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002013
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002014
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002015
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002016Python Mode for Emacs
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002017
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002018(Not revised, possibly not up to date)
2019Type C-c ? when in python-mode for extensive help.
2020INDENTATION
2021Primarily for entering new code:
2022 TAB indent line appropriately
2023 LFD insert newline, then indent
2024 DEL reduce indentation, or delete single character
2025Primarily for reindenting existing code:
2026 C-c : guess py-indent-offset from file content; change locally
2027 C-u C-c : ditto, but change globally
2028 C-c TAB reindent region to match its context
2029 C-c < shift region left by py-indent-offset
2030 C-c > shift region right by py-indent-offset
2031MARKING & MANIPULATING REGIONS OF CODE
2032C-c C-b mark block of lines
2033M-C-h mark smallest enclosing def
2034C-u M-C-h mark smallest enclosing class
2035C-c # comment out region of code
2036C-u C-c # uncomment region of code
2037MOVING POINT
2038C-c C-p move to statement preceding point
2039C-c C-n move to statement following point
2040C-c C-u move up to start of current block
2041M-C-a move to start of def
2042C-u M-C-a move to start of class
2043M-C-e move to end of def
2044C-u M-C-e move to end of class
2045EXECUTING PYTHON CODE
2046C-c C-c sends the entire buffer to the Python interpreter
2047C-c | sends the current region
2048C-c ! starts a Python interpreter window; this will be used by
2049 subsequent C-c C-c or C-c | commands
Raymond Hettingere685f942003-01-26 03:29:15 +00002050C-c C-w runs PyChecker
2051
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002052VARIABLES
2053py-indent-offset indentation increment
2054py-block-comment-prefix comment string used by py-comment-region
2055py-python-command shell command to invoke Python interpreter
2056py-scroll-process-buffer t means always scroll Python process buffer
2057py-temp-directory directory used for temp files (if needed)
2058py-beep-if-tab-change ring the bell if tab-width is changed
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002059
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002060
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002061The Python Debugger
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002062
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002063(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 +00002064
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002065Accessing
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002066
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002067import pdb (it's a module written in Python)
2068 -- defines functions :
2069 run(statement[,globals[, locals]])
2070 -- execute statement string under debugger control, with optional
2071 global & local environment.
2072 runeval(expression[,globals[, locals]])
2073 -- same as run, but evaluate expression and return value.
2074 runcall(function[, argument, ...])
2075 -- run function object with given arg(s)
2076 pm() -- run postmortem on last exception (like debugging a core file)
2077 post_mortem(t)
2078 -- run postmortem on traceback object <t>
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002079
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002080 -- defines class Pdb :
2081 use Pdb to create reusable debugger objects. Object
2082 preserves state (i.e. break points) between calls.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002083
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002084 runs until a breakpoint hit, exception, or end of program
2085 If exception, variable '__exception__' holds (exception,value).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002086
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002087Commands
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002088
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002089h, help
2090 brief reminder of commands
2091b, break [<arg>]
2092 if <arg> numeric, break at line <arg> in current file
2093 if <arg> is function object, break on entry to fcn <arg>
2094 if no arg, list breakpoints
2095cl, clear [<arg>]
2096 if <arg> numeric, clear breakpoint at <arg> in current file
2097 if no arg, clear all breakpoints after confirmation
2098w, where
2099 print current call stack
2100u, up
2101 move up one stack frame (to top-level caller)
2102d, down
2103 move down one stack frame
2104s, step
2105 advance one line in the program, stepping into calls
2106n, next
2107 advance one line, stepping over calls
2108r, return
2109 continue execution until current function returns
2110 (return value is saved in variable "__return__", which
2111 can be printed or manipulated from debugger)
2112c, continue
2113 continue until next breakpoint
Raymond Hettingere685f942003-01-26 03:29:15 +00002114j, jump lineno
2115 Set the next line that will be executed
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002116a, args
2117 print args to current function
2118rv, retval
2119 prints return value from last function that returned
2120p, print <arg>
2121 prints value of <arg> in current stack frame
2122l, list [<first> [, <last>]]
2123 List source code for the current file.
2124 Without arguments, list 11 lines around the current line
2125 or continue the previous listing.
2126 With one argument, list 11 lines starting at that line.
2127 With two arguments, list the given range;
2128 if the second argument is less than the first, it is a count.
2129whatis <arg>
2130 prints type of <arg>
2131!
2132 executes rest of line as a Python statement in the current stack frame
2133q quit
2134 immediately stop execution and leave debugger
2135<return>
2136 executes last command again
2137Any input debugger doesn't recognize as a command is assumed to be a
2138Python statement to execute in the current stack frame, the same way
2139the exclamation mark ("!") command does.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002140
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002141Example
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002142
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002143(1394) python
2144Python 1.0.3 (Sep 26 1994)
2145Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
2146>>> import rm
2147>>> rm.run()
2148Traceback (innermost last):
2149 File "<stdin>", line 1
2150 File "./rm.py", line 7
2151 x = div(3)
2152 File "./rm.py", line 2
2153 return a / r
2154ZeroDivisionError: integer division or modulo
2155>>> import pdb
2156>>> pdb.pm()
2157> ./rm.py(2)div: return a / r
2158(Pdb) list
2159 1 def div(a):
2160 2 -> return a / r
2161 3
2162 4 def run():
2163 5 global r
2164 6 r = 0
2165 7 x = div(3)
2166 8 print x
2167[EOF]
2168(Pdb) print r
21690
2170(Pdb) q
2171>>> pdb.runcall(rm.run)
2172etc.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002173
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002174Quirks
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002175
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002176Breakpoints are stored as filename, line number tuples. If a module is reloaded
2177after editing, any remembered breakpoints are likely to be wrong.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002178
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002179Always single-steps through top-most stack frame. That is, "c" acts like "n".