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