home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !ibrowse / files / pylibi-2 < prev    next >
Encoding:
GNU Info File  |  1996-11-14  |  46.8 KB  |  1,103 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: Built-in Functions,  Prev: Exceptions,  Up: Built-in Objects
  40.  
  41. Built-in Functions
  42. ==================
  43.  
  44. The Python interpreter has a number of functions built into it that are
  45. always available.  They are listed here in alphabetical order.
  46.  
  47.  - built-in function: abs (X)
  48.      Return the absolute value of a number.  The argument may be a plain
  49.      or long integer or a floating point number.
  50.  
  51.  - built-in function: apply (FUNCTION, ARGS[, KEYWORDS])
  52.      The FUNCTION argument must be a callable object (a user-defined or
  53.      built-in function or method, or a class object) and the ARGS
  54.      argument must be a tuple.  The FUNCTION is called with ARGS as
  55.      argument list; the number of arguments is the the length of the
  56.      tuple.  (This is different from just calling `FUNC(ARGS)', since
  57.      in that case there is always exactly one argument.) If the
  58.      optional KEYWORDS argument is present, it must be a dictionary
  59.      whose keys are strings.  It specifies keyword arguments to be
  60.      added to the end of the the argument list.
  61.  
  62.  - built-in function: chr (I)
  63.      Return a string of one character whose ASCII code is the integer
  64.      I, e.g., `chr(97)' returns the string `'a''.  This is the inverse
  65.      of `ord()'.  The argument must be in the range [0..255], inclusive.
  66.  
  67.  - built-in function: cmp (X, Y)
  68.      Compare the two objects X and Y and return an integer according to
  69.      the outcome.  The return value is negative if `X < Y', zero if `X
  70.      == Y' and strictly positive if `X > Y'.
  71.  
  72.  - built-in function: coerce (X, Y)
  73.      Return a tuple consisting of the two numeric arguments converted to
  74.      a common type, using the same rules as used by arithmetic
  75.      operations.
  76.  
  77.  - built-in function: compile (STRING, FILENAME, KIND)
  78.      Compile the STRING into a code object.  Code objects can be
  79.      executed by an `exec' statement or evaluated by a call to
  80.      `eval()'.  The FILENAME argument should give the file from which
  81.      the code was read; pass e.g. `'<string>'' if it wasn't read from a
  82.      file.  The KIND argument specifies what kind of code must be
  83.      compiled; it can be `'exec'' if STRING consists of a sequence of
  84.      statements, `'eval'' if it consists of a single expression, or
  85.      `'single'' if it consists of a single interactive statement (in
  86.      the latter case, expression statements that evaluate to something
  87.      else than `None' will printed).
  88.  
  89.  - built-in function: delattr (OBJECT, NAME)
  90.      This is a relative of `setattr'.  The arguments are an object and
  91.      a string.  The string must be the name of one of the object's
  92.      attributes.  The function deletes the named attribute, provided
  93.      the object allows it.  For example, `delattr(X, 'FOOBAR')' is
  94.      equivalent to `del X.FOOBAR'.
  95.  
  96.  - built-in function: dir ()
  97.      Without arguments, return the list of names in the current local
  98.      symbol table.  With a module, class or class instance object as
  99.      argument (or anything else that has a `__dict__' attribute),
  100.      returns the list of names in that object's attribute dictionary.
  101.      The resulting list is sorted.  For example:
  102.  
  103.           >>> import sys
  104.           >>> dir()
  105.           ['sys']
  106.           >>> dir(sys)
  107.           ['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
  108.           >>>
  109.  
  110.  - built-in function: divmod (A, B)
  111.      Take two numbers as arguments and return a pair of integers
  112.      consisting of their integer quotient and remainder.  With mixed
  113.      operand types, the rules for binary arithmetic operators apply.
  114.      For plain and long integers, the result is the same as `(A / B, A
  115.      % B)'.  For floating point numbers the result is the same as
  116.      `(math.floor(A / B), A % B)'.
  117.  
  118.  - built-in function: eval (EXPRESSION[, GLOBALS[, LOCALS]])
  119.      The arguments are a string and two optional dictionaries.  The
  120.      EXPRESSION argument is parsed and evaluated as a Python expression
  121.      (technically speaking, a condition list) using the GLOBALS and
  122.      LOCALS dictionaries as global and local name space.  If the LOCALS
  123.      dictionary is omitted it defaults to the GLOBALS dictionary.  If
  124.      both dictionaries are omitted, the expression is executed in the
  125.      environment where `eval' is called.  The return value is the
  126.      result of the evaluated expression.  Syntax errors are reported as
  127.      exceptions.  Example:
  128.  
  129.           >>> x = 1
  130.           >>> print eval('x+1')
  131.           2
  132.           >>>
  133.      This function can also be used to execute arbitrary code objects
  134.      (e.g. created by `compile()').  In this case pass a code object
  135.      instead of a string.  The code object must have been compiled
  136.      passing `'eval'' to the KIND argument.
  137.  
  138.      Hints: dynamic execution of statements is supported by the `exec'
  139.      statement.  Execution of statements from a file is supported by
  140.      the `execfile()' function.  The `globals()' and `locals()'
  141.      functions returns the current global and local dictionary,
  142.      respectively, which may be useful to pass around for use by
  143.      `eval()' or `execfile()'.
  144.  
  145.  
  146.  - built-in function: execfile (FILE[, GLOBALS[, LOCALS]])
  147.      This function is similar to the `exec' statement, but parses a
  148.      file instead of a string.  It is different from the `import'
  149.      statement in that it does not use the module administration -- it
  150.      reads the file unconditionally and does not create a new module.(1)
  151.  
  152.      The arguments are a file name and two optional dictionaries.  The
  153.      file is parsed and evaluated as a sequence of Python statements
  154.      (similarly to a module) using the GLOBALS and LOCALS dictionaries
  155.      as global and local name space.  If the LOCALS dictionary is
  156.      omitted it defaults to the GLOBALS dictionary.  If both
  157.      dictionaries are omitted, the expression is executed in the
  158.      environment where `execfile()' is called.  The return value is
  159.      `None'.
  160.  
  161.  - built-in function: filter (FUNCTION, LIST)
  162.      Construct a list from those elements of LIST for which FUNCTION
  163.      returns true.  If LIST is a string or a tuple, the result also has
  164.      that type; otherwise it is always a list.  If FUNCTION is `None',
  165.      the identity function is assumed, i.e. all elements of LIST that
  166.      are false (zero or empty) are removed.
  167.  
  168.  - built-in function: float (X)
  169.      Convert a number to floating point.  The argument may be a plain or
  170.      long integer or a floating point number.
  171.  
  172.  - built-in function: getattr (OBJECT, NAME)
  173.      The arguments are an object and a string.  The string must be the
  174.      name of one of the object's attributes.  The result is the value
  175.      of that attribute.  For example, `getattr(X, 'FOOBAR')' is
  176.      equivalent to `X.FOOBAR'.
  177.  
  178.  - built-in function: globals ()
  179.      Return a dictionary representing the current global symbol table.
  180.      This is always the dictionary of the current module (inside a
  181.      function or method, this is the module where it is defined, not the
  182.      module from which it is called).
  183.  
  184.  - built-in function: hasattr (OBJECT, NAME)
  185.      The arguments are an object and a string.  The result is 1 if the
  186.      string is the name of one of the object's attributes, 0 if not.
  187.      (This is implemented by calling `getattr(object, name)' and seeing
  188.      whether it raises an exception or not.)
  189.  
  190.  - built-in function: hash (OBJECT)
  191.      Return the hash value of the object (if it has one).  Hash values
  192.      are 32-bit integers.  They are used to quickly compare dictionary
  193.      keys during a dictionary lookup.  Numeric values that compare equal
  194.      have the same hash value (even if they are of different types, e.g.
  195.      1 and 1.0).
  196.  
  197.  - built-in function: hex (X)
  198.      Convert an integer number (of any size) to a hexadecimal string.
  199.      The result is a valid Python expression.
  200.  
  201.  - built-in function: id (OBJECT)
  202.      Return the `identity' of an object.  This is an integer which is
  203.      guaranteed to be unique and constant for this object during its
  204.      lifetime.  (Two objects whose lifetimes are disjunct may have the
  205.      same id() value.)  (Implementation note: this is the address of the
  206.      object.)
  207.  
  208.  - built-in function: input ([PROMPT])
  209.      Almost equivalent to `eval(raw_input(PROMPT))'.  Like
  210.      `raw_input()', the PROMPT argument is optional.  The difference is
  211.      that a long input expression may be broken over multiple lines
  212.      using the backslash convention.
  213.  
  214.  - built-in function: int (X)
  215.      Convert a number to a plain integer.  The argument may be a plain
  216.      or long integer or a floating point number.  Conversion of floating
  217.      point numbers to integers is defined by the C semantics; normally
  218.      the conversion truncates towards zero.(2)
  219.  
  220.  - built-in function: len (S)
  221.      Return the length (the number of items) of an object.  The argument
  222.      may be a sequence (string, tuple or list) or a mapping
  223.      (dictionary).
  224.  
  225.  - built-in function: locals ()
  226.      Return a dictionary representing the current local symbol table.
  227.      Inside a function, modifying this dictionary does not always have
  228.      the desired effect.
  229.  
  230.  - built-in function: long (X)
  231.      Convert a number to a long integer.  The argument may be a plain or
  232.      long integer or a floating point number.
  233.  
  234.  - built-in function: map (FUNCTION, LIST, ...)
  235.      Apply FUNCTION to every item of LIST and return a list of the
  236.      results.  If additional LIST arguments are passed, FUNCTION must
  237.      take that many arguments and is applied to the items of all lists
  238.      in parallel; if a list is shorter than another it is assumed to be
  239.      extended with `None' items.  If FUNCTION is `None', the identity
  240.      function is assumed; if there are multiple list arguments, `map'
  241.      returns a list consisting of tuples containing the corresponding
  242.      items from all lists (i.e. a kind of transpose operation).  The
  243.      LIST arguments may be any kind of sequence; the result is always a
  244.      list.
  245.  
  246.  - built-in function: max (S)
  247.      Return the largest item of a non-empty sequence (string, tuple or
  248.      list).
  249.  
  250.  - built-in function: min (S)
  251.      Return the smallest item of a non-empty sequence (string, tuple or
  252.      list).
  253.  
  254.  - built-in function: oct (X)
  255.      Convert an integer number (of any size) to an octal string.  The
  256.      result is a valid Python expression.
  257.  
  258.  - built-in function: open (FILENAME[, MODE[, BUFSIZE]])
  259.      Return a new file object (described earlier under Built-in Types).
  260.      The first two arguments are the same as for `stdio''s `fopen()':
  261.      FILENAME is the file name to be opened, MODE indicates how the
  262.      file is to be opened: `'r'' for reading, `'w'' for writing
  263.      (truncating an existing file), and `'a'' opens it for appending
  264.      (which on *some* UNIX systems means that *all* writes append to
  265.      the end of the file, regardless of the current seek position).
  266.      Modes `'r+'', `'w+'' and `'a+'' open the file for updating,
  267.      provided the underlying `stdio' library understands this.  On
  268.      systems that differentiate between binary and text files, `'b''
  269.      appended to the mode opens the file in binary mode.  If the file
  270.      cannot be opened, `IOError' is raised.  If MODE is omitted, it
  271.      defaults to `'r''.  The optional BUFSIZE argument specifies the
  272.      file's desired buffer size: 0 means unbuffered, 1 means line
  273.      buffered, any other positive value means use a buffer of
  274.      (approximately) that size.  A negative BUFSIZE means to use the
  275.      system default, which is usually line buffered for for tty devices
  276.      and fully buffered for other files.(3)
  277.  
  278.  - built-in function: ord (C)
  279.      Return the ASCII value of a string of one character.  E.g.,
  280.      `ord('a')' returns the integer `97'.  This is the inverse of
  281.      `chr()'.
  282.  
  283.  - built-in function: pow (X, Y[, Z])
  284.      Return X to the power Y; if Z is present, return X to the power Y,
  285.      modulo Z (computed more efficiently than `pow(X, Y) % Z').  The
  286.      arguments must have numeric types.  With mixed operand types, the
  287.      rules for binary arithmetic operators apply.  The effective
  288.      operand type is also the type of the result; if the result is not
  289.      expressible in this type, the function raises an exception; e.g.,
  290.      `pow(2, -1)' or `pow(2, 35000)' is not allowed.
  291.  
  292.  - built-in function: range ([START,] END[, STEP])
  293.      This is a versatile function to create lists containing arithmetic
  294.      progressions.  It is most often used in `for' loops.  The
  295.      arguments must be plain integers.  If the STEP argument is
  296.      omitted, it defaults to `1'.  If the START argument is omitted, it
  297.      defaults to `0'.  The full form returns a list of plain integers
  298.      `[START, START + STEP, START + 2 * STEP, ...]'.  If STEP is
  299.      positive, the last element is the largest `START + I * STEP' less
  300.      than END; if STEP is negative, the last element is the largest
  301.      `START + I * STEP' greater than END.  STEP must not be zero (or
  302.      else an exception is raised).  Example:
  303.  
  304.           >>> range(10)
  305.           [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  306.           >>> range(1, 11)
  307.           [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  308.           >>> range(0, 30, 5)
  309.           [0, 5, 10, 15, 20, 25]
  310.           >>> range(0, 10, 3)
  311.           [0, 3, 6, 9]
  312.           >>> range(0, -10, -1)
  313.           [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  314.           >>> range(0)
  315.           []
  316.           >>> range(1, 0)
  317.           []
  318.           >>>
  319.  
  320.  - built-in function: raw_input ([PROMPT])
  321.      If the PROMPT argument is present, it is written to standard output
  322.      without a trailing newline.  The function then reads a line from
  323.      input, converts it to a string (stripping a trailing newline), and
  324.      returns that.  When EOF is read, `EOFError' is raised. Example:
  325.  
  326.           >>> s = raw_input('--> ')
  327.           --> Monty Python's Flying Circus
  328.           >>> s
  329.           "Monty Python's Flying Circus"
  330.           >>>
  331.  
  332.  - built-in function: reduce (FUNCTION, LIST[, INITIALIZER])
  333.      Apply the binary FUNCTION to the items of LIST so as to reduce the
  334.      list to a single value.  E.g., `reduce(lambda x, y: x*y, LIST, 1)'
  335.      returns the product of the elements of LIST.  The optional
  336.      INITIALIZER can be thought of as being prepended to LIST so as to
  337.      allow reduction of an empty LIST.  The LIST arguments may be any
  338.      kind of sequence.
  339.  
  340.  - built-in function: reload (MODULE)
  341.      Re-parse and re-initialize an already imported MODULE.  The
  342.      argument must be a module object, so it must have been successfully
  343.      imported before.  This is useful if you have edited the module
  344.      source file using an external editor and want to try out the new
  345.      version without leaving the Python interpreter.  The return value
  346.      is the module object (i.e. the same as the MODULE argument).
  347.  
  348.      There are a number of caveats:
  349.  
  350.      If a module is syntactically correct but its initialization fails,
  351.      the first `import' statement for it does not bind its name locally,
  352.      but does store a (partially initialized) module object in
  353.      `sys.modules'.  To reload the module you must first `import' it
  354.      again (this will bind the name to the partially initialized module
  355.      object) before you can `reload()' it.
  356.  
  357.      When a module is reloaded, its dictionary (containing the module's
  358.      global variables) is retained.  Redefinitions of names will
  359.      override the old definitions, so this is generally not a problem.
  360.      If the new version of a module does not define a name that was
  361.      defined by the old version, the old definition remains.  This
  362.      feature can be used to the module's advantage if it maintains a
  363.      global table or cache of objects -- with a `try' statement it can
  364.      test for the table's presence and skip its initialization if
  365.      desired.
  366.  
  367.      It is legal though generally not very useful to reload built-in or
  368.      dynamically loaded modules, except for `sys', `__main__' and
  369.      `__builtin__'.  In certain cases, however, extension modules are
  370.      not designed to be initialized more than once, and may fail in
  371.      arbitrary ways when reloaded.
  372.  
  373.      If a module imports objects from another module using `from' ...
  374.      `import' ..., calling `reload()' for the other module does not
  375.      redefine the objects imported from it -- one way around this is to
  376.      re-execute the `from' statement, another is to use `import' and
  377.      qualified names (MODULE.NAME) instead.
  378.  
  379.      If a module instantiates instances of a class, reloading the module
  380.      that defines the class does not affect the method definitions of
  381.      the instances -- they continue to use the old class definition.
  382.      The same is true for derived classes.
  383.  
  384.  - built-in function: repr (OBJECT)
  385.      Return a string containing a printable representation of an object.
  386.      This is the same value yielded by conversions (reverse quotes).
  387.      It is sometimes useful to be able to access this operation as an
  388.      ordinary function.  For many types, this function makes an attempt
  389.      to return a string that would yield an object with the same value
  390.      when passed to `eval()'.
  391.  
  392.  - built-in function: round (X, N)
  393.      Return the floating point value X rounded to N digits after the
  394.      decimal point.  If N is omitted, it defaults to zero.  The result
  395.      is a floating point number.  Values are rounded to the closest
  396.      multiple of 10 to the power minus N; if two multiples are equally
  397.      close, rounding is done away from 0 (so e.g.  `round(0.5)' is
  398.      `1.0' and `round(-0.5)' is `-1.0').
  399.  
  400.  - built-in function: setattr (OBJECT, NAME, VALUE)
  401.      This is the counterpart of `getattr'.  The arguments are an
  402.      object, a string and an arbitrary value.  The string must be the
  403.      name of one of the object's attributes.  The function assigns the
  404.      value to the attribute, provided the object allows it.  For
  405.      example, `setattr(X, 'FOOBAR', 123)' is equivalent to `X.FOOBAR =
  406.      123'.
  407.  
  408.  - built-in function: str (OBJECT)
  409.      Return a string containing a nicely printable representation of an
  410.      object.  For strings, this returns the string itself.  The
  411.      difference with `repr(OBJECT)' is that `str(OBJECT)' does not
  412.      always attempt to return a string that is acceptable to `eval()';
  413.      its goal is to return a printable string.
  414.  
  415.  - built-in function: tuple (SEQUENCE)
  416.      Return a tuple whose items are the same and in the same order as
  417.      SEQUENCE's items.  If SEQUENCE is alread a tuple, it is returned
  418.      unchanged.  For instance, `tuple('abc')' returns returns `('a',
  419.      'b', 'c')' and `tuple([1, 2, 3])' returns `(1, 2, 3)'.
  420.  
  421.  - built-in function: type (OBJECT)
  422.      Return the type of an OBJECT.  The return value is a type object.
  423.      The standard module `types' defines names for all built-in types.
  424.      For instance:
  425.  
  426.           >>> import types
  427.           >>> if type(x) == types.StringType: print "It's a string"
  428.  
  429.  - built-in function: vars ([OBJECT])
  430.      Without arguments, return a dictionary corresponding to the current
  431.      local symbol table.  With a module, class or class instance object
  432.      as argument (or anything else that has a `__dict__' attribute),
  433.      returns a dictionary corresponding to the object's symbol table.
  434.      The returned dictionary should not be modified: the effects on the
  435.      corresponding symbol table are undefined.(4)
  436.  
  437.  - built-in function: xrange ([START,] END[, STEP])
  438.      This function is very similar to `range()', but returns an "xrange
  439.      object" instead of a list.  This is an opaque sequence type which
  440.      yields the same values as the corresponding list, without actually
  441.      storing them all simultaneously.  The advantage of `xrange()' over
  442.      `range()' is minimal (since `xrange()' still has to create the
  443.      values when asked for them) except when a very large range is used
  444.      on a memory-starved machine (e.g. MS-DOS) or when all of the
  445.      range's elements are never used (e.g. when the loop is usually
  446.      terminated with `break').
  447.  
  448. ---------- Footnotes ----------
  449.  
  450. (1)  It is used relatively rarely so does not warrant being made into a
  451. statement.
  452.  
  453. (2)  This is ugly -- the language definition should require truncation
  454. towards zero.
  455.  
  456. (3)  Specifying a buffer size currently has no effect on systems that
  457. don't have `setvbuf()'.  The interface to specify the buffer size is
  458. not done using a method that calls `setvbuf()', because that may dump
  459. core when called after any I/O has been performed, and there's no
  460. reliable way to determine whether this is the case.
  461.  
  462. (4)  In the current implementation, local variable bindings cannot
  463. normally be affected this way, but variables retrieved from other
  464. scopes (e.g. modules) can be.  This may change.
  465.  
  466. 
  467. File: pylibi,  Node: Python Services,  Next: String Services,  Prev: Built-in Objects,  Up: Top
  468.  
  469. Python Services
  470. ***************
  471.  
  472. The modules described in this chapter provide a wide range of services
  473. related to the Python interpreter and its interaction with its
  474. environment.  Here's an overview:
  475.  
  476. sys
  477.      -- Access system specific parameters and functions.
  478.  
  479. types
  480.      -- Names for all built-in types.
  481.  
  482. traceback
  483.      -- Print or retrieve a stack traceback.
  484.  
  485. pickle
  486.      -- Convert Python objects to streams of bytes and back.
  487.  
  488. shelve
  489.      -- Python object persistency.
  490.  
  491. copy
  492.      -- Shallow and deep copy operations.
  493.  
  494. marshal
  495.      -- Convert Python objects to streams of bytes and back (with
  496.      different constraints).
  497.  
  498. imp
  499.      -- Access the implementation of the `import' statement.
  500.  
  501. parser
  502.      -- Retrieve and submit parse trees from and to the runtime support
  503.      environment.
  504.  
  505. __builtin__
  506.      -- The set of built-in functions.
  507.  
  508. __main__
  509.      -- The environment where the top-level script is run.
  510.  
  511. * Menu:
  512.  
  513. * sys::
  514. * types::
  515. * traceback::
  516. * pickle::
  517. * shelve::
  518. * copy::
  519. * marshal::
  520. * imp::
  521. * __builtin__::
  522. * __main__::
  523.  
  524. 
  525. File: pylibi,  Node: sys,  Next: types,  Prev: Python Services,  Up: Python Services
  526.  
  527. Built-in Module `sys'
  528. =====================
  529.  
  530. This module provides access to some variables used or maintained by the
  531. interpreter and to functions that interact strongly with the
  532. interpreter.  It is always available.
  533.  
  534.  - data of module sys: argv
  535.      The list of command line arguments passed to a Python script.
  536.      `sys.argv[0]' is the script name (it is operating system dependent
  537.      whether this is a full pathname or not).  If the command was
  538.      executed using the `-c' command line option to the interpreter,
  539.      `sys.argv[0]' is set to the string `"-c"'.  If no script name was
  540.      passed to the Python interpreter, `sys.argv' has zero length.
  541.  
  542.  - data of module sys: builtin_module_names
  543.      A list of strings giving the names of all modules that are compiled
  544.      into this Python interpreter.  (This information is not available
  545.      in any other way -- `sys.modules.keys()' only lists the imported
  546.      modules.)
  547.  
  548.  - data of module sys: exc_type
  549.  
  550.  - data of module sys: exc_value
  551.  
  552.  - data of module sys: exc_traceback
  553.      These three variables are not always defined; they are set when an
  554.      exception handler (an `except' clause of a `try' statement) is
  555.      invoked.  Their meaning is: `exc_type' gets the exception type of
  556.      the exception being handled; `exc_value' gets the exception
  557.      parameter (its "associated value" or the second argument to
  558.      `raise'); `exc_traceback' gets a traceback object (see the
  559.      Reference Manual) which encapsulates the call stack at the point
  560.      where the exception originally occurred.
  561.  
  562.  - function of module sys: exit (N)
  563.      Exit from Python with numeric exit status N.  This is implemented
  564.      by raising the `SystemExit' exception, so cleanup actions
  565.      specified by `finally' clauses of `try' statements are honored,
  566.      and it is possible to catch the exit attempt at an outer level.
  567.  
  568.  - data of module sys: exitfunc
  569.      This value is not actually defined by the module, but can be set by
  570.      the user (or by a program) to specify a clean-up action at program
  571.      exit.  When set, it should be a parameterless function.  This
  572.      function will be called when the interpreter exits in any way
  573.      (except when a fatal error occurs: in that case the interpreter's
  574.      internal state cannot be trusted).
  575.  
  576.  - data of module sys: last_type
  577.  
  578.  - data of module sys: last_value
  579.  
  580.  - data of module sys: last_traceback
  581.      These three variables are not always defined; they are set when an
  582.      exception is not handled and the interpreter prints an error
  583.      message and a stack traceback.  Their intended use is to allow an
  584.      interactive user to import a debugger module and engage in
  585.      post-mortem debugging without having to re-execute the command
  586.      that caused the error (which may be hard to reproduce).  The
  587.      meaning of the variables is the same as that of `exc_type',
  588.      `exc_value' and `exc_tracaback', respectively.
  589.  
  590.  - data of module sys: modules
  591.      Gives the list of modules that have already been loaded.  This can
  592.      be manipulated to force reloading of modules and other tricks.
  593.  
  594.  - data of module sys: path
  595.      A list of strings that specifies the search path for modules.
  596.      Initialized from the environment variable `PYTHONPATH', or an
  597.      installation-dependent default.
  598.  
  599.  - data of module sys: platform
  600.      This string contains a platform identifier.  This can be used to
  601.      append platform-specific components to `sys.path', for instance.
  602.  
  603.  - data of module sys: ps1
  604.  
  605.  - data of module sys: ps2
  606.      Strings specifying the primary and secondary prompt of the
  607.      interpreter.  These are only defined if the interpreter is in
  608.      interactive mode.  Their initial values in this case are `'>>> ''
  609.      and `'... ''.
  610.  
  611.  - function of module sys: setcheckinterval (INTERVAL)
  612.      Set the interpreter's "check interval".  This integer value
  613.      determines how often the interpreter checks for periodic things
  614.      such as thread switches and signal handlers.  The default is 10,
  615.      meaning the check is performed every 10 Python virtual
  616.      instructions.  Setting it to a larger value may increase
  617.      performance for programs using threads.  Setting it to a value
  618.      checks every virtual instruction, maximizing responsiveness as
  619.      well as overhead.
  620.  
  621.  - function of module sys: settrace (TRACEFUNC)
  622.      Set the system's trace function, which allows you to implement a
  623.      Python source code debugger in Python.  See section "How It Works"
  624.      in the chapter on the Python Debugger.
  625.  
  626.  - function of module sys: setprofile (PROFILEFUNC)
  627.      Set the system's profile function, which allows you to implement a
  628.      Python source code profiler in Python.  See the chapter on the
  629.      Python Profiler.  The system's profile function is called
  630.      similarly to the system's trace function (see `sys.settrace'), but
  631.      it isn't called for each executed line of code (only on call and
  632.      return and when an exception occurs).  Also, its return value is
  633.      not used, so it can just return `None'.
  634.  
  635.  - data of module sys: stdin
  636.  
  637.  - data of module sys: stdout
  638.  
  639.  - data of module sys: stderr
  640.      File objects corresponding to the interpreter's standard input,
  641.      output and error streams.  `sys.stdin' is used for all interpreter
  642.      input except for scripts but including calls to `input()' and
  643.      `raw_input()'.  `sys.stdout' is used for the output of `print' and
  644.      expression statements and for the prompts of `input()' and
  645.      `raw_input()'.  The interpreter's own prompts and (almost all of)
  646.      its error messages go to `sys.stderr'.  `sys.stdout' and
  647.      `sys.stderr' needn't be built-in file objects: any object is
  648.      acceptable as long as it has a `write' method that takes a string
  649.      argument.  (Changing these objects doesn't affect the standard I/O
  650.      streams of processes executed by `popen()', `system()' or the
  651.      `exec*()' family of functions in the `os' module.)
  652.  
  653.  - data of module sys: tracebacklimit
  654.      When this variable is set to an integer value, it determines the
  655.      maximum number of levels of traceback information printed when an
  656.      unhandled exception occurs.  The default is 1000.  When set to 0 or
  657.      less, all traceback information is suppressed and only the
  658.      exception type and value are printed.
  659.  
  660. 
  661. File: pylibi,  Node: types,  Next: traceback,  Prev: sys,  Up: Python Services
  662.  
  663. Standard Module `types'
  664. =======================
  665.  
  666. This module defines names for all object types that are used by the
  667. standard Python interpreter (but not for the types defined by various
  668. extension modules).  It is safe to use "`from types import *'" -- the
  669. module does not export any other names besides the ones listed here.
  670. New names exported by future versions of this module will all end in
  671. `Type'.
  672.  
  673. Typical use is for functions that do different things depending on
  674. their argument types, like the following:
  675.  
  676.      from types import *
  677.      def delete(list, item):
  678.          if type(item) is IntType:
  679.             del list[item]
  680.          else:
  681.             list.remove(item)
  682.  
  683. The module defines the following names:
  684.  
  685.  - data of module types: NoneType
  686.      The type of `None'.
  687.  
  688.  - data of module types: TypeType
  689.      The type of type objects (such as returned by `type()').
  690.  
  691.  - data of module types: IntType
  692.      The type of integers (e.g. `1').
  693.  
  694.  - data of module types: LongType
  695.      The type of long integers (e.g. `1L').
  696.  
  697.  - data of module types: FloatType
  698.      The type of floating point numbers (e.g. `1.0').
  699.  
  700.  - data of module types: StringType
  701.      The type of character strings (e.g. `'Spam'').
  702.  
  703.  - data of module types: TupleType
  704.      The type of tuples (e.g. `(1, 2, 3, 'Spam')').
  705.  
  706.  - data of module types: ListType
  707.      The type of lists (e.g. `[0, 1, 2, 3]').
  708.  
  709.  - data of module types: DictType
  710.      The type of dictionaries (e.g. `{'Bacon': 1, 'Ham': 0}').
  711.  
  712.  - data of module types: DictionaryType
  713.      An alternative name for `DictType'.
  714.  
  715.  - data of module types: FunctionType
  716.      The type of user-defined functions and lambdas.
  717.  
  718.  - data of module types: LambdaType
  719.      An alternative name for `FunctionType'.
  720.  
  721.  - data of module types: CodeType
  722.      The type for code objects such as returned by `compile()'.
  723.  
  724.  - data of module types: ClassType
  725.      The type of user-defined classes.
  726.  
  727.  - data of module types: InstanceType
  728.      The type of instances of user-defined classes.
  729.  
  730.  - data of module types: MethodType
  731.      The type of methods of user-defined class instances.
  732.  
  733.  - data of module types: UnboundMethodType
  734.      An alternative name for `MethodType'.
  735.  
  736.  - data of module types: BuiltinFunctionType
  737.      The type of built-in functions like `len' or `sys.exit'.
  738.  
  739.  - data of module types: BuiltinMethodType
  740.      An alternative name for `BuiltinFunction'.
  741.  
  742.  - data of module types: ModuleType
  743.      The type of modules.
  744.  
  745.  - data of module types: FileType
  746.      The type of open file objects such as `sys.stdout'.
  747.  
  748.  - data of module types: XRangeType
  749.      The type of range objects returned by `xrange()'.
  750.  
  751.  - data of module types: TracebackType
  752.      The type of traceback objects such as found in `sys.exc_traceback'.
  753.  
  754.  - data of module types: FrameType
  755.      The type of frame objects such as found in `tb.tb_frame' if `tb'
  756.      is a traceback object.
  757.  
  758. 
  759. File: pylibi,  Node: traceback,  Next: pickle,  Prev: types,  Up: Python Services
  760.  
  761. Standard Module `traceback'
  762. ===========================
  763.  
  764. This module provides a standard interface to format and print stack
  765. traces of Python programs.  It exactly mimics the behavior of the
  766. Python interpreter when it prints a stack trace.  This is useful when
  767. you want to print stack traces under program control, e.g. in a
  768. "wrapper" around the interpreter.
  769.  
  770. The module uses traceback objects -- this is the object type that is
  771. stored in the variables `sys.exc_traceback' and `sys.last_traceback'.
  772.  
  773. The module defines the following functions:
  774.  
  775.  - function of module traceback: print_tb (TRACEBACK[, LIMIT])
  776.      Print up to LIMIT stack trace entries from TRACEBACK.  If LIMIT is
  777.      omitted or `None', all entries are printed.
  778.  
  779.  - function of module traceback: extract_tb (TRACEBACK[, LIMIT])
  780.      Return a list of up to LIMIT "pre-processed" stack trace entries
  781.      extracted from TRACEBACK.  It is useful for alternate formatting
  782.      of stack traces.  If LIMIT is omitted or `None', all entries are
  783.      extracted.  A "pre-processed" stack trace entry is a quadruple
  784.      (FILENAME, LINE NUMBER, FUNCTION NAME, LINE TEXT) representing the
  785.      information that is usually printed for a stack trace.  The LINE
  786.      TEXT is a string with leading and trailing whitespace stripped; if
  787.      the source is not available it is `None'.
  788.  
  789.  - function of module traceback: print_exception (TYPE, VALUE,
  790.           TRACEBACK[, LIMIT])
  791.      Print exception information and up to LIMIT stack trace entries
  792.      from TRACEBACK.  This differs from `print_tb' in the following
  793.      ways: (1) if TRACEBACK is not `None', it prints a header
  794.      "`Traceback (innermost last):'"; (2) it prints the exception TYPE
  795.      and VALUE after the stack trace; (3) if TYPE is `SyntaxError' and
  796.      VALUE has the appropriate format, it prints the line where the
  797.      syntax error occurred with a caret indication the approximate
  798.      position of the error.
  799.  
  800.  - function of module traceback: print_exc ([LIMIT])
  801.      This is a shorthand for `print_exception(sys.exc_type,'
  802.      `sys.exc_value,' `sys.exc_traceback,' `limit)'.
  803.  
  804.  - function of module traceback: print_last ([LIMIT])
  805.      This is a shorthand for `print_exception(sys.last_type,'
  806.      `sys.last_value,' `sys.last_traceback,' `limit)'.
  807.  
  808. 
  809. File: pylibi,  Node: pickle,  Next: shelve,  Prev: traceback,  Up: Python Services
  810.  
  811. Standard Module `pickle'
  812. ========================
  813.  
  814. The `pickle' module implements a basic but powerful algorithm for
  815. "pickling" (a.k.a. serializing, marshalling or flattening) nearly
  816. arbitrary Python objects.  This is the act of converting objects to a
  817. stream of bytes (and back: "unpickling").  This is a more primitive
  818. notion than persistency -- although `pickle' reads and writes file
  819. objects, it does not handle the issue of naming persistent objects, nor
  820. the (even more complicated) area of concurrent access to persistent
  821. objects.  The `pickle' module can transform a complex object into a
  822. byte stream and it can transform the byte stream into an object with
  823. the same internal structure.  The most obvious thing to do with these
  824. byte streams is to write them onto a file, but it is also conceivable
  825. to send them across a network or store them in a database.  The module
  826. `shelve' provides a simple interface to pickle and unpickle objects on
  827. "dbm"-style database files.
  828.  
  829. Unlike the built-in module `marshal', `pickle' handles the following
  830. correctly:
  831.  
  832.    * recursive objects (objects containing references to themselves)
  833.  
  834.    * object sharing (references to the same object in different places)
  835.  
  836.    * user-defined classes and their instances
  837.  
  838. The data format used by `pickle' is Python-specific.  This has the
  839. advantage that there are no restrictions imposed by external standards
  840. such as CORBA (which probably can't represent pointer sharing or
  841. recursive objects); however it means that non-Python programs may not
  842. be able to reconstruct pickled Python objects.
  843.  
  844. The `pickle' data format uses a printable ASCII representation.  This
  845. is slightly more voluminous than a binary representation.  However,
  846. small integers actually take *less* space when represented as
  847. minimal-size decimal strings than when represented as 32-bit binary
  848. numbers, and strings are only much longer if they contain many control
  849. characters or 8-bit characters.  The big advantage of using printable
  850. ASCII (and of some other characteristics of `pickle''s representation)
  851. is that for debugging or recovery purposes it is possible for a human
  852. to read the pickled file with a standard text editor.  (I could have
  853. gone a step further and used a notation like S-expressions, but the
  854. parser (currently written in Python) would have been considerably more
  855. complicated and slower, and the files would probably have become much
  856. larger.)
  857.  
  858. The `pickle' module doesn't handle code objects, which the `marshal'
  859. module does.  I suppose `pickle' could, and maybe it should, but
  860. there's probably no great need for it right now (as long as `marshal'
  861. continues to be used for reading and writing code objects), and at
  862. least this avoids the possibility of smuggling Trojan horses into a
  863. program.
  864.  
  865. For the benefit of persistency modules written using `pickle', it
  866. supports the notion of a reference to an object outside the pickled
  867. data stream.  Such objects are referenced by a name, which is an
  868. arbitrary string of printable ASCII characters.  The resolution of such
  869. names is not defined by the `pickle' module -- the persistent object
  870. module will have to implement a method `persistent_load'.  To write
  871. references to persistent objects, the persistent module must define a
  872. method `persistent_id' which returns either `None' or the persistent ID
  873. of the object.
  874.  
  875. There are some restrictions on the pickling of class instances.
  876.  
  877. First of all, the class must be defined at the top level in a module.
  878.  
  879. Next, it must normally be possible to create class instances by calling
  880. the class without arguments.  Usually, this is best accomplished by
  881. providing default values for all arguments to its `__init__' method (if
  882. it has one).  If this is undesirable, the class can define a method
  883. `__getinitargs__()', which should return a *tuple* containing the
  884. arguments to be passed to the class constructor (`__init__()').
  885.  
  886. Classes can further influence how their instances are pickled -- if the
  887. class defines the method `__getstate__()', it is called and the return
  888. state is pickled as the contents for the instance, and if the class
  889. defines the method `__setstate__()', it is called with the unpickled
  890. state.  (Note that these methods can also be used to implement copying
  891. class instances.)  If there is no `__getstate__()' method, the
  892. instance's `__dict__' is pickled.  If there is no `__setstate__()'
  893. method, the pickled object must be a dictionary and its items are
  894. assigned to the new instance's dictionary.  (If a class defines both
  895. `__getstate__()' and `__setstate__()', the state object needn't be a
  896. dictionary -- these methods can do what they want.)  This protocol is
  897. also used by the shallow and deep copying operations defined in the
  898. `copy' module.
  899.  
  900. Note that when class instances are pickled, their class's code and data
  901. are not pickled along with them.  Only the instance data are pickled.
  902. This is done on purpose, so you can fix bugs in a class or add methods
  903. and still load objects that were created with an earlier version of the
  904. class.  If you plan to have long-lived objects that will see many
  905. versions of a class, it may be worthwhile to put a version number in
  906. the objects so that suitable conversions can be made by the class's
  907. `__setstate__()' method.
  908.  
  909. When a class itself is pickled, only its name is pickled -- the class
  910. definition is not pickled, but re-imported by the unpickling process.
  911. Therefore, the restriction that the class must be defined at the top
  912. level in a module applies to pickled classes as well.
  913.  
  914. The interface can be summarized as follows.
  915.  
  916. To pickle an object `x' onto a file `f', open for writing:
  917.  
  918.      p = pickle.Pickler(f)
  919.      p.dump(x)
  920.  
  921. A shorthand for this is:
  922.  
  923.      pickle.dump(x, f)
  924.  
  925. To unpickle an object `x' from a file `f', open for reading:
  926.  
  927.      u = pickle.Unpickler(f)
  928.      x = u.load()
  929.  
  930. A shorthand is:
  931.  
  932.      x = pickle.load(f)
  933.  
  934. The `Pickler' class only calls the method `f.write' with a string
  935. argument.  The `Unpickler' calls the methods `f.read' (with an integer
  936. argument) and `f.readline' (without argument), both returning a string.
  937. It is explicitly allowed to pass non-file objects here, as long as
  938. they have the right methods.
  939.  
  940. The following types can be pickled:
  941.    * `None'
  942.  
  943.    * integers, long integers, floating point numbers
  944.  
  945.    * strings
  946.  
  947.    * tuples, lists and dictionaries containing only picklable objects
  948.  
  949.    * classes that are defined at the top level in a module
  950.  
  951.    * instances of such classes whose `__dict__' or `__setstate__()' is
  952.      picklable
  953.  
  954. Attempts to pickle unpicklable objects will raise the `PicklingError'
  955. exception; when this happens, an unspecified number of bytes may have
  956. been written to the file.
  957.  
  958. It is possible to make multiple calls to the `dump()' method of the
  959. same `Pickler' instance.  These must then be matched to the same number
  960. of calls to the `load()' instance of the corresponding `Unpickler'
  961. instance.  If the same object is pickled by multiple `dump()' calls,
  962. the `load()' will all yield references to the same object.  *Warning*:
  963. this is intended for pickling multiple objects without intervening
  964. modifications to the objects or their parts.  If you modify an object
  965. and then pickle it again using the same `Pickler' instance, the object
  966. is not pickled again -- a reference to it is pickled and the
  967. `Unpickler' will return the old value, not the modified one.  (There
  968. are two problems here: (a) detecting changes, and (b) marshalling a
  969. minimal set of changes.  I have no answers.  Garbage Collection may
  970. also become a problem here.)
  971.  
  972. Apart from the `Pickler' and `Unpickler' classes, the module defines
  973. the following functions, and an exception:
  974.  
  975.  - function of module pickle: dump (OBJECT, FILE)
  976.      Write a pickled representation of OBECT to the open file object
  977.      FILE.  This is equivalent to `Pickler(file).dump(object)'.
  978.  
  979.  - function of module pickle: load (FILE)
  980.      Read a pickled object from the open file object FILE.  This is
  981.      equivalent to `Unpickler(file).load()'.
  982.  
  983.  - function of module pickle: dumps (OBJECT)
  984.      Return the pickled representation of the object as a string,
  985.      instead of writing it to a file.
  986.  
  987.  - function of module pickle: loads (STRING)
  988.      Read a pickled object from a string instead of a file.  Characters
  989.      in the string past the pickled object's representation are ignored.
  990.  
  991.  - exception of module pickle: PicklingError
  992.      This exception is raised when an unpicklable object is passed to
  993.      `Pickler.dump()'.
  994.  
  995. 
  996. File: pylibi,  Node: shelve,  Next: copy,  Prev: pickle,  Up: Python Services
  997.  
  998. Standard Module `shelve'
  999. ========================
  1000.  
  1001. A "shelf" is a persistent, dictionary-like object.  The difference with
  1002. "dbm" databases is that the values (not the keys!) in a shelf can be
  1003. essentially arbitrary Python objects -- anything that the `pickle'
  1004. module can handle.  This includes most class instances, recursive data
  1005. types, and objects containing lots of shared sub-objects.  The keys are
  1006. ordinary strings.
  1007.  
  1008. To summarize the interface (`key' is a string, `data' is an arbitrary
  1009. object):
  1010.  
  1011.      import shelve
  1012.      
  1013.      d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
  1014.      
  1015.      d[key] = data   # store data at key (overwrites old data if
  1016.                      # using an existing key)
  1017.      data = d[key]   # retrieve data at key (raise KeyError if no
  1018.                      # such key)
  1019.      del d[key]      # delete data stored at key (raises KeyError
  1020.                      # if no such key)
  1021.      flag = d.has_key(key)   # true if the key exists
  1022.      list = d.keys() # a list of all existing keys (slow!)
  1023.      
  1024.      d.close()       # close it
  1025.  
  1026. Restrictions:
  1027.  
  1028.    * The choice of which database package will be used (e.g. dbm or
  1029.      gdbm) depends on which interface is available.  Therefore it isn't
  1030.      safe to open the database directly using dbm.  The database is also
  1031.      (unfortunately) subject to the limitations of dbm, if it is used --
  1032.      this means that (the pickled representation of) the objects stored
  1033.      in the database should be fairly small, and in rare cases key
  1034.      collisions may cause the database to refuse updates.
  1035.  
  1036.    * Dependent on the implementation, closing a persistent dictionary
  1037.      may or may not be necessary to flush changes to disk.
  1038.  
  1039.    * The `shelve' module does not support *concurrent* read/write
  1040.      access to shelved objects.  (Multiple simultaneous read accesses
  1041.      are safe.)  When a program has a shelf open for writing, no other
  1042.      program should have it open for reading or writing.  UNIX file
  1043.      locking can be used to solve this, but this differs across UNIX
  1044.      versions and requires knowledge about the database implementation
  1045.      used.
  1046.  
  1047. 
  1048. File: pylibi,  Node: copy,  Next: marshal,  Prev: shelve,  Up: Python Services
  1049.  
  1050. Standard Module `copy'
  1051. ======================
  1052.  
  1053. This module provides generic (shallow and deep) copying operations.
  1054.  
  1055. Interface summary:
  1056.  
  1057.      import copy
  1058.      
  1059.      x = copy.copy(y)        # make a shallow copy of y
  1060.      x = copy.deepcopy(y)    # make a deep copy of y
  1061.  
  1062. For module specific errors, `copy.error' is raised.
  1063.  
  1064. The difference between shallow and deep copying is only relevant for
  1065. compound objects (objects that contain other objects, like lists or
  1066. class instances):
  1067.  
  1068.    * A *shallow copy* constructs a new compound object and then (to the
  1069.      extent possible) inserts *references* into it to the objects found
  1070.      in the original.
  1071.  
  1072.    * A *deep copy* constructs a new compound object and then,
  1073.      recursively, inserts *copies* into it of the objects found in the
  1074.      original.
  1075.  
  1076. Two problems often exist with deep copy operations that don't exist
  1077. with shallow copy operations:
  1078.  
  1079.    * Recursive objects (compound objects that, directly or indirectly,
  1080.      contain a reference to themselves) may cause a recursive loop.
  1081.  
  1082.    * Because deep copy copies *everything* it may copy too much, e.g.
  1083.      administrative data structures that should be shared even between
  1084.      copies.
  1085.  
  1086. Python's `deepcopy()' operation avoids these problems by:
  1087.  
  1088.    * keeping a table of objects already copied during the current
  1089.      copying pass; and
  1090.  
  1091.    * letting user-defined classes override the copying operation or the
  1092.      set of components copied.
  1093.  
  1094. This version does not copy types like module, class, function, method,
  1095. nor stack trace, stack frame, nor file, socket, window, nor array, nor
  1096. any similar types.
  1097.  
  1098. Classes can use the same interfaces to control copying that they use to
  1099. control pickling: they can define methods called `__getinitargs__()',
  1100. `__getstate__()' and `__setstate__()'.  See the description of module
  1101. `pickle' for information on these methods.
  1102.  
  1103.