home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !ibrowse / files / pylibi-1 < prev    next >
Encoding:
GNU Info File  |  1996-11-14  |  38.2 KB  |  1,107 lines

  1. This is Info file pylibi, produced by Makeinfo-1.55 from the input file
  2. lib.texi.
  3.  
  4. This file describes the built-in types, exceptions and functions and the
  5. standard modules that come with the Python system.  It assumes basic
  6. knowledge about the Python language.  For an informal introduction to
  7. the language, see the Python Tutorial.  The Python Reference Manual
  8. gives a more formal definition of the language.  (These manuals are not
  9. yet available in INFO or Texinfo format.)
  10.  
  11. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The
  12. Netherlands.
  13.  
  14. All Rights Reserved
  15.  
  16. Permission to use, copy, modify, and distribute this software and its
  17. documentation for any purpose and without fee is hereby granted,
  18. provided that the above copyright notice appear in all copies and that
  19. both that copyright notice and this permission notice appear in
  20. supporting documentation, and that the names of Stichting Mathematisch
  21. Centrum or CWI or Corporation for National Research Initiatives or CNRI
  22. not be used in advertising or publicity pertaining to distribution of
  23. the software without specific, written prior permission.
  24.  
  25. While CWI is the initial source for this software, a modified version
  26. is made available by the Corporation for National Research Initiatives
  27. (CNRI) at the Internet address ftp://ftp.python.org.
  28.  
  29. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  30. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  31. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  32. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  33. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  34. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  35. ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  36. THIS SOFTWARE.
  37.  
  38. 
  39. File: pylibi,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
  40.  
  41. The Python library
  42. ******************
  43.  
  44. This file describes the built-in types, exceptions and functions and the
  45. standard modules that come with the Python system.  It assumes basic
  46. knowledge about the Python language.  For an informal introduction to
  47. the language, see the `Python Tutorial'.  The `Python Reference Manual'
  48. gives a more formal definition of the language.  (These manuals are not
  49. yet available in INFO or Texinfo format.)
  50.  
  51. This version corresponds to Python version 1.4 (Oct 25 1996).
  52.  
  53. * Menu:
  54.  
  55. * Introduction::
  56. * Built-in Objects::
  57. * Python Services::
  58. * String Services::
  59. * Miscellaneous Services::
  60. * Generic Operating System Services::
  61. * Optional Operating System Services::
  62. * The Python Debugger::
  63. * The Python Profiler::
  64. * Internet and WWW::
  65. * Restricted Execution::
  66. * Cryptographic Services::
  67. * RISCOS ONLY::
  68. * Function Index::
  69. * Variable Index::
  70. * Module Index::
  71. * Concept Index::
  72.  
  73. 
  74. File: pylibi,  Node: Introduction,  Next: Built-in Objects,  Prev: Top,  Up: Top
  75.  
  76. Introduction
  77. ************
  78.  
  79. The "Python library" contains several different kinds of components.
  80.  
  81. It contains data types that would normally be considered part of the
  82. "core" of a language, such as numbers and lists.  For these types, the
  83. Python language core defines the form of literals and places some
  84. constraints on their semantics, but does not fully define the
  85. semantics.  (On the other hand, the language core does define syntactic
  86. properties like the spelling and priorities of operators.)
  87.  
  88. The library also contains built-in functions and exceptions -- objects
  89. that can be used by all Python code without the need of an `import'
  90. statement.  Some of these are defined by the core language, but many
  91. are not essential for the core semantics and are only described here.
  92.  
  93. The bulk of the library, however, consists of a collection of modules.
  94. There are many ways to dissect this collection.  Some modules are
  95. written in C and built in to the Python interpreter; others are written
  96. in Python and imported in source form.  Some modules provide interfaces
  97. that are highly specific to Python, like printing a stack trace; some
  98. provide interfaces that are specific to particular operating systems,
  99. like socket I/O; others provide interfaces that are specific to a
  100. particular application domain, like the World-Wide Web.  Some modules
  101. are avaiable in all versions and ports of Python; others are only
  102. available when the underlying system supports or requires them; yet
  103. others are available only when a particular configuration option was
  104. chosen at the time when Python was compiled and installed.
  105.  
  106. This manual is organized "from the inside out": it first describes the
  107. built-in data types, then the built-in functions and exceptions, and
  108. finally the modules, grouped in chapters of related modules.  The
  109. ordering of the chapters as well as the ordering of the modules within
  110. each chapter is roughly from most relevant to least important.
  111.  
  112. This means that if you start reading this manual from the start, and
  113. skip to the next chapter when you get bored, you will get a reasonable
  114. overview of the available modules and application areas that are
  115. supported by the Python library.  Of course, you don't *have* to read
  116. it like a novel -- you can also browse the table of contents (in front
  117. of the manual), or look for a specific function, module or term in the
  118. index (in the back).  And finally, if you enjoy learning about random
  119. subjects, you choose a random page number (see module `rand') and read
  120. a section or two.
  121.  
  122. Let the show begin!
  123.  
  124. 
  125. File: pylibi,  Node: Built-in Objects,  Next: Python Services,  Prev: Introduction,  Up: Top
  126.  
  127. Built-in Types, Exceptions and Functions
  128. ****************************************
  129.  
  130. Names for built-in exceptions and functions are found in a separate
  131. symbol table.  This table is searched last when the interpreter looks
  132. up the meaning of a name, so local and global user-defined names can
  133. override built-in names.  Built-in types are described together here
  134. for easy reference.(1)
  135.  
  136. The tables in this chapter document the priorities of operators by
  137. listing them in order of ascending priority (within a table) and
  138. grouping operators that have the same priority in the same box.  Binary
  139. operators of the same priority group from left to right.  (Unary
  140. operators group from right to left, but there you have no real choice.)
  141. See Chapter 5 of the Python Reference Manual for the complete picture
  142. on operator priorities.
  143.  
  144. * Menu:
  145.  
  146. * Types::
  147. * Exceptions::
  148. * Built-in Functions::
  149.  
  150. ---------- Footnotes ----------
  151.  
  152. (1)  Most descriptions sorely lack explanations of the exceptions that
  153. may be raised -- this will be fixed in a future version of this manual.
  154.  
  155. 
  156. File: pylibi,  Node: Types,  Next: Exceptions,  Prev: Built-in Objects,  Up: Built-in Objects
  157.  
  158. Built-in Types
  159. ==============
  160.  
  161. The following sections describe the standard types that are built into
  162. the interpreter.  These are the numeric types, sequence types, and
  163. several others, including types themselves.  There is no explicit
  164. Boolean type; use integers instead.
  165.  
  166. Some operations are supported by several object types; in particular,
  167. all objects can be compared, tested for truth value, and converted to a
  168. string (with the ``...`' notation).  The latter conversion is
  169. implicitly used when an object is written by the `print' statement.
  170.  
  171. * Menu:
  172.  
  173. * Truth Value Testing::
  174. * Boolean Operations::
  175. * Comparisons::
  176. * Numeric Types::
  177. * Sequence Types::
  178. * Mapping Types::
  179. * Other Built-in Types::
  180. * Special Attributes::
  181.  
  182. 
  183. File: pylibi,  Node: Truth Value Testing,  Next: Boolean Operations,  Prev: Types,  Up: Types
  184.  
  185. Truth Value Testing
  186. -------------------
  187.  
  188. Any object can be tested for truth value, for use in an `if' or `while'
  189. condition or as operand of the Boolean operations below.  The following
  190. values are considered false:
  191.  
  192.    * `None'
  193.  
  194.    * zero of any numeric type, e.g., `0', `0L', `0.0'.
  195.  
  196.    * any empty sequence, e.g., `''', `()', `[]'.
  197.  
  198.    * any empty mapping, e.g., `{}'.
  199.  
  200.    * instances of user-defined classes, if the class defines a
  201.      `__nonzero__()' or `__len__()' method, when that method returns
  202.      zero.
  203.  
  204. All other values are considered true -- so objects of many types are
  205. always true.
  206.  
  207. Operations and built-in functions that have a Boolean result always
  208. return `0' for false and `1' for true, unless otherwise stated.
  209. (Important exception: the Boolean operations `or' and `and' always
  210. return one of their operands.)
  211.  
  212. 
  213. File: pylibi,  Node: Boolean Operations,  Next: Comparisons,  Prev: Truth Value Testing,  Up: Types
  214.  
  215. Boolean Operations
  216. ------------------
  217.  
  218. These are the Boolean operations, ordered by ascending priority:
  219.  
  220. *Operation*
  221.      *Result*  --  *Notes*
  222.  
  223. `X or Y'
  224.      if X is false, then Y, else X  --  (1)
  225.  
  226. `X and Y'
  227.      if X is false, then X, else Y  --  (1)
  228.  
  229. `not X'
  230.      if X is false, then `1', else `0'  --  (2)
  231.  
  232. Notes:
  233.  
  234. (1)
  235.      These only evaluate their second argument if needed for their
  236.      outcome.
  237.  
  238. (2)
  239.      `not' has a lower priority than non-Boolean operators, so e.g.
  240.      `not a == b' is interpreted as `not(a == b)', and `a == not b' is
  241.      a syntax error.
  242.  
  243. 
  244. File: pylibi,  Node: Comparisons,  Next: Numeric Types,  Prev: Boolean Operations,  Up: Types
  245.  
  246. Comparisons
  247. -----------
  248.  
  249. Comparison operations are supported by all objects.  They all have the
  250. same priority (which is higher than that of the Boolean operations).
  251. Comparisons can be chained arbitrarily, e.g. `x < y <= z' is equivalent
  252. to `x < y and y <= z', except that `y' is evaluated only once (but in
  253. both cases `z' is not evaluated at all when `x < y' is found to be
  254. false).
  255.  
  256. This table summarizes the comparison operations:
  257.  
  258. *Operation*
  259.      *Meaning*  --  *Notes*
  260.  
  261. `<'
  262.      strictly less than
  263.  
  264. `<='
  265.      less than or equal
  266.  
  267. `>'
  268.      strictly greater than
  269.  
  270. `>='
  271.      greater than or equal
  272.  
  273. `=='
  274.      equal
  275.  
  276. `<>'
  277.      not equal  --  (1)
  278.  
  279. `!='
  280.      not equal  --  (1)
  281.  
  282. `is'
  283.      object identity
  284.  
  285. `is not'
  286.      negated object identity
  287.  
  288. Notes:
  289.  
  290. (1)
  291.      `<>' and `!=' are alternate spellings for the same operator.  (I
  292.      couldn't choose between ABC and C! :-)
  293.  
  294. Objects of different types, except different numeric types, never
  295. compare equal; such objects are ordered consistently but arbitrarily
  296. (so that sorting a heterogeneous array yields a consistent result).
  297. Furthermore, some types (e.g., windows) support only a degenerate
  298. notion of comparison where any two objects of that type are unequal.
  299. Again, such objects are ordered arbitrarily but consistently.
  300.  
  301. (Implementation note: objects of different types except numbers are
  302. ordered by their type names; objects of the same types that don't
  303. support proper comparison are ordered by their address.)
  304.  
  305. Two more operations with the same syntactic priority, `in' and `not
  306. in', are supported only by sequence types (below).
  307.  
  308. 
  309. File: pylibi,  Node: Numeric Types,  Next: Sequence Types,  Prev: Comparisons,  Up: Types
  310.  
  311. Numeric Types
  312. -------------
  313.  
  314. There are three numeric types: "plain integers", "long integers", and
  315. "floating point numbers".  Plain integers (also just called "integers")
  316. are implemented using `long' in C, which gives them at least 32 bits of
  317. precision.  Long integers have unlimited precision.  Floating point
  318. numbers are implemented using `double' in C.  All bets on their
  319. precision are off unless you happen to know the machine you are working
  320. with.
  321.  
  322. Numbers are created by numeric literals or as the result of built-in
  323. functions and operators.  Unadorned integer literals (including hex and
  324. octal numbers) yield plain integers.  Integer literals with an `L' or
  325. `l' suffix yield long integers (`L' is preferred because `1l' looks too
  326. much like eleven!).  Numeric literals containing a decimal point or an
  327. exponent sign yield floating point numbers.
  328.  
  329. Python fully supports mixed arithmetic: when a binary arithmetic
  330. operator has operands of different numeric types, the operand with the
  331. "smaller" type is converted to that of the other, where plain integer
  332. is smaller than long integer is smaller than floating point.
  333. Comparisons between numbers of mixed type use the same rule.(1) The
  334. functions `int()', `long()' and `float()' can be used to coerce numbers
  335. to a specific type.
  336.  
  337. All numeric types support the following operations, sorted by ascending
  338. priority (operations in the same box have the same priority; all
  339. numeric operations have a higher priority than comparison operations):
  340.  
  341. *Operation*
  342.      *Result*  --  *Notes*
  343.  
  344. `X + Y'
  345.      sum of X and Y
  346.  
  347. `X - Y'
  348.      difference of X and Y
  349.  
  350. `X * Y'
  351.      product of X and Y
  352.  
  353. `X / Y'
  354.      quotient of X and Y  --  (1)
  355.  
  356. `X % Y'
  357.      remainder of `X / Y'
  358.  
  359. `-X'
  360.      X negated
  361.  
  362. `+X'
  363.      X unchanged
  364.  
  365. `abs(X)'
  366.      absolute value of X
  367.  
  368. `int(X)'
  369.      X converted to integer  --  (2)
  370.  
  371. `long(X)'
  372.      X converted to long integer  --  (2)
  373.  
  374. `float(X)'
  375.      X converted to floating point
  376.  
  377. `divmod(X, Y)'
  378.      the pair `(X / Y, X % Y)'  --  (3)
  379.  
  380. `pow(X, Y)'
  381.      X to the power Y
  382.  
  383. Notes:
  384. (1)
  385.      For (plain or long) integer division, the result is an integer.
  386.      The result is always rounded towards minus infinity: 1/2 is 0,
  387.      (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.
  388.  
  389. (2)
  390.      Conversion from floating point to (long or plain) integer may
  391.      round or truncate as in C; see functions `floor()' and `ceil()' in
  392.      module `math' for well-defined conversions.
  393.  
  394. (3)
  395.      See the section on built-in functions for an exact definition.
  396.  
  397. * Menu:
  398.  
  399. * Bit-string Operations::
  400.  
  401. ---------- Footnotes ----------
  402.  
  403. (1)  As a consequence, the list `[1, 2]' is considered equal to `[1.0,
  404. 2.0]', and similar for tuples.
  405.  
  406. 
  407. File: pylibi,  Node: Bit-string Operations,  Prev: Numeric Types,  Up: Numeric Types
  408.  
  409. Bit-string Operations on Integer Types
  410. ......................................
  411.  
  412. Plain and long integer types support additional operations that make
  413. sense only for bit-strings.  Negative numbers are treated as their 2's
  414. complement value (for long integers, this assumes a sufficiently large
  415. number of bits that no overflow occurs during the operation).
  416.  
  417. The priorities of the binary bit-wise operations are all lower than the
  418. numeric operations and higher than the comparisons; the unary operation
  419. `~' has the same priority as the other unary numeric operations (`+'
  420. and `-').
  421.  
  422. This table lists the bit-string operations sorted in ascending priority
  423. (operations in the same box have the same priority):
  424.  
  425. *Operation*
  426.      *Result*  --  *Notes*
  427.  
  428. `X | Y'
  429.      bitwise "or" of X and Y
  430.  
  431. `X ^ Y'
  432.      bitwise "exclusive or" of X and Y
  433.  
  434. `X & Y'
  435.      bitwise "and" of X and Y
  436.  
  437. `X << N'
  438.      X shifted left by N bits  --  (1), (2)
  439.  
  440. `X >> N'
  441.      X shifted right by N bits  --  (1), (3)
  442.  
  443. `~X'
  444.      the bits of X inverted
  445.  
  446. Notes:
  447. (1)
  448.      Negative shift counts are illegal.
  449.  
  450. (2)
  451.      A left shift by N bits is equivalent to multiplication by `pow(2,
  452.      N)' without overflow check.
  453.  
  454. (3)
  455.      A right shift by N bits is equivalent to division by `pow(2, N)'
  456.      without overflow check.
  457.  
  458. 
  459. File: pylibi,  Node: Sequence Types,  Next: Mapping Types,  Prev: Numeric Types,  Up: Types
  460.  
  461. Sequence Types
  462. --------------
  463.  
  464. There are three sequence types: strings, lists and tuples.
  465.  
  466. Strings literals are written in single or double quotes: `'xyzzy'',
  467. `"frobozz"'.  See Chapter 2 of the Python Reference Manual for more
  468. about string literals.  Lists are constructed with square brackets,
  469. separating items with commas: `[a, b, c]'.  Tuples are constructed by
  470. the comma operator (not within square brackets), with or without
  471. enclosing parentheses, but an empty tuple must have the enclosing
  472. parentheses, e.g., `a, b, c' or `()'.  A single item tuple must have a
  473. trailing comma, e.g., `(d,)'.
  474.  
  475. Sequence types support the following operations.  The `in' and `not,in'
  476. operations have the same priorities as the comparison operations.  The
  477. `+' and `*' operations have the same priority as the corresponding
  478. numeric operations.(1)
  479.  
  480. This table lists the sequence operations sorted in ascending priority
  481. (operations in the same box have the same priority).  In the table, S
  482. and T are sequences of the same type; N, I and J are integers:
  483.  
  484. *Operation*
  485.      *Result*  --  *Notes*
  486.  
  487. `X in S'
  488.      `1' if an item of S is equal to X, else `0'
  489.  
  490. `X not in S'
  491.      `0' if an item of S is equal to X, else `1'
  492.  
  493. `S + T'
  494.      the concatenation of S and T
  495.  
  496. `S * N, N * S'
  497.      N copies of S concatenated
  498.  
  499. `S[I]'
  500.      I'th item of S, origin 0  --  (1)
  501.  
  502. `S[I:J]'
  503.      slice of S from I to J  --  (1), (2)
  504.  
  505. `len(S)'
  506.      length of S
  507.  
  508. `min(S)'
  509.      smallest item of S
  510.  
  511. `max(S)'
  512.      largest item of S
  513.  
  514. Notes:
  515.  
  516. (1)
  517.      If I or J is negative, the index is relative to the end of the
  518.      string, i.e., `len(S) + I' or `len(S) + J' is substituted.  But
  519.      note that `-0' is still `0'.
  520.  
  521. (2)
  522.      The slice of S from I to J is defined as the sequence of items
  523.      with index K such that `I <= K < J'.  If I or J is greater than
  524.      `len(S)', use `len(S)'.  If I is omitted, use `0'.  If J is
  525.      omitted, use `len(S)'.  If I is greater than or equal to J, the
  526.      slice is empty.
  527.  
  528. * Menu:
  529.  
  530. * More String Operations::
  531. * Mutable Sequence Types::
  532.  
  533. ---------- Footnotes ----------
  534.  
  535. (1)  They must have since the parser can't tell the type of the
  536. operands.
  537.  
  538. 
  539. File: pylibi,  Node: More String Operations,  Next: Mutable Sequence Types,  Prev: Sequence Types,  Up: Sequence Types
  540.  
  541. More String Operations
  542. ......................
  543.  
  544. String objects have one unique built-in operation: the `%' operator
  545. (modulo) with a string left argument interprets this string as a C
  546. sprintf format string to be applied to the right argument, and returns
  547. the string resulting from this formatting operation.
  548.  
  549. The right argument should be a tuple with one item for each argument
  550. required by the format string; if the string requires a single
  551. argument, the right argument may also be a single non-tuple object.(1)
  552. The following format characters are understood: %, c, s, i, d, u, o, x,
  553. X, e, E, f, g, G.  Width and precision may be a * to specify that an
  554. integer argument specifies the actual width or precision.  The flag
  555. characters -, +, blank, # and 0 are understood.  The size specifiers h,
  556. l or L may be present but are ignored.  The `%s' conversion takes any
  557. Python object and converts it to a string using `str()' before
  558. formatting it.  The ANSI features `%p' and `%n' are not supported.
  559. Since Python strings have an explicit length, `%s' conversions don't
  560. assume that `'\0'' is the end of the string.
  561.  
  562. For safety reasons, floating point precisions are clipped to 50; `%f'
  563. conversions for numbers whose absolute value is over 1e25 are replaced
  564. by `%g' conversions.(2) All other errors raise exceptions.
  565.  
  566. If the right argument is a dictionary (or any kind of mapping), then
  567. the formats in the string must have a parenthesized key into that
  568. dictionary inserted immediately after the `%' character, and each
  569. format formats the corresponding entry from the mapping.  E.g.
  570.          >>> count = 2
  571.          >>> language = 'Python'
  572.          >>> print '%(language)s has %(count)03d quote types.' % vars()
  573.          Python has 002 quote types.
  574.          >>>
  575. In this case no * specifiers may occur in a format (since they require
  576. a sequential parameter list).
  577.  
  578. Additional string operations are defined in standard module `string'
  579. and in built-in module `regex'.
  580.  
  581. ---------- Footnotes ----------
  582.  
  583. (1)  A tuple object in this case should be a singleton.
  584.  
  585. (2)  These numbers are fairly arbitrary.  They are intended to avoid
  586. printing endless strings of meaningless digits without hampering
  587. correct use and without having to know the exact precision of floating
  588. point values on a particular machine.
  589.  
  590. 
  591. File: pylibi,  Node: Mutable Sequence Types,  Prev: More String Operations,  Up: Sequence Types
  592.  
  593. Mutable Sequence Types
  594. ......................
  595.  
  596. List objects support additional operations that allow in-place
  597. modification of the object.  These operations would be supported by
  598. other mutable sequence types (when added to the language) as well.
  599. Strings and tuples are immutable sequence types and such objects cannot
  600. be modified once created.  The following operations are defined on
  601. mutable sequence types (where X is an arbitrary object):
  602.  
  603. *Operation*
  604.      *Result*  --  *Notes*
  605.  
  606. `S[I] = X'
  607.      item I of S is replaced by X
  608.  
  609. `S[I:J] = T'
  610.      slice of S from I to J is replaced by T
  611.  
  612. `del S[I:J]'
  613.      same as `S[I:J] = []'
  614.  
  615. `S.append(X)'
  616.      same as `S[len(S):len(S)] = [X]'
  617.  
  618. `S.count(X)'
  619.      return number of I's for which `S[I] == X'
  620.  
  621. `S.index(X)'
  622.      return smallest I such that `S[I] == X'  --  (1)
  623.  
  624. `S.insert(I, X)'
  625.      same as `S[I:I] = [X]' if `I >= 0'
  626.  
  627. `S.remove(X)'
  628.      same as `del S[S.index(X)]'  --  (1)
  629.  
  630. `S.reverse()'
  631.      reverses the items of S in place
  632.  
  633. `S.sort()'
  634.      permutes the items of S to satisfy `S[I] <= S[J]', for `I < J'  --
  635.      (2)
  636.  
  637. Notes:
  638. (1)
  639.      Raises an exception when X is not found in S.
  640.  
  641. (2)
  642.      The `sort()' method takes an optional argument specifying a
  643.      comparison function of two arguments (list items) which should
  644.      return `-1', `0' or `1' depending on whether the first argument is
  645.      considered smaller than, equal to, or larger than the second
  646.      argument.  Note that this slows the sorting process down
  647.      considerably; e.g. to sort a list in reverse order it is much
  648.      faster to use calls to `sort()' and `reverse()' than to use
  649.      `sort()' with a comparison function that reverses the ordering of
  650.      the elements.
  651.  
  652. 
  653. File: pylibi,  Node: Mapping Types,  Next: Other Built-in Types,  Prev: Sequence Types,  Up: Types
  654.  
  655. Mapping Types
  656. -------------
  657.  
  658. A "mapping" object maps values of one type (the key type) to arbitrary
  659. objects.  Mappings are mutable objects.  There is currently only one
  660. standard mapping type, the "dictionary".  A dictionary's keys are
  661. almost arbitrary values.  The only types of values not acceptable as
  662. keys are values containing lists or dictionaries or other mutable types
  663. that are compared by value rather than by object identity.  Numeric
  664. types used for keys obey the normal rules for numeric comparison: if
  665. two numbers compare equal (e.g. 1 and 1.0) then they can be used
  666. interchangeably to index the same dictionary entry.
  667.  
  668. Dictionaries are created by placing a comma-separated list of
  669. `KEY:,VALUE' pairs within braces, for example: `{'jack':,4098,
  670. 'sjoerd':,4127}' or `{4098:,'jack', 4127:,'sjoerd'}'.
  671.  
  672. The following operations are defined on mappings (where A is a mapping,
  673. K is a key and X is an arbitrary object):
  674.  
  675. *Operation*
  676.      *Result*  --  *Notes*
  677.  
  678. `len(A)'
  679.      the number of items in A
  680.  
  681. `A[K]'
  682.      the item of A with key K  --  (1)
  683.  
  684. `A[K] = X'
  685.      set `A[K]' to X
  686.  
  687. `del A[K]'
  688.      remove `A[K]' from A  --  (1)
  689.  
  690. `A.items()'
  691.      a copy of A's list of (key, item) pairs  --  (2)
  692.  
  693. `A.keys()'
  694.      a copy of A's list of keys  --  (2)
  695.  
  696. `A.values()'
  697.      a copy of A's list of values  --  (2)
  698.  
  699. `A.has_key(K)'
  700.      `1' if A has a key K, else `0'
  701.  
  702. Notes:
  703. (1)
  704.      Raises an exception if K is not in the map.
  705.  
  706. (2)
  707.      Keys and values are listed in random order.
  708.  
  709. 
  710. File: pylibi,  Node: Other Built-in Types,  Next: Special Attributes,  Prev: Mapping Types,  Up: Types
  711.  
  712. Other Built-in Types
  713. --------------------
  714.  
  715. The interpreter supports several other kinds of objects.  Most of these
  716. support only one or two operations.
  717.  
  718. * Menu:
  719.  
  720. * Modules::
  721. * Classes and Instances::
  722. * Functions::
  723. * Methods::
  724. * Code Objects::
  725. * Type Objects::
  726. * The Null Object::
  727. * File Objects::
  728. * Internal Objects::
  729.  
  730. 
  731. File: pylibi,  Node: Modules,  Next: Classes and Instances,  Prev: Other Built-in Types,  Up: Other Built-in Types
  732.  
  733. Modules
  734. .......
  735.  
  736. The only special operation on a module is attribute access: `M.NAME',
  737. where M is a module and NAME accesses a name defined in M's symbol
  738. table.  Module attributes can be assigned to.  (Note that the `import'
  739. statement is not, strictly spoken, an operation on a module object;
  740. `import FOO' does not require a module object named FOO to exist,
  741. rather it requires an (external) *definition* for a module named FOO
  742. somewhere.)
  743.  
  744. A special member of every module is `__dict__'.  This is the dictionary
  745. containing the module's symbol table.  Modifying this dictionary will
  746. actually change the module's symbol table, but direct assignment to the
  747. `__dict__' attribute is not possible (i.e., you can write
  748. `M.__dict__['a'] = 1', which defines `M.a' to be `1', but you can't
  749. write `M.__dict__ = {}'.
  750.  
  751. Modules are written like this: `<module 'sys'>'.
  752.  
  753. 
  754. File: pylibi,  Node: Classes and Instances,  Next: Functions,  Prev: Modules,  Up: Other Built-in Types
  755.  
  756. Classes and Class Instances
  757. ...........................
  758.  
  759. (See Chapters 3 and 7 of the Python Reference Manual for these.)
  760.  
  761. 
  762. File: pylibi,  Node: Functions,  Next: Methods,  Prev: Classes and Instances,  Up: Other Built-in Types
  763.  
  764. Functions
  765. .........
  766.  
  767. Function objects are created by function definitions.  The only
  768. operation on a function object is to call it: `FUNC(ARGUMENT-LIST)'.
  769.  
  770. There are really two flavors of function objects: built-in functions
  771. and user-defined functions.  Both support the same operation (to call
  772. the function), but the implementation is different, hence the different
  773. object types.
  774.  
  775. The implementation adds two special read-only attributes: `F.func_code'
  776. is a function's "code object" (see below) and `F.func_globals' is the
  777. dictionary used as the function's global name space (this is the same
  778. as `M.__dict__' where M is the module in which the function F was
  779. defined).
  780.  
  781. 
  782. File: pylibi,  Node: Methods,  Next: Code Objects,  Prev: Functions,  Up: Other Built-in Types
  783.  
  784. Methods
  785. .......
  786.  
  787. Methods are functions that are called using the attribute notation.
  788. There are two flavors: built-in methods (such as `append()' on lists)
  789. and class instance methods.  Built-in methods are described with the
  790. types that support them.
  791.  
  792. The implementation adds two special read-only attributes to class
  793. instance methods: `M.im_self' is the object whose method this is, and
  794. `M.im_func' is the function implementing the method.  Calling `M(ARG-1,
  795. ARG-2, ..., ARG-N)' is completely equivalent to calling
  796. `M.im_func(M.im_self, ARG-1, ARG-2, ..., ARG-N)'.
  797.  
  798. (See the Python Reference Manual for more info.)
  799.  
  800. 
  801. File: pylibi,  Node: Code Objects,  Next: Type Objects,  Prev: Methods,  Up: Other Built-in Types
  802.  
  803. Code Objects
  804. ............
  805.  
  806. Code objects are used by the implementation to represent
  807. "pseudo-compiled" executable Python code such as a function body.  They
  808. differ from function objects because they don't contain a reference to
  809. their global execution environment.  Code objects are returned by the
  810. built-in `compile()' function and can be extracted from function
  811. objects through their `func_code' attribute.
  812.  
  813. A code object can be executed or evaluated by passing it (instead of a
  814. source string) to the `exec' statement or the built-in `eval()'
  815. function.
  816.  
  817. (See the Python Reference Manual for more info.)
  818.  
  819. 
  820. File: pylibi,  Node: Type Objects,  Next: The Null Object,  Prev: Code Objects,  Up: Other Built-in Types
  821.  
  822. Type Objects
  823. ............
  824.  
  825. Type objects represent the various object types.  An object's type is
  826. accessed by the built-in function `type()'.  There are no special
  827. operations on types.  The standard module `types' defines names for all
  828. standard built-in types.
  829.  
  830. Types are written like this: `<type 'int'>'.
  831.  
  832. 
  833. File: pylibi,  Node: The Null Object,  Next: File Objects,  Prev: Type Objects,  Up: Other Built-in Types
  834.  
  835. The Null Object
  836. ...............
  837.  
  838. This object is returned by functions that don't explicitly return a
  839. value.  It supports no special operations.  There is exactly one null
  840. object, named `None' (a built-in name).
  841.  
  842. It is written as `None'.
  843.  
  844. 
  845. File: pylibi,  Node: File Objects,  Next: Internal Objects,  Prev: The Null Object,  Up: Other Built-in Types
  846.  
  847. File Objects
  848. ............
  849.  
  850. File objects are implemented using C's `stdio' package and can be
  851. created with the built-in function `open()' described under Built-in
  852. Functions below.  They are also returned by some other built-in
  853. functions and methods, e.g. `posix.popen()' and `posix.fdopen()' and
  854. the `makefile()' method of socket objects.
  855.  
  856. When a file operation fails for an I/O-related reason, the exception
  857. `IOError' is raised.  This includes situations where the operation is
  858. not defined for some reason, like `seek()' on a tty device or writing a
  859. file opened for reading.
  860.  
  861. Files have the following methods:
  862.  
  863.  - Method on file: close ()
  864.      Close the file.  A closed file cannot be read or written anymore.
  865.  
  866.  - Method on file: flush ()
  867.      Flush the internal buffer, like `stdio''s `fflush()'.
  868.  
  869.  - Method on file: isatty ()
  870.      Return `1' if the file is connected to a tty(-like) device, else
  871.      `0'.
  872.  
  873.  - Method on file: read ([SIZE])
  874.      Read at most SIZE bytes from the file (less if the read hits EOF
  875.      or no more data is immediately available on a pipe, tty or similar
  876.      device).  If the SIZE argument is negative or omitted, read all
  877.      data until EOF is reached.  The bytes are returned as a string
  878.      object.  An empty string is returned when EOF is encountered
  879.      immediately.  (For certain files, like ttys, it makes sense to
  880.      continue reading after an EOF is hit.)
  881.  
  882.  - Method on file: readline ([SIZE])
  883.      Read one entire line from the file.  A trailing newline character
  884.      is kept in the string(1) (but may be absent when a file ends with
  885.      an incomplete line).  If the SIZE argument is present and
  886.      non-negative, it is a maximum byte count (including the trailing
  887.      newline) and an incomplete line may be returned.  An empty string
  888.      is returned when EOF is hit immediately.  Note: unlike `stdio''s
  889.      `fgets()', the returned string contains null characters (`'\0'')
  890.      if they occurred in the input.
  891.  
  892.  - Method on file: readlines ()
  893.      Read until EOF using `readline()' and return a list containing the
  894.      lines thus read.
  895.  
  896.  - Method on file: seek (OFFSET, WHENCE)
  897.      Set the file's current position, like `stdio''s `fseek()'.  The
  898.      WHENCE argument is optional and defaults to `0' (absolute file
  899.      positioning); other values are `1' (seek relative to the current
  900.      position) and `2' (seek relative to the file's end).  There is no
  901.      return value.
  902.  
  903.  - Method on file: tell ()
  904.      Return the file's current position, like `stdio''s `ftell()'.
  905.  
  906.  - Method on file: truncate ([SIZE])
  907.      Truncate the file's size.  If the optional size argument present,
  908.      the file is truncated to (at most) that size.  The size defaults
  909.      to the current position.  Availability of this function depends on
  910.      the operating system version (e.g., not all UNIX versions support
  911.      this operation).
  912.  
  913.  - Method on file: write (STR)
  914.      Write a string to the file.  There is no return value.  Note: due
  915.      to buffering, the string may not actually show up in the file until
  916.      the `flush()' or `close()' method is called.
  917.  
  918.  - Method on file: writelines (LIST)
  919.      Write a list of strings to the file.  There is no return value.
  920.      (The name is intended to match `readlines'; `writelines' does not
  921.      add line separators.)
  922.  
  923. ---------- Footnotes ----------
  924.  
  925. (1)  The advantage of leaving the newline on is that an empty string
  926. can be returned to mean EOF without being ambiguous.  Another advantage
  927. is that (in cases where it might matter, e.g. if you want to make an
  928. exact copy of a file while scanning its lines) you can tell whether the
  929. last line of a file ended in a newline or not (yes this happens!).
  930.  
  931. 
  932. File: pylibi,  Node: Internal Objects,  Prev: File Objects,  Up: Other Built-in Types
  933.  
  934. Internal Objects
  935. ................
  936.  
  937. (See the Python Reference Manual for these.)
  938.  
  939. 
  940. File: pylibi,  Node: Special Attributes,  Prev: Other Built-in Types,  Up: Types
  941.  
  942. Special Attributes
  943. ------------------
  944.  
  945. The implementation adds a few special read-only attributes to several
  946. object types, where they are relevant:
  947.  
  948.    * `X.__dict__' is a dictionary of some sort used to store an
  949.      object's (writable) attributes;
  950.  
  951.    * `X.__methods__' lists the methods of many built-in object types,
  952.      e.g., `[].__methods__' yields `['append', 'count', 'index',
  953.      'insert', 'remove', 'reverse', 'sort']';
  954.  
  955.    * `X.__members__' lists data attributes;
  956.  
  957.    * `X.__class__' is the class to which a class instance belongs;
  958.  
  959.    * `X.__bases__' is the tuple of base classes of a class object.
  960.  
  961. 
  962. File: pylibi,  Node: Exceptions,  Next: Built-in Functions,  Prev: Types,  Up: Built-in Objects
  963.  
  964. Built-in Exceptions
  965. ===================
  966.  
  967. Exceptions are string objects.  Two distinct string objects with the
  968. same value are different exceptions.  This is done to force programmers
  969. to use exception names rather than their string value when specifying
  970. exception handlers.  The string value of all built-in exceptions is
  971. their name, but this is not a requirement for user-defined exceptions
  972. or exceptions defined by library modules.
  973.  
  974. The following exceptions can be generated by the interpreter or
  975. built-in functions.  Except where mentioned, they have an `associated
  976. value' indicating the detailed cause of the error.  This may be a
  977. string or a tuple containing several items of information (e.g., an
  978. error code and a string explaining the code).
  979.  
  980. User code can raise built-in exceptions.  This can be used to test an
  981. exception handler or to report an error condition `just like' the
  982. situation in which the interpreter raises the same exception; but
  983. beware that there is nothing to prevent user code from raising an
  984. inappropriate error.
  985.  
  986.  - built-in exception: AttributeError
  987.      Raised when an attribute reference or assignment fails.  (When an
  988.      object does not support attribute references or attribute
  989.      assignments at all, `TypeError' is raised.)
  990.  
  991.  - built-in exception: EOFError
  992.      Raised when one of the built-in functions (`input()' or
  993.      `raw_input()') hits an end-of-file condition (EOF) without reading
  994.      any data.  (N.B.: the `read()' and `readline()' methods of file
  995.      objects return an empty string when they hit EOF.)  No associated
  996.      value.
  997.  
  998.  - built-in exception: IOError
  999.      Raised when an I/O operation (such as a `print' statement, the
  1000.      built-in `open()' function or a method of a file object) fails for
  1001.      an I/O-related reason, e.g., `file not found', `disk full'.
  1002.  
  1003.  - built-in exception: ImportError
  1004.      Raised when an `import' statement fails to find the module
  1005.      definition or when a `from ... import' fails to find a name that
  1006.      is to be imported.
  1007.  
  1008.  - built-in exception: IndexError
  1009.      Raised when a sequence subscript is out of range.  (Slice indices
  1010.      are silently truncated to fall in the allowed range; if an index
  1011.      is not a plain integer, `TypeError' is raised.)
  1012.  
  1013.  - built-in exception: KeyError
  1014.      Raised when a mapping (dictionary) key is not found in the set of
  1015.      existing keys.
  1016.  
  1017.  - built-in exception: KeyboardInterrupt
  1018.      Raised when the user hits the interrupt key (normally `Control-C'
  1019.      or DEL).  During execution, a check for interrupts is made
  1020.      regularly.  Interrupts typed when a built-in function `input()' or
  1021.      `raw_input()') is waiting for input also raise this exception.  No
  1022.      associated value.
  1023.  
  1024.  - built-in exception: MemoryError
  1025.      Raised when an operation runs out of memory but the situation may
  1026.      still be rescued (by deleting some objects).  The associated value
  1027.      is a string indicating what kind of (internal) operation ran out
  1028.      of memory.  Note that because of the underlying memory management
  1029.      architecture (C's `malloc()' function), the interpreter may not
  1030.      always be able to completely recover from this situation; it
  1031.      nevertheless raises an exception so that a stack traceback can be
  1032.      printed, in case a run-away program was the cause.
  1033.  
  1034.  - built-in exception: NameError
  1035.      Raised when a local or global name is not found.  This applies only
  1036.      to unqualified names.  The associated value is the name that could
  1037.      not be found.
  1038.  
  1039.  - built-in exception: OverflowError
  1040.      Raised when the result of an arithmetic operation is too large to
  1041.      be represented.  This cannot occur for long integers (which would
  1042.      rather raise `MemoryError' than give up).  Because of the lack of
  1043.      standardization of floating point exception handling in C, most
  1044.      floating point operations also aren't checked.  For plain integers,
  1045.      all operations that can overflow are checked except left shift,
  1046.      where typical applications prefer to drop bits than raise an
  1047.      exception.
  1048.  
  1049.  - built-in exception: RuntimeError
  1050.      Raised when an error is detected that doesn't fall in any of the
  1051.      other categories.  The associated value is a string indicating what
  1052.      precisely went wrong.  (This exception is a relic from a previous
  1053.      version of the interpreter; it is not used any more except by some
  1054.      extension modules that haven't been converted to define their own
  1055.      exceptions yet.)
  1056.  
  1057.  - built-in exception: SyntaxError
  1058.      Raised when the parser encounters a syntax error.  This may occur
  1059.      in an `import' statement, in an `exec' statement, in a call to the
  1060.      built-in function `eval()' or `input()', or when reading the
  1061.      initial script or standard input (also interactively).
  1062.  
  1063.  - built-in exception: SystemError
  1064.      Raised when the interpreter finds an internal error, but the
  1065.      situation does not look so serious to cause it to abandon all hope.
  1066.      The associated value is a string indicating what went wrong (in
  1067.      low-level terms).
  1068.  
  1069.      You should report this to the author or maintainer of your Python
  1070.      interpreter.  Be sure to report the version string of the Python
  1071.      interpreter (`sys.version'; it is also printed at the start of an
  1072.      interactive Python session), the exact error message (the
  1073.      exception's associated value) and if possible the source of the
  1074.      program that triggered the error.
  1075.  
  1076.  - built-in exception: SystemExit
  1077.      This exception is raised by the `sys.exit()' function.  When it is
  1078.      not handled, the Python interpreter exits; no stack traceback is
  1079.      printed.  If the associated value is a plain integer, it specifies
  1080.      the system exit status (passed to C's `exit()' function); if it is
  1081.      `None', the exit status is zero; if it has another type (such as a
  1082.      string), the object's value is printed and the exit status is one.
  1083.  
  1084.      A call to `sys.exit' is translated into an exception so that
  1085.      clean-up handlers (`finally' clauses of `try' statements) can be
  1086.      executed, and so that a debugger can execute a script without
  1087.      running the risk of losing control.  The `posix._exit()' function
  1088.      can be used if it is absolutely positively necessary to exit
  1089.      immediately (e.g., after a `fork()' in the child process).
  1090.  
  1091.  - built-in exception: TypeError
  1092.      Raised when a built-in operation or function is applied to an
  1093.      object of inappropriate type.  The associated value is a string
  1094.      giving details about the type mismatch.
  1095.  
  1096.  - built-in exception: ValueError
  1097.      Raised when a built-in operation or function receives an argument
  1098.      that has the right type but an inappropriate value, and the
  1099.      situation is not described by a more precise exception such as
  1100.      `IndexError'.
  1101.  
  1102.  - built-in exception: ZeroDivisionError
  1103.      Raised when the second argument of a division or modulo operation
  1104.      is zero.  The associated value is a string indicating the type of
  1105.      the operands and the operation.
  1106.  
  1107.