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