PageRenderTime 2066ms CodeModel.GetById 161ms app.highlight 1278ms RepoModel.GetById 154ms app.codeStats 2ms

/Misc/cheatsheet

http://unladen-swallow.googlecode.com/
#! | 2273 lines | 2013 code | 260 blank | 0 comment | 0 complexity | 6d0877ea0a3c35766882171baeedf190 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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 emtpy.
 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 a 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 paramenter 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 paramenter 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 a 8-bit string, using
1057encoding[, error    thegiven encoding 

Large files files are truncated, but you can click here to view the full file