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