PageRenderTime 61ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/Misc/cheatsheet

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