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