{"title": "About the Python Documentation", "text": "./ | About the Python Documentation\nUp:\nPython Documentation Index (./)\n---\n## About the Python Documentation\nThe Python documentation was originally written by Guido van\nRossum, but has increasingly become a community effort over the\npast several years. This growing collection of documents is\navailable in several formats, including typeset versions in PDF\nand PostScript for printing, from the Python Web site (http://www.python.org/).\nA list of contributors (acks.html) is available.\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---", "python_version": "2.2", "length": 1201, "url": "https://docs.python.org/2.2/about.html"} {"title": "Acknowledgements", "text": "./ | Acknowledgements\n---\n## Acknowledgements\nThese people have contributed in some way to the Python\ndocumentation. This list is probably not complete -- if you feel that\nyou or anyone else should be on this list, please let us know (send\nemail to python-docs@python.org (mailto:python-docs@python.org)), and\nwe will be glad to correct the problem.\nIt is only with the input and contributions of the Python community\nthat Python has such wonderful documentation -- Thank You!\nAahz | Nadim Ghaznavi | Piers Lauder | Nick Russo\nMichael Abbott | Jonathan Giddy | Glyph Lefkowitz | Chris Ryland\nSteve Alexander | Shelley Gooch | Marc-Andr Lemburg | Constantina S.\nJim Ahlstrom | Nathaniel Gray | Ulf A. Lindgren | Hugh Sasse\nFred Allen | Grant Griffin | Everett Lipman | Bob Savage\nA. Amoroso | Thomas Guettler | Mirko Liss | Scott Schram\nPehr Anderson | Anders Hammarquist | Martin von Lwis | Neil Schemenauer\nOliver Andrich | Mark Hammond | Fredrik Lundh | Barry Scott\nJess Cea Avin | Harald Hanche-Olsen | Jeff MacDonald | Joakim Sernbrant\nDaniel Barclay | Manus Hand | John Machin | Justin Sheehy\nChris Barker | Gerhard Hring | Andrew MacIntyre | Michael Simcich\nDon Bashford | Travis B. Hartwell | Vladimir Marangozov | Ionel Simionescu\nAnthony Baxter | Janko Hauser | Vincent Marchetti | Roy Smith\nBennett Benson | Bernhard Herzog | Laura Matson | Clay Spence\nJonathan Black | Magnus L. Hetland | Daniel May | Nicholas Spies\nRobin Boerdijk | Konrad Hinsen | Doug Mennella | Tage Stabell-Kulo\nMichal Bozon | Stefan Hoffmeister | Paolo Milani | Frank Stajano\nAaron Brancotti | Albert Hofkamp | Skip Montanaro | Anthony Starks\nKeith Briggs | Gregor Hoffleit | Paul Moore | Greg Stein\nLee Busby | Steve Holden | Ross Moore | Peter Stoehr\nLorenzo M. Catucci | Thomas Holenstein | Sjoerd Mullender | Mark Summerfield\nMauro Cicognini | Gerrit Holl | Dale Nagata | Reuben Sumner\nGilles Civario | Rob Hooft | Ng Pheng Siong | Kalle Svensson\nMike Clarkson | Brian Hooper | Koray Oner | Jim Tittsler\nSteve Clift | Randall Hopper | Denis S. Otkidach | Martijn Vries\nMatthew Cowles | Michael Hudson | Zooko O'Whielacronx | Charles G. Waldman\nJeremy Craven | Jeremy Hylton | William Park | Greg Ward\nAndrew Dalke | Roger Irwin | Joonas Paalasmaa | Barry Warsaw\nBen Darnell | Jack Jansen | Harri Pasanen | Corran Webster\nRobert Donohue | Philip H. Jensen | Tim Peters | Glyn Webster\nFred L. Drake, Jr. | Pedro Diaz Jimenez | Christopher Petrilli | Bob Weiner\nJeff Epler | Lucas de Jonge | Justin D. Pettit | Eddy Welbourne\nMichael Ernst | Andreas Jung | Chris Phoenix | Mats Wichmann\nBlame Andy Eskilsson | Robert Kern | Franois Pinard | Gerry Wiener\nCarey Evans | Jim Kerr | Paul Prescod | Timothy Wild\nMartijn Faassen | Jan Kim | Eric S. Raymond | Blake Winton\nCarl Feynman | Greg Kochanski | Edward K. Ream | Dan Wolfe\nHernan Martinez Foffani | Guido Kollerie | Sean Reifschneider | Steven Work\nStefan Franke | Peter A. Koren | Bernhard Reiter | Thomas Wouters\nJim Fulton | Daniel Kozan | Armin Rigo | Ka-Ping Yee\nPeter Funk | Andrew M. Kuchling | Wes Rishel | Moshe Zadka\nLele Gaifax | Dave Kuhlman | Jim Roskind | Milan Zamazal\nMatthew Gallagher | Erno Kuusela | Guido van Rossum | Cheng Zhang\nBen Gertzfield | Detlef Lannert | Donald Wallace Rouse II\n---\n./ | Acknowledgements", "python_version": "2.2", "length": 3270, "url": "https://docs.python.org/2.2/acks.html"} {"title": "About this document ...", "text": "genindex.html | api.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# About this document ...\nPython/C API Reference Manual,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | api.html | Python/C API Reference Manual | contents.html | genindex.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1723, "url": "https://docs.python.org/2.2/api/about.html"} {"title": "6. Abstract Objects Layer", "text": "arg-parsing.html | api.html | object.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6. Abstract Objects Layer\nThe functions in this chapter interact with Python objects regardless\nof their type, or with wide classes of object types (e.g. all\nnumerical types, or all sequence types). When used on object types\nfor which they do not apply, they will raise a Python exception.", "python_version": "2.2", "length": 401, "url": "https://docs.python.org/2.2/api/abstract.html"} {"title": "8.3 Advanced Debugger Support", "text": "profiling.html | initialization.html | memory.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 8.3 Advanced Debugger Support\nThese functions are only intended to be used by advanced debugging\ntools.", "python_version": "2.2", "length": 224, "url": "https://docs.python.org/2.2/api/advanced-debugging.html"} {"title": "10.1 Allocating Objects on the Heap", "text": "newTypes.html | newTypes.html | common-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.1 Allocating Objects on the Heap\nDL_IMPORT", "python_version": "2.2", "length": 167, "url": "https://docs.python.org/2.2/api/allocating-objects.html"} {"title": "Python/C API Reference Manual", "text": "../index.html | front.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 241, "url": "https://docs.python.org/2.2/api/api.html"} {"title": "5.5 Parsing arguments and building values", "text": "marshalling-utils.html | utilities.html | abstract.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.5 Parsing arguments and building values\nThese functions are useful when creating your own extensions functions\nand methods. Additional information and examples are available in\nExtending and Embedding the Python\nInterpreter (../ext/ext.html).", "python_version": "2.2", "length": 370, "url": "https://docs.python.org/2.2/api/arg-parsing.html"} {"title": "10.6 Buffer Object Structures", "text": "sequence-structs.html | newTypes.html | supporting-iteration.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.6 Buffer Object Structures\nThe buffer interface exports a model where an object can expose its\ninternal data as a set of chunks of data, where each chunk is\nspecified as a pointer/length pair. These chunks are called\nsegments and are presumed to be non-contiguous in memory.\nIf an object does not export the buffer interface, then its\ntp_as_buffer member in the PyTypeObject structure\nshould be NULL. Otherwise, the tp_as_buffer will point to\na PyBufferProcs structure.\nNote:\nIt is very important that your PyTypeObject structure\nuses Py_TPFLAGS_DEFAULT for the value of the\ntp_flags member rather than `0`. This tells the Python\nruntime that your PyBufferProcs structure contains the\nbf_getcharbuffer slot. Older versions of Python did not have\nthis member, so a new Python interpreter using an old extension needs\nto be able to test for its presence before using it.", "python_version": "2.2", "length": 1007, "url": "https://docs.python.org/2.2/api/buffer-structs.html"} {"title": "7.3.3 Buffer Objects", "text": "unicodeMethodsAndSlots.html | sequenceObjects.html | tupleObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.3.3 Buffer Objects\nPython objects implemented in C can export a group of functions called\nthe ``bufferinterface.'' These functions can\nbe used by an object to expose its data in a raw, byte-oriented\nformat. Clients of the object can use the buffer interface to access\nthe object data directly, without needing to copy it first.\nTwo examples of objects that support\nthe buffer interface are strings and arrays. The string object exposes\nthe character contents in the buffer interface's byte-oriented\nform. An array can also expose its contents, but it should be noted\nthat array elements may be multi-byte values.\nAn example user of the buffer interface is the file object's\nwrite() method. Any object that can export a series of bytes\nthrough the buffer interface can be written to a file. There are a\nnumber of format codes to PyArg_ParseTuple() that operate\nagainst an object's buffer interface, returning data from the target\nobject.\nMore information on the buffer interface is provided in the section\n``Buffer Object Structures'' (section 10.6 (buffer-structs.html#buffer-structs)), under\nthe description for PyBufferProcs.\nA ``buffer object'' is defined in the bufferobject.h header\n(included by Python.h). These objects look very similar to\nstring objects at the Python programming level: they support slicing,\nindexing, concatenation, and some other standard string\noperations. However, their data can come from one of two sources: from\na block of memory, or from another object which exports the buffer\ninterface.\nBuffer objects are useful as a way to expose the data from another\nobject's buffer interface to the Python programmer. They can also be\nused as a zero-copy slicing mechanism. Using their ability to\nreference a block of memory, it is possible to expose any data to the\nPython programmer quite easily. The memory could be a large, constant\narray in a C extension, it could be a raw block of memory for\nmanipulation before passing to an operating system library, or it\ncould be used to pass around structured data in its native, in-memory\nformat.", "python_version": "2.2", "length": 2209, "url": "https://docs.python.org/2.2/api/bufferObjects.html"} {"title": "7.3.2.1 Built-in Codecs", "text": "unicodeObjects.html | unicodeObjects.html | unicodeMethodsAndSlots.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.3.2.1 Built-in Codecs\nPython provides a set of builtin codecs which are written in C\nfor speed. All of these codecs are directly usable via the\nfollowing functions.\nMany of the following APIs take two arguments encoding and\nerrors. These parameters encoding and errors have the same semantics\nas the ones of the builtin unicode() Unicode object constructor.\nSetting encoding to NULL causes the default encoding to be used\nwhich is ASCII. The file system calls should use\nPy_FileSystemDefaultEncoding as the encoding for file\nnames. This variable should be treated as read-only: On some systems,\nit will be a pointer to a static string, on others, it will change at\nrun-time, e.g. when the application invokes setlocale.\nError handling is set by errors which may also be set to NULL\nmeaning to use the default handling defined for the codec. Default\nerror handling for all builtin codecs is ``strict''\n(ValueError is raised).\nThe codecs all use a similar interface. Only deviation from the\nfollowing generic ones are documented for simplicity.\nThese are the generic codec APIs:\nThese are the UTF-8 codec APIs:\nThese are the UTF-16 codec APIs:\nThese are the ``Unicode Esacpe'' codec APIs:\nThese are the ``Raw Unicode Esacpe'' codec APIs:\nThese are the Latin-1 codec APIs:\nLatin-1 corresponds to the first 256 Unicode ordinals and only these\nare accepted by the codecs during encoding.\nThese are the ASCII codec APIs. Only 7-bit ASCII data is\naccepted. All other codes generate errors.\nThese are the mapping codec APIs:\nThis codec is special in that it can be used to implement many\ndifferent codecs (and this is in fact what was done to obtain most of\nthe standard codecs included in the encodings package). The\ncodec uses mapping to encode and decode characters.\nDecoding mappings must map single string characters to single Unicode\ncharacters, integers (which are then interpreted as Unicode ordinals)\nor None (meaning \"undefined mapping\" and causing an error).\nEncoding mappings must map single Unicode characters to single string\ncharacters, integers (which are then interpreted as Latin-1 ordinals)\nor None (meaning \"undefined mapping\" and causing an error).\nThe mapping objects provided must only support the __getitem__ mapping\ninterface.\nIf a character lookup fails with a LookupError, the character is\ncopied as-is meaning that its ordinal value will be interpreted as\nUnicode or Latin-1 ordinal resp. Because of this, mappings only need\nto contain those mappings which map characters to different code\npoints.\nThe following codec API is special in that maps Unicode to Unicode.\nThese are the MBCS codec APIs. They are currently only available on\nWindows and use the Win32 MBCS converters to implement the\nconversions. Note that MBCS (or DBCS) is a class of encodings, not\njust one. The target encoding is defined by the user settings on the\nmachine running the codec.", "python_version": "2.2", "length": 3021, "url": "https://docs.python.org/2.2/api/builtinCodecs.html"} {"title": "7.5.10 Cell Objects", "text": "cObjects.html | otherObjects.html | initialization.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.10 Cell Objects\n``Cell'' objects are used to implement variables referenced by\nmultiple scopes. For each such variable, a cell object is created to\nstore the value; the local variables of each stack frame that\nreferences the value contains a reference to the cells from outer\nscopes which also use that variable. When the value is accessed, the\nvalue contained in the cell is used instead of the cell object\nitself. This de-referencing of the cell object requires support from\nthe generated byte-code; these are not automatically de-referenced\nwhen accessed. Cell objects are not likely to be useful elsewhere.", "python_version": "2.2", "length": 741, "url": "https://docs.python.org/2.2/api/cell-objects.html"} {"title": "7.5.9 CObjects", "text": "weakref-objects.html | otherObjects.html | cell-objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.9 CObjects\nRefer to Extending and Embedding the Python Interpreter,\nsection 1.12, ``Providing a C API for an Extension Module,'' for more\ninformation on using these objects.", "python_version": "2.2", "length": 309, "url": "https://docs.python.org/2.2/api/cObjects.html"} {"title": "10.2 Common Object Structures", "text": "allocating-objects.html | newTypes.html | mapping-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.2 Common Object Structures\nPyObject, PyVarObject\nPyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD\nTypedefs:\nunaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,\nintintargfunc, intobjargproc, intintobjargproc, objobjargproc,\ndestructor, printfunc, getattrfunc, getattrofunc, setattrfunc,\nsetattrofunc, cmpfunc, reprfunc, hashfunc\nThe ml_meth is a C function pointer. The functions may be of\ndifferent types, but they always return PyObject*. If the\nfunction is not of the PyCFunction, the compiler will require\na cast in the method table. Even though PyCFunction defines\nthe first parameter as PyObject*, it is common that the method\nimplementation uses a the specific C type of the self object.\nThe flags can have the following values. Only METH_VARARGS\nand METH_KEYWORDS can be combined; the others can't.", "python_version": "2.2", "length": 960, "url": "https://docs.python.org/2.2/api/common-structs.html"} {"title": "7.2.4 Complex Number Objects", "text": "floatObjects.html | numericObjects.html | node37.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.4 Complex Number Objects\nPython's complex number objects are implemented as two distinct types\nwhen viewed from the C API: one is the Python object exposed to\nPython programs, and the other is a C structure which represents the\nactual complex number value. The API provides functions for working\nwith both.", "python_version": "2.2", "length": 435, "url": "https://docs.python.org/2.2/api/complexObjects.html"} {"title": "7. Concrete Objects Layer", "text": "iterator.html | api.html | fundamental.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7. Concrete Objects Layer\nThe functions in this chapter are specific to certain Python object\ntypes. Passing them an object of the wrong type is not a good idea;\nif you receive an object from a Python program and you are not sure\nthat it has the right type, you must perform a type check first;\nfor example, to check that an object is a dictionary, use\nPyDict_Check(). The chapter is structured like the\n``family tree'' of Python object types.\nWarning:\nWhile the functions described in this chapter carefully check\nthe type of the objects which are passed in, many of them do not check\nfor NULL being passed instead of a valid object. Allowing NULL\nto be passed in can cause memory access violations and immediate\ntermination of the interpreter.", "python_version": "2.2", "length": 859, "url": "https://docs.python.org/2.2/api/concrete.html"} {"title": "Contents", "text": "front.html | api.html | intro.html | Python/C API Reference Manual | genindex.html\n---\n## Contents\nTable of Contents\n- Front Matter (front.html)\n 1. Introduction (intro.html)\n - 1.1 Include Files (includes.html)\n 1.2 Objects, Types and Reference Counts (objects.html)\n - 1.2.1 Reference Counts (refcounts.html)\n 1.2.2 Types (types.html)\n 1.3 Exceptions (exceptions.html)\n 1.4 Embedding Python (embedding.html)\n 2. The Very High Level Layer (veryhigh.html)\n 3. Reference Counting (countingRefs.html)\n 4. Exception Handling (exceptionHandling.html)\n - 4.1 Standard Exceptions (standardExceptions.html)\n 4.2 Deprecation of String Exceptions (node15.html)\n 5. Utilities (utilities.html)\n - 5.1 Operating System Utilities (os.html)\n 5.2 Process Control (processControl.html)\n 5.3 Importing Modules (importing.html)\n 5.4 Data marshalling support (marshalling-utils.html)\n 5.5 Parsing arguments and building values (arg-parsing.html)\n 6. Abstract Objects Layer (abstract.html)\n - 6.1 Object Protocol (object.html)\n 6.2 Number Protocol (number.html)\n 6.3 Sequence Protocol (sequence.html)\n 6.4 Mapping Protocol (mapping.html)\n 6.5 Iterator Protocol (iterator.html)\n 7. Concrete Objects Layer (concrete.html)\n - 7.1 Fundamental Objects (fundamental.html)\n - 7.1.1 Type Objects (typeObjects.html)\n 7.1.2 The None Object (noneObject.html)\n 7.2 Numeric Objects (numericObjects.html)\n - 7.2.1 Plain Integer Objects (intObjects.html)\n 7.2.2 Long Integer Objects (longObjects.html)\n 7.2.3 Floating Point Objects (floatObjects.html)\n 7.2.4 Complex Number Objects (complexObjects.html)\n 7.3 Sequence Objects (sequenceObjects.html)\n - 7.3.1 String Objects (stringObjects.html)\n 7.3.2 Unicode Objects (unicodeObjects.html)\n 7.3.3 Buffer Objects (bufferObjects.html)\n 7.3.4 Tuple Objects (tupleObjects.html)\n 7.3.5 List Objects (listObjects.html)\n 7.4 Mapping Objects (mapObjects.html)\n - 7.4.1 Dictionary Objects (dictObjects.html)\n 7.5 Other Objects (otherObjects.html)\n - 7.5.1 File Objects (fileObjects.html)\n 7.5.2 Instance Objects (instanceObjects.html)\n 7.5.3 Method Objects (method-objects.html)\n 7.5.4 Module Objects (moduleObjects.html)\n 7.5.5 Iterator Objects (iterator-objects.html)\n 7.5.6 Descriptor Objects (descriptor-objects.html)\n 7.5.7 Slice Objects (slice-objects.html)\n 7.5.8 Weak Reference Objects (weakref-objects.html)\n 7.5.9 CObjects (cObjects.html)\n 7.5.10 Cell Objects (cell-objects.html)\n 8. Initialization, Finalization, and Threads (initialization.html)\n - 8.1 Thread State and the Global Interpreter Lock (threads.html)\n 8.2 Profiling and Tracing (profiling.html)\n 8.3 Advanced Debugger Support (advanced-debugging.html)\n 9. Memory Management (memory.html)\n - 9.1 Overview (memoryOverview.html)\n 9.2 Memory Interface (memoryInterface.html)\n 9.3 Examples (memoryExamples.html)\n 10. Defining New Object Types (newTypes.html)\n - 10.1 Allocating Objects on the Heap (allocating-objects.html)\n 10.2 Common Object Structures (common-structs.html)\n 10.3 Mapping Object Structures (mapping-structs.html)\n 10.4 Number Object Structures (number-structs.html)\n 10.5 Sequence Object Structures (sequence-structs.html)\n 10.6 Buffer Object Structures (buffer-structs.html)\n 10.7 Supporting the Iterator Protocol (supporting-iteration.html)\n 10.8 Supporting Cyclic Garbarge Collection (supporting-cycle-detection.html)\n - 10.8.1 Example Cycle Collector Support (example-cycle-support.html)\n A. Reporting Bugs (reporting-bugs.html)\n B. History and License (node79.html)\n - B.1 History of the software (node80.html)\n B.2 Terms and conditions for accessing or otherwise using Python (node81.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.2", "length": 3726, "url": "https://docs.python.org/2.2/api/contents.html"} {"title": "3. Reference Counting", "text": "veryhigh.html | api.html | exceptionHandling.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 3. Reference Counting\nThe macros in this section are used for managing reference counts\nof Python objects.", "python_version": "2.2", "length": 226, "url": "https://docs.python.org/2.2/api/countingRefs.html"} {"title": "7.5.6 Descriptor Objects", "text": "iterator-objects.html | otherObjects.html | slice-objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.6 Descriptor Objects\n``Descriptors'' are objects that describe some attribute of an object.\nThey are found in the dictionary of type objects.", "python_version": "2.2", "length": 279, "url": "https://docs.python.org/2.2/api/descriptor-objects.html"} {"title": "7.4.1 Dictionary Objects", "text": "mapObjects.html | mapObjects.html | otherObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.4.1 Dictionary Objects", "python_version": "2.2", "length": 149, "url": "https://docs.python.org/2.2/api/dictObjects.html"} {"title": "1.4 Embedding Python", "text": "exceptions.html | intro.html | veryhigh.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.4 Embedding Python\nThe one important task that only embedders (as opposed to extension\nwriters) of the Python interpreter have to worry about is the\ninitialization, and possibly the finalization, of the Python\ninterpreter. Most functionality of the interpreter can only be used\nafter the interpreter has been initialized.\nThe basic initialization function is\nPy_Initialize()\nThis initializes the table of loaded modules, and creates the\nfundamental modules __builtin__\n__main__ sys\nand exceptions. It also initializes\nthe module search path (`sys.path`).\nPy_Initialize() does not set the ``script argument list''\n(`sys.argv`). If this variable is needed by Python code that\nwill be executed later, it must be set explicitly with a call to\n`PySys_SetArgv( argc , argv )`subsequent to the call to\nPy_Initialize().\nOn most systems (in particular, on Unix and Windows, although the\ndetails are slightly different),\nPy_Initialize() calculates the module search path based\nupon its best guess for the location of the standard Python\ninterpreter executable, assuming that the Python library is found in a\nfixed location relative to the Python interpreter executable. In\nparticular, it looks for a directory named\nlib/python2.2 relative to the parent directory where\nthe executable named python is found on the shell command\nsearch path (the environment variable PATH).\nFor instance, if the Python executable is found in\n/usr/local/bin/python, it will assume that the libraries are in\n/usr/local/lib/python2.2. (In fact, this particular path\nis also the ``fallback'' location, used when no executable file named\npython is found along PATH.) The user can override\nthis behavior by setting the environment variable PYTHONHOME,\nor insert additional directories in front of the standard path by\nsetting PYTHONPATH.\nThe embedding application can steer the search by calling\n`Py_SetProgramName( file )`before calling\nPy_Initialize(). Note that PYTHONHOME still\noverrides this and PYTHONPATH is still inserted in front of\nthe standard path. An application that requires total control has to\nprovide its own implementation of\nPy_GetPath()\nPy_GetPrefix()\nPy_GetExecPrefix() and\nPy_GetProgramFullPath()(all\ndefined in Modules/getpath.c).", "python_version": "2.2", "length": 2336, "url": "https://docs.python.org/2.2/api/embedding.html"} {"title": "10.8.1 Example Cycle Collector Support", "text": "supporting-cycle-detection.html | supporting-cycle-detection.html | reporting-bugs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 10.8.1 Example Cycle Collector Support\nThis example shows only enough of the implementation of an extension\ntype to show how the garbage collector support needs to be added. It\nshows the definition of the object structure, the\ntp_traverse, tp_clear and tp_dealloc\nimplementations, the type structure, and a constructor -- the module\ninitialization needed to export the constructor to Python is not shown\nas there are no special considerations there for the collector. To\nmake this interesting, assume that the module exposes ways for the\ncontainer field of the object to be modified. Note that\nsince no checks are made on the type of the object used to initialize\ncontainer, we have to assume that it may be a container.\n```text\n\n#include \"Python.h\"\n\ntypedef struct {\nPyObject_HEAD\nPyObject *container;\n} MyObject;\n\nstatic int\nmy_traverse(MyObject *self, visitproc visit, void *arg)\n{\nif (self->container != NULL)\nreturn visit(self->container, arg);\nelse\nreturn 0;\n}\n\nstatic int\nmy_clear(MyObject *self)\n{\nPy_XDECREF(self->container);\nself->container = NULL;\n\nreturn 0;\n}\n\nstatic void\nmy_dealloc(MyObject *self)\n{\nPyObject_GC_UnTrack((PyObject *) self);\nPy_XDECREF(self->container);\nPyObject_GC_Del(self);\n}\n```\n```text\n\nstatichere PyTypeObject\nMyObject_Type = {\nPyObject_HEAD_INIT(NULL)\n0,\n\"MyObject\",\nsizeof(MyObject),\n0,\n(destructor)my_dealloc, /* tp_dealloc */\n0, /* tp_print */\n0, /* tp_getattr */\n0, /* tp_setattr */\n0, /* tp_compare */\n0, /* tp_repr */\n0, /* tp_as_number */\n0, /* tp_as_sequence */\n0, /* tp_as_mapping */\n0, /* tp_hash */\n0, /* tp_call */\n0, /* tp_str */\n0, /* tp_getattro */\n0, /* tp_setattro */\n0, /* tp_as_buffer */\nPy_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,\n0, /* tp_doc */\n(traverseproc)my_traverse, /* tp_traverse */\n(inquiry)my_clear, /* tp_clear */\n0, /* tp_richcompare */\n0, /* tp_weaklistoffset */\n};\n\n/* This constructor should be made accessible from Python. */\nstatic PyObject *\nnew_object(PyObject *unused, PyObject *args)\n{\nPyObject *container = NULL;\nMyObject *result = NULL;\n\nif (PyArg_ParseTuple(args, \"|O:new_object\", &container)) {\nresult = PyObject_GC_New(MyObject, &MyObject_Type);\nif (result != NULL) {\nresult->container = container;\nPyObject_GC_Track(result);\n}\n}\nreturn (PyObject *) result;\n}\n```", "python_version": "2.2", "length": 2402, "url": "https://docs.python.org/2.2/api/example-cycle-support.html"} {"title": "4. Exception Handling", "text": "countingRefs.html | api.html | standardExceptions.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 4. Exception Handling\nThe functions described in this chapter will let you handle and raise Python\nexceptions. It is important to understand some of the basics of\nPython exception handling. It works somewhat like the\nUnix errno variable: there is a global indicator (per\nthread) of the last error that occurred. Most functions don't clear\nthis on success, but will set it to indicate the cause of the error on\nfailure. Most functions also return an error indicator, usually\nNULL if they are supposed to return a pointer, or `-1` if they\nreturn an integer (exception: the PyArg_*() functions\nreturn `1` for success and `0` for failure).\nWhen a function must fail because some function it called failed, it\ngenerally doesn't set the error indicator; the function it called\nalready set it. It is responsible for either handling the error and\nclearing the exception or returning after cleaning up any resources it\nholds (such as object references or memory allocations); it should\nnot continue normally if it is not prepared to handle the\nerror. If returning due to an error, it is important to indicate to\nthe caller that an error has been set. If the error is not handled or\ncarefully propogated, additional calls into the Python/C API may not\nbehave as intended and may fail in mysterious ways.\nThe error indicator consists of three Python objects corresponding to\nthe Python variables `sys.exc_type`, `sys.exc_value` and\n`sys.exc_traceback`. API functions exist to interact with the\nerror indicator in various ways. There is a separate error indicator\nfor each thread.", "python_version": "2.2", "length": 1693, "url": "https://docs.python.org/2.2/api/exceptionHandling.html"} {"title": "1.3 Exceptions", "text": "types.html | intro.html | embedding.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.3 Exceptions\nThe Python programmer only needs to deal with exceptions if specific\nerror handling is required; unhandled exceptions are automatically\npropagated to the caller, then to the caller's caller, and so on, until\nthey reach the top-level interpreter, where they are reported to the\nuser accompanied by a stack traceback.\nFor C programmers, however, error checking always has to be explicit.\nAll functions in the Python/C API can raise exceptions, unless an\nexplicit claim is made otherwise in a function's documentation. In\ngeneral, when a function encounters an error, it sets an exception,\ndiscards any object references that it owns, and returns an\nerror indicator -- usually NULL or `-1`. A few functions\nreturn a Boolean true/false result, with false indicating an error.\nVery few functions return no explicit error indicator or have an\nambiguous return value, and require explicit testing for errors with\nPyErr_Occurred()\nException state is maintained in per-thread storage (this is\nequivalent to using global storage in an unthreaded application). A\nthread can be in one of two states: an exception has occurred, or not.\nThe function PyErr_Occurred() can be used to check for\nthis: it returns a borrowed reference to the exception type object\nwhen an exception has occurred, and NULL otherwise. There are a\nnumber of functions to set the exception state:\nPyErr_SetString()is the most\ncommon (though not the most general) function to set the exception\nstate, and PyErr_Clear()clears the\nexception state.\nThe full exception state consists of three objects (all of which can\nbe NULL): the exception type, the corresponding exception\nvalue, and the traceback. These have the same meanings as the Python\nobjects `sys.exc_type`, `sys.exc_value`, and\n`sys.exc_traceback`; however, they are not the same: the Python\nobjects represent the last exception being handled by a Python\ntry ... except statement, while the C level\nexception state only exists while an exception is being passed on\nbetween C functions until it reaches the Python bytecode interpreter's\nmain loop, which takes care of transferring it to `sys.exc_type`\nand friends.\nNote that starting with Python 1.5, the preferred, thread-safe way to\naccess the exception state from Python code is to call the function\nsys.exc_info(), which returns the per-thread exception state\nfor Python code. Also, the semantics of both ways to access the\nexception state have changed so that a function which catches an\nexception will save and restore its thread's exception state so as to\npreserve the exception state of its caller. This prevents common bugs\nin exception handling code caused by an innocent-looking function\noverwriting the exception being handled; it also reduces the often\nunwanted lifetime extension for objects that are referenced by the\nstack frames in the traceback.\nAs a general principle, a function that calls another function to\nperform some task should check whether the called function raised an\nexception, and if so, pass the exception state on to its caller. It\nshould discard any object references that it owns, and return an\nerror indicator, but it should not set another exception --\nthat would overwrite the exception that was just raised, and lose\nimportant information about the exact cause of the error.\nA simple example of detecting exceptions and passing them on is shown\nin the sum_sequence()example\nabove. It so happens that that example doesn't need to clean up any\nowned references when it detects an error. The following example\nfunction shows some error cleanup. First, to remind you why you like\nPython, we show the equivalent Python code:\n```text\n\ndef incr_item(dict, key):\ntry:\nitem = dict[key]\nexcept KeyError:\nitem = 0\ndict[key] = item + 1\n```\nHere is the corresponding C code, in all its glory:\n```text\n\nint\nincr_item(PyObject *dict, PyObject *key)\n{\n/* Objects all initialized to NULL for Py_XDECREF */\nPyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;\nint rv = -1; /* Return value initialized to -1 (failure) */\n\nitem = PyObject_GetItem(dict, key);\nif (item == NULL) {\n/* Handle KeyError only: */\nif (!PyErr_ExceptionMatches(PyExc_KeyError))\ngoto error;\n\n/* Clear the error and use zero: */\nPyErr_Clear();\nitem = PyInt_FromLong(0L);\nif (item == NULL)\ngoto error;\n}\nconst_one = PyInt_FromLong(1L);\nif (const_one == NULL)\ngoto error;\n\nincremented_item = PyNumber_Add(item, const_one);\nif (incremented_item == NULL)\ngoto error;\n\nif (PyObject_SetItem(dict, key, incremented_item) < 0)\ngoto error;\nrv = 0; /* Success */\n/* Continue with cleanup code */\n\nerror:\n/* Cleanup code, shared by success and failure path */\n\n/* Use Py_XDECREF() to ignore NULL references */\nPy_XDECREF(item);\nPy_XDECREF(const_one);\nPy_XDECREF(incremented_item);\n\nreturn rv; /* -1 for error, 0 for success */\n}\n```\nThis example represents an endorsed use of the goto statement\nin C! It illustrates the use of\nPyErr_ExceptionMatches()and\nPyErr_Clear()to\nhandle specific exceptions, and the use of\nPy_XDECREF()to\ndispose of owned references that may be NULL (note the\n\"X\" in the name; Py_DECREF() would crash when\nconfronted with a NULL reference). It is important that the\nvariables used to hold owned references are initialized to NULL for\nthis to work; likewise, the proposed return value is initialized to\n`-1` (failure) and only set to success after the final call made\nis successful.", "python_version": "2.2", "length": 5495, "url": "https://docs.python.org/2.2/api/exceptions.html"} {"title": "7.5.1 File Objects", "text": "otherObjects.html | otherObjects.html | instanceObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.1 File Objects\nPython's built-in file objects are implemented entirely on the\nFILE* support from the C standard library. This is an\nimplementation detail and may change in future releases of Python.", "python_version": "2.2", "length": 334, "url": "https://docs.python.org/2.2/api/fileObjects.html"} {"title": "7.2.3 Floating Point Objects", "text": "longObjects.html | numericObjects.html | complexObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.3 Floating Point Objects", "python_version": "2.2", "length": 160, "url": "https://docs.python.org/2.2/api/floatObjects.html"} {"title": "Front Matter", "text": "api.html | api.html | contents.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# Front Matter\nCopyright © 2001 Python Software Foundation.\nAll rights reserved.\nCopyright © 2000 BeOpen.com.\nAll rights reserved.\nCopyright © 1995-2000 Corporation for National Research Initiatives.\nAll rights reserved.\nCopyright © 1991-1995 Stichting Mathematisch Centrum.\nAll rights reserved.\nSee the end of this document for complete license and permissions\ninformation.\n### Abstract:\nThis manual documents the API used by C and C++ programmers who\nwant to write extension modules or embed Python. It is a companion to\nExtending and Embedding the Python\nInterpreter (../ext/ext.html), which describes the general principles of extension\nwriting but does not document the API functions in detail.\nWarning:\nThe current version of this document is incomplete. I hope\nthat it is nevertheless useful. I will continue to work on it, and\nrelease new versions from time to time, independent from Python source\ncode releases.", "python_version": "2.2", "length": 1024, "url": "https://docs.python.org/2.2/api/front.html"} {"title": "7.1 Fundamental Objects", "text": "concrete.html | concrete.html | typeObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.1 Fundamental Objects\nThis section describes Python type objects and the singleton object\n`None`.", "python_version": "2.2", "length": 218, "url": "https://docs.python.org/2.2/api/fundamental.html"} {"title": "Index", "text": "node81.html | api.html | about.html | Python/C API Reference Manual | contents.html\n---\n## Index\n---\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\nk (#letter-k) |\nl (#letter-l) |\nm (#letter-m) |\nn (#letter-n) |\no (#letter-o) |\np (#letter-p) |\nr (#letter-r) |\ns (#letter-s) |\nt (#letter-t) |\nu (#letter-u) |\nv (#letter-v)\n---\n## _ (underscore)\n---\n## A\n---\n## B\n---\n## C\n---\n## D\n---\n## E\n---\n## F\n---\n## G\n---\n## H\n---\n## I\n---\n## K\n---\n## L\n---\n## M\n---\n## N\n---\n## O\n---\n## P\n---\n## R\n---\n## S\n---\n## T\n---\n## U\n---\n## V", "python_version": "2.2", "length": 636, "url": "https://docs.python.org/2.2/api/genindex.html"} {"title": "5.3 Importing Modules", "text": "processControl.html | utilities.html | marshalling-utils.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.3 Importing Modules", "python_version": "2.2", "length": 153, "url": "https://docs.python.org/2.2/api/importing.html"} {"title": "1.1 Include Files", "text": "intro.html | intro.html | objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.1 Include Files\nAll function, type and macro definitions needed to use the Python/C\nAPI are included in your code by the following line:\n```text\n\n#include \"Python.h\"\n```\nThis implies inclusion of the following standard headers:\n``, ``, ``,\n``, and `` (if available).\nSince Python may define some pre-processor definitions which affect\nthe standard headers on some systems, you must include Python.h\nbefore any standard headers are included.\nAll user visible names defined by Python.h (except those defined by\nthe included standard headers) have one of the prefixes \"Py\" or\n\"_Py\". Names beginning with \"_Py\" are for internal use by\nthe Python implementation and should not be used by extension writers.\nStructure member names do not have a reserved prefix.\nImportant: user code should never define names that begin\nwith \"Py\" or \"_Py\". This confuses the reader, and\njeopardizes the portability of the user code to future Python\nversions, which may define additional names beginning with one of\nthese prefixes.\nThe header files are typically installed with Python. On Unix, these\nare located in the directories\nprefix/include/pythonversion/ and\nexec_prefix/include/pythonversion/, where\nprefix and exec_prefix are defined by the\ncorresponding parameters to Python's configure script and\nversion is `sys.version[:3]`. On Windows, the headers are\ninstalled in prefix/include, where prefix is\nthe installation directory specified to the installer.\nTo include the headers, place both directories (if different) on your\ncompiler's search path for includes. Do not place the parent\ndirectories on the search path and then use\n\"#include \"; this will break on\nmulti-platform builds since the platform independent headers under\nprefix include the platform specific headers from\nexec_prefix.\nC++ users should note that though the API is defined entirely using\nC, the header files do properly declare the entry points to be\n`extern \"C\"`, so there is no need to do anything special to use\nthe API from C++.", "python_version": "2.2", "length": 2170, "url": "https://docs.python.org/2.2/api/includes.html"} {"title": "Python/C API Reference Manual", "text": "../index.html | front.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 241, "url": "https://docs.python.org/2.2/api/index.html"} {"title": "8. Initialization, Finalization, and Threads", "text": "cell-objects.html | api.html | threads.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 8. Initialization, Finalization, and Threads", "python_version": "2.2", "length": 158, "url": "https://docs.python.org/2.2/api/initialization.html"} {"title": "7.5.2 Instance Objects", "text": "fileObjects.html | otherObjects.html | method-objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.2 Instance Objects\nThere are very few functions specific to instance objects.", "python_version": "2.2", "length": 211, "url": "https://docs.python.org/2.2/api/instanceObjects.html"} {"title": "7.2.1 Plain Integer Objects", "text": "numericObjects.html | numericObjects.html | longObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.1 Plain Integer Objects", "python_version": "2.2", "length": 159, "url": "https://docs.python.org/2.2/api/intObjects.html"} {"title": "1. Introduction", "text": "contents.html | api.html | includes.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1. Introduction\nThe Application Programmer's Interface to Python gives C and\nC++ programmers access to the Python interpreter at a variety of\nlevels. The API is equally usable from C++, but for brevity it is\ngenerally referred to as the Python/C API. There are two\nfundamentally different reasons for using the Python/C API. The first\nreason is to write extension modules for specific purposes;\nthese are C modules that extend the Python interpreter. This is\nprobably the most common use. The second reason is to use Python as a\ncomponent in a larger application; this technique is generally\nreferred to as embedding Python in an application.\nWriting an extension module is a relatively well-understood process,\nwhere a ``cookbook'' approach works well. There are several tools\nthat automate the process to some extent. While people have embedded\nPython in other applications since its early existence, the process of\nembedding Python is less straightforward than writing an extension.\nMany API functions are useful independent of whether you're embedding\nor extending Python; moreover, most applications that embed Python\nwill need to provide a custom extension as well, so it's probably a\ngood idea to become familiar with writing an extension before\nattempting to embed Python in a real application.", "python_version": "2.2", "length": 1413, "url": "https://docs.python.org/2.2/api/intro.html"} {"title": "7.5.5 Iterator Objects", "text": "moduleObjects.html | otherObjects.html | descriptor-objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.5 Iterator Objects\nPython provides two general-purpose iterator objects. The first, a\nsequence iterator, works with an arbitrary sequence supporting the\n__getitem__() method. The second works with a callable\nobject and a sentinel value, calling the callable for each item in the\nsequence, and ending the iteration when the sentinel value is\nreturned.", "python_version": "2.2", "length": 490, "url": "https://docs.python.org/2.2/api/iterator-objects.html"} {"title": "6.5 Iterator Protocol", "text": "mapping.html | abstract.html | concrete.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.5 Iterator Protocol\nNew in version 2.2.\nThere are only a couple of functions specifically for working with\niterators.\nTo write a loop which iterates over an iterator, the C code should\nlook something like this:", "python_version": "2.2", "length": 327, "url": "https://docs.python.org/2.2/api/iterator.html"} {"title": "7.3.5 List Objects", "text": "tupleObjects.html | sequenceObjects.html | mapObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.3.5 List Objects", "python_version": "2.2", "length": 148, "url": "https://docs.python.org/2.2/api/listObjects.html"} {"title": "7.2.2 Long Integer Objects", "text": "intObjects.html | numericObjects.html | floatObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.2 Long Integer Objects", "python_version": "2.2", "length": 155, "url": "https://docs.python.org/2.2/api/longObjects.html"} {"title": "7.4 Mapping Objects", "text": "listObjects.html | concrete.html | dictObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.4 Mapping Objects", "python_version": "2.2", "length": 141, "url": "https://docs.python.org/2.2/api/mapObjects.html"} {"title": "10.3 Mapping Object Structures", "text": "common-structs.html | newTypes.html | number-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.3 Mapping Object Structures", "python_version": "2.2", "length": 158, "url": "https://docs.python.org/2.2/api/mapping-structs.html"} {"title": "6.4 Mapping Protocol", "text": "sequence.html | abstract.html | iterator.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.4 Mapping Protocol", "python_version": "2.2", "length": 136, "url": "https://docs.python.org/2.2/api/mapping.html"} {"title": "5.4 Data marshalling support", "text": "importing.html | utilities.html | arg-parsing.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.4 Data marshalling support\nThese routines allow C code to work with serialized objects using the\nsame data format as the marshal module. There are functions\nto write data into the serialization format, and additional functions\nthat can be used to read the data back. Files used to store marshalled\ndata must be opened in binary mode.\nNumeric values are stored with the least significant byte first.\nThe following functions allow marshalled values to be read back in.\nXXX What about error detection? It appears that reading past the end\nof the file will always result in a negative numeric value (where\nthat's relevant), but it's not clear that negative values won't be\nhandled properly when there's no error. What's the right way to tell?\nShould only non-negative values be written using these routines?", "python_version": "2.2", "length": 926, "url": "https://docs.python.org/2.2/api/marshalling-utils.html"} {"title": "9. Memory Management", "text": "advanced-debugging.html | api.html | memoryOverview.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9. Memory Management", "python_version": "2.2", "length": 147, "url": "https://docs.python.org/2.2/api/memory.html"} {"title": "9.3 Examples", "text": "memoryInterface.html | memory.html | newTypes.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9.3 Examples\nHere is the example from section 9.1 (memoryOverview.html#memoryOverview), rewritten so\nthat the I/O buffer is allocated from the Python heap by using the\nfirst function set:\n```text\n\nPyObject *res;\nchar *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */\n\nif (buf == NULL)\nreturn PyErr_NoMemory();\n/* ...Do some I/O operation involving buf... */\nres = PyString_FromString(buf);\nPyMem_Free(buf); /* allocated with PyMem_Malloc */\nreturn res;\n```\nThe same code using the type-oriented function set:\n```text\n\nPyObject *res;\nchar *buf = PyMem_New(char, BUFSIZ); /* for I/O */\n\nif (buf == NULL)\nreturn PyErr_NoMemory();\n/* ...Do some I/O operation involving buf... */\nres = PyString_FromString(buf);\nPyMem_Del(buf); /* allocated with PyMem_New */\nreturn res;\n```\nNote that in the two examples above, the buffer is always\nmanipulated via functions belonging to the same set. Indeed, it\nis required to use the same memory API family for a given\nmemory block, so that the risk of mixing different allocators is\nreduced to a minimum. The following code sequence contains two errors,\none of which is labeled as fatal because it mixes two different\nallocators operating on different heaps.\n```text\n\nchar *buf1 = PyMem_New(char, BUFSIZ);\nchar *buf2 = (char *) malloc(BUFSIZ);\nchar *buf3 = (char *) PyMem_Malloc(BUFSIZ);\n...\nPyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */\nfree(buf2); /* Right -- allocated via malloc() */\nfree(buf1); /* Fatal -- should be PyMem_Del() */\n```\nIn addition to the functions aimed at handling raw memory blocks from\nthe Python heap, objects in Python are allocated and released with\nPyObject_New(), PyObject_NewVar() and\nPyObject_Del(), or with their corresponding macros\nPyObject_NEW(), PyObject_NEW_VAR() and\nPyObject_DEL().", "python_version": "2.2", "length": 1885, "url": "https://docs.python.org/2.2/api/memoryExamples.html"} {"title": "9.2 Memory Interface", "text": "memoryOverview.html | memory.html | memoryExamples.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9.2 Memory Interface\nThe following function sets, modeled after the ANSI C standard, are\navailable for allocating and releasing memory from the Python heap:\nThe following type-oriented macros are provided for convenience. Note\nthat TYPE refers to any C type.\nIn addition, the following macro sets are provided for calling the\nPython memory allocator directly, without involving the C API functions\nlisted above. However, note that their use does not preserve binary\ncompatibility accross Python versions and is therefore deprecated in\nextension modules.\nPyMem_MALLOC(), PyMem_REALLOC(), PyMem_FREE().\nPyMem_NEW(), PyMem_RESIZE(), PyMem_DEL().", "python_version": "2.2", "length": 768, "url": "https://docs.python.org/2.2/api/memoryInterface.html"} {"title": "9.1 Overview", "text": "memory.html | memory.html | memoryInterface.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9.1 Overview\nMemory management in Python involves a private heap containing all\nPython objects and data structures. The management of this private\nheap is ensured internally by the Python memory manager. The\nPython memory manager has different components which deal with various\ndynamic storage management aspects, like sharing, segmentation,\npreallocation or caching.\nAt the lowest level, a raw memory allocator ensures that there is\nenough room in the private heap for storing all Python-related data\nby interacting with the memory manager of the operating system. On top\nof the raw memory allocator, several object-specific allocators\noperate on the same heap and implement distinct memory management\npolicies adapted to the peculiarities of every object type. For\nexample, integer objects are managed differently within the heap than\nstrings, tuples or dictionaries because integers imply different\nstorage requirements and speed/space tradeoffs. The Python memory\nmanager thus delegates some of the work to the object-specific\nallocators, but ensures that the latter operate within the bounds of\nthe private heap.\nIt is important to understand that the management of the Python heap\nis performed by the interpreter itself and that the user has no\ncontrol on it, even if she regularly manipulates object pointers to\nmemory blocks inside that heap. The allocation of heap space for\nPython objects and other internal buffers is performed on demand by\nthe Python memory manager through the Python/C API functions listed in\nthis document.\nTo avoid memory corruption, extension writers should never try to\noperate on Python objects with the functions exported by the C\nlibrary: malloc(),\ncalloc(),\nrealloc()and\nfree(). This will result in\nmixed calls between the C allocator and the Python memory manager\nwith fatal consequences, because they implement different algorithms\nand operate on different heaps. However, one may safely allocate and\nrelease memory blocks with the C library allocator for individual\npurposes, as shown in the following example:\n```text\n\nPyObject *res;\nchar *buf = (char *) malloc(BUFSIZ); /* for I/O */\n\nif (buf == NULL)\nreturn PyErr_NoMemory();\n...Do some I/O operation involving buf...\nres = PyString_FromString(buf);\nfree(buf); /* malloc'ed */\nreturn res;\n```\nIn this example, the memory request for the I/O buffer is handled by\nthe C library allocator. The Python memory manager is involved only\nin the allocation of the string object returned as a result.\nIn most situations, however, it is recommended to allocate memory from\nthe Python heap specifically because the latter is under control of\nthe Python memory manager. For example, this is required when the\ninterpreter is extended with new object types written in C. Another\nreason for using the Python heap is the desire to inform the\nPython memory manager about the memory needs of the extension module.\nEven when the requested memory is used exclusively for internal,\nhighly-specific purposes, delegating all memory requests to the Python\nmemory manager causes the interpreter to have a more accurate image of\nits memory footprint as a whole. Consequently, under certain\ncircumstances, the Python memory manager may or may not trigger\nappropriate actions, like garbage collection, memory compaction or\nother preventive procedures. Note that by using the C library\nallocator as shown in the previous example, the allocated memory for\nthe I/O buffer escapes completely the Python memory manager.", "python_version": "2.2", "length": 3599, "url": "https://docs.python.org/2.2/api/memoryOverview.html"} {"title": "7.5.3 Method Objects", "text": "instanceObjects.html | otherObjects.html | moduleObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.3 Method Objects\nThere are some useful functions that are useful for working with\nmethod objects.", "python_version": "2.2", "length": 234, "url": "https://docs.python.org/2.2/api/method-objects.html"} {"title": "7.5.4 Module Objects", "text": "method-objects.html | otherObjects.html | iterator-objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.4 Module Objects\nThere are only a few functions special to module objects.", "python_version": "2.2", "length": 213, "url": "https://docs.python.org/2.2/api/moduleObjects.html"} {"title": "10. Defining New Object Types", "text": "memoryExamples.html | api.html | allocating-objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10. Defining New Object Types", "python_version": "2.2", "length": 156, "url": "https://docs.python.org/2.2/api/newTypes.html"} {"title": "4.2 Deprecation of String Exceptions", "text": "standardExceptions.html | exceptionHandling.html | utilities.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 4.2 Deprecation of String Exceptions\nAll exceptions built into Python or provided in the standard library\nare derived from Exception.", "python_version": "2.2", "length": 269, "url": "https://docs.python.org/2.2/api/node15.html"} {"title": "7.2.4.1 Complex Numbers as C Structures", "text": "complexObjects.html | complexObjects.html | node38.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.2.4.1 Complex Numbers as C Structures\nNote that the functions which accept these structures as parameters\nand return them as results do so by value rather than\ndereferencing them through pointers. This is consistent throughout\nthe API.", "python_version": "2.2", "length": 365, "url": "https://docs.python.org/2.2/api/node37.html"} {"title": "7.2.4.2 Complex Numbers as Python Objects", "text": "node37.html | complexObjects.html | sequenceObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.2.4.2 Complex Numbers as Python Objects", "python_version": "2.2", "length": 170, "url": "https://docs.python.org/2.2/api/node38.html"} {"title": "7.4.4.1 Complex Numbers as C Structures", "text": "complexObjects.html | complexObjects.html | node45.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.4.4.1 Complex Numbers as C Structures\nNote that the functions which accept these structures as parameters\nand return them as results do so by value rather than\ndereferencing them through pointers. This is consistent throughout\nthe API.", "python_version": "2.2", "length": 365, "url": "https://docs.python.org/2.2/api/node44.html"} {"title": "7.4.4.2 Complex Numbers as Python Objects", "text": "node44.html | complexObjects.html | otherObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.4.4.2 Complex Numbers as Python Objects", "python_version": "2.2", "length": 167, "url": "https://docs.python.org/2.2/api/node45.html"} {"title": "B. History and License", "text": "reporting-bugs.html | api.html | node80.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# B. History and License", "python_version": "2.2", "length": 137, "url": "https://docs.python.org/2.2/api/node79.html"} {"title": "B.1 History of the software", "text": "node79.html | node79.html | node81.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# B.1 History of the software\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands\nas a successor of a language called ABC. Guido remains Python's\nprincipal author, although it includes many contributions from others.\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)\nin Reston, Virginia where he released several versions of the\nsoftware.\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team. In October of the same\nyear, the PythonLabs team moved to Zope Corporation (then Digital\nCreations; see http://www.zope.com/). In 2001, the Python\nSoftware Foundation (PSF, see http://www.python.org/psf/) was\nformed, a non-profit organization created specifically to own\nPython-related Intellectual Property. Digital Creations is a\nsponsoring member of the PSF.\nAll Python releases are Open Source (see\nhttp://www.opensource.org/ for the Open Source Definition).\nHistorically, most, but not all, Python releases have also been\nGPL-compatible; the table below summarizes the various releases.\nNote:\nGPL-compatible doesn't mean that we're distributing\nPython under the GPL. All Python licenses, unlike the GPL, let you\ndistribute a modified version without making your changes open source.\nThe GPL-compatible licenses make it possible to combine Python with\nother software that is released under the GPL; the others don't.\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.", "python_version": "2.2", "length": 1768, "url": "https://docs.python.org/2.2/api/node80.html"} {"title": "B.2 Terms and conditions for accessing or otherwise using Python", "text": "node80.html | node79.html | genindex.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# B.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.2\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.2 software in source or binary\nform and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, PSF\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python\n2.2 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001 Python Software Foundation; All Rights\nReserved'' are retained in Python 2.2 alone or in any\nderivative version prepared by Licensee.\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 2.2 or any part thereof, and wants to\nmake the derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 2.2.\n4. PSF is making Python 2.2 available to Licensee on an ``AS IS''\nbasis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE\nPOSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee. This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n8. By copying, installing or otherwise using Python 2.2, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (``Licensee'') accessing and otherwise\nusing this software in source or binary form and its associated\ndocumentation (``the Software'').\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n3. BeOpen is making the Software available to Licensee on an ``AS IS''\nbasis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions. Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee. This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party. As an exception, the ``BeOpen Python'' logos available\nat http://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (``CNRI''), and the Individual or Organization\n(``Licensee'') accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., ``Copyright\n© 1995-2001 Corporation for National Research Initiatives;\nAll Rights Reserved'' are retained in Python 1.6.1 alone or in any\nderivative version prepared by Licensee. Alternately, in lieu of\nCNRI's License Agreement, Licensee may substitute the following text\n(omitting the quotes): ``Python 1.6.1 is made available subject to the\nterms and conditions in CNRI's License Agreement. This Agreement\ntogether with Python 1.6.1 may be located on the Internet using the\nfollowing unique, persistent identifier (known as a handle):\n1895.22/1013. This Agreement may also be obtained from a proxy server\non the Internet using the following URL:\nhttp://hdl.handle.net/1895.22/1013.''\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''\nbasis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement. Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee. This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n8. By clicking on the ``ACCEPT'' button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\nACCEPT\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\nCopyright © 1991 - 1995, Stichting Mathematisch Centrum\nAmsterdam, The Netherlands. All rights reserved.\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", "python_version": "2.2", "length": 9775, "url": "https://docs.python.org/2.2/api/node81.html"} {"title": "7.1.2 The None Object", "text": "typeObjects.html | fundamental.html | numericObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.1.2 The None Object\nNote that the PyTypeObject for `None` is not directly\nexposed in the Python/C API. Since `None` is a singleton,\ntesting for object identity (using \"==\" in C) is sufficient.\nThere is no PyNone_Check() function for the same reason.", "python_version": "2.2", "length": 380, "url": "https://docs.python.org/2.2/api/noneObject.html"} {"title": "10.4 Number Object Structures", "text": "mapping-structs.html | newTypes.html | sequence-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.4 Number Object Structures", "python_version": "2.2", "length": 160, "url": "https://docs.python.org/2.2/api/number-structs.html"} {"title": "6.2 Number Protocol", "text": "object.html | abstract.html | sequence.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.2 Number Protocol", "python_version": "2.2", "length": 133, "url": "https://docs.python.org/2.2/api/number.html"} {"title": "7.2 Numeric Objects", "text": "noneObject.html | concrete.html | intObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.2 Numeric Objects", "python_version": "2.2", "length": 139, "url": "https://docs.python.org/2.2/api/numericObjects.html"} {"title": "6.1 Object Protocol", "text": "abstract.html | abstract.html | number.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.1 Object Protocol\nSubclass determination is done in a fairly straightforward way, but\nincludes a wrinkle that implementors of extensions to the class system\nmay want to be aware of. If A and B are class\nobjects, B is a subclass of A if it inherits from\nA either directly or indirectly. If either is not a class\nobject, a more general mechanism is used to determine the class\nrelationship of the two objects. When testing if B is a\nsubclass of A, if A is B,\nPyObject_IsSubclass() returns true. If A and\nB are different objects, B's __bases__ attribute\nis searched in a depth-first fashion for A -- the presence of\nthe __bases__ attribute is considered sufficient for this\ndetermination.", "python_version": "2.2", "length": 801, "url": "https://docs.python.org/2.2/api/object.html"} {"title": "1.2 Objects, Types and Reference Counts", "text": "includes.html | intro.html | refcounts.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.2 Objects, Types and Reference Counts\nMost Python/C API functions have one or more arguments as well as a\nreturn value of type PyObject*. This type is a pointer\nto an opaque data type representing an arbitrary Python\nobject. Since all Python object types are treated the same way by the\nPython language in most situations (e.g., assignments, scope rules,\nand argument passing), it is only fitting that they should be\nrepresented by a single C type. Almost all Python objects live on the\nheap: you never declare an automatic or static variable of type\nPyObject, only pointer variables of type PyObject* can\nbe declared. The sole exception are the type objects\nsince these must never be deallocated, they are typically static\nPyTypeObject objects.\nAll Python objects (even Python integers) have a type and a\nreference count. An object's type determines what kind of object\nit is (e.g., an integer, a list, or a user-defined function; there are\nmany more as explained in the Python\nReference Manual (../ref/ref.html)). For each of the well-known types there is a macro\nto check whether an object is of that type; for instance,\n\"PyList_Check(a)\" is true if (and only if) the object\npointed to by a is a Python list.", "python_version": "2.2", "length": 1327, "url": "https://docs.python.org/2.2/api/objects.html"} {"title": "5.1 Operating System Utilities", "text": "utilities.html | utilities.html | processControl.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.1 Operating System Utilities", "python_version": "2.2", "length": 154, "url": "https://docs.python.org/2.2/api/os.html"} {"title": "7.5 Other Objects", "text": "dictObjects.html | concrete.html | fileObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.5 Other Objects", "python_version": "2.2", "length": 139, "url": "https://docs.python.org/2.2/api/otherObjects.html"} {"title": "5.2 Process Control", "text": "os.html | utilities.html | importing.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.2 Process Control", "python_version": "2.2", "length": 131, "url": "https://docs.python.org/2.2/api/processControl.html"} {"title": "8.2 Profiling and Tracing", "text": "threads.html | initialization.html | advanced-debugging.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 8.2 Profiling and Tracing\nThe Python interpreter provides some low-level support for attaching\nprofiling and execution tracing facilities. These are used for\nprofiling, debugging, and coverage analysis tools.\nStarting with Python 2.2, the implementation of this facility was\nsubstantially revised, and an interface from C was added. This C\ninterface allows the profiling or tracing code to avoid the overhead\nof calling through Python-level callable objects, making a direct C\nfunction call instead. The essential attributes of the facility have\nnot changed; the interface allows trace functions to be installed\nper-thread, and the basic events reported to the trace function are\nthe same as had been reported to the Python-level trace functions in\nprevious versions.", "python_version": "2.2", "length": 898, "url": "https://docs.python.org/2.2/api/profiling.html"} {"title": "1.2.1.1 Reference Count Details", "text": "refcounts.html | refcounts.html | types.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 1.2.1.1 Reference Count Details\nThe reference count behavior of functions in the Python/C API is best\nexplained in terms of ownership of references. Note that we\ntalk of owning references, never of owning objects; objects are always\nshared! When a function owns a reference, it has to dispose of it\nproperly -- either by passing ownership on (usually to its caller) or\nby calling Py_DECREF() or Py_XDECREF(). When\na function passes ownership of a reference on to its caller, the\ncaller is said to receive a new reference. When no ownership\nis transferred, the caller is said to borrow the reference.\nNothing needs to be done for a borrowed reference.\nConversely, when a calling function passes it a reference to an\nobject, there are two possibilities: the function steals a\nreference to the object, or it does not. Few functions steal\nreferences; the two notable exceptions are\nPyList_SetItem()and\nPyTuple_SetItem() which\nsteal a reference to the item (but not to the tuple or list into which\nthe item is put!). These functions were designed to steal a reference\nbecause of a common idiom for populating a tuple or list with newly\ncreated objects; for example, the code to create the tuple `(1,\n2, \"three\")` could look like this (forgetting about error handling for\nthe moment; a better way to code this is shown below):\n```text\n\nPyObject *t;\n\nt = PyTuple_New(3);\nPyTuple_SetItem(t, 0, PyInt_FromLong(1L));\nPyTuple_SetItem(t, 1, PyInt_FromLong(2L));\nPyTuple_SetItem(t, 2, PyString_FromString(\"three\"));\n```\nIncidentally, PyTuple_SetItem() is the only way to\nset tuple items; PySequence_SetItem() and\nPyObject_SetItem() refuse to do this since tuples are an\nimmutable data type. You should only use\nPyTuple_SetItem() for tuples that you are creating\nyourself.\nEquivalent code for populating a list can be written using\nPyList_New() and PyList_SetItem(). Such code\ncan also use PySequence_SetItem(); this illustrates the\ndifference between the two (the extra Py_DECREF() calls):\n```text\n\nPyObject *l, *x;\n\nl = PyList_New(3);\nx = PyInt_FromLong(1L);\nPySequence_SetItem(l, 0, x); Py_DECREF(x);\nx = PyInt_FromLong(2L);\nPySequence_SetItem(l, 1, x); Py_DECREF(x);\nx = PyString_FromString(\"three\");\nPySequence_SetItem(l, 2, x); Py_DECREF(x);\n```\nYou might find it strange that the ``recommended'' approach takes more\ncode. However, in practice, you will rarely use these ways of\ncreating and populating a tuple or list. There's a generic function,\nPy_BuildValue(), that can create most common objects from\nC values, directed by a format string. For example, the\nabove two blocks of code could be replaced by the following (which\nalso takes care of the error checking):\n```text\n\nPyObject *t, *l;\n\nt = Py_BuildValue(\"(iis)\", 1, 2, \"three\");\nl = Py_BuildValue(\"[iis]\", 1, 2, \"three\");\n```\nIt is much more common to use PyObject_SetItem() and\nfriends with items whose references you are only borrowing, like\narguments that were passed in to the function you are writing. In\nthat case, their behaviour regarding reference counts is much saner,\nsince you don't have to increment a reference count so you can give a\nreference away (``have it be stolen''). For example, this function\nsets all items of a list (actually, any mutable sequence) to a given\nitem:\n```text\n\nint\nset_all(PyObject *target, PyObject *item)\n{\nint i, n;\n\nn = PyObject_Length(target);\nif (n < 0)\nreturn -1;\nfor (i = 0; i < n; i++) {\nif (PyObject_SetItem(target, i, item) < 0)\nreturn -1;\n}\nreturn 0;\n}\n```\nThe situation is slightly different for function return values.\nWhile passing a reference to most functions does not change your\nownership responsibilities for that reference, many functions that\nreturn a referece to an object give you ownership of the reference.\nThe reason is simple: in many cases, the returned object is created\non the fly, and the reference you get is the only reference to the\nobject. Therefore, the generic functions that return object\nreferences, like PyObject_GetItem() and\nPySequence_GetItem(), always return a new reference (the\ncaller becomes the owner of the reference).\nIt is important to realize that whether you own a reference returned\nby a function depends on which function you call only -- the\nplumage (the type of the type of the object passed as an\nargument to the function) doesn't enter into it! Thus, if you\nextract an item from a list using PyList_GetItem(), you\ndon't own the reference -- but if you obtain the same item from the\nsame list using PySequence_GetItem() (which happens to\ntake exactly the same arguments), you do own a reference to the\nreturned object.\nHere is an example of how you could write a function that computes the\nsum of the items in a list of integers; once using\nPyList_GetItem() and once using\nPySequence_GetItem()\n```text\n\nlong\nsum_list(PyObject *list)\n{\nint i, n;\nlong total = 0;\nPyObject *item;\n\nn = PyList_Size(list);\nif (n < 0)\nreturn -1; /* Not a list */\nfor (i = 0; i < n; i++) {\nitem = PyList_GetItem(list, i); /* Can't fail */\nif (!PyInt_Check(item)) continue; /* Skip non-integers */\ntotal += PyInt_AsLong(item);\n}\nreturn total;\n}\n```\n```text\n\nlong\nsum_sequence(PyObject *sequence)\n{\nint i, n;\nlong total = 0;\nPyObject *item;\nn = PySequence_Length(sequence);\nif (n < 0)\nreturn -1; /* Has no length */\nfor (i = 0; i < n; i++) {\nitem = PySequence_GetItem(sequence, i);\nif (item == NULL)\nreturn -1; /* Not a sequence, or other failure */\nif (PyInt_Check(item))\ntotal += PyInt_AsLong(item);\nPy_DECREF(item); /* Discard reference ownership */\n}\nreturn total;\n}\n```", "python_version": "2.2", "length": 5615, "url": "https://docs.python.org/2.2/api/refcountDetails.html"} {"title": "1.2.1 Reference Counts", "text": "objects.html | objects.html | refcountDetails.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 1.2.1 Reference Counts\nThe reference count is important because today's computers have a\nfinite (and often severely limited) memory size; it counts how many\ndifferent places there are that have a reference to an object. Such a\nplace could be another object, or a global (or static) C variable, or\na local variable in some C function. When an object's reference count\nbecomes zero, the object is deallocated. If it contains references to\nother objects, their reference count is decremented. Those other\nobjects may be deallocated in turn, if this decrement makes their\nreference count become zero, and so on. (There's an obvious problem\nwith objects that reference each other here; for now, the solution is\n``don't do that.'')\nReference counts are always manipulated explicitly. The normal way is\nto use the macro Py_INCREF()to\nincrement an object's reference count by one, and\nPy_DECREF()to decrement it by\none. The Py_DECREF() macro is considerably more complex\nthan the incref one, since it must check whether the reference count\nbecomes zero and then cause the object's deallocator to be called.\nThe deallocator is a function pointer contained in the object's type\nstructure. The type-specific deallocator takes care of decrementing\nthe reference counts for other objects contained in the object if this\nis a compound object type, such as a list, as well as performing any\nadditional finalization that's needed. There's no chance that the\nreference count can overflow; at least as many bits are used to hold\nthe reference count as there are distinct memory locations in virtual\nmemory (assuming `sizeof(long) >= sizeof(char*)`). Thus, the\nreference count increment is a simple operation.\nIt is not necessary to increment an object's reference count for every\nlocal variable that contains a pointer to an object. In theory, the\nobject's reference count goes up by one when the variable is made to\npoint to it and it goes down by one when the variable goes out of\nscope. However, these two cancel each other out, so at the end the\nreference count hasn't changed. The only real reason to use the\nreference count is to prevent the object from being deallocated as\nlong as our variable is pointing to it. If we know that there is at\nleast one other reference to the object that lives at least as long as\nour variable, there is no need to increment the reference count\ntemporarily. An important situation where this arises is in objects\nthat are passed as arguments to C functions in an extension module\nthat are called from Python; the call mechanism guarantees to hold a\nreference to every argument for the duration of the call.\nHowever, a common pitfall is to extract an object from a list and\nhold on to it for a while without incrementing its reference count.\nSome other operation might conceivably remove the object from the\nlist, decrementing its reference count and possible deallocating it.\nThe real danger is that innocent-looking operations may invoke\narbitrary Python code which could do this; there is a code path which\nallows control to flow back to the user from a Py_DECREF(),\nso almost any operation is potentially dangerous.\nA safe approach is to always use the generic operations (functions\nwhose name begins with \"PyObject_\", \"PyNumber_\",\n\"PySequence_\" or \"PyMapping_\"). These operations always\nincrement the reference count of the object they return. This leaves\nthe caller with the responsibility to call\nPy_DECREF() when they are done with the result; this soon\nbecomes second nature.", "python_version": "2.2", "length": 3626, "url": "https://docs.python.org/2.2/api/refcounts.html"} {"title": "A. Reporting Bugs", "text": "example-cycle-support.html | api.html | node79.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# A. Reporting Bugs\nPython is a mature programming language which has established a\nreputation for stability. In order to maintain this reputation, the\ndevelopers would like to know of any deficiencies you find in Python\nor its documentation.\nAll bug reports should be submitted via the Python Bug Tracker on\nSourceForge (http://sourceforge.net/bugs/?group_id=5470). The\nbug tracker offers a Web form which allows pertinent information to be\nentered and submitted to the developers.\nBefore submitting a report, please log into SourceForge if you are a\nmember; this will make it possible for the developers to contact you\nfor additional information if needed. If you are not a SourceForge\nmember but would not mind the developers contacting you, you may\ninclude your email address in your bug description. In this case,\nplease realize that the information is publically available and cannot\nbe protected.\nThe first step in filing a report is to determine whether the problem\nhas already been reported. The advantage in doing so, aside from\nsaving the developers time, is that you learn what has been done to\nfix it; it may be that the problem has already been fixed for the next\nrelease, or additional information is needed (in which case you are\nwelcome to provide it if you can!). To do this, search the bug\ndatabase using the search box near the bottom of the page.\nIf the problem you're reporting is not already in the bug tracker, go\nback to the Python Bug Tracker\n(http://sourceforge.net/bugs/?group_id=5470). Select the\n``Submit a Bug'' link at the top of the page to open the bug reporting\nform.\nThe submission form has a number of fields. The only fields that are\nrequired are the ``Summary'' and ``Details'' fields. For the summary,\nenter a very short description of the problem; less than ten\nwords is good. In the Details field, describe the problem in detail,\nincluding what you expected to happen and what did happen. Be sure to\ninclude the version of Python you used, whether any extension modules\nwere involved, and what hardware and software platform you were using\n(including version information as appropriate).\nThe only other field that you may want to set is the ``Category''\nfield, which allows you to place the bug report into a broad category\n(such as ``Documentation'' or ``Library'').\nEach bug report will be assigned to a developer who will determine\nwhat needs to be done to correct the problem. If you have a\nSourceForge account and logged in to report the problem, you will\nreceive an update each time action is taken on the bug.\nSee Also:", "python_version": "2.2", "length": 2688, "url": "https://docs.python.org/2.2/api/reporting-bugs.html"} {"title": "10.5 Sequence Object Structures", "text": "number-structs.html | newTypes.html | buffer-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.5 Sequence Object Structures", "python_version": "2.2", "length": 159, "url": "https://docs.python.org/2.2/api/sequence-structs.html"} {"title": "6.3 Sequence Protocol", "text": "number.html | abstract.html | mapping.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.3 Sequence Protocol", "python_version": "2.2", "length": 134, "url": "https://docs.python.org/2.2/api/sequence.html"} {"title": "7.3 Sequence Objects", "text": "node38.html | concrete.html | stringObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.3 Sequence Objects\nGeneric operations on sequence objects were discussed in the previous\nchapter; this section deals with the specific kinds of sequence\nobjects that are intrinsic to the Python language.", "python_version": "2.2", "length": 324, "url": "https://docs.python.org/2.2/api/sequenceObjects.html"} {"title": "7.5.7 Slice Objects", "text": "descriptor-objects.html | otherObjects.html | weakref-objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.7 Slice Objects", "python_version": "2.2", "length": 157, "url": "https://docs.python.org/2.2/api/slice-objects.html"} {"title": "4.1 Standard Exceptions", "text": "exceptionHandling.html | exceptionHandling.html | node15.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 4.1 Standard Exceptions\nAll standard Python exceptions are available as global variables whose\nnames are \"PyExc_\" followed by the Python exception name. These\nhave the type PyObject*; they are all class objects. For\ncompleteness, here are all the variables:\nNotes:\n(1): This is a base class for other standard exceptions.\n(2): This is the same as weakref.ReferenceError.\n(3): Only defined on Windows; protect code that uses this by testing that\nthe preprocessor macro `MS_WINDOWS` is defined.", "python_version": "2.2", "length": 624, "url": "https://docs.python.org/2.2/api/standardExceptions.html"} {"title": "7.3.1 String Objects", "text": "sequenceObjects.html | sequenceObjects.html | unicodeObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.3.1 String Objects\nThese functions raise TypeError when expecting a string\nparameter and are called with a non-string parameter.", "python_version": "2.2", "length": 267, "url": "https://docs.python.org/2.2/api/stringObjects.html"} {"title": "10.8 Supporting Cyclic Garbarge Collection", "text": "supporting-iteration.html | newTypes.html | example-cycle-support.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.8 Supporting Cyclic Garbarge Collection\nPython's support for detecting and collecting garbage which involves\ncircular references requires support from object types which are\n``containers'' for other objects which may also be containers. Types\nwhich do not store references to other objects, or which only store\nreferences to atomic types (such as numbers or strings), do not need\nto provide any explicit support for garbage collection.\nTo create a container type, the tp_flags field of the type\nobject must include the Py_TPFLAGS_HAVE_GC and provide an\nimplementation of the tp_traverse handler. If instances of the\ntype are mutable, a tp_clear implementation must also be\nprovided.\nConstructors for container types must conform to two rules:\n1. The memory for the object must be allocated using\nPyObject_GC_New() or PyObject_GC_VarNew().\n2. Once all the fields which may contain references to other\ncontainers are initialized, it must call\nPyObject_GC_Track().\nSimilarly, the deallocator for the object must conform to a similar\npair of rules:\n1. Before fields which refer to other containers are invalidated,\nPyObject_GC_UnTrack() must be called.\n2. The object's memory must be deallocated using\nPyObject_GC_Del().\nThe tp_traverse handler accepts a function parameter of this\ntype:\nThe tp_traverse handler must have the following type:\nThe tp_clear handler must be of the inquiry type, or\nNULL if the object is immutable.", "python_version": "2.2", "length": 1567, "url": "https://docs.python.org/2.2/api/supporting-cycle-detection.html"} {"title": "10.7 Supporting the Iterator Protocol", "text": "buffer-structs.html | newTypes.html | supporting-cycle-detection.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.7 Supporting the Iterator Protocol", "python_version": "2.2", "length": 177, "url": "https://docs.python.org/2.2/api/supporting-iteration.html"} {"title": "8.1 Thread State and the Global Interpreter Lock", "text": "initialization.html | initialization.html | profiling.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 8.1 Thread State and the Global Interpreter Lock\nThe Python interpreter is not fully thread safe. In order to support\nmulti-threaded Python programs, there's a global lock that must be\nheld by the current thread before it can safely access Python objects.\nWithout the lock, even the simplest operations could cause problems in\na multi-threaded program: for example, when two threads simultaneously\nincrement the reference count of the same object, the reference count\ncould end up being incremented only once instead of twice.\nTherefore, the rule exists that only the thread that has acquired the\nglobal interpreter lock may operate on Python objects or call Python/C\nAPI functions. In order to support multi-threaded Python programs,\nthe interpreter regularly releases and reacquires the lock -- by\ndefault, every ten bytecode instructions (this can be changed with\nsys.setcheckinterval()). The lock is also released and\nreacquired around potentially blocking I/O operations like reading or\nwriting a file, so that other threads can run while the thread that\nrequests the I/O is waiting for the I/O operation to complete.\nThe Python interpreter needs to keep some bookkeeping information\nseparate per thread -- for this it uses a data structure called\nPyThreadState. This is new in Python\n1.5; in earlier versions, such state was stored in global variables,\nand switching threads could cause problems. In particular, exception\nhandling is now thread safe, when the application uses\nsys.exc_info() to access the exception last raised in the\ncurrent thread.\nThere's one global variable left, however: the pointer to the current\nPyThreadStatestructure. While most\nthread packages have a way to store ``per-thread global data,''\nPython's internal platform independent thread abstraction doesn't\nsupport this yet. Therefore, the current thread state must be\nmanipulated explicitly.\nThis is easy enough in most cases. Most code manipulating the global\ninterpreter lock has the following simple structure:\n```text\n\nSave the thread state in a local variable.\nRelease the interpreter lock.\n...Do some blocking I/O operation...\nReacquire the interpreter lock.\nRestore the thread state from the local variable.\n```\nThis is so common that a pair of macros exists to simplify it:\n```text\n\nPy_BEGIN_ALLOW_THREADS\n...Do some blocking I/O operation...\nPy_END_ALLOW_THREADS\n```\nThe `Py_BEGIN_ALLOW_THREADS`macro\nopens a new block and declares a hidden local variable; the\n`Py_END_ALLOW_THREADS`macro closes\nthe block. Another advantage of using these two macros is that when\nPython is compiled without thread support, they are defined empty,\nthus saving the thread state and lock manipulations.\nWhen thread support is enabled, the block above expands to the\nfollowing code:\n```text\n\nPyThreadState *_save;\n\n_save = PyEval_SaveThread();\n...Do some blocking I/O operation...\nPyEval_RestoreThread(_save);\n```\nUsing even lower level primitives, we can get roughly the same effect\nas follows:\n```text\n\nPyThreadState *_save;\n\n_save = PyThreadState_Swap(NULL);\nPyEval_ReleaseLock();\n...Do some blocking I/O operation...\nPyEval_AcquireLock();\nPyThreadState_Swap(_save);\n```\nThere are some subtle differences; in particular,\nPyEval_RestoreThread()saves\nand restores the value of the global variable\nerrno, since the lock manipulation does not\nguarantee that errno is left alone. Also, when thread support\nis disabled,\nPyEval_SaveThread()and\nPyEval_RestoreThread() don't manipulate the lock; in this\ncase, PyEval_ReleaseLock()and\nPyEval_AcquireLock()are not\navailable. This is done so that dynamically loaded extensions\ncompiled with thread support enabled can be loaded by an interpreter\nthat was compiled with disabled thread support.\nThe global interpreter lock is used to protect the pointer to the\ncurrent thread state. When releasing the lock and saving the thread\nstate, the current thread state pointer must be retrieved before the\nlock is released (since another thread could immediately acquire the\nlock and store its own thread state in the global variable).\nConversely, when acquiring the lock and restoring the thread state,\nthe lock must be acquired before storing the thread state pointer.\nWhy am I going on with so much detail about this? Because when\nthreads are created from C, they don't have the global interpreter\nlock, nor is there a thread state data structure for them. Such\nthreads must bootstrap themselves into existence, by first creating a\nthread state data structure, then acquiring the lock, and finally\nstoring their thread state pointer, before they can start using the\nPython/C API. When they are done, they should reset the thread state\npointer, release the lock, and finally free their thread state data\nstructure.\nWhen creating a thread data structure, you need to provide an\ninterpreter state data structure. The interpreter state data\nstructure hold global data that is shared by all threads in an\ninterpreter, for example the module administration\n(`sys.modules`). Depending on your needs, you can either create\na new interpreter state data structure, or share the interpreter state\ndata structure used by the Python main thread (to access the latter,\nyou must obtain the thread state and access its interp member;\nthis must be done by a thread that is created by Python or by the main\nthread after Python is initialized).\nThe following macros are normally used without a trailing semicolon;\nlook for example usage in the Python source distribution.\nAll of the following functions are only available when thread support\nis enabled at compile time, and must be called only when the\ninterpreter lock has been created.", "python_version": "2.2", "length": 5757, "url": "https://docs.python.org/2.2/api/threads.html"} {"title": "7.3.4 Tuple Objects", "text": "bufferObjects.html | sequenceObjects.html | listObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.3.4 Tuple Objects", "python_version": "2.2", "length": 151, "url": "https://docs.python.org/2.2/api/tupleObjects.html"} {"title": "7.1.1 Type Objects", "text": "fundamental.html | fundamental.html | noneObject.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.1.1 Type Objects", "python_version": "2.2", "length": 143, "url": "https://docs.python.org/2.2/api/typeObjects.html"} {"title": "1.2.2 Types", "text": "refcountDetails.html | objects.html | exceptions.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 1.2.2 Types\nThere are few other data types that play a significant role in\nthe Python/C API; most are simple C types such as int,\nlong, double and char*. A few structure types\nare used to describe static tables used to list the functions exported\nby a module or the data attributes of a new object type, and another\nis used to describe the value of a complex number. These will\nbe discussed together with the functions that use them.", "python_version": "2.2", "length": 558, "url": "https://docs.python.org/2.2/api/types.html"} {"title": "7.3.2.2 Methods and Slot Functions", "text": "builtinCodecs.html | unicodeObjects.html | bufferObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.3.2.2 Methods and Slot Functions\nThe following APIs are capable of handling Unicode objects and strings\non input (we refer to them as strings in the descriptions) and return\nUnicode objects or integers as apporpriate.\nThey all return NULL or `-1` if an exception occurs.", "python_version": "2.2", "length": 406, "url": "https://docs.python.org/2.2/api/unicodeMethodsAndSlots.html"} {"title": "7.3.2 Unicode Objects", "text": "stringObjects.html | sequenceObjects.html | builtinCodecs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.3.2 Unicode Objects\nThese are the basic Unicode object types used for the Unicode\nimplementation in Python:\nThe following APIs are really C macros and can be used to do fast\nchecks and to access internal read-only data of Unicode objects:\nUnicode provides many different character properties. The most often\nneeded ones are available through these macros which are mapped to C\nfunctions depending on the Python configuration.\nThese APIs can be used for fast direct character conversions:\nTo create Unicode objects and access their basic sequence properties,\nuse these APIs:\nIf the platform supports wchar_t and provides a header file\nwchar.h, Python can interface directly to this type using the\nfollowing functions. Support is optimized if Python's own\nPy_UNICODE type is identical to the system's wchar_t.", "python_version": "2.2", "length": 943, "url": "https://docs.python.org/2.2/api/unicodeObjects.html"} {"title": "5. Utilities", "text": "node15.html | api.html | os.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5. Utilities\nThe functions in this chapter perform various utility tasks, ranging\nfrom helping C code be more portable across platforms, using Python\nmodules from C, and parsing function arguments and constructing Python\nvalues from C values.", "python_version": "2.2", "length": 345, "url": "https://docs.python.org/2.2/api/utilities.html"} {"title": "2. The Very High Level Layer", "text": "embedding.html | api.html | countingRefs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 2. The Very High Level Layer\nThe functions in this chapter will let you execute Python source code\ngiven in a file or a buffer, but they will not let you interact in a\nmore detailed way with the interpreter.\nSeveral of these functions accept a start symbol from the grammar as a\nparameter. The available start symbols are Py_eval_input,\nPy_file_input, and Py_single_input. These are\ndescribed following the functions which accept them as parameters.\nNote also that several of these functions take FILE*\nparameters. On particular issue which needs to be handled carefully\nis that the FILE structure for different C libraries can be\ndifferent and incompatible. Under Windows (at least), it is possible\nfor dynamically linked extensions to actually use different libraries,\nso care should be taken that FILE* parameters are only passed\nto these functions if it is certain that they were created by the same\nlibrary that the Python runtime is using.", "python_version": "2.2", "length": 1061, "url": "https://docs.python.org/2.2/api/veryhigh.html"} {"title": "7.5.8 Weak Reference Objects", "text": "slice-objects.html | otherObjects.html | cObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.8 Weak Reference Objects\nPython supports weak references as first-class objects. There\nare two specific object types which directly implement weak\nreferences. The first is a simple reference object, and the second\nacts as a proxy for the original object as much as it can.", "python_version": "2.2", "length": 402, "url": "https://docs.python.org/2.2/api/weakref-objects.html"} {"title": "About this document ...", "text": "module-distutils.sysconfig.html | dist.html | Distributing Python Modules\n---\n# About this document ...\nDistributing Python Modules\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nmodule-distutils.sysconfig.html | dist.html | Distributing Python Modules\n---", "python_version": "2.2", "length": 1602, "url": "https://docs.python.org/2.2/dist/about.html"} {"title": "About this document ...", "text": "sdist-cmd.html | dist.html | Distributing Python Modules\n---\n# About this document ...\nDistributing Python Modules\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nsdist-cmd.html | dist.html | Distributing Python Modules\n---", "python_version": "2.2", "length": 1568, "url": "https://docs.python.org/2.2/dist/bdist-cmds.html"} {"title": "6 Creating Built Distributions", "text": "source-dist.html | dist.html | sdist-cmd.html | Distributing Python Modules\n---\n- 6.1 Creating dumb built distributions (#SECTION000610000000000000000)\n 6.2 Creating RPM packages (#SECTION000620000000000000000)\n 6.3 Creating Windows installers (#SECTION000630000000000000000)\n---\n# 6 Creating Built Distributions\nA ``built distribution'' is what you're probably used to thinking of\neither as a ``binary package'' or an ``installer'' (depending on your\nbackground). It's not necessarily binary, though, because it might\ncontain only Python source code and/or byte-code; and we don't call it a\npackage, because that word is already spoken for in Python. (And\n``installer'' is a term specific to the Windows world. ** do Mac\npeople use it? **)\nA built distribution is how you make life as easy as possible for\ninstallers of your module distribution: for users of RPM-based Linux\nsystems, it's a binary RPM; for Windows users, it's an executable\ninstaller; for Debian-based Linux users, it's a Debian package; and so\nforth. Obviously, no one person will be able to create built\ndistributions for every platform under the sun, so the Distutils are\ndesigned to enable module developers to concentrate on their\nspecialty--writing code and creating source distributions--while an\nintermediary species of packager springs up to turn source\ndistributions into built distributions for as many platforms as there\nare packagers.\nOf course, the module developer could be his own packager; or the\npackager could be a volunteer ``out there'' somewhere who has access to\na platform which the original developer does not; or it could be\nsoftware periodically grabbing new source distributions and turning them\ninto built distributions for as many platforms as the software has\naccess to. Regardless of the nature of the beast, a packager uses the\nsetup script and the `bdist` command family to generate built\ndistributions.\nAs a simple example, if I run the following command in the Distutils\nsource tree:\n```text\n\npython setup.py bdist\n```\nthen the Distutils builds my module distribution (the Distutils itself\nin this case), does a ``fake'' installation (also in the build\ndirectory), and creates the default type of built distribution for my\nplatform. The default format for built distributions is a ``dumb'' tar\nfile on Unix, and an simple executable installer on Windows. (That tar\nfile is considered ``dumb'' because it has to be unpacked in a specific\nlocation to work.)\nThus, the above command on a Unix system creates\nDistutils-0.9.1.plat.tar.gz; unpacking this tarball\nfrom the right place installs the Distutils just as though you had\ndownloaded the source distribution and run `python setup.py\ninstall`. (The ``right place'' is either the root of the filesystem or\nPython's prefix directory, depending on the options given to\nthe `bdist_dumb` command; the default is to make dumb\ndistributions relative to prefix.)\nObviously, for pure Python distributions, this isn't a huge win--but\nfor non-pure distributions, which include extensions that would need to\nbe compiled, it can mean the difference between someone being able to\nuse your extensions or not. And creating ``smart'' built distributions,\nsuch as an RPM package or an executable installer for Windows, is a big\nwin for users even if your distribution doesn't include any extensions.\nThe `bdist` command has a --formats option,\nsimilar to the `sdist` command, which you can use to select the\ntypes of built distribution to generate: for example,\n```text\n\npython setup.py bdist --format=zip\n```\nwould, when run on a Unix system, create\nDistutils-0.8.plat.zip--again, this archive would be\nunpacked from the root directory to install the Distutils.\nThe available formats for built distributions are:\nNotes:\n(1): default on Unix\n(2): default on Windows ** to-do! **\n(3): requires external utilities: tar and possibly one\nof gzip, bzip2, or compress\n(4): requires either external zip utility or\nzipfile module (not part of the standard Python library)\n(5): requires external rpm utility, version 3.0.4 or\nbetter (use `rpm -version` to find out which version you have)\nYou don't have to use the `bdist` command with the\n--formats option; you can also use the command that\ndirectly implements the format you're interested in. Some of these\n`bdist` ``sub-commands'' actually generate several similar\nformats; for instance, the `bdist_dumb` command generates all\nthe ``dumb'' archive formats (`tar`, `ztar`, `gztar`, and\n`zip`), and `bdist_rpm` generates both binary and source\nRPMs. The `bdist` sub-commands, and the formats generated by\neach, are:\nThe following sections give details on the individual `bdist_*`\ncommands.\n## 6.1 Creating dumb built distributions\n** Need to document absolute vs. prefix-relative packages here, but\nfirst I have to implement it! **\n## 6.2 Creating RPM packages\nThe RPM format is used by many of popular Linux distributions, including\nRed Hat, SuSE, and Mandrake. If one of these (or any of the other\nRPM-based Linux distributions) is your usual environment, creating RPM\npackages for other users of that same distribution is trivial.\nDepending on the complexity of your module distribution and differences\nbetween Linux distributions, you may also be able to create RPMs that\nwork on different RPM-based distributions.\nThe usual way to create an RPM of your module distribution is to run the\n`bdist_rpm` command:\n```text\n\npython setup.py bdist_rpm\n```\nor the `bdist` command with the --format option:\n```text\n\npython setup.py bdist --formats=rpm\n```\nThe former allows you to specify RPM-specific options; the latter allows\nyou to easily specify multiple formats in one run. If you need to do\nboth, you can explicitly specify multiple `bdist_*` commands\nand their options:\n```text\n\npython setup.py bdist_rpm --packager=\"John Doe \" \\\nbdist_wininst --target_version=\"2.0\"\n```\nCreating RPM packages is driven by a .spec file, much as using\nthe Distutils is driven by the setup script. To make your life easier,\nthe `bdist_rpm` command normally creates a .spec file\nbased on the information you supply in the setup script, on the command\nline, and in any Distutils configuration files. Various options and\nsections in the .spec file are derived from options in the setup\nscript as follows:\nAdditionally, there many options in .spec files that don't have\ncorresponding options in the setup script. Most of these are handled\nthrough options to the `bdist_rpm` command as follows:\nObviously, supplying even a few of these options on the command-line\nwould be tedious and error-prone, so it's usually best to put them in\nthe setup configuration file, setup.cfg--see\nsection 4 (setup-config.html#setup-config). If you distribute or package many Python\nmodule distributions, you might want to put options that apply to all of\nthem in your personal Distutils configuration file\n( /.pydistutils.cfg).\nThere are three steps to building a binary RPM package, all of which are\nhandled automatically by the Distutils:\n1. create a .spec file, which describes the package (analogous\nto the Distutils setup script; in fact, much of the information in the\nsetup script winds up in the .spec file)\n2. create the source RPM\n3. create the ``binary'' RPM (which may or may not contain binary\ncode, depending on whether your module distribution contains Python\nextensions)\nNormally, RPM bundles the last two steps together; when you use the\nDistutils, all three steps are typically bundled together.\nIf you wish, you can separate these three steps. You can use the\n--spec-only option to make `bdist_rpm` just\ncreate the .spec file and exit; in this case, the .spec\nfile will be written to the ``distribution directory''--normally\ndist/, but customizable with the --dist-dir\noption. (Normally, the .spec file winds up deep in the ``build\ntree,'' in a temporary directory created by `bdist_rpm`.)\n** this isn't implemented yet--is it needed?! **\nYou can also specify a custom .spec file with the\n--spec-file option; used in conjunction with\n--spec-only, this gives you an opportunity to customize\nthe .spec file manually:\n```text\n\n> python setup.py bdist_rpm --spec-only\n# ...edit dist/FooBar-1.0.spec\n> python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec\n```\n(Although a better way to do this is probably to override the standard\n`bdist_rpm` command with one that writes whatever else you want\nto the .spec file; see section #extending for information on\nextending the Distutils.)\n## 6.3 Creating Windows installers\nExecutable Windows installers are the natural format for binary\ndistributions on Windows. They display a nice graphical user interface,\ndisplay some information of the module distribution to be installed, taken\nfrom the meta-data in the setup script, let the user select a few\n(currently maybe too few) options, and start or cancel the installation.\nSince the meta-data is taken from the setup script, creating\nWindows installers is usually as easy as running:\n```text\n\npython setup.py bdist_wininst\n```\nor the `bdist` command with the --format option:\n```text\n\npython setup.py bdist --formats=wininst\n```\nIf you have a pure module distribution (only containing pure\nPython modules and packages), the resulting installer will be\nversion independent and have a name like Foo-1.0.win32.exe.\nThese installers can even be created on Unix or MacOS platforms.\nIf you have a non-pure distribution, the extensions can only be\ncreated on a Windows platform, and will be Python version dependend.\nThe installer filename will reflect this and now has the form\nFoo-1.0.win32-py2.0.exe. You have to create a separate installer\nfor every Python version you want to support.\nThe installer will try to compile pure modules into bytecode after\ninstallation on the target system in normal and optimizing mode.\nIf you don't want this to happen for some reason, you can run\nthe bdist_wininst command with the --no-target-compile and/or\nthe --no-target-optimize option.", "python_version": "2.2", "length": 9941, "url": "https://docs.python.org/2.2/dist/creating-wininst.html"} {"title": "Distributing Python Modules", "text": "../index.html | intro.html | Distributing Python Modules\n---\n# Distributing Python Modules\nGreg Ward\nEmail: gward@python.net\n### Abstract:\nThis document describes the Python Distribution Utilities\n(``Distutils'') from the module developer's point-of-view, describing\nhow to use the Distutils to make Python modules and extensions easily\navailable to a wider audience with very little overhead for\nbuild/release/install mechanics.", "python_version": "2.2", "length": 429, "url": "https://docs.python.org/2.2/dist/dist.html"} {"title": "Distributing Python Modules", "text": "../index.html | intro.html | Distributing Python Modules\n---\n# Distributing Python Modules\nGreg Ward\nEmail: gward@python.net\n### Abstract:\nThis document describes the Python Distribution Utilities\n(``Distutils'') from the module developer's point-of-view, describing\nhow to use the Distutils to make Python modules and extensions easily\navailable to a wider audience with very little overhead for\nbuild/release/install mechanics.", "python_version": "2.2", "length": 429, "url": "https://docs.python.org/2.2/dist/index.html"} {"title": "1 Introduction", "text": "dist.html | dist.html | simple-example.html | Distributing Python Modules\n---\n# 1 Introduction\nIn the past, Python module developers have not had much infrastructure\nsupport for distributing modules, nor have Python users had much support\nfor installing and maintaining third-party modules. With the\nintroduction of the Python Distribution Utilities (Distutils for short)\nin Python 1.6, this situation should start to improve.\nThis document only covers using the Distutils to distribute your Python\nmodules. Using the Distutils does not tie you to Python 1.6, though:\nthe Distutils work just fine with Python 1.5.2, and it is reasonable\n(and expected to become commonplace) to expect users of Python 1.5.2 to\ndownload and install the Distutils separately before they can install\nyour modules. Python 1.6 (or later) users, of course, won't have to add\nanything to their Python installation in order to use the Distutils to\ninstall third-party modules.\nThis document concentrates on the role of developer/distributor: if\nyou're looking for information on installing Python modules, you\nshould refer to the Installing Python\nModules (../inst/inst.html) manual.", "python_version": "2.2", "length": 1157, "url": "https://docs.python.org/2.2/dist/intro.html"} {"title": "8 distutils.sysconfig -- System configuration information", "text": "sdist-cmd.html | dist.html | about.html | Distributing Python Modules\n---\n# 8 distutils.sysconfig --\nSystem configuration information\nThe distutils.sysconfig module provides access to Python's\nlow-level configuration information. The specific configuration\nvariables available depend heavily on the platform and configuration.\nThe specific variables depend on the build process for the specific\nversion of Python being run; the variables are those found in the\nMakefile and configuration header that are installed with\nPython on Unix systems. The configuration header is called\npyconfig.h for Python versions starting with 2.2, and\nconfig.h for earlier versions of Python.\nSome additional functions are provided which perform some useful\nmanipulations for other parts of the distutils package.\nThe following function is only intended for use within the\ndistutils package.\nThis function is even more special-purpose, and should only be used\nfrom Python's own build procedures.", "python_version": "2.2", "length": 975, "url": "https://docs.python.org/2.2/dist/module-distutils.sysconfig.html"} {"title": "7 Reference", "text": "creating-wininst.html | dist.html | module-distutils.sysconfig.html | Distributing Python Modules\n---\n- 7.1 Installing modules: the `install` command family (#SECTION000710000000000000000)\n - 7.1.1 `install_data` (#SECTION000711000000000000000)\n 7.1.2 `install_scripts` (#SECTION000712000000000000000)\n 7.2 Creating a source distribution: the\n `sdist` command (#SECTION000720000000000000000)\n---\n# 7 Reference\n## 7.1 Installing modules: the `install` command family\nThe install command ensures that the build commands have been run and then\nruns the subcommands `install_lib`,\n`install_data` and\n`install_scripts`.\n### 7.1.1 `install_data`\nThis command installs all data files provided with the distribution.\n### 7.1.2 `install_scripts`\nThis command installs all (Python) scripts in the distribution.\n## 7.2 Creating a source distribution: the\n`sdist` command\n** fragment moved down from above: needs context! **\nThe manifest template commands are:\nThe patterns here are Unix-style ``glob'' patterns: `*` matches any\nsequence of regular filename characters, `?` matches any single\nregular filename character, and `[ range ]` matches any of the\ncharacters in range (e.g., `a-z`, `a-zA-Z`,\n`a-f0-9_.`). The definition of ``regular filename character'' is\nplatform-specific: on Unix it is anything except slash; on Windows\nanything except backslash or colon; on MacOS anything except colon.\n** Windows and MacOS support not there yet **", "python_version": "2.2", "length": 1437, "url": "https://docs.python.org/2.2/dist/sdist-cmd.html"} {"title": "4 Writing the Setup Configuration File", "text": "setup-script.html | dist.html | source-dist.html | Distributing Python Modules\n---\n# 4 Writing the Setup Configuration File\nOften, it's not possible to write down everything needed to build a\ndistribution a priori: you may need to get some information from\nthe user, or from the user's system, in order to proceed. As long as\nthat information is fairly simple--a list of directories to search for\nC header files or libraries, for example--then providing a\nconfiguration file, setup.cfg, for users to edit is a cheap and\neasy way to solicit it. Configuration files also let you provide\ndefault values for any command option, which the installer can then\noverride either on the command-line or by editing the config file.\n(If you have more advanced needs, such as determining which extensions\nto build based on what capabilities are present on the target system,\nthen you need the Distutils ``auto-configuration'' facility. This\nstarted to appear in Distutils 0.9 but, as of this writing, isn't mature\nor stable enough yet for real-world use.)\nThe setup configuration file is a useful middle-ground between the setup\nscript--which, ideally, would be opaque to installers2 (#foot247)--and the command-line to the setup\nscript, which is outside of your control and entirely up to the\ninstaller. In fact, setup.cfg (and any other Distutils\nconfiguration files present on the target system) are processed after\nthe contents of the setup script, but before the command-line. This has\nseveral useful consequences:\n- installers can override some of what you put in setup.py by\nediting setup.cfg\n- you can provide non-standard defaults for options that are not\neasily set in setup.py\n- installers can override anything in setup.cfg using the\ncommand-line options to setup.py\nThe basic syntax of the configuration file is simple:\n```text\n\n[command]\noption=value\n...\n```\nwhere command is one of the Distutils commands (e.g.\n`build_py`, `install`), and option is one of the\noptions that command supports. Any number of options can be supplied\nfor each command, and any number of command sections can be included in\nthe file. Blank lines are ignored, as are comments (from a\n\"#\" character to end-of-line). Long option values can be\nsplit across multiple lines simply by indenting the continuation lines.\nYou can find out the list of options supported by a particular command\nwith the universal --help option, e.g.\n```text\n\n> python setup.py --help build_ext\n[...]\nOptions for 'build_ext' command:\n--build-lib (-b) directory for compiled extension modules\n--build-temp (-t) directory for temporary files (build by-products)\n--inplace (-i) ignore build-lib and put compiled extensions into the\nsource directory alongside your pure Python modules\n--include-dirs (-I) list of directories to search for header files\n--define (-D) C preprocessor macros to define\n--undef (-U) C preprocessor macros to undefine\n[...]\n```\nOr consult section 7 (sdist-cmd.html#reference) of this document (the command\nreference).\nNote that an option spelled --foo-bar on the command-line\nis spelled foo_bar in configuration files.\nFor example, say you want your extensions to be built\n``in-place''--that is, you have an extension pkg.ext, and you\nwant the compiled extension file (ext.so on Unix, say) to be put\nin the same source directory as your pure Python modules\npkg.mod1 and pkg.mod2. You can always use the\n--inplace option on the command-line to ensure this:\n```text\n\npython setup.py build_ext --inplace\n```\nBut this requires that you always specify the `build_ext`\ncommand explicitly, and remember to provide --inplace.\nAn easier way is to ``set and forget'' this option, by encoding it in\nsetup.cfg, the configuration file for this distribution:\n```text\n\n[build_ext]\ninplace=1\n```\nThis will affect all builds of this module distribution, whether or not\nyou explcitly specify `build_ext`. If you include\nsetup.cfg in your source distribution, it will also affect\nend-user builds--which is probably a bad idea for this option, since\nalways building extensions in-place would break installation of the\nmodule distribution. In certain peculiar cases, though, modules are\nbuilt right in their installation directory, so this is conceivably a\nuseful ability. (Distributing extensions that expect to be built in\ntheir installation directory is almost always a bad idea, though.)\nAnother example: certain commands take a lot of options that don't\nchange from run-to-run; for example, `bdist_rpm` needs to know\neverything required to generate a ``spec'' file for creating an RPM\ndistribution. Some of this information comes from the setup script, and\nsome is automatically generated by the Distutils (such as the list of\nfiles installed). But some of it has to be supplied as options to\n`bdist_rpm`, which would be very tedious to do on the\ncommand-line for every run. Hence, here is a snippet from the\nDistutils' own setup.cfg:\n```text\n\n[bdist_rpm]\nrelease = 1\npackager = Greg Ward \ndoc_files = CHANGES.txt\nREADME.txt\nUSAGE.txt\ndoc/\nexamples/\n```\nNote that the doc_files option is simply a\nwhitespace-separated string split across multiple lines for readability.\nSee Also:", "python_version": "2.2", "length": 5153, "url": "https://docs.python.org/2.2/dist/setup-config.html"} {"title": "3 Writing the Setup Script", "text": "simple-example.html | dist.html | setup-config.html | Distributing Python Modules\n---\n- 3.1 Listing whole packages (#SECTION000310000000000000000)\n 3.2 Listing individual modules (#SECTION000320000000000000000)\n 3.3 Describing extension modules (#SECTION000330000000000000000)\n - 3.3.1 Extension names and packages (#SECTION000331000000000000000)\n 3.3.2 Extension source files (#SECTION000332000000000000000)\n 3.3.3 Preprocessor options (#SECTION000333000000000000000)\n 3.3.4 Library options (#SECTION000334000000000000000)\n 3.3.5 Other options (#SECTION000335000000000000000)\n 3.4 Listing scripts (#SECTION000340000000000000000)\n 3.5 Listing additional files (#SECTION000350000000000000000)\n---\n# 3 Writing the Setup Script\nThe setup script is the centre of all activity in building,\ndistributing, and installing modules using the Distutils. The main\npurpose of the setup script is to describe your module distribution to\nthe Distutils, so that the various commands that operate on your modules\ndo the right thing. As we saw in section 2.1 (simple-example.html#simple-example) above,\nthe setup script consists mainly of a call to setup(), and\nmost information supplied to the Distutils by the module developer is\nsupplied as keyword arguments to setup().\nHere's a slightly more involved example, which we'll follow for the next\ncouple of sections: the Distutils' own setup script. (Keep in mind that\nalthough the Distutils are included with Python 1.6 and later, they also\nhave an independent existence so that Python 1.5.2 users can use them to\ninstall other module distributions. The Distutils' own setup script,\nshown here, is used to install the package into Python 1.5.2.)\n```text\n\n#!/usr/bin/env python\n\nfrom distutils.core import setup\n\nsetup(name=\"Distutils\",\nversion=\"1.0\",\ndescription=\"Python Distribution Utilities\",\nauthor=\"Greg Ward\",\nauthor_email=\"gward@python.net\",\nurl=\"http://www.python.org/sigs/distutils-sig/\",\npackages=['distutils', 'distutils.command'],\n)\n```\nThere are only two differences between this and the trivial one-file\ndistribution presented in section 2.1 (simple-example.html#simple-example): more\nmeta-data, and the specification of pure Python modules by package,\nrather than by module. This is important since the Distutils consist of\na couple of dozen modules split into (so far) two packages; an explicit\nlist of every module would be tedious to generate and difficult to\nmaintain.\nNote that any pathnames (files or directories) supplied in the setup\nscript should be written using the Unix convention, i.e.\nslash-separated. The Distutils will take care of converting this\nplatform-neutral representation into whatever is appropriate on your\ncurrent platform before actually using the pathname. This makes your\nsetup script portable across operating systems, which of course is one\nof the major goals of the Distutils. In this spirit, all pathnames in\nthis document are slash-separated (MacOS programmers should keep in\nmind that the absence of a leading slash indicates a relative\npath, the opposite of the MacOS convention with colons).\nThis, of course, only applies to pathnames given to Distutils functions.\nIf you, for example, use standard python functions such as glob.glob\nor os.listdir to specify files, you should be careful to write portable\ncode instead of hardcoding path separators:\n```text\n\nglob.glob(os.path.join('mydir', 'subdir', '*.html'))\nos.listdir(os.path.join('mydir', 'subdir'))\n```\n## 3.1 Listing whole packages\nThe packages option tells the Distutils to process (build,\ndistribute, install, etc.) all pure Python modules found in each package\nmentioned in the packages list. In order to do this, of\ncourse, there has to be a correspondence between package names and\ndirectories in the filesystem. The default correspondence is the most\nobvious one, i.e. package distutils is found in the directory\ndistutils relative to the distribution root. Thus, when you say\n`packages = ['foo']` in your setup script, you are promising that\nthe Distutils will find a file foo/__init__.py (which might\nbe spelled differently on your system, but you get the idea) relative to\nthe directory where your setup script lives. (If you break this\npromise, the Distutils will issue a warning but process the broken\npackage anyways.)\nIf you use a different convention to lay out your source directory,\nthat's no problem: you just have to supply the package_dir\noption to tell the Distutils about your convention. For example, say\nyou keep all Python source under lib, so that modules in the\n``root package'' (i.e., not in any package at all) are right in\nlib, modules in the foo package are in lib/foo,\nand so forth. Then you would put\n```text\n\npackage_dir = {'': 'lib'}\n```\nin your setup script. (The keys to this dictionary are package names,\nand an empty package name stands for the root package. The values are\ndirectory names relative to your distribution root.) In this case, when\nyou say `packages = ['foo']`, you are promising that the file\nlib/foo/__init__.py exists.\nAnother possible convention is to put the foo package right in\nlib, the foo.bar package in lib/bar, etc. This\nwould be written in the setup script as\n```text\n\npackage_dir = {'foo': 'lib'}\n```\nA `package : dir` entry in the package_dir\ndictionary implicitly applies to all packages below package, so\nthe foo.bar case is automatically handled here. In this\nexample, having `packages = ['foo', 'foo.bar']` tells the Distutils\nto look for lib/__init__.py and\nlib/bar/__init__.py. (Keep in mind that although\npackage_dir applies recursively, you must explicitly list all\npackages in packages: the Distutils will not recursively\nscan your source tree looking for any directory with an\n__init__.py file.)\n## 3.2 Listing individual modules\nFor a small module distribution, you might prefer to list all modules\nrather than listing packages--especially the case of a single module\nthat goes in the ``root package'' (i.e., no package at all). This\nsimplest case was shown in section 2.1 (simple-example.html#simple-example); here is a\nslightly more involved example:\n```text\n\npy_modules = ['mod1', 'pkg.mod2']\n```\nThis describes two modules, one of them in the ``root'' package, the\nother in the pkg package. Again, the default package/directory\nlayout implies that these two modules can be found in mod1.py and\npkg/mod2.py, and that pkg/__init__.py exists as well.\nAnd again, you can override the package/directory correspondence using\nthe package_dir option.\n## 3.3 Describing extension modules\nJust as writing Python extension modules is a bit more complicated than\nwriting pure Python modules, describing them to the Distutils is a bit\nmore complicated. Unlike pure modules, it's not enough just to list\nmodules or packages and expect the Distutils to go out and find the\nright files; you have to specify the extension name, source file(s), and\nany compile/link requirements (include directories, libraries to link\nwith, etc.).\nAll of this is done through another keyword argument to\nsetup(), the extensions option. extensions\nis just a list of Extension instances, each of which describes a\nsingle extension module. Suppose your distribution includes a single\nextension, called foo and implemented by foo.c. If no\nadditional instructions to the compiler/linker are needed, describing\nthis extension is quite simple:\n```text\n\nExtension(\"foo\", [\"foo.c\"])\n```\nThe Extension class can be imported from\ndistutils.core, along with setup(). Thus, the setup\nscript for a module distribution that contains only this one extension\nand nothing else might be:\n```text\n\nfrom distutils.core import setup, Extension\nsetup(name=\"foo\", version=\"1.0\",\next_modules=[Extension(\"foo\", [\"foo.c\"])])\n```\nThe Extension class (actually, the underlying extension-building\nmachinery implemented by the `build_ext` command) supports a\ngreat deal of flexibility in describing Python extensions, which is\nexplained in the following sections.\n### 3.3.1 Extension names and packages\nThe first argument to the Extension constructor is always the\nname of the extension, including any package names. For example,\n```text\n\nExtension(\"foo\", [\"src/foo1.c\", \"src/foo2.c\"])\n```\ndescribes an extension that lives in the root package, while\n```text\n\nExtension(\"pkg.foo\", [\"src/foo1.c\", \"src/foo2.c\"])\n```\ndescribes the same extension in the pkg package. The source\nfiles and resulting object code are identical in both cases; the only\ndifference is where in the filesystem (and therefore where in Python's\nnamespace hierarchy) the resulting extension lives.\nIf you have a number of extensions all in the same package (or all under\nthe same base package), use the ext_package keyword argument\nto setup(). For example,\n```text\n\nsetup(...\next_package=\"pkg\",\next_modules=[Extension(\"foo\", [\"foo.c\"]),\nExtension(\"subpkg.bar\", [\"bar.c\"])]\n)\n```\nwill compile foo.c to the extension pkg.foo, and\nbar.c to pkg.subpkg.bar.\n### 3.3.2 Extension source files\nThe second argument to the Extension constructor is a list of\nsource files. Since the Distutils currently only support C/C++\nextensions, these are normally C/C++ source files. (Be sure to use\nappropriate extensions to distinguish C++ source files: .cc and\n.cpp seem to be recognized by both Unix and Windows compilers.)\nHowever, you can also include SWIG interface (.i) files in the\nlist; the `build_ext` command knows how to deal with SWIG\nextensions: it will run SWIG on the interface file and compile the\nresulting C/C++ file into your extension.\n** SWIG support is rough around the edges and largely untested;\nespecially SWIG support of C++ extensions! Explain in more detail\nhere when the interface firms up. **\nOn some platforms, you can include non-source files that are processed\nby the compiler and included in your extension. Currently, this just\nmeans Windows message text (.mc) files and resource definition\n(.rc) files for Visual C++. These will be compiled to binary resource\n(.res) files and linked into the executable.\n### 3.3.3 Preprocessor options\nThree optional arguments to Extension will help if you need to\nspecify include directories to search or preprocessor macros to\ndefine/undefine: `include_dirs`, `define_macros`, and\n`undef_macros`.\nFor example, if your extension requires header files in the\ninclude directory under your distribution root, use the\n`include_dirs` option:\n```text\n\nExtension(\"foo\", [\"foo.c\"], include_dirs=[\"include\"])\n```\nYou can specify absolute directories there; if you know that your\nextension will only be built on Unix systems with X11R6 installed to\n/usr, you can get away with\n```text\n\nExtension(\"foo\", [\"foo.c\"], include_dirs=[\"/usr/include/X11\"])\n```\nYou should avoid this sort of non-portable usage if you plan to\ndistribute your code: it's probably better to write your code to include\n(e.g.) ``.\nIf you need to include header files from some other Python extension,\nyou can take advantage of the fact that the Distutils install extension\nheader files in a consistent way. For example, the Numerical Python\nheader files are installed (on a standard Unix installation) to\n/usr/local/include/python1.5/Numerical. (The exact location will\ndiffer according to your platform and Python installation.) Since the\nPython include directory--/usr/local/include/python1.5 in this\ncase--is always included in the search path when building Python\nextensions, the best approach is to include (e.g.)\n``. If you insist on putting the\nNumerical include directory right into your header search path,\nthough, you can find that directory using the Distutils\nsysconfig module:\n```text\n\nfrom distutils.sysconfig import get_python_inc\nincdir = os.path.join(get_python_inc(plat_specific=1), \"Numerical\")\nsetup(...,\nExtension(..., include_dirs=[incdir]))\n```\nEven though this is quite portable--it will work on any Python\ninstallation, regardless of platform--it's probably easier to just\nwrite your C code in the sensible way.\nYou can define and undefine pre-processor macros with the\n`define_macros` and `undef_macros` options.\n`define_macros` takes a list of `(name, value)` tuples, where\n`name` is the name of the macro to define (a string) and\n`value` is its value: either a string or `None`. (Defining a\nmacro `FOO` to `None` is the equivalent of a bare\n`#define FOO` in your C source: with most compilers, this sets\n`FOO` to the string `1`.) `undef_macros` is just\na list of macros to undefine.\nFor example:\n```text\n\nExtension(...,\ndefine_macros=[('NDEBUG', '1')],\n('HAVE_STRFTIME', None),\nundef_macros=['HAVE_FOO', 'HAVE_BAR'])\n```\nis the equivalent of having this at the top of every C source file:\n```text\n\n#define NDEBUG 1\n#define HAVE_STRFTIME\n#undef HAVE_FOO\n#undef HAVE_BAR\n```\n### 3.3.4 Library options\nYou can also specify the libraries to link against when building your\nextension, and the directories to search for those libraries. The\n`libraries` option is a list of libraries to link against,\n`library_dirs` is a list of directories to search for libraries at\nlink-time, and `runtime_library_dirs` is a list of directories to\nsearch for shared (dynamically loaded) libraries at run-time.\nFor example, if you need to link against libraries known to be in the\nstandard library search path on target systems\n```text\n\nExtension(...,\nlibraries=[\"gdbm\", \"readline\"])\n```\nIf you need to link with libraries in a non-standard location, you'll\nhave to include the location in `library_dirs`:\n```text\n\nExtension(...,\nlibrary_dirs=[\"/usr/X11R6/lib\"],\nlibraries=[\"X11\", \"Xt\"])\n```\n(Again, this sort of non-portable construct should be avoided if you\nintend to distribute your code.)\n** Should mention clib libraries here or somewhere else! **\n### 3.3.5 Other options\nThere are still some other options which can be used to handle special\ncases.\nThe extra_objects option is a list of object files to be passed\nto the linker. These files must not have extensions, as the default\nextension for the compiler is used.\nextra_compile_args and extra_link_args can be used\nto specify additional command line options for the compiler resp.\nthe linker command line.\nexport_symbols is only useful on windows, it can contain a list\nof symbols (functions or variables) to be exported. This option\nis not needed when building compiled extensions: the `initmodule`\nfunction will automatically be added to the exported symbols list\nby Distutils.\n## 3.4 Listing scripts\nSo far we have been dealing with pure and non-pure Python modules,\nwhich are usually not run by themselves but imported by scripts.\nScripts are files containing Python source code, indended to be started\nfrom the command line.\nDistutils doesn't provide much functionality for the scripts: the only\nsupport Distutils gives is to adjust the first line of the script\nif it starts with `#!` and contains the word ``python'' to refer\nto the current interpreter location.\nThe scripts option simply is a list of files to be handled\nin this way.\n## 3.5 Listing additional files\nThe data_files option can be used to specify additional\nfiles needed by the module distribution: configuration files,\ndata files, anything which does not fit in the previous categories.\ndata_files specify a sequence of `(directory, files)`\npairs in the following way:\n```text\n\nsetup(...\ndata_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),\n('config', ['cfg/data.cfg'])])\n```\nNote that you can specify the directory names where the data files\nwill be installed, but you cannot rename the data files themselves.\nYou can specify the data_files options as a simple sequence\nof files without specifying a target directory, but this is not recommended,\nand the `install` command will print a warning in this case.\nTo install data files directly in the target directory, an empty\nstring should be given as the directory.", "python_version": "2.2", "length": 15739, "url": "https://docs.python.org/2.2/dist/setup-script.html"} {"title": "2 Concepts & Terminology", "text": "intro.html | dist.html | setup-script.html | Distributing Python Modules\n---\n- 2.1 A simple example (#SECTION000210000000000000000)\n 2.2 General Python terminology (#SECTION000220000000000000000)\n 2.3 Distutils-specific terminology (#SECTION000230000000000000000)\n---\n# 2 Concepts & Terminology\nUsing the Distutils is quite simple, both for module developers and for\nusers/administrators installing third-party modules. As a developer,\nyour responsibilities (apart from writing solid, well-documented and\nwell-tested code, of course!) are:\n- write a setup script (setup.py by convention)\n- (optional) write a setup configuration file\n- create a source distribution\n- (optional) create one or more built (binary) distributions\nEach of these tasks is covered in this document.\nNot all module developers have access to a multitude of platforms, so\nit's not always feasible to expect them to create a multitude of built\ndistributions. It is hoped that a class of intermediaries, called\npackagers, will arise to address this need. Packagers will take\nsource distributions released by module developers, build them on one or\nmore platforms, and release the resulting built distributions. Thus,\nusers on the most popular platforms will be able to install most popular\nPython module distributions in the most natural way for their platform,\nwithout having to run a single setup script or compile a line of code.\n## 2.1 A simple example\nThe setup script is usually quite simple, although since it's written in\nPython, there are no arbitrary limits to what you can do with\nit.1 (#foot684) If\nall you want to do is distribute a module called foo, contained\nin a file foo.py, then your setup script can be as little as\nthis:\n```text\n\nfrom distutils.core import setup\nsetup(name=\"foo\",\nversion=\"1.0\",\npy_modules=[\"foo\"])\n```\nSome observations:\n- most information that you supply to the Distutils is supplied as\nkeyword arguments to the setup() function\n- those keyword arguments fall into two categories: package\nmeta-data (name, version number) and information about what's in the\npackage (a list of pure Python modules, in this case)\n- modules are specified by module name, not filename (the same will\nhold true for packages and extensions)\n- it's recommended that you supply a little more meta-data, in\nparticular your name, email address and a URL for the project\n(see section 3 (setup-script.html#setup-script) for an example)\nTo create a source distribution for this module, you would create a\nsetup script, setup.py, containing the above code, and run:\n```text\n\npython setup.py sdist\n```\nwhich will create an archive file (e.g., tarball on Unix, ZIP file on\nWindows) containing your setup script, setup.py, and your module,\nfoo.py. The archive file will be named Foo-1.0.tar.gz (or\n.zip), and will unpack into a directory Foo-1.0.\nIf an end-user wishes to install your foo module, all she has\nto do is download Foo-1.0.tar.gz (or .zip), unpack it,\nand--from the Foo-1.0 directory--run\n```text\n\npython setup.py install\n```\nwhich will ultimately copy foo.py to the appropriate directory\nfor third-party modules in their Python installation.\nThis simple example demonstrates some fundamental concepts of the\nDistutils: first, both developers and installers have the same basic\nuser interface, i.e. the setup script. The difference is which\nDistutils commands they use: the `sdist` command is\nalmost exclusively for module developers, while `install` is\nmore often for installers (although most developers will want to install\ntheir own code occasionally).\nIf you want to make things really easy for your users, you can create\none or more built distributions for them. For instance, if you are\nrunning on a Windows machine, and want to make things easy for other\nWindows users, you can create an executable installer (the most\nappropriate type of built distribution for this platform) with the\n`bdist_wininst` command. For example:\n```text\n\npython setup.py bdist_wininst\n```\nwill create an executable installer, Foo-1.0.win32.exe, in the\ncurrent directory.\nCurrently (Distutils 0.9.2), the only other useful built\ndistribution format is RPM, implemented by the `bdist_rpm`\ncommand. For example, the following command will create an RPM file\ncalled Foo-1.0.noarch.rpm:\n```text\n\npython setup.py bdist_rpm\n```\n(This uses the `rpm` command, so has to be run on an RPM-based\nsystem such as Red Hat Linux, SuSE Linux, or Mandrake Linux.)\nYou can find out what distribution formats are available at any time by\nrunning\n```text\n\npython setup.py bdist --help-formats\n```\n## 2.2 General Python terminology\nIf you're reading this document, you probably have a good idea of what\nmodules, extensions, and so forth are. Nevertheless, just to be sure\nthat everyone is operating from a common starting point, we offer the\nfollowing glossary of common Python terms:\nmodule: the basic unit of code reusability in Python: a block of\ncode imported by some other code. Three types of modules concern us\nhere: pure Python modules, extension modules, and packages.\npure Python module: a module written in Python and contained in a\nsingle .py file (and possibly associated .pyc and/or\n.pyo files). Sometimes referred to as a ``pure module.''\nextension module: a module written in the low-level language of\nthe Python implementation: C/C++ for Python, Java for JPython.\nTypically contained in a single dynamically loadable pre-compiled\nfile, e.g. a shared object (.so) file for Python extensions on\nUnix, a DLL (given the .pyd extension) for Python extensions\non Windows, or a Java class file for JPython extensions. (Note that\ncurrently, the Distutils only handles C/C++ extensions for Python.)\npackage: a module that contains other modules; typically contained\nin a directory in the filesystem and distinguished from other\ndirectories by the presence of a file __init__.py.\nroot package: the root of the hierarchy of packages. (This isn't\nreally a package, since it doesn't have an __init__.py\nfile. But we have to call it something.) The vast majority of the\nstandard library is in the root package, as are many small, standalone\nthird-party modules that don't belong to a larger module collection.\nUnlike regular packages, modules in the root package can be found in\nmany directories: in fact, every directory listed in `sys.path`\ncan contribute modules to the root package.\n## 2.3 Distutils-specific terminology\nThe following terms apply more specifically to the domain of\ndistributing Python modules using the Distutils:\nmodule distribution: a collection of Python modules distributed\ntogether as a single downloadable resource and meant to be installed\nen masse. Examples of some well-known module distributions are\nNumeric Python, PyXML, PIL (the Python Imaging Library), or\nmxDateTime. (This would be called a package, except that term\nis already taken in the Python context: a single module distribution\nmay contain zero, one, or many Python packages.)\npure module distribution: a module distribution that contains only\npure Python modules and packages. Sometimes referred to as a ``pure\ndistribution.''\nnon-pure module distribution: a module distribution that contains\nat least one extension module. Sometimes referred to as a ``non-pure\ndistribution.''\ndistribution root: the top-level directory of your source tree (or\nsource distribution); the directory where setup.py exists and\nis run from", "python_version": "2.2", "length": 7372, "url": "https://docs.python.org/2.2/dist/simple-example.html"} {"title": "5 Creating a Source Distribution", "text": "setup-config.html | dist.html | creating-wininst.html | Distributing Python Modules\n---\n- 5.1 Specifying the files to distribute (#SECTION000510000000000000000)\n 5.2 Manifest-related options (#SECTION000520000000000000000)\n---\n# 5 Creating a Source Distribution\nAs shown in section 2.1 (simple-example.html#simple-example), you use the\n`sdist` command to create a source distribution. In the\nsimplest case,\n```text\n\npython setup.py sdist\n```\n(assuming you haven't specified any `sdist` options in the setup\nscript or config file), `sdist` creates the archive of the\ndefault format for the current platform. The default format is gzip'ed\ntar file (.tar.gz) on Unix, and ZIP file on Windows.\n** no MacOS support here **\nYou can specify as many formats as you like using the\n--formats option, for example:\n```text\n\npython setup.py sdist --formats=gztar,zip\n```\nto create a gzipped tarball and a zip file. The available formats are:\nNotes:\n(1): default on Windows\n(2): default on Unix\n(3): requires either external zip utility or\nzipfile module (not part of the standard Python library)\n(4): requires external utilities: tar and possibly one\nof gzip, bzip2, or compress\n## 5.1 Specifying the files to distribute\nIf you don't supply an explicit list of files (or instructions on how to\ngenerate one), the `sdist` command puts a minimal default set\ninto the source distribution:\n- all Python source files implied by the py_modules and\npackages options\n- all C source files mentioned in the ext_modules or\nlibraries options (** getting C library sources currently\nbroken - no get_source_files() method in build_clib.py! **)\n- anything that looks like a test script: test/test*.py\n(currently, the Distutils don't do anything with test scripts except\ninclude them in source distributions, but in the future there will be\na standard for testing Python module distributions)\n- README.txt (or README), setup.py (or whatever\nyou called your setup script), and setup.cfg\nSometimes this is enough, but usually you will want to specify\nadditional files to distribute. The typical way to do this is to write\na manifest template, called MANIFEST.in by default. The\nmanifest template is just a list of instructions for how to generate\nyour manifest file, MANIFEST, which is the exact list of files to\ninclude in your source distribution. The `sdist` command\nprocesses this template and generates a manifest based on its\ninstructions and what it finds in the filesystem.\nIf you prefer to roll your own manifest file, the format is simple: one\nfilename per line, regular files (or symlinks to them) only. If you do\nsupply your own MANIFEST, you must specify everything: the\ndefault set of files described above does not apply in this case.\nThe manifest template has one command per line, where each command\nspecifies a set of files to include or exclude from the source\ndistribution. For an example, again we turn to the Distutils' own\nmanifest template:\n```text\n\ninclude *.txt\nrecursive-include examples *.txt *.py\nprune examples/sample?/build\n```\nThe meanings should be fairly clear: include all files in the\ndistribution root matching `*.txt`, all files anywhere under the\nexamples directory matching `*.txt` or `*.py`, and\nexclude all directories matching `examples/sample?/build`. All of\nthis is done after the standard include set, so you can exclude\nfiles from the standard set with explicit instructions in the manifest\ntemplate. (Or, you can use the --no-defaults option to\ndisable the standard set entirely.) There are several other commands\navailable in the manifest template mini-language; see\nsection 7.2 (sdist-cmd.html#sdist-cmd).\nThe order of commands in the manifest template matters: initially, we\nhave the list of default files as described above, and each command in\nthe template adds to or removes from that list of files. Once we have\nfully processed the manifest template, we remove files that should not\nbe included in the source distribution:\n- all files in the Distutils ``build'' tree (default build/)\n- all files in directories named RCS or CVS\nNow we have our complete list of files, which is written to the manifest\nfor future reference, and then used to build the source distribution\narchive(s).\nYou can disable the default set of included files with the\n--no-defaults option, and you can disable the standard\nexclude set with --no-prune.\nFollowing the Distutils' own manifest template, let's trace how the\n`sdist` command builds the list of files to include in the\nDistutils source distribution:\n1. include all Python source files in the distutils and\ndistutils/command subdirectories (because packages\ncorresponding to those two directories were mentioned in the\npackages option in the setup script--see\nsection 3 (setup-script.html#setup-script))\n2. include README.txt, setup.py, and setup.cfg\n(standard files)\n3. include test/test*.py (standard files)\n4. include *.txt in the distribution root (this will find\nREADME.txt a second time, but such redundancies are weeded out\nlater)\n5. include anything matching *.txt or *.py in the\nsub-tree under examples,\n6. exclude all files in the sub-trees starting at directories\nmatching examples/sample?/build--this may exclude files\nincluded by the previous two steps, so it's important that the\n`prune` command in the manifest template comes after the\n`recursive-include` command\n7. exclude the entire build tree, and any RCS or\nCVS directories\nJust like in the setup script, file and directory names in the manifest\ntemplate should always be slash-separated; the Distutils will take care\nof converting them to the standard representation on your platform.\nThat way, the manifest template is portable across operating systems.\n## 5.2 Manifest-related options\nThe normal course of operations for the `sdist` command is as\nfollows:\n- if the manifest file, MANIFEST doesn't exist, read\nMANIFEST.in and create the manifest\n- if neither MANIFEST nor MANIFEST.in exist, create a\nmanifest with just the default file set3 (#foot691)\n- if either MANIFEST.in or the setup script (setup.py)\nare more recent than MANIFEST, recreate MANIFEST by\nreading MANIFEST.in\n- use the list of files now in MANIFEST (either just\ngenerated or read in) to create the source distribution archive(s)\nThere are a couple of options that modify this behaviour. First, use\nthe --no-defaults and --no-prune to\ndisable the standard ``include'' and ``exclude'' sets.4 (#foot692)\nSecond, you might want to force the manifest to be regenerated--for\nexample, if you have added or removed files or directories that match an\nexisting pattern in the manifest template, you should regenerate the\nmanifest:\n```text\n\npython setup.py sdist --force-manifest\n```\nOr, you might just want to (re)generate the manifest, but not create a\nsource distribution:\n```text\n\npython setup.py sdist --manifest-only\n```\n--manifest-only implies --force-manifest.\n-o is a shortcut for --manifest-only, and\n-f for --force-manifest.", "python_version": "2.2", "length": 6923, "url": "https://docs.python.org/2.2/dist/source-dist.html"} {"title": "About this document ...", "text": "discussion.html | doc.html | Documenting Python | contents.html\n---\n# About this document ...\nDocumenting Python,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ndiscussion.html | doc.html | Documenting Python | contents.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1662, "url": "https://docs.python.org/2.2/doc/about.html"} {"title": "5 Document Classes", "text": "latex-syntax.html | doc.html | special-constructs.html | Documenting Python | contents.html\n---\n# 5 Document Classes\nTwo LATEX document classes are defined specifically for use with\nthe Python documentation. The `manual` class is for large\ndocuments which are sectioned into chapters, and the `howto`\nclass is for smaller documents.\nThe `manual` documents are larger and are used for most of the\nstandard documents. This document class is based on the standard\nLATEX `report` class and is formatted very much like a long\ntechnical report. The Python Reference\nManual (../ref/ref.html) is a good example of a `manual` document, and the\nPython Library Reference (../lib/lib.html) is a large\nexample.\nThe `howto` documents are shorter, and don't have the large\nstructure of the `manual` documents. This class is based on\nthe standard LATEX `article` class and is formatted somewhat\nlike the Linux Documentation Project's ``HOWTO'' series as done\noriginally using the LinuxDoc software. The original intent for the\ndocument class was that it serve a similar role as the LDP's HOWTO\nseries, but the applicability of the class turns out to be somewhat\nbroader. This class is used for ``how-to'' documents (this\ndocument is an example) and for shorter reference manuals for small,\nfairly cohesive module libraries. Examples of the later use include\nUsing\nKerberos from Python (http://starship.python.net/crew/fdrake/manuals/krb5py/krb5py.html), which contains reference material for an\nextension package. These documents are roughly equivalent to a\nsingle chapter from a larger work.", "python_version": "2.2", "length": 1576, "url": "https://docs.python.org/2.2/doc/classes.html"} {"title": "Contents", "text": "doc.html | doc.html | intro.html | Documenting Python\n---\n## Contents\nTable of Contents\n- 1 Introduction (intro.html)\n 2 Directory Structure (directories.html)\n 3 Style Guide (style-guide.html)\n 4 LATEX Primer (latex-primer.html)\n - 4.1 Syntax (node6.html)\n 4.2 Hierarchical Structure (latex-syntax.html)\n 5 Document Classes (classes.html)\n 6 Special Markup Constructs (special-constructs.html)\n - 6.1 Markup for the Preamble (preamble-info.html)\n 6.2 Meta-information Markup (meta-info.html)\n 6.3 Information Units (info-units.html)\n 6.4 Showing Code Examples (showing-examples.html)\n 6.5 Inline Markup (inline-markup.html)\n 6.6 Miscellaneous Text Markup (misc-text-markup.html)\n 6.7 Module-specific Markup (module-markup.html)\n 6.8 Library-level Markup (library-markup.html)\n 6.9 Table Markup (table-markup.html)\n 6.10 Reference List Markup (references.html)\n 6.11 Index-generating Markup (indexing.html)\n 6.12 Grammar Production Displays (grammar-displays.html)\n 7 Graphical Interface Components (gui-markup.html)\n 8 Processing Tools (tools.html)\n - 8.1 External Tools (tools-external.html)\n 8.2 Internal Tools (tools-internal.html)\n 9 Future Directions (futures.html)\n - 9.1 Structured Documentation (structured.html)\n 9.2 Discussion Forums (discussion.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.2", "length": 1352, "url": "https://docs.python.org/2.2/doc/contents.html"} {"title": "2 Directory Structure", "text": "intro.html | doc.html | style-guide.html | Documenting Python | contents.html\n---\n# 2 Directory Structure\nThe source distribution for the standard Python documentation\ncontains a large number of directories. While third-party documents\ndo not need to be placed into this structure or need to be placed\nwithin a similar structure, it can be helpful to know where to look\nfor examples and tools when developing new documents using the\nPython documentation tools. This section describes this directory\nstructure.\nThe documentation sources are usually placed within the Python\nsource distribution as the top-level directory Doc/, but\nare not dependent on the Python source distribution in any way.\nThe Doc/ directory contains a few files and several\nsubdirectories. The files are mostly self-explanatory, including a\nREADME and a Makefile. The directories fall into\nthree categories:", "python_version": "2.2", "length": 879, "url": "https://docs.python.org/2.2/doc/directories.html"} {"title": "9.2 Discussion Forums", "text": "structured.html | futures.html | about.html | Documenting Python | contents.html\n---\n## 9.2 Discussion Forums\nDiscussion of the future of the Python documentation and related\ntopics takes place in the Documentation Special Interest Group, or\n``Doc-SIG.'' Information on the group, including mailing list\narchives and subscription information, is available at\nhttp://www.python.org/sigs/doc-sig/. The SIG is open to all\ninterested parties.\nComments and bug reports on the standard documents should be sent\nto python-docs@python.org. This may include comments\nabout formatting, content, grammatical and spelling errors, or\nthis document. You can also send comments on this document\ndirectly to the author at fdrake@acm.org.", "python_version": "2.2", "length": 721, "url": "https://docs.python.org/2.2/doc/discussion.html"} {"title": "Documenting Python", "text": "../index.html | contents.html | Documenting Python | contents.html\n---\n# Documenting Python\nFred L. Drake, Jr.\nPythonLabs\nEmail: fdrake@acm.org\nRelease 2.2\nDecember 21, 2001\n### Abstract:\nThe Python language has a substantial body of\ndocumentation, much of it contributed by various authors. The markup\nused for the Python documentation is based on LATEX and requires a\nsignificant set of macros written specifically for documenting Python.\nThis document describes the macros introduced to support Python\ndocumentation and how they should be used to support a wide range of\noutput formats.\nThis document describes the document classes and special markup used\nin the Python documentation. Authors may use this guide, in\nconjunction with the template files provided with the\ndistribution, to create or maintain whole documents or sections.", "python_version": "2.2", "length": 837, "url": "https://docs.python.org/2.2/doc/doc.html"} {"title": "9 Future Directions", "text": "tools-internal.html | doc.html | structured.html | Documenting Python | contents.html\n---\n# 9 Future Directions\nThe history of the Python documentation is full of changes, most of\nwhich have been fairly small and evolutionary. There has been a\ngreat deal of discussion about making large changes in the markup\nlanguages and tools used to process the documentation. This section\ndeals with the nature of the changes and what appears to be the most\nlikely path of future development.", "python_version": "2.2", "length": 481, "url": "https://docs.python.org/2.2/doc/futures.html"} {"title": "6.12 Grammar Production Displays", "text": "indexing.html | special-constructs.html | gui-markup.html | Documenting Python | contents.html\n---\n## 6.12 Grammar Production Displays\nSpecial markup is available for displaying the productions of a\nformal grammar. The markup is simple and does not attempt to\nmodel all aspects of BNF (or any derived forms), but provides\nenough to allow context-free grammars to be displayed in a way\nthat causes uses of a symbol to be rendered as hyperlinks to the\ndefinition of the symbol. There is one environment and a pair of\nmacros:\nNote that the entire grammar does not need to be defined in a\nsingle \\productionlist environment; any number of\ngroupings may be used to describe the grammar. Every use of the\n\\token must correspond to a \\production.\nThe following is an example taken from the\nPython Reference Manual (../ref/identifiers.html):\n```text\n\n\\begin{productionlist}\n\\production{identifier}\n{(\\token{letter}|\"_\") (\\token{letter} | \\token{digit} | \"_\")*}\n\\production{letter}\n{\\token{lowercase} | \\token{uppercase}}\n\\production{lowercase}\n{\"a\"...\"z\"}\n\\production{uppercase}\n{\"A\"...\"Z\"}\n\\production{digit}\n{\"0\"...\"9\"}\n\\end{productionlist}\n```", "python_version": "2.2", "length": 1138, "url": "https://docs.python.org/2.2/doc/grammar-displays.html"} {"title": "7 Graphical Interface Components", "text": "grammar-displays.html | doc.html | tools.html | Documenting Python | contents.html\n---\n# 7 Graphical Interface Components\nThe components of graphical interfaces will be assigned markup, but\nthe specifics have not been determined.", "python_version": "2.2", "length": 229, "url": "https://docs.python.org/2.2/doc/gui-markup.html"} {"title": "Documenting Python", "text": "../index.html | contents.html | Documenting Python | contents.html\n---\n# Documenting Python\nFred L. Drake, Jr.\nPythonLabs\nEmail: fdrake@acm.org\nRelease 2.2\nDecember 21, 2001\n### Abstract:\nThe Python language has a substantial body of\ndocumentation, much of it contributed by various authors. The markup\nused for the Python documentation is based on LATEX and requires a\nsignificant set of macros written specifically for documenting Python.\nThis document describes the macros introduced to support Python\ndocumentation and how they should be used to support a wide range of\noutput formats.\nThis document describes the document classes and special markup used\nin the Python documentation. Authors may use this guide, in\nconjunction with the template files provided with the\ndistribution, to create or maintain whole documents or sections.", "python_version": "2.2", "length": 837, "url": "https://docs.python.org/2.2/doc/index.html"} {"title": "6.11 Index-generating Markup", "text": "references.html | special-constructs.html | grammar-displays.html | Documenting Python | contents.html\n---\n## 6.11 Index-generating Markup\nEffective index generation for technical documents can be very\ndifficult, especially for someone familiar with the topic but not\nthe creation of indexes. Much of the difficulty arises in the\narea of terminology: including the terms an expert would use for a\nconcept is not sufficient. Coming up with the terms that a novice\nwould look up is fairly difficult for an author who, typically, is\nan expert in the area she is writing on.\nThe truly difficult aspects of index generation are not areas with\nwhich the documentation tools can help. However, ease\nof producing the index once content decisions are made is within\nthe scope of the tools. Markup is provided which the processing\nsoftware is able to use to generate a variety of kinds of index\nentry with minimal effort. Additionally, many of the environments\ndescribed in section 6.3 (info-units.html#info-units), ``Information Units,'' will\ngenerate appropriate entries into the general and module indexes.\nThe following macro can be used to control the generation of index\ndata, and should be used in the document preamble:\nThere are a number of macros that are useful for adding index\nentries for particular concepts, many of which are specific to\nprogramming languages or even Python.\nAdditional macros are provided which are useful for conveniently\ncreating general index entries which should appear at many places\nin the index by rotating a list of words. These are simple macros\nthat simply use \\index to build some number of index\nentries. Index entries build using these macros contain both\nprimary and secondary text.", "python_version": "2.2", "length": 1719, "url": "https://docs.python.org/2.2/doc/indexing.html"} {"title": "6.3 Information Units", "text": "meta-info.html | special-constructs.html | showing-examples.html | Documenting Python | contents.html\n---\n## 6.3 Information Units\nXXX Explain terminology, or come up with something more ``lay.''\nThere are a number of environments used to describe specific\nfeatures provided by modules. Each environment requires\nparameters needed to provide basic information about what is being\ndescribed, and the environment content should be the description.\nMost of these environments make entries in the general index (if\none is being produced for the document); if no index entry is\ndesired, non-indexing variants are available for many of these\nenvironments. The environments have names of the form\n`feature desc`, and the non-indexing variants are named\n`feature descni`. The available variants are explicitly\nincluded in the list below.\nFor each of these environments, the first parameter, name,\nprovides the name by which the feature is accessed.\nEnvironments which describe features of objects within a module,\nsuch as object methods or data attributes, allow an optional\ntype name parameter. When the feature is an attribute of\nclass instances, type name only needs to be given if the\nclass was not the most recently described class in the module; the\nname value from the most recent \\classdesc is implied.\nFor features of built-in or extension types, the type name\nvalue should always be provided. Another special case includes\nmethods and members of general ``protocols,'' such as the\nformatter and writer protocols described for the\nformatter module: these may be documented without any\nspecific implementation classes, and will always require the\ntype name parameter to be provided.", "python_version": "2.2", "length": 1682, "url": "https://docs.python.org/2.2/doc/info-units.html"} {"title": "6.5 Inline Markup", "text": "showing-examples.html | special-constructs.html | misc-text-markup.html | Documenting Python | contents.html\n---\n## 6.5 Inline Markup\nThe macros described in this section are used to mark just about\nanything interesting in the document text. They may be used in\nheadings (though anything involving hyperlinks should be avoided\nthere) as well as in the body text.", "python_version": "2.2", "length": 362, "url": "https://docs.python.org/2.2/doc/inline-markup.html"} {"title": "1 Introduction", "text": "contents.html | doc.html | directories.html | Documenting Python | contents.html\n---\n# 1 Introduction\nPython's documentation has long been considered to be good for a\nfree programming language. There are a number of reasons for this,\nthe most important being the early commitment of Python's creator,\nGuido van Rossum, to providing documentation on the language and its\nlibraries, and the continuing involvement of the user community in\nproviding assistance for creating and maintaining documentation.\nThe involvement of the community takes many forms, from authoring to\nbug reports to just plain complaining when the documentation could\nbe more complete or easier to use. All of these forms of input from\nthe community have proved useful during the time I've been involved\nin maintaining the documentation.\nThis document is aimed at authors and potential authors of\ndocumentation for Python. More specifically, it is for people\ncontributing to the standard documentation and developing additional\ndocuments using the same tools as the standard documents. This\nguide will be less useful for authors using the Python documentation\ntools for topics other than Python, and less useful still for\nauthors not using the tools at all.\nThe material in this guide is intended to assist authors using the\nPython documentation tools. It includes information on the source\ndistribution of the standard documentation, a discussion of the\ndocument types, reference material on the markup defined in the\ndocument classes, a list of the external tools needed for processing\ndocuments, and reference material on the tools provided with the\ndocumentation resources. At the end, there is also a section\ndiscussing future directions for the Python documentation and where\nto turn for more information.", "python_version": "2.2", "length": 1781, "url": "https://docs.python.org/2.2/doc/intro.html"} {"title": "4 LATEX Primer", "text": "style-guide.html | doc.html | node6.html | Documenting Python | contents.html\n---\n# 4 LATEX Primer\nThis section is a brief introduction to LATEX concepts and\nsyntax, to provide authors enough information to author documents\nproductively without having to become ``TEXnicians.''\nPerhaps the most important concept to keep in mind while marking up\nPython documentation is that while TEX is unstructured, LATEX was\ndesigned as a layer on top of TEX which specifically supports\nstructured markup. The Python-specific markup is intended to extend\nthe structure provided by standard LATEX document classes to\nsupport additional information specific to Python.\nLATEX documents contain two parts: the preamble and the body.\nThe preamble is used to specify certain metadata about the document\nitself, such as the title, the list of authors, the date, and the\nclass the document belongs to. Additional information used\nto control index generation and the use of bibliographic databases\ncan also be placed in the preamble. For most authors, the preamble\ncan be most easily created by copying it from an existing document\nand modifying a few key pieces of information.\nThe class of a document is used to place a document within a\nbroad category of documents and set some fundamental formatting\nproperties. For Python documentation, two classes are used: the\n`manual` class and the `howto` class. These classes also\ndefine the additional markup used to document Python concepts and\nstructures. Specific information about these classes is provided in\nsection 5 (classes.html#classes), ``Document Classes,'' below. The first thing\nin the preamble is the declaration of the document's class.\nAfter the class declaration, a number of macros are used to\nprovide further information about the document and setup any\nadditional markup that is needed. No output is generated from the\npreamble; it is an error to include free text in the preamble\nbecause it would cause output.\nThe document body follows the preamble. This contains all the\nprinted components of the document marked up structurally. Generic\nLATEX structures include hierarchical sections, numbered and\nbulleted lists, and special structures for the document abstract and\nindexes.", "python_version": "2.2", "length": 2223, "url": "https://docs.python.org/2.2/doc/latex-primer.html"} {"title": "4.2 Hierarchical Structure", "text": "node6.html | latex-primer.html | classes.html | Documenting Python | contents.html\n---\n## 4.2 Hierarchical Structure\nLATEX expects documents to be arranged in a conventional,\nhierarchical way, with chapters, sections, sub-sections,\nappendixes, and the like. These are marked using macros rather\nthan environments, probably because the end of a section can be\nsafely inferred when a section of equal or higher level starts.\nThere are six ``levels'' of sectioning in the document classes\nused for Python documentation, and the deepest two\nlevels1 (#foot167) are not used. The levels are:\nNotes:\n(1): Only used for the `manual` documents, as described in\nsection 5 (classes.html#classes), ``Document Classes.''\n(2): Not the same as a paragraph of text; nobody seems to use this.", "python_version": "2.2", "length": 775, "url": "https://docs.python.org/2.2/doc/latex-syntax.html"} {"title": "6.8 Library-level Markup", "text": "module-markup.html | special-constructs.html | table-markup.html | Documenting Python | contents.html\n---\n## 6.8 Library-level Markup\nThis markup is used when describing a selection of modules. For\nexample, the Macintosh Library\nModules (../mac/mac.html) document uses this to help provide an overview of the\nmodules in the collection, and many chapters in the\nPython Library Reference (../lib/lib.html) use it for\nthe same purpose.", "python_version": "2.2", "length": 432, "url": "https://docs.python.org/2.2/doc/library-markup.html"} {"title": "6.2 Meta-information Markup", "text": "preamble-info.html | special-constructs.html | info-units.html | Documenting Python | contents.html\n---\n## 6.2 Meta-information Markup", "python_version": "2.2", "length": 134, "url": "https://docs.python.org/2.2/doc/meta-info.html"} {"title": "6.6 Miscellaneous Text Markup", "text": "inline-markup.html | special-constructs.html | module-markup.html | Documenting Python | contents.html\n---\n## 6.6 Miscellaneous Text Markup\nIn addition to the inline markup, some additional ``block'' markup\nis defined to make it easier to bring attention to various bits of\ntext. The markup described here serves this purpose, and is\nintended to be used when marking one or more paragraphs or other\nblock constructs (such as \\verbatim environments).", "python_version": "2.2", "length": 449, "url": "https://docs.python.org/2.2/doc/misc-text-markup.html"} {"title": "6.7 Module-specific Markup", "text": "misc-text-markup.html | special-constructs.html | library-markup.html | Documenting Python | contents.html\n---\n## 6.7 Module-specific Markup\nThe markup described in this section is used to provide information\nabout a module being documented. A typical use of this markup\nappears at the top of the section used to document a module. A\ntypical example might look like this:\n```text\n\n\\section{\\module{spam} ---\nAccess to the SPAM facility}\n\n\\declaremodule{extension}{spam}\n\\platform{Unix}\n\\modulesynopsis{Access to the SPAM facility of \\UNIX.}\n\\moduleauthor{Jane Doe}{jane.doe@frobnitz.org}\n```\nPython packages-- collections of modules that can\nbe described as a unit -- are documented using the same markup as\nmodules. The name for a module in a package should be typed in\n``fully qualified'' form (it should include the package name).\nFor example, a module ``foo'' in package ``bar'' should be marked as\n`\\module{bar.foo}`, and the beginning of the reference\nsection would appear as:\n```text\n\n\\section{\\module{bar.foo} ---\nModule from the \\module{bar} package}\n\n\\declaremodule{extension}{bar.foo}\n\\modulesynopsis{Nifty module from the \\module{bar} package.}\n\\moduleauthor{Jane Doe}{jane.doe@frobnitz.org}\n```\nNote that the name of a package is also marked using\n\\module.", "python_version": "2.2", "length": 1269, "url": "https://docs.python.org/2.2/doc/module-markup.html"} {"title": "5.4 Showing Code Examples", "text": "info-units.html | node8.html | node13.html | Documenting Python | contents.html\n---\n## 5.4 Showing Code Examples\nExamples of Python source code or interactive sessions are\nrepresented as \\verbatim environments. This environment\nis a standard part of LATEX. It is important to only use\nspaces for indentation in code examples since TEX drops tabs\ninstead of converting them to spaces.\nRepresenting an interactive session requires including the prompts\nand output along with the Python code. No special markup is\nrequired for interactive sessions. After the last line of input\nor output presented, there should not be an ``unused'' primary\nprompt; this is an example of what not to do:\n```text\n\n>>> 1 + 1\n2\n>>>\n```\nWithin the \\verbatim environment, characters special to\nLATEX do not need to be specially marked in any way. The entire\nexample will be presented in a monospaced font; no attempt at\n``pretty-printing'' is made, as the environment must work for\nnon-Python code and non-code displays. There should be no blank\nlines at the top or bottom of any \\verbatim display.\nThe Python Documentation Special Interest Group has discussed a\nnumber of approaches to creating pretty-printed code displays and\ninteractive sessions; see the Doc-SIG area on the Python Web site\nfor more information on this topic.", "python_version": "2.2", "length": 1305, "url": "https://docs.python.org/2.2/doc/node12.html"} {"title": "5.5 Inline Markup", "text": "node12.html | node8.html | node14.html | Documenting Python | contents.html\n---\n## 5.5 Inline Markup\nThe macros described in this section are used to mark just about\nanything interesting in the document text. They may be used in\nheadings (though anything involving hyperlinks should be avoided\nthere) as well as in the body text.", "python_version": "2.2", "length": 329, "url": "https://docs.python.org/2.2/doc/node13.html"} {"title": "5.6 Module-specific Markup", "text": "node13.html | node8.html | node15.html | Documenting Python | contents.html\n---\n## 5.6 Module-specific Markup\nThe markup described in this section is used to provide information\nabout a module being documented. A typical use of this markup\nappears at the top of the section used to document a module. A\ntypical example might look like this:\n```text\n\n\\section{\\module{spam} ---\nAccess to the SPAM facility}\n\n\\declaremodule{extension}{spam}\n\\platform{Unix}\n\\modulesynopsis{Access to the SPAM facility of \\UNIX{}.}\n\\moduleauthor{Jane Doe}{jane.doe@frobnitz.org}\n```\nPython packages-- collections of modules that can\nbe described as a unit -- are documented using the same markup as\nmodules. The name for a module in a package should be typed in\n``fully qualified'' form (i.e., it should include the package name).\nFor example, a module ``foo'' in package ``bar'' should be marked as\n\"\\module{bar.foo}\", and the beginning of the reference\nsection would appear as:\n```text\n\n\\section{\\module{bar.foo} ---\nModule from the \\module{bar} package}\n\n\\declaremodule{extension}{bar.foo}\n\\modulesynopsis{Nifty module from the \\module{bar} package.}\n\\moduleauthor{Jane Doe}{jane.doe@frobnitz.org}\n```\nNote that the name of a package is also marked using\n\\module.", "python_version": "2.2", "length": 1246, "url": "https://docs.python.org/2.2/doc/node14.html"} {"title": "5.7 Library-level Markup", "text": "node14.html | node8.html | node16.html | Documenting Python | contents.html\n---\n## 5.7 Library-level Markup\nThis markup is used when describing a selection of modules. For\nexample, the Macintosh Library\nModules (../mac/mac.html) document uses this to help provide an overview of the\nmodules in the collection, and many chapters in the\nPython Library Reference (../lib/lib.html) use it for\nthe same purpose.", "python_version": "2.2", "length": 406, "url": "https://docs.python.org/2.2/doc/node15.html"} {"title": "5.8 Table Markup", "text": "node15.html | node8.html | references.html | Documenting Python | contents.html\n---\n## 5.8 Table Markup\nThere are three general-purpose table environments defined which\nshould be used whenever possible. These environments are defined\nto provide tables of specific widths and some convenience for\nformatting. These environments are not meant to be general\nreplacements for the standard LATEX table environments, but can\nbe used for an advantage when the documents are processed using\nthe tools for Python documentation processing. In particular, the\ngenerated HTML looks good! There is also an advantage for the\neventual conversion of the documentation to SGML (see section\n8 (futures.html#futures), ``Future Directions'').\nEach environment is named \\tablecols, where cols\nis the number of columns in the table specified in lower-case\nRoman numerals. Within each of these environments, an additional\nmacro, \\linecols, is defined, where cols\nmatches the cols value of the corresponding table\nenvironment. These are supported for cols values of\n`ii`, `iii`, and `iv`. These environments are all\nbuilt on top of the \\tabular environment. Variants based on\nthe \\longtable environment are also provided.\nNote that all tables in the standard Python documentation use\nvertical lines between columns, and this must be specified in the\nmarkup for each table. A general border around the outside of the\ntable is not used, but would be the responsibility of the\nprocessor; the document markup should not include an exterior\nborder.\nThe \\longtable-based variants of the table environments are\nformatted with extra space before and after, so should only be\nused on tables which are long enough that splitting over multiple\npages is reasonable; tables with fewer than twenty rows should\nnever by marked using the long flavors of the table environments.\nThe header row is repeated across the top of each part of the\ntable.\nAn additional table-like environment is \\synopsistable. The\ntable generated by this environment contains two columns, and each\nrow is defined by an alternate definition of\n\\modulesynopsis. This environment is not normally used by\nauthors, but is created by the \\localmoduletable macro.", "python_version": "2.2", "length": 2192, "url": "https://docs.python.org/2.2/doc/node16.html"} {"title": "6 Special Names", "text": "indexing.html | doc.html | node20.html | Documenting Python | contents.html\n---\n# 6 Special Names\nMany special names are used in the Python documentation, including\nthe names of operating systems, programming languages, standards\nbodies, and the like. Many of these were assigned LATEX macros\nat some point in the distant past, and these macros lived on long\npast their usefulness. In the current markup, these entities are\nnot assigned any special markup, but the preferred spellings are\ngiven here to aid authors in maintaining the consistency of\npresentation in the Python documentation.\nPOSIX: The name assigned to a particular group of standards. This is\nalways uppercase.\nPython: The name of our favorite programming language is always\ncapitalized.\nUnicode: The name of a character set and matching encoding. This is\nalways written capitalized.", "python_version": "2.2", "length": 850, "url": "https://docs.python.org/2.2/doc/node19.html"} {"title": "1 Introduction", "text": "contents.html | doc.html | node3.html | Documenting Python | contents.html\n---\n# 1 Introduction\nPython's documentation has long been considered to be good for a\nfree programming language. There are a number of reasons for this,\nthe most important being the early commitment of Python's creator,\nGuido van Rossum, to providing documentation on the language and its\nlibraries, and the continuing involvement of the user community in\nproviding assistance for creating and maintaining documentation.\nThe involvement of the community takes many forms, from authoring to\nbug reports to just plain complaining when the documentation could\nbe more complete or easier to use. All of these forms of input from\nthe community have proved useful during the time I've been involved\nin maintaining the documentation.\nThis document is aimed at authors and potential authors of\ndocumentation for Python. More specifically, it is for people\ncontributing to the standard documentation and developing additional\ndocuments using the same tools as the standard documents. This\nguide will be less useful for authors using the Python documentation\ntools for topics other than Python, and less useful still for\nauthors not using the tools at all.\nThe material in this guide is intended to assist authors using the\nPython documentation tools. It includes information on the source\ndistribution of the standard documentation, a discussion of the\ndocument types, reference material on the markup defined in the\ndocument classes, a list of the external tools needed for processing\ndocuments, and reference material on the tools provided with the\ndocumentation resources. At the end, there is also a section\ndiscussing future directions for the Python documentation and where\nto turn for more information.", "python_version": "2.2", "length": 1775, "url": "https://docs.python.org/2.2/doc/node2.html"} {"title": "7 Processing Tools", "text": "node19.html | doc.html | node21.html | Documenting Python | contents.html\n---\n# 7 Processing Tools", "python_version": "2.2", "length": 98, "url": "https://docs.python.org/2.2/doc/node20.html"} {"title": "7.1 External Tools", "text": "node20.html | node20.html | node22.html | Documenting Python | contents.html\n---\n## 7.1 External Tools\nMany tools are needed to be able to process the Python\ndocumentation if all supported formats are required. This\nsection lists the tools used and when each is required. Consult\nthe Doc/README file to see if there are specific version\nrequirements for any of these.\ndvips: This program is a typical part of TEX installations. It is\nused to generate PostScript from the ``device independent''\n.dvi files. It is needed for the conversion to\nPostScript.\nemacs: Emacs is the kitchen sink of programmers' editors, and a damn\nfine kitchen sink it is. It also comes with some of the\nprocessing needed to support the proper menu structures for\nTexinfo documents when an info conversion is desired. This is\nneeded for the info conversion. Using xemacs\ninstead of FSF emacs may lead to instability in the\nconversion, but that's because nobody seems to maintain the\nEmacs Texinfo code in a portable manner.\nlatex: This is a world-class typesetter by Donald Knuth. It is used\nfor the conversion to PostScript, and is needed for the HTML\nconversion as well (LATEX2HTML requires one of the\nintermediate files it creates).\nlatex2html: Probably the longest Perl script anyone ever attempted to\nmaintain. This converts LATEX documents to HTML documents,\nand does a pretty reasonable job. It is required for the\nconversions to HTML and GNU info.\nlynx: This is a text-mode Web browser which includes an\nHTML-to-plain text conversion. This is used to convert\n`howto` documents to text.\nmake: Just about any version should work for the standard documents,\nbut GNU make is required for the experimental\nprocesses in Doc/tools/sgmlconv/, at least while\nthey're experimental.\nmakeindex: This is a standard program for converting LATEX index data\nto a formatted index; it should be included with all LATEX\ninstallations. It is needed for the PDF and PostScript\nconversions.\nmakeinfo: GNU makeinfo is used to convert Texinfo documents to\nGNU info files. Since Texinfo is used as an intermediate\nformat in the info conversion, this program is needed in that\nconversion.\npdflatex: pdfTEX is a relatively new variant of TEX, and is used to\ngenerate the PDF version of the manuals. It is typically\ninstalled as part of most of the large TEX distributions.\npdflatex is pdfTEX using the LATEX format.\nperl: Perl is required for LATEX2HTML and one of the scripts used\nto post-process LATEX2HTML output, as well as the\nHTML-to-Texinfo conversion. This is required for\nthe HTML and GNU info conversions.\npython: Python is used for many of the scripts in the\nDoc/tools/ directory; it is required for all\nconversions. This shouldn't be a problem if you're interested\nin writing documentation for Python!", "python_version": "2.2", "length": 2768, "url": "https://docs.python.org/2.2/doc/node21.html"} {"title": "7.2 Internal Tools", "text": "node21.html | node20.html | futures.html | Documenting Python | contents.html\n---\n## 7.2 Internal Tools\nThis section describes the various scripts that are used to\nimplement various stages of document processing or to orchestrate\nentire build sequences. Most of these tools are only useful\nin the context of building the standard documentation, but some\nare more general.\nmkhowto: This is the primary script used to format third-party\ndocuments. It contains all the logic needed to ``get it\nright.'' The proper way to use this script is to make a\nsymbolic link to it or run it in place; the actual script file\nmust be stored as part of the documentation source tree,\nthough it may be used to format documents outside the\ntree. Use mkhowto --help\nfor a list of\ncommand line options.\nmkhowto can be used for both `howto` and\n`manual` class documents. (For the later, be sure to get\nthe latest version from the Python CVS repository rather than\nthe version distributed in the latex-1.5.2.tgz source\narchive.)\nXXX Need more here.", "python_version": "2.2", "length": 1025, "url": "https://docs.python.org/2.2/doc/node22.html"} {"title": "2 Directory Structure", "text": "node2.html | doc.html | latex-primer.html | Documenting Python | contents.html\n---\n# 2 Directory Structure\nThe source distribution for the standard Python documentation\ncontains a large number of directories. While third-party documents\ndo not need to be placed into this structure or need to be placed\nwithin a similar structure, it can be helpful to know where to look\nfor examples and tools when developing new documents using the\nPython documentation tools. This section describes this directory\nstructure.\nThe documentation sources are usually placed within the Python\nsource distribution as the top-level directory Doc/, but\nare not dependent on the Python source distribution in any way.\nThe Doc/ directory contains a few files and several\nsubdirectories. The files are mostly self-explanatory, including a\nREADME and a Makefile. The directories fall into\nthree categories:", "python_version": "2.2", "length": 880, "url": "https://docs.python.org/2.2/doc/node3.html"} {"title": "3.1 Syntax", "text": "latex-primer.html | latex-primer.html | node6.html | Documenting Python | contents.html\n---\n## 3.1 Syntax\nThere are a things that an author of Python documentation needs to\nknow about LATEX syntax.\nA comment is started by the ``percent'' character\n(\"%\") and continues through the end of the line and all\nleading whitespace on the following line. This is a little\ndifferent from any programming language I know of, so an example\nis in order:\n```text\n\nThis is text.% comment\nThis is more text. % another comment\nStill more text.\n```\nThe first non-comment character following the first comment is the\nletter \"T\" on the second line; the leading whitespace on\nthat line is consumed as part of the first comment. This means\nthat there is no space between the first and second sentences, so\nthe period and letter \"T\" will be directly adjacent in\nthe typeset document.\nNote also that though the first non-comment character after the\nsecond comment is the letter \"S\", there is whitespace\npreceding the comment, so the two sentences are separated as\nexpected.\nA group is an enclosure for a collection of text and\ncommands which encloses the formatting context and constrains the\nscope of any changes to that context made by commands within the\ngroup. Groups can be nested hierarchically. The formatting\ncontext includes the font and the definition of additional macros\n(or overrides of macros defined in outer groups). Syntactically,\ngroups are enclosed in braces:\n```text\n\n{text in a group}\n```\nAn alternate syntax for a group using brackets (`[...]`) is\nused by macros and environment constructors which take optional\nparameters; brackets do not normally hold syntactic significance.\nA degenerate group, containing only one atomic bit of content,\ndoes not need to have an explicit group, unless it is required to\navoid ambiguity. Since Python tends toward the explicit, groups\nare also made explicit in the documentation markup.\nGroups are used only sparingly in the Python documentation, except\nfor their use in marking parameters to macros and environments.\nA macro is usually simple construct which is identified by\nname and can take some number of parameters. In normal LATEX\nusage, one of these can be optional. The markup is introduced\nusing the backslash character (\"\\\"), and the name is\ngiven by alphabetic characters (no digits, hyphens, or\nunderscores). Required parameters should be marked as a group,\nand optional parameters should be marked using the alternate\nsyntax for a group.\nFor example, a macro named ``foo'' which takes a single parameter\nwould appear like this:\n```text\n\n\\name{parameter}\n```\nA macro which takes an optional parameter would be typed like this\nwhen the optional paramter is given:\n```text\n\n\\name[optional]\n```\nIf both optional and required parameters are to be required, it\nlooks like this:\n```text\n\n\\name[optional]{required}\n```\nA macro name may be followed by a space or newline; a space\nbetween the macro name and any parameters will be consumed, but\nthis usage is not practiced in the Python documentation. Such a\nspace is still consumed if there are no parameters to the marco,\nin which case inserting an empty group (`{}`) or explicit\nword space (\"\\ \") immediately after the macro name helps to\navoid running the expansion of the macro into the following text.\nMacros which take no parameters but which should not be followed\nby a word space do not need special treatment if the following\ncharacter in the document source if not a name character (such as\npuctuation).\nEach line of this example shows an appropriate way to write text\nwhich includes a macro which takes no parameters:\n```text\n\nThis \\UNIX{} is followed by a space.\nThis \\UNIX\\ is also followed by a space.\n\\UNIX, followed by a comma, needs no additional markup.\n```\nAn environment is a larger construct than a macro, and can\nbe used for things with more content that would conveniently fit\nin a macro parameter. They are primarily used when formatting\nparameters need to be changed before and after a large chunk of\ncontent, but the content itself needs to be highly flexible. Code\nsamples are presented using an environment, and descriptions of\nfunctions, methods, and classes are also marked using envionments.\nSince the content of an environment is free-form and can consist\nof several paragraphs, they are actually marked using a pair of\nmacros: \\begin and \\end. These macros both take the\nname of the environment as a parameter. An example is the\nenvironment used to mark the abstract of a document:\n```text\n\n\\begin{abstract}\nThis is the text of the abstract. It concisely explains what\ninformation is found in the document.\n\nIt can consist of multiple paragraphs.\n\\end{abstract}\n```\nAn environment can also have required and optional parameters of\nits own. These follow the parameter of the \\begin macro.\nThis example shows an environment which takes a single required\nparameter:\n```text\n\n\\begin{datadesc}{controlnames}\nA 33-element string array that contains the \\ASCII{} mnemonics for\nthe thirty-two \\ASCII{} control characters from 0 (NUL) to 0x1f\n(US), in order, plus the mnemonic \\samp{SP} for the space character.\n\\end{datadesc}\n```\nThere are a number of less-used marks in LATEX are used to\nenter non-ASCII characters, especially those used in European\nnames. Given that these are often used adjacent to other\ncharacters, the markup required to produce the proper character\nmay need to be followed by a space or an empty group, or the the\nmarkup can be enclosed in a group. Some which are found in Python\ndocumentation are:", "python_version": "2.2", "length": 5535, "url": "https://docs.python.org/2.2/doc/node5.html"} {"title": "4.1 Syntax", "text": "latex-primer.html | latex-primer.html | latex-syntax.html | Documenting Python | contents.html\n---\n## 4.1 Syntax\nThere are some things that an author of Python documentation needs\nto know about LATEX syntax.\nA comment is started by the ``percent'' character\n(\"%\") and continues through the end of the line and all\nleading whitespace on the following line. This is a little\ndifferent from any programming language I know of, so an example\nis in order:\n```text\n\nThis is text.% comment\nThis is more text. % another comment\nStill more text.\n```\nThe first non-comment character following the first comment is the\nletter \"T\" on the second line; the leading whitespace on\nthat line is consumed as part of the first comment. This means\nthat there is no space between the first and second sentences, so\nthe period and letter \"T\" will be directly adjacent in\nthe typeset document.\nNote also that though the first non-comment character after the\nsecond comment is the letter \"S\", there is whitespace\npreceding the comment, so the two sentences are separated as\nexpected.\nA group is an enclosure for a collection of text and\ncommands which encloses the formatting context and constrains the\nscope of any changes to that context made by commands within the\ngroup. Groups can be nested hierarchically. The formatting\ncontext includes the font and the definition of additional macros\n(or overrides of macros defined in outer groups). Syntactically,\ngroups are enclosed in braces:\n```text\n\n{text in a group}\n```\nAn alternate syntax for a group using brackets, `[...]`, is\nused by macros and environment constructors which take optional\nparameters; brackets do not normally hold syntactic significance.\nA degenerate group, containing only one atomic bit of content,\ndoes not need to have an explicit group, unless it is required to\navoid ambiguity. Since Python tends toward the explicit, groups\nare also made explicit in the documentation markup.\nGroups are used only sparingly in the Python documentation, except\nfor their use in marking parameters to macros and environments.\nA macro is usually a simple construct which is identified by\nname and can take some number of parameters. In normal LATEX\nusage, one of these can be optional. The markup is introduced\nusing the backslash character (\"\\\"), and the name is\ngiven by alphabetic characters (no digits, hyphens, or\nunderscores). Required parameters should be marked as a group,\nand optional parameters should be marked using the alternate\nsyntax for a group.\nFor example, a macro named ``foo'' which takes a single parameter\nwould appear like this:\n```text\n\n\\name{parameter}\n```\nA macro which takes an optional parameter would be typed like this\nwhen the optional paramter is given:\n```text\n\n\\name[optional]\n```\nIf both optional and required parameters are to be required, it\nlooks like this:\n```text\n\n\\name[optional]{required}\n```\nA macro name may be followed by a space or newline; a space\nbetween the macro name and any parameters will be consumed, but\nthis usage is not practiced in the Python documentation. Such a\nspace is still consumed if there are no parameters to the macro,\nin which case inserting an empty group (`{}`) or explicit\nword space (\"\\ \") immediately after the macro name helps to\navoid running the expansion of the macro into the following text.\nMacros which take no parameters but which should not be followed\nby a word space do not need special treatment if the following\ncharacter in the document source if not a name character (such as\npunctuation).\nEach line of this example shows an appropriate way to write text\nwhich includes a macro which takes no parameters:\n```text\n\nThis \\UNIX{} is followed by a space.\nThis \\UNIX\\ is also followed by a space.\n\\UNIX, followed by a comma, needs no additional markup.\n```\nAn environment is a larger construct than a macro, and can\nbe used for things with more content than would conveniently fit\nin a macro parameter. They are primarily used when formatting\nparameters need to be changed before and after a large chunk of\ncontent, but the content itself needs to be highly flexible. Code\nsamples are presented using an environment, and descriptions of\nfunctions, methods, and classes are also marked using environments.\nSince the content of an environment is free-form and can consist\nof several paragraphs, they are actually marked using a pair of\nmacros: \\begin and \\end. These macros both take the\nname of the environment as a parameter. An example is the\nenvironment used to mark the abstract of a document:\n```text\n\n\\begin{abstract}\nThis is the text of the abstract. It concisely explains what\ninformation is found in the document.\n\nIt can consist of multiple paragraphs.\n\\end{abstract}\n```\nAn environment can also have required and optional parameters of\nits own. These follow the parameter of the \\begin macro.\nThis example shows an environment which takes a single required\nparameter:\n```text\n\n\\begin{datadesc}{controlnames}\nA 33-element string array that contains the \\ASCII{} mnemonics for\nthe thirty-two \\ASCII{} control characters from 0 (NUL) to 0x1f\n(US), in order, plus the mnemonic \\samp{SP} for the space character.\n\\end{datadesc}\n```\nThere are a number of less-used marks in LATEX which are used\nto enter non-ASCII characters, especially those used in\nEuropean names. Given that these are often used adjacent to other\ncharacters, the markup required to produce the proper character\nmay need to be followed by a space or an empty group, or the\nmarkup can be enclosed in a group. Some which are found in Python\ndocumentation are:", "python_version": "2.2", "length": 5551, "url": "https://docs.python.org/2.2/doc/node6.html"} {"title": "5 Special Markup Constructs", "text": "classes.html | doc.html | preamble-info.html | Documenting Python | contents.html\n---\n# 5 Special Markup Constructs\nThe Python document classes define a lot of new environments and\nmacros. This section contains the reference material for these\nfacilities.", "python_version": "2.2", "length": 255, "url": "https://docs.python.org/2.2/doc/node8.html"} {"title": "6.1 Markup for the Preamble", "text": "special-constructs.html | special-constructs.html | meta-info.html | Documenting Python | contents.html\n---\n## 6.1 Markup for the Preamble", "python_version": "2.2", "length": 138, "url": "https://docs.python.org/2.2/doc/preamble-info.html"} {"title": "6.10 Reference List Markup", "text": "table-markup.html | special-constructs.html | indexing.html | Documenting Python | contents.html\n---\n## 6.10 Reference List Markup\nMany sections include a list of references to module documentation\nor external documents. These lists are created using the\n\\seealso or \\seealso* environments. These environments\ndefine some additional macros to support creating reference\nentries in a reasonable manner.\nThe \\seealso environment is typically placed in a section\njust before any sub-sections. This is done to ensure that\nreference links related to the section are not hidden in a\nsubsection in the hypertext renditions of the documentation. For\nthe HTML output, it is shown as a ``side bar,'' boxed off from the\nmain flow of the text. The \\seealso* environment is\ndifferent in that it should be used when a list of references is\nbeing presented as part of the primary content; it is not\nspecially set off from the text.\nFor each of the following macros, why should be one or more\ncomplete sentences, starting with a capital letter (unless it\nstarts with an identifier, which should not be modified), and\nending with the apropriate punctuation.\nThese macros are only defined within the content of the\n\\seealso and \\seealso* environments.", "python_version": "2.2", "length": 1233, "url": "https://docs.python.org/2.2/doc/references.html"} {"title": "6.4 Showing Code Examples", "text": "info-units.html | special-constructs.html | inline-markup.html | Documenting Python | contents.html\n---\n## 6.4 Showing Code Examples\nExamples of Python source code or interactive sessions are\nrepresented as \\verbatim environments. This environment\nis a standard part of LATEX. It is important to only use\nspaces for indentation in code examples since TEX drops tabs\ninstead of converting them to spaces.\nRepresenting an interactive session requires including the prompts\nand output along with the Python code. No special markup is\nrequired for interactive sessions. After the last line of input\nor output presented, there should not be an ``unused'' primary\nprompt; this is an example of what not to do:\n```text\n\n>>> 1 + 1\n2\n>>>\n```\nWithin the \\verbatim environment, characters special to\nLATEX do not need to be specially marked in any way. The entire\nexample will be presented in a monospaced font; no attempt at\n``pretty-printing'' is made, as the environment must work for\nnon-Python code and non-code displays. There should be no blank\nlines at the top or bottom of any \\verbatim display.\nLonger displays of verbatim text may be included by storing the\nexample text in an external file containing only plain text. The\nfile may be included using the standard \\verbatiminput\nmacro; this macro takes a single argument naming the file\ncontaining the text. For example, to include the Python source\nfile example.py, use:\n```text\n\n\\verbatiminput{example.py}\n```\nUse of \\verbatiminput allows easier use of special editing\nmodes for the included file. The file should be placed in the\nsame directory as the LATEX files for the document.\nThe Python Documentation Special Interest Group has discussed a\nnumber of approaches to creating pretty-printed code displays and\ninteractive sessions; see the Doc-SIG area on the Python Web site\nfor more information on this topic.", "python_version": "2.2", "length": 1865, "url": "https://docs.python.org/2.2/doc/showing-examples.html"} {"title": "6 Special Markup Constructs", "text": "classes.html | doc.html | preamble-info.html | Documenting Python | contents.html\n---\n# 6 Special Markup Constructs\nThe Python document classes define a lot of new environments and\nmacros. This section contains the reference material for these\nfacilities.", "python_version": "2.2", "length": 255, "url": "https://docs.python.org/2.2/doc/special-constructs.html"} {"title": "9.1 Structured Documentation", "text": "futures.html | futures.html | discussion.html | Documenting Python | contents.html\n---\n## 9.1 Structured Documentation\nMost of the small changes to the LATEX markup have been made\nwith an eye to divorcing the markup from the presentation, making\nboth a bit more maintainable. Over the course of 1998, a large\nnumber of changes were made with exactly this in mind; previously,\nchanges had been made but in a less systematic manner and with\nmore concern for not needing to update the existing content. The\nresult has been a highly structured and semantically loaded markup\nlanguage implemented in LATEX. With almost no basic TEX or\nLATEX markup in use, however, the markup syntax is about the\nonly evidence of LATEX in the actual document sources.\nOne side effect of this is that while we've been able to use\nstandard ``engines'' for manipulating the documents, such as\nLATEX and LATEX2HTML, most of the actual transformations have\nbeen created specifically for Python. The LATEX document\nclasses and LATEX2HTML support are both complete implementations\nof the specific markup designed for these documents.\nCombining highly customized markup with the somewhat esoteric\nsystems used to process the documents leads us to ask some\nquestions: Can we do this more easily? and, Can we do this\nbetter? After a great deal of discussion with the community, we\nhave determined that actively pursuing modern structured\ndocumentation systems is worth some investment of time.\nThere appear to be two real contenders in this arena: the Standard\nGeneral Markup Language (SGML), and the Extensible Markup Language\n(XML). Both of these standards have advantages and disadvantages,\nand many advantages are shared.\nSGML offers advantages which may appeal most to authors,\nespecially those using ordinary text editors. There are also\nadditional abilities to define content models. A number of\nhigh-quality tools with demonstrated maturity are available, but\nmost are not free; for those which are, portability issues remain\na problem.\nThe advantages of XML include the availability of a large number\nof evolving tools. Unfortunately, many of the associated\nstandards are still evolving, and the tools will have to follow\nalong. This means that developing a robust tool set that uses\nmore than the basic XML 1.0 recommendation is not possible in the\nshort term. The promised availability of a wide variety of\nhigh-quality tools which support some of the most important\nrelated standards is not immediate. Many tools are likely to be\nfree, and the portability issues of those which are, are not\nexpected to be significant.\nIt turns out that converting to an XML or SGML system holds\npromise for translators as well; how much can be done to ease the\nburden on translators remains to be seen, and may have some impact\non the schema and specific technologies used.\nXXX Eventual migration to XML.\nThe documentation will be moved to XML in the future, and tools\nare being written which will convert the documentation from the\ncurrent format to something close to a finished version, to the\nextent that the desired information is already present in the\ndocumentation. Some XSLT stylesheets have been started for\npresenting a preliminary XML version as HTML, but the results are\nfairly rough..\nThe timeframe for the conversion is not clear since there doesn't\nseem to be much time available to work on this, but the appearant\nbenefits are growing more substantial at a moderately rapid pace.", "python_version": "2.2", "length": 3460, "url": "https://docs.python.org/2.2/doc/structured.html"} {"title": "3 Style Guide", "text": "directories.html | doc.html | latex-primer.html | Documenting Python | contents.html\n---\n# 3 Style Guide\nThe Python documentation should follow the Apple Publications Style Guide (http://developer.apple.com/techpubs/macos8/pdf/apple_styleguide00.pdf) wherever possible. This particular\nstyle guide was selected mostly because it seems reasonable and is\neasy to get online. (Printed copies are available; see the Apple's\nDeveloper\nDocumentation FAQ (http://developer.apple.com/techpubs/faq.html) for more information.)\nTopics which are not covered in the Apple's style guide will be\ndiscussed in this document if necessary.\nMany special names are used in the Python documentation, including\nthe names of operating systems, programming languages, standards\nbodies, and the like. Many of these were assigned LATEX macros\nat some point in the distant past, and these macros lived on long\npast their usefulness. In the current markup, most of these entities\nare not assigned any special markup, but the preferred spellings are\ngiven here to aid authors in maintaining the consistency of\npresentation in the Python documentation.\nOther terms and words deserve special mention as well; these conventions\nshould be used to ensure consistency throughout the documentation:\nCPU: For ``central processing unit.'' Many style guides say this\nshould be spelled out on the first use (and if you must use it,\ndo so!). For the Python documentation, this abbreviation should\nbe avoided since there's no reasonable way to predict which occurance\nwill be the first seen by the reader. It is better to use the\nword ``processor'' instead.\nPOSIX: The name assigned to a particular group of standards. This is\nalways uppercase. Use the macro \\POSIX to represent this\nname.\nPython: The name of our favorite programming language is always\ncapitalized.\nUnicode: The name of a character set and matching encoding. This is\nalways written capitalized.\nUnix: The name of the operating system developed at AT&T Bell Labs\nin the early 1970s. Use the macro \\UNIX to use this name.", "python_version": "2.2", "length": 2046, "url": "https://docs.python.org/2.2/doc/style-guide.html"} {"title": "6.9 Table Markup", "text": "library-markup.html | special-constructs.html | references.html | Documenting Python | contents.html\n---\n## 6.9 Table Markup\nThere are three general-purpose table environments defined which\nshould be used whenever possible. These environments are defined\nto provide tables of specific widths and some convenience for\nformatting. These environments are not meant to be general\nreplacements for the standard LATEX table environments, but can\nbe used for an advantage when the documents are processed using\nthe tools for Python documentation processing. In particular, the\ngenerated HTML looks good! There is also an advantage for the\neventual conversion of the documentation to XML (see section\n9 (futures.html#futures), ``Future Directions'').\nEach environment is named \\tablecols, where cols\nis the number of columns in the table specified in lower-case\nRoman numerals. Within each of these environments, an additional\nmacro, \\linecols, is defined, where cols\nmatches the cols value of the corresponding table\nenvironment. These are supported for cols values of\n`ii`, `iii`, and `iv`. These environments are all\nbuilt on top of the \\tabular environment. Variants based on\nthe \\longtable environment are also provided.\nNote that all tables in the standard Python documentation use\nvertical lines between columns, and this must be specified in the\nmarkup for each table. A general border around the outside of the\ntable is not used, but would be the responsibility of the\nprocessor; the document markup should not include an exterior\nborder.\nThe \\longtable-based variants of the table environments are\nformatted with extra space before and after, so should only be\nused on tables which are long enough that splitting over multiple\npages is reasonable; tables with fewer than twenty rows should\nnever by marked using the long flavors of the table environments.\nThe header row is repeated across the top of each part of the\ntable.\nAn additional table-like environment is \\synopsistable. The\ntable generated by this environment contains two columns, and each\nrow is defined by an alternate definition of\n\\modulesynopsis. This environment is not normally used by\nauthors, but is created by the \\localmoduletable macro.\nHere is a small example of a table given in the documentation for\nthe warnings module; markup inside the table cells is\nminimal so the markup for the table itself is readily discernable.\nHere is the markup for the table:\n```text\n\n\\begin{tableii}{l|l}{exception}{Class}{Description}\n\\lineii{Warning}\n{This is the base class of all warning category classes. It\nis a subclass of \\exception{Exception}.}\n\\lineii{UserWarning}\n{The default category for \\function{warn()}.}\n\\lineii{DeprecationWarning}\n{Base category for warnings about deprecated features.}\n\\lineii{SyntaxWarning}\n{Base category for warnings about dubious syntactic\nfeatures.}\n\\lineii{RuntimeWarning}\n{Base category for warnings about dubious runtime features.}\n\\end{tableii}\n```\nHere is the resulting table:\nNote that the class names are implicitly marked using the\n\\exception macro, since that is given as the col1font\nvalue for the \\tableii environment. To create a table using\ndifferent markup for the first column, use `textrm` for the\ncol1font value and mark each entry individually.\nTo add a horizontal line between vertical sections of a table, use\nthe standard \\hline macro between the rows which should be\nseparated:\n```text\n\n\\begin{tableii}{l|l}{constant}{Language}{Audience}\n\\lineii{APL}{Masochists.}\n\\lineii{BASIC}{First-time programmers on PC hardware.}\n\\lineii{C}{\\UNIX{} \\&\\ Linux kernel developers.}\n\\hline\n\\lineii{Python}{Everyone!}\n\\end{tableii}\n```\nNote that not all presentation formats are capable of displaying a\nhorizontal rule in this position. This is how the table looks in\nthe format you're reading now:", "python_version": "2.2", "length": 3804, "url": "https://docs.python.org/2.2/doc/table-markup.html"} {"title": "8.1 External Tools", "text": "tools.html | tools.html | tools-internal.html | Documenting Python | contents.html\n---\n## 8.1 External Tools\nMany tools are needed to be able to process the Python\ndocumentation if all supported formats are required. This\nsection lists the tools used and when each is required. Consult\nthe Doc/README file to see if there are specific version\nrequirements for any of these.\ndvips: This program is a typical part of TEX installations. It is\nused to generate PostScript from the ``device independent''\n.dvi files. It is needed for the conversion to\nPostScript.\nemacs: Emacs is the kitchen sink of programmers' editors, and a damn\nfine kitchen sink it is. It also comes with some of the\nprocessing needed to support the proper menu structures for\nTexinfo documents when an info conversion is desired. This is\nneeded for the info conversion. Using xemacs\ninstead of FSF emacs may lead to instability in the\nconversion, but that's because nobody seems to maintain the\nEmacs Texinfo code in a portable manner.\nlatex: LATEX is a large and extensible macro package by Leslie\nLamport, based on TEX, a world-class typesetter by Donald\nKnuth. It is used for the conversion to PostScript, and is\nneeded for the HTML conversion as well (LATEX2HTML requires\none of the intermediate files it creates).\nlatex2html: Probably the longest Perl script anyone ever attempted to\nmaintain. This converts LATEX documents to HTML documents,\nand does a pretty reasonable job. It is required for the\nconversions to HTML and GNU info.\nlynx: This is a text-mode Web browser which includes an\nHTML-to-plain text conversion. This is used to convert\n`howto` documents to text.\nmake: Just about any version should work for the standard documents,\nbut GNU make is required for the experimental\nprocesses in Doc/tools/sgmlconv/, at least while\nthey're experimental. This is not required for running the\nmkhowto script.\nmakeindex: This is a standard program for converting LATEX index data\nto a formatted index; it should be included with all LATEX\ninstallations. It is needed for the PDF and PostScript\nconversions.\nmakeinfo: GNU makeinfo is used to convert Texinfo documents to\nGNU info files. Since Texinfo is used as an intermediate\nformat in the info conversion, this program is needed in that\nconversion.\npdflatex: pdfTEX is a relatively new variant of TEX, and is used to\ngenerate the PDF version of the manuals. It is typically\ninstalled as part of most of the large TEX distributions.\npdflatex is pdfTEX using the LATEX format.\nperl: Perl is required for LATEX2HTML and one of the scripts used\nto post-process LATEX2HTML output, as well as the\nHTML-to-Texinfo conversion. This is required for\nthe HTML and GNU info conversions.\npython: Python is used for many of the scripts in the\nDoc/tools/ directory; it is required for all\nconversions. This shouldn't be a problem if you're interested\nin writing documentation for Python!", "python_version": "2.2", "length": 2898, "url": "https://docs.python.org/2.2/doc/tools-external.html"} {"title": "8.2 Internal Tools", "text": "tools-external.html | tools.html | futures.html | Documenting Python | contents.html\n---\n## 8.2 Internal Tools\nThis section describes the various scripts that are used to\nimplement various stages of document processing or to orchestrate\nentire build sequences. Most of these tools are only useful\nin the context of building the standard documentation, but some\nare more general.\nmkhowto: This is the primary script used to format third-party\ndocuments. It contains all the logic needed to ``get it\nright.'' The proper way to use this script is to make a\nsymbolic link to it or run it in place; the actual script file\nmust be stored as part of the documentation source tree,\nthough it may be used to format documents outside the\ntree. Use mkhowto --help\nfor a list of\ncommand line options.\nmkhowto can be used for both `howto` and\n`manual` class documents. (For the later, be sure to get\nthe latest version from the Python CVS repository rather than\nthe version distributed in the latex-1.5.2.tgz source\narchive.)\nXXX Need more here.", "python_version": "2.2", "length": 1032, "url": "https://docs.python.org/2.2/doc/tools-internal.html"} {"title": "8 Processing Tools", "text": "gui-markup.html | doc.html | tools-external.html | Documenting Python | contents.html\n---\n# 8 Processing Tools", "python_version": "2.2", "length": 110, "url": "https://docs.python.org/2.2/doc/tools.html"} {"title": "About this document ...", "text": "node48.html | ext.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# About this document ...\nExtending and Embedding the Python Interpreter,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nnode48.html | ext.html | Extending and Embedding the Python Interpreter | contents.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1738, "url": "https://docs.python.org/2.2/ext/about.html"} {"title": "1.3 Back to the Example", "text": "errors.html | intro.html | methodTable.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.3 Back to the Example\nGoing back to our example function, you should now be able to\nunderstand this statement:\n```text\n\nif (!PyArg_ParseTuple(args, \"s\", &command))\nreturn NULL;\n```\nIt returns NULL (the error indicator for functions returning\nobject pointers) if an error is detected in the argument list, relying\non the exception set by PyArg_ParseTuple(). Otherwise the\nstring value of the argument has been copied to the local variable\ncommand. This is a pointer assignment and you are not supposed\nto modify the string to which it points (so in Standard C, the variable\ncommand should properly be declared as \"const char\n*command\").\nThe next statement is a call to the Unix function\nsystem(), passing it the string we just got from\nPyArg_ParseTuple():\n```text\n\nsts = system(command);\n```\nOur spam.system() function must return the value of\nsts as a Python object. This is done using the function\nPy_BuildValue(), which is something like the inverse of\nPyArg_ParseTuple(): it takes a format string and an\narbitrary number of C values, and returns a new Python object.\nMore info on Py_BuildValue() is given later.\n```text\n\nreturn Py_BuildValue(\"i\", sts);\n```\nIn this case, it will return an integer object. (Yes, even integers\nare objects on the heap in Python!)\nIf you have a C function that returns no useful argument (a function\nreturning void), the corresponding Python function must return\n`None`. You need this idiom to do so:\n```text\n\nPy_INCREF(Py_None);\nreturn Py_None;\n```\nPy_None is the C name for the special Python object\n`None`. It is a genuine Python object rather than a NULL\npointer, which means ``error'' in most contexts, as we have seen.", "python_version": "2.2", "length": 1774, "url": "https://docs.python.org/2.2/ext/backToExample.html"} {"title": "3. Building C and C++ Extensions on Unix", "text": "node28.html | ext.html | custom-interps.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3. Building C and C++ Extensions on Unix\nStarting in Python 1.4, Python provides a special make file for\nbuilding make files for building dynamically-linked extensions and\ncustom interpreters. The make file make file builds a make file\nthat reflects various system variables determined by configure when\nthe Python interpreter was built, so people building module's don't\nhave to resupply these settings. This vastly simplifies the process\nof building extensions and custom interpreters on Unix systems.\nThe make file make file is distributed as the file\nMisc/Makefile.pre.in in the Python source distribution. The\nfirst step in building extensions or custom interpreters is to copy\nthis make file to a development directory containing extension module\nsource.\nThe make file make file, Makefile.pre.in uses metadata\nprovided in a file named Setup. The format of the Setup\nfile is the same as the Setup (or Setup.dist) file\nprovided in the Modules/ directory of the Python source\ndistribution. The Setup file contains variable definitions:\n```text\n\nEC=/projects/ExtensionClass\n```\nand module description lines. It can also contain blank lines and\ncomment lines that start with \"#\".\nA module description line includes a module name, source files,\noptions, variable references, and other input files, such\nas libraries or object files. Consider a simple example:\n```text\n\nExtensionClass ExtensionClass.c\n```\nThis is the simplest form of a module definition line. It defines a\nmodule, ExtensionClass, which has a single source file,\nExtensionClass.c.\nThis slightly more complex example uses an -I option to\nspecify an include directory:\n```text\n\nEC=/projects/ExtensionClass\ncPersistence cPersistence.c -I$(EC)\n```\nThis example also illustrates the format for variable references.\nFor systems that support dynamic linking, the Setup file should\nbegin:\n```text\n\n*shared*\n```\nto indicate that the modules defined in Setup are to be built\nas dynamically linked modules. A line containing only \"*static*\"can be used to indicate the subsequently listed modules should be\nstatically linked.\nHere is a complete Setup file for building a\ncPersistent module:\n```text\n\n# Set-up file to build the cPersistence module.\n# Note that the text should begin in the first column.\n*shared*\n\n# We need the path to the directory containing the ExtensionClass\n# include file.\nEC=/projects/ExtensionClass\ncPersistence cPersistence.c -I$(EC)\n```\nAfter the Setup file has been created, Makefile.pre.in\nis run with the \"boot\" target to create a make file:\n```text\n\nmake -f Makefile.pre.in boot\n```\nThis creates the file, Makefile. To build the extensions, simply\nrun the created make file:\n```text\n\nmake\n```\nIt's not necessary to re-run Makefile.pre.in if the\nSetup file is changed. The make file automatically rebuilds\nitself if the Setup file changes.", "python_version": "2.2", "length": 2938, "url": "https://docs.python.org/2.2/ext/building-on-unix.html"} {"title": "4. Building C and C++ Extensions on Windows", "text": "distributing.html | ext.html | win-cookbook.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 4. Building C and C++ Extensions on Windows\nThis chapter briefly explains how to create a Windows extension module\nfor Python using Microsoft Visual C++, and follows with more\ndetailed background information on how it works. The explanatory\nmaterial is useful for both the Windows programmer learning to build\nPython extensions and the Unix programmer interested in producing\nsoftware which can be successfully built on both Unix and Windows.", "python_version": "2.2", "length": 562, "url": "https://docs.python.org/2.2/ext/building-on-windows.html"} {"title": "1.9 Building Arbitrary Values", "text": "parseTupleAndKeywords.html | intro.html | refcounts.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.9 Building Arbitrary Values\nThis function is the counterpart to PyArg_ParseTuple(). It is\ndeclared as follows:\n```text\n\nPyObject *Py_BuildValue(char *format, ...);\n```\nIt recognizes a set of format units similar to the ones recognized by\nPyArg_ParseTuple(), but the arguments (which are input to the\nfunction, not output) must not be pointers, just values. It returns a\nnew Python object, suitable for returning from a C function called\nfrom Python.\nOne difference with PyArg_ParseTuple(): while the latter\nrequires its first argument to be a tuple (since Python argument lists\nare always represented as tuples internally),\nPy_BuildValue() does not always build a tuple. It builds\na tuple only if its format string contains two or more format units.\nIf the format string is empty, it returns `None`; if it contains\nexactly one format unit, it returns whatever object is described by\nthat format unit. To force it to return a tuple of size 0 or one,\nparenthesize the format string.\nWhen memory buffers are passed as parameters to supply data to build\nobjects, as for the \"s\" and \"s#\" formats, the required data\nis copied. Buffers provided by the caller are never referenced by the\nobjects created by Py_BuildValue(). In other words, if\nyour code invokes malloc() and passes the allocated memory\nto Py_BuildValue(), your code is responsible for\ncalling free() for that memory once\nPy_BuildValue() returns.\nIn the following description, the quoted form is the format unit; the\nentry in (round) parentheses is the Python object type that the format\nunit will return; and the entry in [square] brackets is the type of\nthe C value(s) to be passed.\nThe characters space, tab, colon and comma are ignored in format\nstrings (but not within format units such as \"s#\"). This can be\nused to make long format strings a tad more readable.\n\"s\" (string) [char *]: Convert a null-terminated C string to a Python object. If the C\nstring pointer is NULL, `None` is used.\n\"s#\" (string) [char *, int]: Convert a C string and its length to a Python object. If the C string\npointer is NULL, the length is ignored and `None` is\nreturned.\n\"z\" (string or `None`) [char *]: Same as \"s\".\n\"z#\" (string or `None`) [char *, int]: Same as \"s#\".\n\"u\" (Unicode string) [Py_UNICODE *]: Convert a null-terminated buffer of Unicode (UCS-2) data to a Python\nUnicode object. If the Unicode buffer pointer is NULL,\n`None` is returned.\n\"u#\" (Unicode string) [Py_UNICODE *, int]: Convert a Unicode (UCS-2) data buffer and its length to a Python\nUnicode object. If the Unicode buffer pointer is NULL, the length\nis ignored and `None` is returned.\n\"i\" (integer) [int]: Convert a plain C int to a Python integer object.\n\"b\" (integer) [char]: Same as \"i\".\n\"h\" (integer) [short int]: Same as \"i\".\n\"l\" (integer) [long int]: Convert a C long int to a Python integer object.\n\"c\" (string of length 1) [char]: Convert a C int representing a character to a Python string of\nlength 1.\n\"d\" (float) [double]: Convert a C double to a Python floating point number.\n\"f\" (float) [float]: Same as \"d\".\n\"D\" (complex) [Py_complex *]: Convert a C Py_complex structure to a Python complex number.\n\"O\" (object) [PyObject *]: Pass a Python object untouched (except for its reference count, which\nis incremented by one). If the object passed in is a NULL\npointer, it is assumed that this was caused because the call producing\nthe argument found an error and set an exception. Therefore,\nPy_BuildValue() will return NULL but won't raise an\nexception. If no exception has been raised yet,\nPyExc_SystemError is set.\n\"S\" (object) [PyObject *]: Same as \"O\".\n\"U\" (object) [PyObject *]: Same as \"O\".\n\"N\" (object) [PyObject *]: Same as \"O\", except it doesn't increment the reference count on\nthe object. Useful when the object is created by a call to an object\nconstructor in the argument list.\n\"O&\" (object) [converter, anything]: Convert anything to a Python object through a converter\nfunction. The function is called with anything (which should be\ncompatible with void *) as its argument and should return a\n``new'' Python object, or NULL if an error occurred.\n\"(items)\" (tuple) [matching-items]: Convert a sequence of C values to a Python tuple with the same number\nof items.\n\"[items]\" (list) [matching-items]: Convert a sequence of C values to a Python list with the same number\nof items.\n\"{items}\" (dictionary) [matching-items]: Convert a sequence of C values to a Python dictionary. Each pair of\nconsecutive C values adds one item to the dictionary, serving as key\nand value, respectively.\nIf there is an error in the format string, the\nPyExc_SystemError exception is raised and NULL returned.\nExamples (to the left the call, to the right the resulting Python value):\n```text\n\nPy_BuildValue(\"\") None\nPy_BuildValue(\"i\", 123) 123\nPy_BuildValue(\"iii\", 123, 456, 789) (123, 456, 789)\nPy_BuildValue(\"s\", \"hello\") 'hello'\nPy_BuildValue(\"ss\", \"hello\", \"world\") ('hello', 'world')\nPy_BuildValue(\"s#\", \"hello\", 4) 'hell'\nPy_BuildValue(\"()\") ()\nPy_BuildValue(\"(i)\", 123) (123,)\nPy_BuildValue(\"(ii)\", 123, 456) (123, 456)\nPy_BuildValue(\"(i,i)\", 123, 456) (123, 456)\nPy_BuildValue(\"[i,i]\", 123, 456) [123, 456]\nPy_BuildValue(\"{s:i,s:i}\",\n\"abc\", 123, \"def\", 456) {'abc': 123, 'def': 456}\nPy_BuildValue(\"((ii)(ii)) (ii)\",\n1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))\n```", "python_version": "2.2", "length": 5417, "url": "https://docs.python.org/2.2/ext/buildValue.html"} {"title": "1.6 Calling Python Functions from C", "text": "compilation.html | intro.html | parseTuple.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.6 Calling Python Functions from C\nSo far we have concentrated on making C functions callable from\nPython. The reverse is also useful: calling Python functions from C.\nThis is especially the case for libraries that support so-called\n``callback'' functions. If a C interface makes use of callbacks, the\nequivalent Python often needs to provide a callback mechanism to the\nPython programmer; the implementation will require calling the Python\ncallback functions from a C callback. Other uses are also imaginable.\nFortunately, the Python interpreter is easily called recursively, and\nthere is a standard interface to call a Python function. (I won't\ndwell on how to call the Python parser with a particular string as\ninput -- if you're interested, have a look at the implementation of\nthe -c command line option in Python/pythonmain.c\nfrom the Python source code.)\nCalling a Python function is easy. First, the Python program must\nsomehow pass you the Python function object. You should provide a\nfunction (or some other interface) to do this. When this function is\ncalled, save a pointer to the Python function object (be careful to\nPy_INCREF() it!) in a global variable -- or wherever you\nsee fit. For example, the following function might be part of a module\ndefinition:\n```text\n\nstatic PyObject *my_callback = NULL;\n\nstatic PyObject *\nmy_set_callback(dummy, args)\nPyObject *dummy, *args;\n{\nPyObject *result = NULL;\nPyObject *temp;\n\nif (PyArg_ParseTuple(args, \"O:set_callback\", &temp)) {\nif (!PyCallable_Check(temp)) {\nPyErr_SetString(PyExc_TypeError, \"parameter must be callable\");\nreturn NULL;\n}\nPy_XINCREF(temp); /* Add a reference to new callback */\nPy_XDECREF(my_callback); /* Dispose of previous callback */\nmy_callback = temp; /* Remember new callback */\n/* Boilerplate to return \"None\" */\nPy_INCREF(Py_None);\nresult = Py_None;\n}\nreturn result;\n}\n```\nThis function must be registered with the interpreter using the\nMETH_VARARGS flag; this is described in section\n1.4 (methodTable.html#methodTable), ``The Module's Method Table and Initialization\nFunction.'' The PyArg_ParseTuple() function and its\narguments are documented in section 1.7 (parseTuple.html#parseTuple), ``Extracting\nParameters in Extension Functions.''\nThe macros Py_XINCREF() and Py_XDECREF()\nincrement/decrement the reference count of an object and are safe in\nthe presence of NULL pointers (but note that temp will not be\nNULL in this context). More info on them in\nsection 1.10 (refcounts.html#refcounts), ``Reference Counts.''\nLater, when it is time to call the function, you call the C function\nPyEval_CallObject(). This\nfunction has two arguments, both pointers to arbitrary Python objects:\nthe Python function, and the argument list. The argument list must\nalways be a tuple object, whose length is the number of arguments. To\ncall the Python function with no arguments, pass an empty tuple; to\ncall it with one argument, pass a singleton tuple.\nPy_BuildValue() returns a tuple when its format string\nconsists of zero or more format codes between parentheses. For\nexample:\n```text\n\nint arg;\nPyObject *arglist;\nPyObject *result;\n...\narg = 123;\n...\n/* Time to call the callback */\narglist = Py_BuildValue(\"(i)\", arg);\nresult = PyEval_CallObject(my_callback, arglist);\nPy_DECREF(arglist);\n```\nPyEval_CallObject() returns a Python object pointer: this is\nthe return value of the Python function. PyEval_CallObject() is\n``reference-count-neutral'' with respect to its arguments. In the\nexample a new tuple was created to serve as the argument list, which\nis Py_DECREF()-ed immediately after the call.\nThe return value of PyEval_CallObject() is ``new'': either it\nis a brand new object, or it is an existing object whose reference\ncount has been incremented. So, unless you want to save it in a\nglobal variable, you should somehow Py_DECREF() the result,\neven (especially!) if you are not interested in its value.\nBefore you do this, however, it is important to check that the return\nvalue isn't NULL. If it is, the Python function terminated by\nraising an exception. If the C code that called\nPyEval_CallObject() is called from Python, it should now\nreturn an error indication to its Python caller, so the interpreter\ncan print a stack trace, or the calling Python code can handle the\nexception. If this is not possible or desirable, the exception should\nbe cleared by calling PyErr_Clear(). For example:\n```text\n\nif (result == NULL)\nreturn NULL; /* Pass error back */\n...use result...\nPy_DECREF(result);\n```\nDepending on the desired interface to the Python callback function,\nyou may also have to provide an argument list to\nPyEval_CallObject(). In some cases the argument list is\nalso provided by the Python program, through the same interface that\nspecified the callback function. It can then be saved and used in the\nsame manner as the function object. In other cases, you may have to\nconstruct a new tuple to pass as the argument list. The simplest way\nto do this is to call Py_BuildValue(). For example, if\nyou want to pass an integral event code, you might use the following\ncode:\n```text\n\nPyObject *arglist;\n...\narglist = Py_BuildValue(\"(l)\", eventcode);\nresult = PyEval_CallObject(my_callback, arglist);\nPy_DECREF(arglist);\nif (result == NULL)\nreturn NULL; /* Pass error back */\n/* Here maybe use the result */\nPy_DECREF(result);\n```\nNote the placement of \"Py_DECREF(arglist)\" immediately after the\ncall, before the error check! Also note that strictly spoken this\ncode is not complete: Py_BuildValue() may run out of\nmemory, and this should be checked.", "python_version": "2.2", "length": 5657, "url": "https://docs.python.org/2.2/ext/callingPython.html"} {"title": "1.5 Compilation and Linkage", "text": "methodTable.html | intro.html | callingPython.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.5 Compilation and Linkage\nThere are two more things to do before you can use your new extension:\ncompiling and linking it with the Python system. If you use dynamic\nloading, the details depend on the style of dynamic loading your\nsystem uses; see the chapters about building extension modules on\nUnix (chapter 3 (building-on-unix.html#building-on-unix)) and Windows (chapter\n4 (building-on-windows.html#building-on-windows)) for more information about this.\nIf you can't use dynamic loading, or if you want to make your module a\npermanent part of the Python interpreter, you will have to change the\nconfiguration setup and rebuild the interpreter. Luckily, this is\nvery simple: just place your file (spammodule.c for example) in\nthe Modules/ directory of an unpacked source distribution, add\na line to the file Modules/Setup.local describing your file:\n```text\n\nspam spammodule.o\n```\nand rebuild the interpreter by running make in the toplevel\ndirectory. You can also run make in the Modules/\nsubdirectory, but then you must first rebuild Makefile\nthere by running `make Makefile'. (This is necessary each\ntime you change the Setup file.)\nIf your module requires additional libraries to link with, these can\nbe listed on the line in the configuration file as well, for instance:\n```text\n\nspam spammodule.o -lX11\n```", "python_version": "2.2", "length": 1439, "url": "https://docs.python.org/2.2/ext/compilation.html"} {"title": "Contents", "text": "front.html | ext.html | intro.html | Extending and Embedding the Python Interpreter\n---\n## Contents\nTable of Contents\n- Front Matter (front.html)\n 1. Extending Python with C or C++ (intro.html)\n - 1.1 A Simple Example (simpleExample.html)\n 1.2 Intermezzo: Errors and Exceptions (errors.html)\n 1.3 Back to the Example (backToExample.html)\n 1.4 The Module's Method Table and Initialization Function (methodTable.html)\n 1.5 Compilation and Linkage (compilation.html)\n 1.6 Calling Python Functions from C (callingPython.html)\n 1.7 Extracting Parameters in Extension Functions (parseTuple.html)\n 1.8 Keyword Parameters for Extension Functions (parseTupleAndKeywords.html)\n 1.9 Building Arbitrary Values (buildValue.html)\n 1.10 Reference Counts (refcounts.html)\n - 1.10.1 Reference Counting in Python (refcountsInPython.html)\n 1.10.2 Ownership Rules (ownershipRules.html)\n 1.10.3 Thin Ice (thinIce.html)\n 1.10.4 NULL Pointers (nullPointers.html)\n 1.11 Writing Extensions in C++ (cplusplus.html)\n 1.12 Providing a C API for an Extension Module (using-cobjects.html)\n 2. Defining New Types (defining-new-types.html)\n - 2.1 The Basics (dnt-basics.html)\n 2.2 Type Methods (dnt-type-methods.html)\n - 2.2.1 Finalization and De-allocation (node23.html)\n 2.2.2 Object Representation (node24.html)\n 2.2.3 Attribute Management Functions (node25.html)\n 2.2.4 Object Comparison (node26.html)\n 2.2.5 Abstract Protocol Support (node27.html)\n 2.2.6 More Suggestions (node28.html)\n 3. Building C and C++ Extensions on Unix (building-on-unix.html)\n - 3.1 Building Custom Interpreters (custom-interps.html)\n 3.2 Module Definition Options (module-defn-options.html)\n 3.3 Example (module-defn-example.html)\n 3.4 Distributing your extension modules (distributing.html)\n 4. Building C and C++ Extensions on Windows (building-on-windows.html)\n - 4.1 A Cookbook Approach (win-cookbook.html)\n 4.2 Differences Between Unix and Windows (dynamic-linking.html)\n 4.3 Using DLLs in Practice (win-dlls.html)\n 5. Embedding Python in Another Application (embedding.html)\n - 5.1 Very High Level Embedding (high-level-embedding.html)\n 5.2 Beyond Very High Level Embedding: An overview (lower-level-embedding.html)\n 5.3 Pure Embedding (pure-embedding.html)\n 5.4 Extending Embedded Python (extending-with-embedding.html)\n 5.5 Embedding Python in C++ (embeddingInCplusplus.html)\n 5.6 Linking Requirements (link-reqs.html)\n A. Reporting Bugs (reporting-bugs.html)\n B. History and License (node46.html)\n - B.1 History of the software (node47.html)\n B.2 Terms and conditions for accessing or otherwise using Python (node48.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.2", "length": 2690, "url": "https://docs.python.org/2.2/ext/contents.html"} {"title": "1.11 Writing Extensions in C++", "text": "nullPointers.html | intro.html | using-cobjects.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.11 Writing Extensions in C++\nIt is possible to write extension modules in C++. Some restrictions\napply. If the main program (the Python interpreter) is compiled and\nlinked by the C compiler, global or static objects with constructors\ncannot be used. This is not a problem if the main program is linked\nby the C++ compiler. Functions that will be called by the\nPython interpreter (in particular, module initalization functions)\nhave to be declared using `extern \"C\"`.\nIt is unnecessary to enclose the Python header files in\n`extern \"C\" {...}` -- they use this form already if the symbol\n\"__cplusplus\" is defined (all recent C++ compilers define this\nsymbol).", "python_version": "2.2", "length": 783, "url": "https://docs.python.org/2.2/ext/cplusplus.html"} {"title": "3.1 Building Custom Interpreters", "text": "building-on-unix.html | building-on-unix.html | module-defn-options.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3.1 Building Custom Interpreters\nThe make file built by Makefile.pre.in can be run with the\n\"static\" target to build an interpreter:\n```text\n\nmake static\n```\nAny modules defined in the Setup file before the\n\"*shared*\" line will be statically linked into the interpreter.\nTypically, a \"*shared*\" line is omitted from the\nSetup file when a custom interpreter is desired.", "python_version": "2.2", "length": 512, "url": "https://docs.python.org/2.2/ext/custom-interps.html"} {"title": "2. Defining New Types", "text": "using-cobjects.html | ext.html | dnt-basics.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2. Defining New Types\nAs mentioned in the last chapter, Python allows the writer of an\nextension module to define new types that can be manipulated from\nPython code, much like strings and lists in core Python.\nThis is not hard; the code for all extension types follows a pattern,\nbut there are some details that you need to understand before you can\nget started.", "python_version": "2.2", "length": 482, "url": "https://docs.python.org/2.2/ext/defining-new-types.html"} {"title": "3.4 Distributing your extension modules", "text": "module-defn-example.html | building-on-unix.html | building-on-windows.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3.4 Distributing your extension modules\nThere are two ways to distribute extension modules for others to use.\nThe way that allows the easiest cross-platform support is to use the\ndistutilspackage. The manual\nDistributing Python Modules (../dist/dist.html) contains\ninformation on this approach. It is recommended that all new\nextensions be distributed using this approach to allow easy building\nand installation across platforms. Older extensions should migrate to\nthis approach as well.\nWhat follows describes the older approach; there are still many\nextensions which use this.\nWhen distributing your extension modules in source form, make sure to\ninclude a Setup file. The Setup file should be named\nSetup.in in the distribution. The make file make file,\nMakefile.pre.in, will copy Setup.in to Setup if\nthe person installing the extension doesn't do so manually.\nDistributing a Setup.in file makes it easy for people to\ncustomize the Setup file while keeping the original in\nSetup.in.\nIt is a good idea to include a copy of Makefile.pre.in for\npeople who do not have a source distribution of Python.", "python_version": "2.2", "length": 1248, "url": "https://docs.python.org/2.2/ext/distributing.html"} {"title": "2.1 The Basics", "text": "defining-new-types.html | defining-new-types.html | dnt-type-methods.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2.1 The Basics\nThe Python runtime sees all Python objects as variables of type\nPyObject*. A PyObject is not a very magnificent\nobject - it just contains the refcount and a pointer to the object's\n``type object''. This is where the action is; the type object\ndetermines which (C) functions get called when, for instance, an\nattribute gets looked up on an object or it is multiplied by another\nobject. I call these C functions ``type methods'' to distinguish them\nfrom things like `[].append` (which I will call ``object\nmethods'' when I get around to them).\nSo, if you want to define a new object type, you need to create a new\ntype object.\nThis sort of thing can only be explained by example, so here's a\nminimal, but complete, module that defines a new type:\n```text\n\n#include \n\nstaticforward PyTypeObject noddy_NoddyType;\n\ntypedef struct {\nPyObject_HEAD\n} noddy_NoddyObject;\n\nstatic PyObject*\nnoddy_new_noddy(PyObject* self, PyObject* args)\n{\nnoddy_NoddyObject* noddy;\n\nif (!PyArg_ParseTuple(args,\":new_noddy\"))\nreturn NULL;\n\nnoddy = PyObject_New(noddy_NoddyObject, &noddy_NoddyType);\n\nreturn (PyObject*)noddy;\n}\n\nstatic void\nnoddy_noddy_dealloc(PyObject* self)\n{\nPyObject_Del(self);\n}\n\nstatic PyTypeObject noddy_NoddyType = {\nPyObject_HEAD_INIT(NULL)\n0,\n\"Noddy\",\nsizeof(noddy_NoddyObject),\n0,\nnoddy_noddy_dealloc, /*tp_dealloc*/\n0, /*tp_print*/\n0, /*tp_getattr*/\n0, /*tp_setattr*/\n0, /*tp_compare*/\n0, /*tp_repr*/\n0, /*tp_as_number*/\n0, /*tp_as_sequence*/\n0, /*tp_as_mapping*/\n0, /*tp_hash */\n};\n\nstatic PyMethodDef noddy_methods[] = {\n{\"new_noddy\", noddy_new_noddy, METH_VARARGS,\n\"Create a new Noddy object.\"},\n{NULL, NULL, 0, NULL}\n};\n\nDL_EXPORT(void)\ninitnoddy(void)\n{\nnoddy_NoddyType.ob_type = &PyType_Type;\n\nPy_InitModule(\"noddy\", noddy_methods);\n}\n```\nNow that's quite a bit to take in at once, but hopefully bits will\nseem familiar from the last chapter.\nThe first bit that will be new is:\n```text\n\nstaticforward PyTypeObject noddy_NoddyType;\n```\nThis names the type object that will be defining further down in the\nfile. It can't be defined here because its definition has to refer to\nfunctions that have no yet been defined, but we need to be able to\nrefer to it, hence the declaration.\nThe `staticforward` is required to placate various brain dead\ncompilers.\n```text\n\ntypedef struct {\nPyObject_HEAD\n} noddy_NoddyObject;\n```\nThis is what a Noddy object will contain. In this case nothing more\nthan every Python object contains - a refcount and a pointer to a type\nobject. These are the fields the `PyObject_HEAD` macro brings\nin. The reason for the macro is to standardize the layout and to\nenable special debugging fields to be brought in debug builds.\nFor contrast\n```text\n\ntypedef struct {\nPyObject_HEAD\nlong ob_ival;\n} PyIntObject;\n```\nis the corresponding definition for standard Python integers.\nNext up is:\n```text\n\nstatic PyObject*\nnoddy_new_noddy(PyObject* self, PyObject* args)\n{\nnoddy_NoddyObject* noddy;\n\nif (!PyArg_ParseTuple(args,\":new_noddy\"))\nreturn NULL;\n\nnoddy = PyObject_New(noddy_NoddyObject, &noddy_NoddyType);\n\nreturn (PyObject*)noddy;\n}\n```\nThis is in fact just a regular module function, as described in the\nlast chapter. The reason it gets special mention is that this is\nwhere we create our Noddy object. Defining PyTypeObject structures is\nall very well, but if there's no way to actually create one\nof the wretched things it is not going to do anyone much good.\nAlmost always, you create objects with a call of the form:\n```text\n\nPyObject_New(, &);\n```\nThis allocates the memory and then initializes the object (sets\nthe reference count to one, makes the ob_type pointer point at\nthe right place and maybe some other stuff, depending on build options).\nYou can do these steps separately if you have some reason to\n-- but at this level we don't bother.\nWe cast the return value to a PyObject* because that's what\nthe Python runtime expects. This is safe because of guarantees about\nthe layout of structures in the C standard, and is a fairly common C\nprogramming trick. One could declare noddy_new_noddy to\nreturn a noddy_NoddyObject* and then put a cast in the\ndefinition of noddy_methods further down the file -- it\ndoesn't make much difference.\nNow a Noddy object doesn't do very much and so doesn't need to\nimplement many type methods. One you can't avoid is handling\ndeallocation, so we find\n```text\n\nstatic void\nnoddy_noddy_dealloc(PyObject* self)\n{\nPyObject_Del(self);\n}\n```\nThis is so short as to be self explanatory. This function will be\ncalled when the reference count on a Noddy object reaches `0` (or\nit is found as part of an unreachable cycle by the cyclic garbage\ncollector). PyObject_Del() is what you call when you want\nan object to go away. If a Noddy object held references to other\nPython objects, one would decref them here.\nMoving on, we come to the crunch -- the type object.\n```text\n\nstatic PyTypeObject noddy_NoddyType = {\nPyObject_HEAD_INIT(NULL)\n0,\n\"Noddy\",\nsizeof(noddy_NoddyObject),\n0,\nnoddy_noddy_dealloc, /*tp_dealloc*/\n0, /*tp_print*/\n0, /*tp_getattr*/\n0, /*tp_setattr*/\n0, /*tp_compare*/\n0, /*tp_repr*/\n0, /*tp_as_number*/\n0, /*tp_as_sequence*/\n0, /*tp_as_mapping*/\n0, /*tp_hash */\n};\n```\nNow if you go and look up the definition of PyTypeObject in\nobject.h you'll see that it has many, many more fields that the\ndefinition above. The remaining fields will be filled with zeros by\nthe C compiler, and it's common practice to not specify them\nexplicitly unless you need them.\nThis is so important that I'm going to pick the top of it apart still\nfurther:\n```text\n\nPyObject_HEAD_INIT(NULL)\n```\nThis line is a bit of a wart; what we'd like to write is:\n```text\n\nPyObject_HEAD_INIT(&PyType_Type)\n```\nas the type of a type object is ``type'', but this isn't strictly\nconforming C and some compilers complain. So instead we fill in the\nob_type field of noddy_NoddyType at the earliest\noppourtunity -- in initnoddy().\n```text\n\n0,\n```\nXXX why does the type info struct start PyObject_*VAR*_HEAD??\n```text\n\n\"Noddy\",\n```\nThe name of our type. This will appear in the default textual\nrepresentation of our objects and in some error messages, for example:\n```text\n\n>>> \"\" + noddy.new_noddy()\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: cannot add type \"Noddy\" to string\n```\n```text\n\nsizeof(noddy_NoddyObject),\n```\nThis is so that Python knows how much memory to allocate when you call\nPyObject_New.\n```text\n\n0,\n```\nThis has to do with variable length objects like lists and strings.\nIgnore for now...\nNow we get into the type methods, the things that make your objects\ndifferent from the others. Of course, the Noddy object doesn't\nimplement many of these, but as mentioned above you have to implement\nthe deallocation function.\n```text\n\nnoddy_noddy_dealloc, /*tp_dealloc*/\n```\nFrom here, all the type methods are nil so I won't go over them yet -\nthat's for the next section!\nEverything else in the file should be familiar, except for this line\nin initnoddy:\n```text\n\nnoddy_NoddyType.ob_type = &PyType_Type;\n```\nThis was alluded to above -- the noddy_NoddyType object should\nhave type ``type'', but `&PyType_Type` is not constant and so\ncan't be used in its initializer. To work around this, we patch it up\nin the module initialization.\nThat's it! All that remains is to build it; put the above code in a\nfile called noddymodule.c and\n```text\n\nfrom distutils.core import setup, Extension\nsetup(name = \"noddy\", version = \"1.0\",\next_modules = [Extension(\"noddy\", [\"noddymodule.c\"])])\n```\nin a file called setup.py; then typing\n```text\n\n$ python setup.py build%$\n```\nat a shell should produce a file noddy.so in a subdirectory;\nmove to that directory and fire up Python -- you should be able to\n`import noddy` and play around with Noddy objects.\nThat wasn't so hard, was it?", "python_version": "2.2", "length": 7938, "url": "https://docs.python.org/2.2/ext/dnt-basics.html"} {"title": "2.2 Type Methods", "text": "dnt-basics.html | defining-new-types.html | node23.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2.2 Type Methods\nThis section aims to give a quick fly-by on the various type methods\nyou can implement and what they do.\nHere is the definition of PyTypeObject, with some fields only\nused in debug builds omitted:\n```text\n\ntypedef struct _typeobject {\nPyObject_VAR_HEAD\nchar *tp_name; /* For printing */\nint tp_basicsize, tp_itemsize; /* For allocation */\n\n/* Methods to implement standard operations */\n\ndestructor tp_dealloc;\nprintfunc tp_print;\ngetattrfunc tp_getattr;\nsetattrfunc tp_setattr;\ncmpfunc tp_compare;\nreprfunc tp_repr;\n\n/* Method suites for standard classes */\n\nPyNumberMethods *tp_as_number;\nPySequenceMethods *tp_as_sequence;\nPyMappingMethods *tp_as_mapping;\n\n/* More standard operations (here for binary compatibility) */\n\nhashfunc tp_hash;\nternaryfunc tp_call;\nreprfunc tp_str;\ngetattrofunc tp_getattro;\nsetattrofunc tp_setattro;\n\n/* Functions to access object as input/output buffer */\nPyBufferProcs *tp_as_buffer;\n\n/* Flags to define presence of optional/expanded features */\nlong tp_flags;\n\nchar *tp_doc; /* Documentation string */\n\n/* Assigned meaning in release 2.0 */\n/* call function for all accessible objects */\ntraverseproc tp_traverse;\n\n/* delete references to contained objects */\ninquiry tp_clear;\n\n/* Assigned meaning in release 2.1 */\n/* rich comparisons */\nrichcmpfunc tp_richcompare;\n\n/* weak reference enabler */\nlong tp_weaklistoffset;\n\n/* Added in release 2.2 */\n/* Iterators */\ngetiterfunc tp_iter;\niternextfunc tp_iternext;\n\n/* Attribute descriptor and subclassing stuff */\nstruct PyMethodDef *tp_methods;\nstruct memberlist *tp_members;\nstruct getsetlist *tp_getset;\nstruct _typeobject *tp_base;\nPyObject *tp_dict;\ndescrgetfunc tp_descr_get;\ndescrsetfunc tp_descr_set;\nlong tp_dictoffset;\ninitproc tp_init;\nallocfunc tp_alloc;\nnewfunc tp_new;\ndestructor tp_free; /* Low-level free-memory routine */\nPyObject *tp_bases;\nPyObject *tp_mro; /* method resolution order */\nPyObject *tp_defined;\n\n} PyTypeObject;\n```\nNow that's a lot of methods. Don't worry too much though - if\nyou have a type you want to define, the chances are very good that you\nwill only implement a handful of these.\nAs you probably expect by now, we're going to go over this and give\nmore information about the various handlers. We won't go in the order\nthey are defined in the structure, because there is a lot of\nhistorical baggage that impacts the ordering of the fields; be sure\nyour type initializaion keeps the fields in the right order! It's\noften easiest to find an example that includes all the fields you need\n(even if they're initialized to `0`) and then change the values\nto suit your new type.\n```text\n\nchar *tp_name; /* For printing */\n```\nThe name of the type - as mentioned in the last section, this will\nappear in various places, almost entirely for diagnostic purposes.\nTry to choose something that will be helpful in such a situation!\n```text\n\nint tp_basicsize, tp_itemsize; /* For allocation */\n```\nThese fields tell the runtime how much memory to allocate when new\nobjects of this typed are created. Python has some builtin support\nfor variable length structures (think: strings, lists) which is where\nthe tp_itemsize field comes in. This will be dealt with\nlater.\n```text\n\nchar *tp_doc;\n```\nHere you can put a string (or its address) that you want returned when\nthe Python script references `obj.__doc__` to retrieve the\ndocstring.\nNow we come to the basic type methods--the ones most extension types\nwill implement.", "python_version": "2.2", "length": 3573, "url": "https://docs.python.org/2.2/ext/dnt-type-methods.html"} {"title": "4.2 Differences Between Unix and Windows", "text": "win-cookbook.html | building-on-windows.html | win-dlls.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 4.2 Differences Between Unix and Windows\nUnix and Windows use completely different paradigms for run-time\nloading of code. Before you try to build a module that can be\ndynamically loaded, be aware of how your system works.\nIn Unix, a shared object (.so) file contains code to be used by the\nprogram, and also the names of functions and data that it expects to\nfind in the program. When the file is joined to the program, all\nreferences to those functions and data in the file's code are changed\nto point to the actual locations in the program where the functions\nand data are placed in memory. This is basically a link operation.\nIn Windows, a dynamic-link library (.dll) file has no dangling\nreferences. Instead, an access to functions or data goes through a\nlookup table. So the DLL code does not have to be fixed up at runtime\nto refer to the program's memory; instead, the code already uses the\nDLL's lookup table, and the lookup table is modified at runtime to\npoint to the functions and data.\nIn Unix, there is only one type of library file (.a) which\ncontains code from several object files (.o). During the link\nstep to create a shared object file (.so), the linker may find\nthat it doesn't know where an identifier is defined. The linker will\nlook for it in the object files in the libraries; if it finds it, it\nwill include all the code from that object file.\nIn Windows, there are two types of library, a static library and an\nimport library (both called .lib). A static library is like a\nUnix .a file; it contains code to be included as necessary.\nAn import library is basically used only to reassure the linker that a\ncertain identifier is legal, and will be present in the program when\nthe DLL is loaded. So the linker uses the information from the\nimport library to build the lookup table for using identifiers that\nare not included in the DLL. When an application or a DLL is linked,\nan import library may be generated, which will need to be used for all\nfuture DLLs that depend on the symbols in the application or DLL.\nSuppose you are building two dynamic-load modules, B and C, which should\nshare another block of code A. On Unix, you would not pass\nA.a to the linker for B.so and C.so; that would\ncause it to be included twice, so that B and C would each have their\nown copy. In Windows, building A.dll will also build\nA.lib. You do pass A.lib to the linker for B and\nC. A.lib does not contain code; it just contains information\nwhich will be used at runtime to access A's code.\nIn Windows, using an import library is sort of like using \"import\nspam\"; it gives you access to spam's names, but does not create a\nseparate copy. On Unix, linking with a library is more like\n\"from spam import *\"; it does create a separate copy.", "python_version": "2.2", "length": 2876, "url": "https://docs.python.org/2.2/ext/dynamic-linking.html"} {"title": "5. Embedding Python in Another Application", "text": "win-dlls.html | ext.html | high-level-embedding.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 5. Embedding Python in Another Application\nThe previous chapters discussed how to extend Python, that is, how to\nextend the functionality of Python by attaching a library of C\nfunctions to it. It is also possible to do it the other way around:\nenrich your C/C++ application by embedding Python in it. Embedding\nprovides your application with the ability to implement some of the\nfunctionality of your application in Python rather than C or C++.\nThis can be used for many purposes; one example would be to allow\nusers to tailor the application to their needs by writing some scripts\nin Python. You can also use it yourself if some of the functionality\ncan be written in Python more easily.\nEmbedding Python is similar to extending it, but not quite. The\ndifference is that when you extend Python, the main program of the\napplication is still the Python interpreter, while if you embed\nPython, the main program may have nothing to do with Python --\ninstead, some parts of the application occasionally call the Python\ninterpreter to run some Python code.\nSo if you are embedding Python, you are providing your own main\nprogram. One of the things this main program has to do is initialize\nthe Python interpreter. At the very least, you have to call the\nfunction Py_Initialize() (on Mac OS, call\nPyMac_Initialize() instead). There are optional calls to\npass command line arguments to Python. Then later you can call the\ninterpreter from any part of the application.\nThere are several different ways to call the interpreter: you can pass\na string containing Python statements to\nPyRun_SimpleString(), or you can pass a stdio file pointer\nand a file name (for identification in error messages only) to\nPyRun_SimpleFile(). You can also call the lower-level\noperations described in the previous chapters to construct and use\nPython objects.\nA simple demo of embedding Python can be found in the directory\nDemo/embed/ of the source distribution.\nSee Also:", "python_version": "2.2", "length": 2069, "url": "https://docs.python.org/2.2/ext/embedding.html"} {"title": "5.5 Embedding Python in C++", "text": "extending-with-embedding.html | embedding.html | link-reqs.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 5.5 Embedding Python in C++\nIt is also possible to embed Python in a C++ program; precisely how this\nis done will depend on the details of the C++ system used; in general you\nwill need to write the main program in C++, and use the C++ compiler\nto compile and link your program. There is no need to recompile Python\nitself using C++.", "python_version": "2.2", "length": 467, "url": "https://docs.python.org/2.2/ext/embeddingInCplusplus.html"} {"title": "1.2 Intermezzo: Errors and Exceptions", "text": "simpleExample.html | intro.html | backToExample.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.2 Intermezzo: Errors and Exceptions\nAn important convention throughout the Python interpreter is the\nfollowing: when a function fails, it should set an exception condition\nand return an error value (usually a NULL pointer). Exceptions\nare stored in a static global variable inside the interpreter; if this\nvariable is NULL no exception has occurred. A second global\nvariable stores the ``associated value'' of the exception (the second\nargument to raise). A third variable contains the stack\ntraceback in case the error originated in Python code. These three\nvariables are the C equivalents of the Python variables\n`sys.exc_type`, `sys.exc_value` and `sys.exc_traceback` (see\nthe section on module sys in the\nPython Library Reference (../lib/lib.html)). It is\nimportant to know about them to understand how errors are passed\naround.\nThe Python API defines a number of functions to set various types of\nexceptions.\nThe most common one is PyErr_SetString(). Its arguments\nare an exception object and a C string. The exception object is\nusually a predefined object like PyExc_ZeroDivisionError. The\nC string indicates the cause of the error and is converted to a\nPython string object and stored as the ``associated value'' of the\nexception.\nAnother useful function is PyErr_SetFromErrno(), which only\ntakes an exception argument and constructs the associated value by\ninspection of the global variable errno. The most\ngeneral function is PyErr_SetObject(), which takes two object\narguments, the exception and its associated value. You don't need to\nPy_INCREF() the objects passed to any of these functions.\nYou can test non-destructively whether an exception has been set with\nPyErr_Occurred(). This returns the current exception object,\nor NULL if no exception has occurred. You normally don't need\nto call PyErr_Occurred() to see whether an error occurred in a\nfunction call, since you should be able to tell from the return value.\nWhen a function f that calls another function g detects\nthat the latter fails, f should itself return an error value\n(usually NULL or `-1`). It should not call one of the\nPyErr_*() functions -- one has already been called by g.\nf's caller is then supposed to also return an error indication\nto its caller, again without calling PyErr_*(),\nand so on -- the most detailed cause of the error was already\nreported by the function that first detected it. Once the error\nreaches the Python interpreter's main loop, this aborts the currently\nexecuting Python code and tries to find an exception handler specified\nby the Python programmer.\n(There are situations where a module can actually give a more detailed\nerror message by calling another PyErr_*() function, and in\nsuch cases it is fine to do so. As a general rule, however, this is\nnot necessary, and can cause information about the cause of the error\nto be lost: most operations can fail for a variety of reasons.)\nTo ignore an exception set by a function call that failed, the exception\ncondition must be cleared explicitly by calling PyErr_Clear().\nThe only time C code should call PyErr_Clear() is if it doesn't\nwant to pass the error on to the interpreter but wants to handle it\ncompletely by itself (possibly by trying something else, or pretending\nnothing went wrong).\nEvery failing malloc() call must be turned into an\nexception -- the direct caller of malloc() (or\nrealloc()) must call PyErr_NoMemory() and\nreturn a failure indicator itself. All the object-creating functions\n(for example, PyInt_FromLong()) already do this, so this\nnote is only relevant to those who call malloc() directly.\nAlso note that, with the important exception of\nPyArg_ParseTuple() and friends, functions that return an\ninteger status usually return a positive value or zero for success and\n`-1` for failure, like Unix system calls.\nFinally, be careful to clean up garbage (by making\nPy_XDECREF() or Py_DECREF() calls for objects\nyou have already created) when you return an error indicator!\nThe choice of which exception to raise is entirely yours. There are\npredeclared C objects corresponding to all built-in Python exceptions,\nsuch as PyExc_ZeroDivisionError, which you can use directly.\nOf course, you should choose exceptions wisely -- don't use\nPyExc_TypeError to mean that a file couldn't be opened (that\nshould probably be PyExc_IOError). If something's wrong with\nthe argument list, the PyArg_ParseTuple() function usually\nraises PyExc_TypeError. If you have an argument whose value\nmust be in a particular range or must satisfy other conditions,\nPyExc_ValueError is appropriate.\nYou can also define a new exception that is unique to your module.\nFor this, you usually declare a static object variable at the\nbeginning of your file:\n```text\n\nstatic PyObject *SpamError;\n```\nand initialize it in your module's initialization function\n(initspam()) with an exception object (leaving out\nthe error checking for now):\n```text\n\nvoid\ninitspam(void)\n{\nPyObject *m, *d;\n\nm = Py_InitModule(\"spam\", SpamMethods);\nd = PyModule_GetDict(m);\nSpamError = PyErr_NewException(\"spam.error\", NULL, NULL);\nPyDict_SetItemString(d, \"error\", SpamError);\n}\n```\nNote that the Python name for the exception object is\nspam.error. The PyErr_NewException() function\nmay create a class with the base class being Exception\n(unless another class is passed in instead of NULL), described in the\nPython Library Reference (../lib/lib.html) under ``Built-in\nExceptions.''\nNote also that the SpamError variable retains a reference to\nthe newly created exception class; this is intentional! Since the\nexception could be removed from the module by external code, an owned\nreference to the class is needed to ensure that it will not be\ndiscarded, causing SpamError to become a dangling pointer.\nShould it become a dangling pointer, C code which raises the exception\ncould cause a core dump or other unintended side effects.", "python_version": "2.2", "length": 5984, "url": "https://docs.python.org/2.2/ext/errors.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "../index.html | front.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# Extending and Embedding the Python Interpreter\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 259, "url": "https://docs.python.org/2.2/ext/ext.html"} {"title": "5.4 Extending Embedded Python", "text": "pure-embedding.html | embedding.html | embeddingInCplusplus.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 5.4 Extending Embedded Python\nUntil now, the embedded Python interpreter had no access to\nfunctionality from the application itself. The Python API allows this\nby extending the embedded interpreter. That is, the embedded\ninterpreter gets extended with routines provided by the application.\nWhile it sounds complex, it is not so bad. Simply forget for a while\nthat the application starts the Python interpreter. Instead, consider\nthe application to be a set of subroutines, and write some glue code\nthat gives Python access to those routines, just like you would write\na normal Python extension. For example:\n```text\n\nstatic int numargs=0;\n\n/* Return the number of arguments of the application command line */\nstatic PyObject*\nemb_numargs(PyObject *self, PyObject *args)\n{\nif(!PyArg_ParseTuple(args, \":numargs\"))\nreturn NULL;\nreturn Py_BuildValue(\"i\", numargs);\n}\n\nstatic PyMethodDef EmbMethods[] = {\n{\"numargs\", emb_numargs, METH_VARARGS,\n\"Return the number of arguments received by the process.\"},\n{NULL, NULL, 0, NULL}\n};\n```\nInsert the above code just above the main() function.\nAlso, insert the following two statements directly after\nPy_Initialize():\n```text\n\nnumargs = argc;\nPy_InitModule(\"emb\", EmbMethods);\n```\nThese two lines initialize the `numargs` variable, and make the\nemb.numargs() function accessible to the embedded Python\ninterpreter. With these extensions, the Python script can do things\nlike\n```text\n\nimport emb\nprint \"Number of arguments\", emb.numargs()\n```\nIn a real application, the methods will expose an API of the\napplication to Python.", "python_version": "2.2", "length": 1699, "url": "https://docs.python.org/2.2/ext/extending-with-embedding.html"} {"title": "Front Matter", "text": "ext.html | ext.html | contents.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# Front Matter\nCopyright © 2001 Python Software Foundation.\nAll rights reserved.\nCopyright © 2000 BeOpen.com.\nAll rights reserved.\nCopyright © 1995-2000 Corporation for National Research Initiatives.\nAll rights reserved.\nCopyright © 1991-1995 Stichting Mathematisch Centrum.\nAll rights reserved.\nSee the end of this document for complete license and permissions\ninformation.\n### Abstract:\nPython is an interpreted, object-oriented programming language. This\ndocument describes how to write modules in C or C++ to extend the\nPython interpreter with new modules. Those modules can define new\nfunctions but also new object types and their methods. The document\nalso describes how to embed the Python interpreter in another\napplication, for use as an extension language. Finally, it shows how\nto compile and link extension modules so that they can be loaded\ndynamically (at run time) into the interpreter, if the underlying\noperating system supports this feature.\nThis document assumes basic knowledge about Python. For an informal\nintroduction to the language, see the\nPython Tutorial (../tut/tut.html). The\nPython Reference Manual (../ref/ref.html) gives a more\nformal definition of the language. The\nPython Library Reference (../lib/lib.html) documents the\nexisting object types, functions and modules (both built-in and\nwritten in Python) that give the language its wide application range.\nFor a detailed description of the whole Python/C API, see the separate\nPython/C API Reference Manual (../api/api.html).", "python_version": "2.2", "length": 1614, "url": "https://docs.python.org/2.2/ext/front.html"} {"title": "5.1 Very High Level Embedding", "text": "embedding.html | embedding.html | lower-level-embedding.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 5.1 Very High Level Embedding\nThe simplest form of embedding Python is the use of the very\nhigh level interface. This interface is intended to execute a\nPython script without needing to interact with the application\ndirectly. This can for example be used to perform some operation\non a file.\n```text\n\n#include \n\nint\nmain(int argc, char *argv[])\n{\nPy_Initialize();\nPyRun_SimpleString(\"from time import time,ctime\\n\"\n\"print 'Today is',ctime(time())\\n\");\nPy_Finalize();\nreturn 0;\n}\n```\nThe above code first initializes the Python interpreter with\nPy_Initialize(), followed by the execution of a hard-coded\nPython script that print the date and time. Afterwards, the\nPy_Finalize() call shuts the interpreter down, followed by\nthe end of the program. In a real program, you may want to get the\nPython script from another source, perhaps a text-editor routine, a\nfile, or a database. Getting the Python code from a file can better\nbe done by using the PyRun_SimpleFile() function, which\nsaves you the trouble of allocating memory space and loading the file\ncontents.", "python_version": "2.2", "length": 1202, "url": "https://docs.python.org/2.2/ext/high-level-embedding.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "../index.html | front.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# Extending and Embedding the Python Interpreter\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 259, "url": "https://docs.python.org/2.2/ext/index.html"} {"title": "1. Extending Python with C or C++", "text": "contents.html | ext.html | simpleExample.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1. Extending Python with C or C++\nIt is quite easy to add new built-in modules to Python, if you know\nhow to program in C. Such extension modules can do two things\nthat can't be done directly in Python: they can implement new built-in\nobject types, and they can call C library functions and system calls.\nTo support extensions, the Python API (Application Programmers\nInterface) defines a set of functions, macros and variables that\nprovide access to most aspects of the Python run-time system. The\nPython API is incorporated in a C source file by including the header\n`\"Python.h\"`.\nThe compilation of an extension module depends on its intended use as\nwell as on your system setup; details are given in later chapters.", "python_version": "2.2", "length": 836, "url": "https://docs.python.org/2.2/ext/intro.html"} {"title": "5.6 Linking Requirements", "text": "embeddingInCplusplus.html | embedding.html | reporting-bugs.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 5.6 Linking Requirements\nWhile the configure script shipped with the Python sources\nwill correctly build Python to export the symbols needed by\ndynamically linked extensions, this is not automatically inherited by\napplications which embed the Python library statically, at least on\nUnix. This is an issue when the application is linked to the static\nruntime library (libpython.a) and needs to load dynamic\nextensions (implemented as .so files).\nThe problem is that some entry points are defined by the Python\nruntime solely for extension modules to use. If the embedding\napplication does not use any of these entry points, some linkers will\nnot include those entries in the symbol table of the finished\nexecutable. Some additional options are needed to inform the linker\nnot to remove these symbols.\nDetermining the right options to use for any given platform can be\nquite difficult, but fortunately the Python configuration already has\nthose values. To retrieve them from an installed Python interpreter,\nstart an interactive interpreter and have a short session like this:\n```text\n\n>>> import distutils.sysconfig\n>>> distutils.sysconfig.get_config_var('LINKFORSHARED')\n'-Xlinker -export-dynamic'\n```\nThe contents of the string presented will be the options that should\nbe used. If the string is empty, there's no need to add any\nadditional options. The LINKFORSHARED definition\ncorresponds to the variable of the same name in Python's top-level\nMakefile.", "python_version": "2.2", "length": 1592, "url": "https://docs.python.org/2.2/ext/link-reqs.html"} {"title": "5.2 Beyond Very High Level Embedding: An overview", "text": "high-level-embedding.html | embedding.html | pure-embedding.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 5.2 Beyond Very High Level Embedding: An overview\nThe high level interface gives you the ability to execute\narbitrary pieces of Python code from your application, but\nexchanging data values is quite cumbersome to say the least. If\nyou want that, you should use lower level calls. At the cost of\nhaving to write more C code, you can achieve almost anything.\nIt should be noted that extending Python and embedding Python\nis quite the same activity, despite the different intent. Most\ntopics discussed in the previous chapters are still valid. To\nshow this, consider what the extension code from Python to C\nreally does:\n1. Convert data values from Python to C,\n2. Perform a function call to a C routine using the\nconverted values, and\n3. Convert the data values from the call from C to Python.\nWhen embedding Python, the interface code does:\n1. Convert data values from C to Python,\n2. Perform a function call to a Python interface routine\nusing the converted values, and\n3. Convert the data values from the call from Python to C.\nAs you can see, the data conversion steps are simply swapped to\naccomodate the different direction of the cross-language transfer.\nThe only difference is the routine that you call between both\ndata conversions. When extending, you call a C routine, when\nembedding, you call a Python routine.\nThis chapter will not discuss how to convert data from Python\nto C and vice versa. Also, proper use of references and dealing\nwith errors is assumed to be understood. Since these aspects do not\ndiffer from extending the interpreter, you can refer to earlier\nchapters for the required information.", "python_version": "2.2", "length": 1753, "url": "https://docs.python.org/2.2/ext/lower-level-embedding.html"} {"title": "1.4 The Module's Method Table and Initialization Function", "text": "backToExample.html | intro.html | compilation.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.4 The Module's Method Table and Initialization Function\nI promised to show how spam_system() is called from Python\nprograms. First, we need to list its name and address in a ``method\ntable'':\n```text\n\nstatic PyMethodDef SpamMethods[] = {\n...\n{\"system\", spam_system, METH_VARARGS,\n\"Execute a shell command.\"},\n...\n{NULL, NULL, 0, NULL} /* Sentinel */\n};\n```\nNote the third entry (\"METH_VARARGS\"). This is a flag telling\nthe interpreter the calling convention to be used for the C\nfunction. It should normally always be \"METH_VARARGS\" or\n\"METH_VARARGS | METH_KEYWORDS\"; a value of `0` means that an\nobsolete variant of PyArg_ParseTuple() is used.\nWhen using only \"METH_VARARGS\", the function should expect\nthe Python-level parameters to be passed in as a tuple acceptable for\nparsing via PyArg_ParseTuple(); more information on this\nfunction is provided below.\nThe METH_KEYWORDS bit may be set in the third field if\nkeyword arguments should be passed to the function. In this case, the\nC function should accept a third \"PyObject *\" parameter which\nwill be a dictionary of keywords. Use\nPyArg_ParseTupleAndKeywords() to parse the arguments to\nsuch a function.\nThe method table must be passed to the interpreter in the module's\ninitialization function. The initialization function must be named\ninitname(), where name is the name of the\nmodule, and should be the only non-static item defined in\nthe module file:\n```text\n\nvoid\ninitspam(void)\n{\n(void) Py_InitModule(\"spam\", SpamMethods);\n}\n```\nNote that for C++, this method must be declared `extern \"C\"`.\nWhen the Python program imports module spam for the first\ntime, initspam() is called. (See below for comments about\nembedding Python.) It calls\nPy_InitModule(), which creates a ``module object'' (which\nis inserted in the dictionary `sys.modules` under the key\n`\"spam\"`), and inserts built-in function objects into the newly\ncreated module based upon the table (an array of PyMethodDef\nstructures) that was passed as its second argument.\nPy_InitModule() returns a pointer to the module object\nthat it creates (which is unused here). It aborts with a fatal error\nif the module could not be initialized satisfactorily, so the caller\ndoesn't need to check for errors.\nWhen embedding Python, the initspam() function is not\ncalled automatically unless there's an entry in the\n_PyImport_Inittab table. The easiest way to handle this is to\nstatically initialize your statically-linked modules by directly\ncalling initspam() after the call to\nPy_Initialize() or PyMac_Initialize():\n```text\n\nint main(int argc, char **argv)\n{\n/* Pass argv[0] to the Python interpreter */\nPy_SetProgramName(argv[0]);\n\n/* Initialize the Python interpreter. Required. */\nPy_Initialize();\n\n/* Add a static module */\ninitspam();\n```\nAn example may be found in the file Demo/embed/demo.c in the\nPython source distribution.\nNote:\nRemoving entries from `sys.modules` or importing\ncompiled modules into multiple interpreters within a process (or\nfollowing a fork() without an intervening\nexec()) can create problems for some extension modules.\nExtension module authors should exercise caution when initializing\ninternal data structures.\nNote also that the reload() function can be used with\nextension modules, and will call the module initialization function\n(initspam() in the example), but will not load the module\nagain if it was loaded from a dynamically loadable object file\n(.so on Unix, .dll on Windows).\nA more substantial example module is included in the Python source\ndistribution as Modules/xxmodule.c. This file may be used as a\ntemplate or simply read as an example. The modulator.py\nscript included in the source distribution or Windows install provides\na simple graphical user interface for declaring the functions and\nobjects which a module should implement, and can generate a template\nwhich can be filled in. The script lives in the\nTools/modulator/ directory; see the README file there\nfor more information.", "python_version": "2.2", "length": 4065, "url": "https://docs.python.org/2.2/ext/methodTable.html"} {"title": "3.3 Example", "text": "module-defn-options.html | building-on-unix.html | distributing.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3.3 Example\nHere is a more complicated example from Modules/Setup.dist:\n```text\n\nGMP=/ufs/guido/src/gmp\nmpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a\n```\nwhich could also be written as:\n```text\n\nmpz mpzmodule.c -I$(GMP) -L$(GMP) -lgmp\n```", "python_version": "2.2", "length": 373, "url": "https://docs.python.org/2.2/ext/module-defn-example.html"} {"title": "3.2 Module Definition Options", "text": "custom-interps.html | building-on-unix.html | module-defn-example.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3.2 Module Definition Options\nSeveral compiler options are supported:\nOther compiler options can be included (snuck in) by putting them\nin variables.\nSource files can include files with .c, .C, .cc,\n.cpp, .cxx, and .c++ extensions.\nOther input files include files with .a, .o, .sl,\nand .so extensions.", "python_version": "2.2", "length": 443, "url": "https://docs.python.org/2.2/ext/module-defn-options.html"} {"title": "2.2.1 Finalization and De-allocation", "text": "dnt-type-methods.html | dnt-type-methods.html | node24.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 2.2.1 Finalization and De-allocation\n```text\n\ndestructor tp_dealloc;\n```\nThis function is called when the reference count of the instance of\nyour type is reduced to zero and the Python interpreter wants to\nreclaim it. If your type has memory to free or other clean-up to\nperform, put it here. The object itself needs to be freed here as\nwell. Here is an example of this function:\n```text\n\nstatic void\nnewdatatype_dealloc(newdatatypeobject * obj)\n{\nfree(obj->obj_UnderlyingDatatypePtr);\nPyObject_DEL(obj);\n}\n```\nOne important requirement of the deallocator function is that it\nleaves any pending exceptions alone. This is important since\ndeallocators are frequently called as the interpreter unwinds the\nPython stack; when the stack is unwound due to an exception (rather\nthan normal returns), nothing is done to protect the deallocators from\nseeing that an exception has already been set. Any actions which a\ndeallocator performs which may cause additional Python code to be\nexecuted may detect that an exception has been set. This can lead to\nmisleading errors from the interpreter. The proper way to protect\nagainst this is to save a pending exception before performing the\nunsafe action, and restoring it when done. This can be done using the\nPyErr_Fetch()and\nPyErr_Restore()functions:\n```text\n\nstatic void\nmy_dealloc(PyObject *obj)\n{\nMyObject *self = (MyObject *) obj;\nPyObject *cbresult;\n\nif (self->my_callback != NULL) {\nPyObject *err_type, *err_value, *err_traceback;\nint have_error = PyErr_Occurred() ? 1 : 0;\n\nif (have_error)\nPyErr_Fetch(&err_type, &err_value, &err_traceback);\n\ncbresult = PyObject_CallObject(self->my_callback, NULL);\nif (cbresult == NULL)\nPyErr_WriteUnraisable();\nelse\nPy_DECREF(cbresult);\n\nif (have_error)\nPyErr_Restore(err_type, err_value, err_traceback);\n\nPy_DECREF(self->my_callback);\n}\nPyObject_DEL(obj);\n}\n```", "python_version": "2.2", "length": 1975, "url": "https://docs.python.org/2.2/ext/node23.html"} {"title": "2.2.2 Object Representation", "text": "node23.html | dnt-type-methods.html | node25.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 2.2.2 Object Representation\nIn Python, there are three ways to generate a textual representation\nof an object: the repr()function (or\nequivalent backtick syntax), the str()function, and the print statement. For most objects, the\nprint statement is equivalent to the str()\nfunction, but it is possible to special-case printing to a\nFILE* if necessary; this should only be done if efficiency is\nidentified as a problem and profiling suggests that creating a\ntemporary string object to be written to a file is too expensive.\nThese handlers are all optional, and most types at most need to\nimplement the tp_str and tp_repr handlers.\n```text\n\nreprfunc tp_repr;\nreprfunc tp_str;\nprintfunc tp_print;\n```\nThe tp_repr handler should return a string object containing\na representation of the instance for which it is called. Here is a\nsimple example:\n```text\n\nstatic PyObject *\nnewdatatype_repr(newdatatypeobject * obj)\n{\nreturn PyString_FromFormat(\"Repr-ified_newdatatype{{size:\\%d}}\",\nobj->obj_UnderlyingDatatypePtr->size);\n}\n```\nIf no tp_repr handler is specified, the interpreter will\nsupply a representation that uses the type's tp_name and a\nuniquely-identifying value for the object.\nThe tp_str handler is to str() what the\ntp_repr handler described above is to repr(); that\nis, it is called when Python code calls str() on an\ninstance of your object. It's implementation is very similar to the\ntp_repr function, but the resulting string is intended for\nhuman consumption. It tp_str is not specified, the\ntp_repr handler is used instead.\nHere is a simple example:\n```text\n\nstatic PyObject *\nnewdatatype_str(newdatatypeobject * obj)\n{\nreturn PyString_FromFormat(\"Stringified_newdatatype{{size:\\%d}}\",\nobj->obj_UnderlyingDatatypePtr->size\n);\n}\n```\nThe print function will be called whenever Python needs to \"print\" an\ninstance of the type. For example, if 'node' is an instance of type\nTreeNode, then the print function is called when Python code calls:\n```text\n\nprint node\n```\nThere is a flags argument and one flag, Py_PRINT_RAW, and\nit suggests that you print without string quotes and possibly without\ninterpreting escape sequences.\nThe print function receives a file object as an argument. You will\nlikely want to write to that file object.\nHere is a sampe print function:\n```text\n\nstatic int\nnewdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)\n{\nif (flags & Py_PRINT_RAW) {\nfprintf(fp, \"<{newdatatype object--size: %d}>\",\nobj->obj_UnderlyingDatatypePtr->size);\n}\nelse {\nfprintf(fp, \"\\\"<{newdatatype object--size: %d}>\\\"\",\nobj->obj_UnderlyingDatatypePtr->size);\n}\nreturn 0;\n}\n```", "python_version": "2.2", "length": 2712, "url": "https://docs.python.org/2.2/ext/node24.html"} {"title": "2.2.3 Attribute Management Functions", "text": "node24.html | dnt-type-methods.html | node26.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 2.2.3 Attribute Management Functions\n```text\n\ngetattrfunc tp_getattr;\nsetattrfunc tp_setattr;\n```\nThe tp_getattr handle is called when the object requires an\nattribute look-up. It is called in the same situations where the\n__getattr__() method of a class would be called.\nA likely way to handle this is (1) to implement a set of functions\n(such as newdatatype_getSize() and\nnewdatatype_setSize() in the example below), (2) provide a\nmethod table listing these functions, and (3) provide a getattr\nfunction that returns the result of a lookup in that table.\nHere is an example:\n```text\n\nstatic PyMethodDef newdatatype_methods[] = {\n{\"getSize\", (PyCFunction)newdatatype_getSize, METH_VARARGS,\n\"Return the current size.\"},\n{\"setSize\", (PyCFunction)newdatatype_setSize, METH_VARARGS,\n\"Set the size.\"},\n{NULL, NULL, 0, NULL} /* sentinel */\n};\n\nstatic PyObject *\nnewdatatype_getattr(newdatatypeobject *obj, char *name)\n{\nreturn Py_FindMethod(newdatatype_methods, (PyObject *)obj, name);\n}\n```\nThe tp_setattr handler is called when the\n__setattr__() or __delattr__() method of a class\ninstance would be called. When an attribute should be deleted, the\nthird parameter will be NULL. Here is an example that simply raises\nan exception; if this were really all you wanted, the\ntp_setattr handler should be set to NULL.\n```text\n\nstatic int\nnewdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)\n{\n(void)PyErr_Format(PyExc_RuntimeError, \"Read-only attribute: \\%s\", name);\nreturn -1;\n}\n```", "python_version": "2.2", "length": 1612, "url": "https://docs.python.org/2.2/ext/node25.html"} {"title": "2.2.4 Object Comparison", "text": "node25.html | dnt-type-methods.html | node27.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 2.2.4 Object Comparison\n```text\n\ncmpfunc tp_compare;\n```\nThe tp_compare handler is called when comparisons are needed\nare the object does not implement the specific rich comparison method\nwhich matches the requested comparison. (It is always used if defined\nand the PyObject_Compare() or PyObject_Cmp()\nfunctions are used, or if cmp() is used from Python.)\nIt is analogous to the __cmp__() method. This function\nshould return `-1` if obj1 is less than\nobj2, `0` if they are equal, and `1` if\nobj1 is greater than\nobj2.\n(It was previously allowed to return arbitrary negative or positive\nintegers for less than and greater than, respectively; as of Python\n2.2, this is no longer allowed. In the future, other return values\nmay be assigned a different meaning.)\nA tp_compare handler may raise an exception. In this case it\nshould return a negative value. The caller has to test for the\nexception using PyErr_Occurred().\nHere is a sample implementation:\n```text\n\nstatic int\nnewdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2)\n{\nlong result;\n\nif (obj1->obj_UnderlyingDatatypePtr->size <\nobj2->obj_UnderlyingDatatypePtr->size) {\nresult = -1;\n}\nelse if (obj1->obj_UnderlyingDatatypePtr->size >\nobj2->obj_UnderlyingDatatypePtr->size) {\nresult = 1;\n}\nelse {\nresult = 0;\n}\nreturn result;\n}\n```", "python_version": "2.2", "length": 1426, "url": "https://docs.python.org/2.2/ext/node26.html"} {"title": "2.2.5 Abstract Protocol Support", "text": "node26.html | dnt-type-methods.html | node28.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 2.2.5 Abstract Protocol Support\n```text\n\ntp_as_number;\ntp_as_sequence;\ntp_as_mapping;\n```\nIf you wish your object to be able to act like a number, a sequence,\nor a mapping object, then you place the address of a structure that\nimplements the C type PyNumberMethods,\nPySequenceMethods, or PyMappingMethods, respectively.\nIt is up to you to fill in this structure with appropriate values. You\ncan find examples of the use of each of these in the Objects\ndirectory of the Python source distribution.\n```text\n\nhashfunc tp_hash;\n```\nThis function, if you choose to provide it, should return a hash\nnumber for an instance of your datatype. Here is a moderately\npointless example:\n```text\n\nstatic long\nnewdatatype_hash(newdatatypeobject *obj)\n{\nlong result;\nresult = obj->obj_UnderlyingDatatypePtr->size;\nresult = result * 3;\nreturn result;\n}\n```\n```text\n\nternaryfunc tp_call;\n```\nThis function is called when an instance of your datatype is \"called\",\nfor example, if `obj1` is an instance of your datatype and the Python\nscript contains `obj1('hello')`, the tp_call handler is\ninvoked.\nThis function takes three arguments:\n1. arg1 is the instance of the datatype which is the subject of\nthe call. If the call is `obj1('hello')`, then arg1 is\n`obj1`.\n2. arg2 is a tuple containing the arguments to the call. You\ncan use PyArg_ParseTuple() to extract the arguments.\n3. arg3 is a dictionary of keyword arguments that were passed.\nIf this is non-NULL and you support keyword arguments, use\nPyArg_ParseTupleAndKeywords() to extract the\narguments. If you do not want to support keyword arguments and\nthis is non-NULL, raise a TypeError with a message\nsaying that keyword arguments are not supported.\nHere is a desultory example of the implementation of call function.\n```text\n\n/* Implement the call function.\n* obj1 is the instance receiving the call.\n* obj2 is a tuple containing the arguments to the call, in this\n* case 3 strings.\n*/\nstatic PyObject *\nnewdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)\n{\nPyObject *result;\nchar *arg1;\nchar *arg2;\nchar *arg3;\n\nif (!PyArg_ParseTuple(args, \"sss:call\", &arg1, &arg2, &arg3)) {\nreturn NULL;\n}\nresult = PyString_FromFormat(\n\"Returning -- value: [\\%d] arg1: [\\%s] arg2: [\\%s] arg3: [\\%s]\\n\",\nobj->obj_UnderlyingDatatypePtr->size,\narg1, arg2, arg3);\nprintf(\"\\%s\", PyString_AS_STRING(result));\nreturn result;\n}\n```", "python_version": "2.2", "length": 2492, "url": "https://docs.python.org/2.2/ext/node27.html"} {"title": "2.2.6 More Suggestions", "text": "node27.html | dnt-type-methods.html | building-on-unix.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 2.2.6 More Suggestions\nRemember that you can omit most of these functions, in which case you\nprovide `0` as a value.\nIn the Objects directory of the Python source distribution,\nthere is a file xxobject.c, which is intended to be used as a\ntemplate for the implementation of new types. One useful strategy\nfor implementing a new type is to copy and rename this file, then\nread the instructions at the top of it.\nThere are type definitions for each of the functions you must\nprovide. They are in object.h in the Python include\ndirectory that comes with the source distribution of Python.\nIn order to learn how to implement any specific method for your new\ndatatype, do the following: Download and unpack the Python source\ndistribution. Go the the Objects directory, then search the\nC source files for `tp_` plus the function you want (for\nexample, `tp_print` or `tp_compare`). You will find\nexamples of the function you want to implement.\nWhen you need to verify that the type of an object is indeed the\nobject you are implementing and if you use xxobject.c as an starting\ntemplate for your implementation, then there is a macro defined for\nthis purpose. The macro definition will look something like this:\n```text\n\n#define is_newdatatypeobject(v) ((v)->ob_type == &Newdatatypetype)\n```\nAnd, a sample of its use might be something like the following:", "python_version": "2.2", "length": 1480, "url": "https://docs.python.org/2.2/ext/node28.html"} {"title": "B. History and License", "text": "reporting-bugs.html | ext.html | node47.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# B. History and License", "python_version": "2.2", "length": 138, "url": "https://docs.python.org/2.2/ext/node46.html"} {"title": "B.1 History of the software", "text": "node46.html | node46.html | node48.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# B.1 History of the software\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands\nas a successor of a language called ABC. Guido remains Python's\nprincipal author, although it includes many contributions from others.\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)\nin Reston, Virginia where he released several versions of the\nsoftware.\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team. In October of the same\nyear, the PythonLabs team moved to Zope Corporation (then Digital\nCreations; see http://www.zope.com/). In 2001, the Python\nSoftware Foundation (PSF, see http://www.python.org/psf/) was\nformed, a non-profit organization created specifically to own\nPython-related Intellectual Property. Digital Creations is a\nsponsoring member of the PSF.\nAll Python releases are Open Source (see\nhttp://www.opensource.org/ for the Open Source Definition).\nHistorically, most, but not all, Python releases have also been\nGPL-compatible; the table below summarizes the various releases.\nNote:\nGPL-compatible doesn't mean that we're distributing\nPython under the GPL. All Python licenses, unlike the GPL, let you\ndistribute a modified version without making your changes open source.\nThe GPL-compatible licenses make it possible to combine Python with\nother software that is released under the GPL; the others don't.\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.", "python_version": "2.2", "length": 1769, "url": "https://docs.python.org/2.2/ext/node47.html"} {"title": "B.2 Terms and conditions for accessing or otherwise using Python", "text": "node47.html | node46.html | about.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# B.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.2\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.2 software in source or binary\nform and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, PSF\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python\n2.2 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001 Python Software Foundation; All Rights\nReserved'' are retained in Python 2.2 alone or in any\nderivative version prepared by Licensee.\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 2.2 or any part thereof, and wants to\nmake the derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 2.2.\n4. PSF is making Python 2.2 available to Licensee on an ``AS IS''\nbasis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE\nPOSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee. This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n8. By copying, installing or otherwise using Python 2.2, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (``Licensee'') accessing and otherwise\nusing this software in source or binary form and its associated\ndocumentation (``the Software'').\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n3. BeOpen is making the Software available to Licensee on an ``AS IS''\nbasis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions. Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee. This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party. As an exception, the ``BeOpen Python'' logos available\nat http://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (``CNRI''), and the Individual or Organization\n(``Licensee'') accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., ``Copyright\n© 1995-2001 Corporation for National Research Initiatives;\nAll Rights Reserved'' are retained in Python 1.6.1 alone or in any\nderivative version prepared by Licensee. Alternately, in lieu of\nCNRI's License Agreement, Licensee may substitute the following text\n(omitting the quotes): ``Python 1.6.1 is made available subject to the\nterms and conditions in CNRI's License Agreement. This Agreement\ntogether with Python 1.6.1 may be located on the Internet using the\nfollowing unique, persistent identifier (known as a handle):\n1895.22/1013. This Agreement may also be obtained from a proxy server\non the Internet using the following URL:\nhttp://hdl.handle.net/1895.22/1013.''\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''\nbasis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement. Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee. This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n8. By clicking on the ``ACCEPT'' button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\nACCEPT\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\nCopyright © 1991 - 1995, Stichting Mathematisch Centrum\nAmsterdam, The Netherlands. All rights reserved.\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", "python_version": "2.2", "length": 9773, "url": "https://docs.python.org/2.2/ext/node48.html"} {"title": "1.10.4 NULL Pointers", "text": "thinIce.html | refcounts.html | cplusplus.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.4 NULL Pointers\nIn general, functions that take object references as arguments do not\nexpect you to pass them NULL pointers, and will dump core (or\ncause later core dumps) if you do so. Functions that return object\nreferences generally return NULL only to indicate that an\nexception occurred. The reason for not testing for NULL\narguments is that functions often pass the objects they receive on to\nother function -- if each function were to test for NULL,\nthere would be a lot of redundant tests and the code would run more\nslowly.\nIt is better to test for NULL only at the ``source:'' when a\npointer that may be NULL is received, for example, from\nmalloc() or from a function that may raise an exception.\nThe macros Py_INCREF() and Py_DECREF()\ndo not check for NULL pointers -- however, their variants\nPy_XINCREF() and Py_XDECREF() do.\nThe macros for checking for a particular object type\n(`Py type _Check()`) don't check for NULL pointers --\nagain, there is much code that calls several of these in a row to test\nan object against various different expected types, and this would\ngenerate redundant tests. There are no variants with NULL\nchecking.\nThe C function calling mechanism guarantees that the argument list\npassed to C functions (`args` in the examples) is never\nNULL -- in fact it guarantees that it is always a tuple.1.4 (#foot698)\nIt is a severe error to ever let a NULL pointer ``escape'' to\nthe Python user.", "python_version": "2.2", "length": 1547, "url": "https://docs.python.org/2.2/ext/nullPointers.html"} {"title": "1.10.2 Ownership Rules", "text": "refcountsInPython.html | refcounts.html | thinIce.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.2 Ownership Rules\nWhenever an object reference is passed into or out of a function, it\nis part of the function's interface specification whether ownership is\ntransferred with the reference or not.\nMost functions that return a reference to an object pass on ownership\nwith the reference. In particular, all functions whose function it is\nto create a new object, such as PyInt_FromLong() and\nPy_BuildValue(), pass ownership to the receiver. Even if\nthe object is not actually new, you still receive ownership of a new\nreference to that object. For instance, PyInt_FromLong()\nmaintains a cache of popular values and can return a reference to a\ncached item.\nMany functions that extract objects from other objects also transfer\nownership with the reference, for instance\nPyObject_GetAttrString(). The picture is less clear, here,\nhowever, since a few common routines are exceptions:\nPyTuple_GetItem(), PyList_GetItem(),\nPyDict_GetItem(), and PyDict_GetItemString()\nall return references that you borrow from the tuple, list or\ndictionary.\nThe function PyImport_AddModule() also returns a borrowed\nreference, even though it may actually create the object it returns:\nthis is possible because an owned reference to the object is stored in\n`sys.modules`.\nWhen you pass an object reference into another function, in general,\nthe function borrows the reference from you -- if it needs to store\nit, it will use Py_INCREF() to become an independent\nowner. There are exactly two important exceptions to this rule:\nPyTuple_SetItem() and PyList_SetItem(). These\nfunctions take over ownership of the item passed to them -- even if\nthey fail! (Note that PyDict_SetItem() and friends don't\ntake over ownership -- they are ``normal.'')\nWhen a C function is called from Python, it borrows references to its\narguments from the caller. The caller owns a reference to the object,\nso the borrowed reference's lifetime is guaranteed until the function\nreturns. Only when such a borrowed reference must be stored or passed\non, it must be turned into an owned reference by calling\nPy_INCREF().\nThe object reference returned from a C function that is called from\nPython must be an owned reference -- ownership is tranferred from the\nfunction to its caller.", "python_version": "2.2", "length": 2360, "url": "https://docs.python.org/2.2/ext/ownershipRules.html"} {"title": "1.7 Extracting Parameters in Extension Functions", "text": "callingPython.html | intro.html | parseTupleAndKeywords.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.7 Extracting Parameters in Extension Functions\nThe PyArg_ParseTuple() function is declared as follows:\n```text\n\nint PyArg_ParseTuple(PyObject *arg, char *format, ...);\n```\nThe arg argument must be a tuple object containing an argument\nlist passed from Python to a C function. The format argument\nmust be a format string, whose syntax is explained below. The\nremaining arguments must be addresses of variables whose type is\ndetermined by the format string. For the conversion to succeed, the\narg object must match the format and the format must be\nexhausted. On success, PyArg_ParseTuple() returns true,\notherwise it returns false and raises an appropriate exception.\nNote that while PyArg_ParseTuple() checks that the Python\narguments have the required types, it cannot check the validity of the\naddresses of C variables passed to the call: if you make mistakes\nthere, your code will probably crash or at least overwrite random bits\nin memory. So be careful!\nA format string consists of zero or more ``format units''. A format\nunit describes one Python object; it is usually a single character or\na parenthesized sequence of format units. With a few exceptions, a\nformat unit that is not a parenthesized sequence normally corresponds\nto a single address argument to PyArg_ParseTuple(). In the\nfollowing description, the quoted form is the format unit; the entry\nin (round) parentheses is the Python object type that matches the\nformat unit; and the entry in [square] brackets is the type of the C\nvariable(s) whose address should be passed. (Use the \"&\"operator to pass a variable's address.)\nNote that any Python object references which are provided to the\ncaller are borrowed references; do not decrement their\nreference count!\n\"s\" (string or Unicode object) [char *]: Convert a Python string or Unicode object to a C pointer to a\ncharacter string. You must not provide storage for the string\nitself; a pointer to an existing string is stored into the character\npointer variable whose address you pass. The C string is\nnull-terminated. The Python string must not contain embedded null\nbytes; if it does, a TypeError exception is raised.\nUnicode objects are converted to C strings using the default\nencoding. If this conversion fails, an UnicodeError is\nraised.\n\"s#\" (string, Unicode or any read buffer compatible object)\n[char *, int]: This variant on \"s\" stores into two C variables, the first one a\npointer to a character string, the second one its length. In this\ncase the Python string may contain embedded null bytes. Unicode\nobjects pass back a pointer to the default encoded string version of the\nobject if such a conversion is possible. All other read buffer\ncompatible objects pass back a reference to the raw internal data\nrepresentation.\n\"z\" (string or `None`) [char *]: Like \"s\", but the Python object may also be `None`, in which\ncase the C pointer is set to NULL.\n\"z#\" (string or `None` or any read buffer compatible object)\n[char *, int]: This is to \"s#\" as \"z\" is to \"s\".\n\"u\" (Unicode object) [Py_UNICODE *]: Convert a Python Unicode object to a C pointer to a null-terminated\nbuffer of 16-bit Unicode (UTF-16) data. As with \"s\", there is no need\nto provide storage for the Unicode data buffer; a pointer to the\nexisting Unicode data is stored into the Py_UNICODE pointer variable whose\naddress you pass.\n\"u#\" (Unicode object) [Py_UNICODE *, int]: This variant on \"u\" stores into two C variables, the first one\na pointer to a Unicode data buffer, the second one its length.\n\"es\" (string, Unicode object or character buffer compatible\nobject) [const char *encoding, char **buffer]: This variant on \"s\" is used for encoding Unicode and objects\nconvertible to Unicode into a character buffer. It only works for\nencoded data without embedded NULL bytes.\nThe variant reads one C variable and stores into two C variables, the\nfirst one a pointer to an encoding name string (encoding), and the\nsecond a pointer to a pointer to a character buffer (**buffer,\nthe buffer used for storing the encoded data).\nThe encoding name must map to a registered codec. If set to NULL,\nthe default encoding is used.\nPyArg_ParseTuple() will allocate a buffer of the needed\nsize using PyMem_NEW(), copy the encoded data into this\nbuffer and adjust *buffer to reference the newly allocated\nstorage. The caller is responsible for calling\nPyMem_Free() to free the allocated buffer after usage.\n\"et\" (string, Unicode object or character buffer compatible\nobject) [const char *encoding, char **buffer]: Same as \"es\" except that string objects are passed through without\nrecoding them. Instead, the implementation assumes that the string\nobject uses the encoding passed in as parameter.\n\"es#\" (string, Unicode object or character buffer compatible\nobject) [const char *encoding, char **buffer, int *buffer_length]: This variant on \"s#\" is used for encoding Unicode and objects\nconvertible to Unicode into a character buffer. It reads one C\nvariable and stores into three C variables, the first one a pointer to\nan encoding name string (encoding), the second a pointer to a\npointer to a character buffer (**buffer, the buffer used for\nstoring the encoded data) and the third one a pointer to an integer\n(*buffer_length, the buffer length).\nThe encoding name must map to a registered codec. If set to NULL,\nthe default encoding is used.\nThere are two modes of operation:\nIf *buffer points a NULL pointer,\nPyArg_ParseTuple() will allocate a buffer of the needed\nsize using PyMem_NEW(), copy the encoded data into this\nbuffer and adjust *buffer to reference the newly allocated\nstorage. The caller is responsible for calling\nPyMem_Free() to free the allocated buffer after usage.\nIf *buffer points to a non-NULL pointer (an already allocated\nbuffer), PyArg_ParseTuple() will use this location as\nbuffer and interpret *buffer_length as buffer size. It will then\ncopy the encoded data into the buffer and 0-terminate it. Buffer\noverflow is signalled with an exception.\nIn both cases, *buffer_length is set to the length of the\nencoded data without the trailing 0-byte.\n\"et#\" (string, Unicode object or character buffer compatible\nobject) [const char *encoding, char **buffer]: Same as \"es#\" except that string objects are passed through without\nrecoding them. Instead, the implementation assumes that the string\nobject uses the encoding passed in as parameter.\n\"b\" (integer) [char]: Convert a Python integer to a tiny int, stored in a C char.\n\"h\" (integer) [short int]: Convert a Python integer to a C short int.\n\"i\" (integer) [int]: Convert a Python integer to a plain C int.\n\"l\" (integer) [long int]: Convert a Python integer to a C long int.\n\"L\" (integer) [LONG_LONG]: Convert a Python integer to a C long long. This format is only\navailable on platforms that support long long (or _int64\non Windows).\n\"c\" (string of length 1) [char]: Convert a Python character, represented as a string of length 1, to a\nC char.\n\"f\" (float) [float]: Convert a Python floating point number to a C float.\n\"d\" (float) [double]: Convert a Python floating point number to a C double.\n\"D\" (complex) [Py_complex]: Convert a Python complex number to a C Py_complex structure.\n\"O\" (object) [PyObject *]: Store a Python object (without any conversion) in a C object pointer.\nThe C program thus receives the actual object that was passed. The\nobject's reference count is not increased. The pointer stored is not\nNULL.\n\"O!\" (object) [typeobject, PyObject *]: Store a Python object in a C object pointer. This is similar to\n\"O\", but takes two C arguments: the first is the address of a\nPython type object, the second is the address of the C variable (of\ntype PyObject *) into which the object pointer is stored.\nIf the Python object does not have the required type,\nTypeError is raised.\n\"O&\" (object) [converter, anything]: Convert a Python object to a C variable through a converter\nfunction. This takes two arguments: the first is a function, the\nsecond is the address of a C variable (of arbitrary type), converted\nto void *. The converter function in turn is called as\nfollows:\nstatus`=`converter`(`object, address`);`\nwhere object is the Python object to be converted and\naddress is the void * argument that was passed to\nPyArg_ConvertTuple(). The returned status should be\n`1` for a successful conversion and `0` if the conversion\nhas failed. When the conversion fails, the converter function\nshould raise an exception.\n\"S\" (string) [PyStringObject *]: Like \"O\" but requires that the Python object is a string object.\nRaises TypeError if the object is not a string object.\nThe C variable may also be declared as PyObject *.\n\"U\" (Unicode string) [PyUnicodeObject *]: Like \"O\" but requires that the Python object is a Unicode object.\nRaises TypeError if the object is not a Unicode object.\nThe C variable may also be declared as PyObject *.\n\"t#\" (read-only character buffer) [char *, int]: Like \"s#\", but accepts any object which implements the read-only\nbuffer interface. The char * variable is set to point to the\nfirst byte of the buffer, and the int is set to the length of\nthe buffer. Only single-segment buffer objects are accepted;\nTypeError is raised for all others.\n\"w\" (read-write character buffer) [char *]: Similar to \"s\", but accepts any object which implements the\nread-write buffer interface. The caller must determine the length of\nthe buffer by other means, or use \"w#\" instead. Only\nsingle-segment buffer objects are accepted; TypeError is\nraised for all others.\n\"w#\" (read-write character buffer) [char *, int]: Like \"s#\", but accepts any object which implements the\nread-write buffer interface. The char * variable is set to\npoint to the first byte of the buffer, and the int is set to\nthe length of the buffer. Only single-segment buffer objects are\naccepted; TypeError is raised for all others.\n\"(items)\" (tuple) [matching-items]: The object must be a Python sequence whose length is the number of\nformat units in items. The C arguments must correspond to the\nindividual format units in items. Format units for sequences\nmay be nested.\nNote:\nPrior to Python version 1.5.2, this format specifier\nonly accepted a tuple containing the individual parameters, not an\narbitrary sequence. Code which previously caused\nTypeError to be raised here may now proceed without an\nexception. This is not expected to be a problem for existing code.\nIt is possible to pass Python long integers where integers are\nrequested; however no proper range checking is done -- the most\nsignificant bits are silently truncated when the receiving field is\ntoo small to receive the value (actually, the semantics are inherited\nfrom downcasts in C -- your mileage may vary).\nA few other characters have a meaning in a format string. These may\nnot occur inside nested parentheses. They are:\n\"|\": Indicates that the remaining arguments in the Python argument list are\noptional. The C variables corresponding to optional arguments should\nbe initialized to their default value -- when an optional argument is\nnot specified, PyArg_ParseTuple() does not touch the contents\nof the corresponding C variable(s).\n\":\": The list of format units ends here; the string after the colon is used\nas the function name in error messages (the ``associated value'' of\nthe exception that PyArg_ParseTuple() raises).\n\";\": The list of format units ends here; the string after the semicolon is\nused as the error message instead of the default error message.\nClearly, \":\" and \";\" mutually exclude each other.\nSome example calls:\n```text\n\nint ok;\nint i, j;\nlong k, l;\nchar *s;\nint size;\n\nok = PyArg_ParseTuple(args, \"\"); /* No arguments */\n/* Python call: f() */\n```\n```text\n\nok = PyArg_ParseTuple(args, \"s\", &s); /* A string */\n/* Possible Python call: f('whoops!') */\n```\n```text\n\nok = PyArg_ParseTuple(args, \"lls\", &k, &l, &s); /* Two longs and a string */\n/* Possible Python call: f(1, 2, 'three') */\n```\n```text\n\nok = PyArg_ParseTuple(args, \"(ii)s#\", &i, &j, &s, &size);\n/* A pair of ints and a string, whose size is also returned */\n/* Possible Python call: f((1, 2), 'three') */\n```\n```text\n\n{\nchar *file;\nchar *mode = \"r\";\nint bufsize = 0;\nok = PyArg_ParseTuple(args, \"s|si\", &file, &mode, &bufsize);\n/* A string, and optionally another string and an integer */\n/* Possible Python calls:\nf('spam')\nf('spam', 'w')\nf('spam', 'wb', 100000) */\n}\n```\n```text\n\n{\nint left, top, right, bottom, h, v;\nok = PyArg_ParseTuple(args, \"((ii)(ii))(ii)\",\n&left, &top, &right, &bottom, &h, &v);\n/* A rectangle and a point */\n/* Possible Python call:\nf(((0, 0), (400, 300)), (10, 10)) */\n}\n```\n```text\n\n{\nPy_complex c;\nok = PyArg_ParseTuple(args, \"D:myfunction\", &c);\n/* a complex, also providing a function name for errors */\n/* Possible Python call: myfunction(1+2j) */\n}\n```", "python_version": "2.2", "length": 12825, "url": "https://docs.python.org/2.2/ext/parseTuple.html"} {"title": "1.8 Keyword Parameters for Extension Functions", "text": "parseTuple.html | intro.html | buildValue.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.8 Keyword Parameters for Extension Functions\nThe PyArg_ParseTupleAndKeywords() function is declared as\nfollows:\n```text\n\nint PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,\nchar *format, char **kwlist, ...);\n```\nThe arg and format parameters are identical to those of the\nPyArg_ParseTuple() function. The kwdict parameter\nis the dictionary of keywords received as the third parameter from the\nPython runtime. The kwlist parameter is a NULL-terminated\nlist of strings which identify the parameters; the names are matched\nwith the type information from format from left to right. On\nsuccess, PyArg_ParseTupleAndKeywords() returns true,\notherwise it returns false and raises an appropriate exception.\nNote:\nNested tuples cannot be parsed when using keyword\narguments! Keyword parameters passed in which are not present in the\nkwlist will cause TypeError to be raised.\nHere is an example module which uses keywords, based on an example by\nGeoff Philbrick (philbrick@hks.com):\n```text\n\n#include \"Python.h\"\n\nstatic PyObject *\nkeywdarg_parrot(self, args, keywds)\nPyObject *self;\nPyObject *args;\nPyObject *keywds;\n{\nint voltage;\nchar *state = \"a stiff\";\nchar *action = \"voom\";\nchar *type = \"Norwegian Blue\";\n\nstatic char *kwlist[] = {\"voltage\", \"state\", \"action\", \"type\", NULL};\n\nif (!PyArg_ParseTupleAndKeywords(args, keywds, \"i|sss\", kwlist,\n&voltage, &state, &action, &type))\nreturn NULL;\n\nprintf(\"-- This parrot wouldn't %s if you put %i Volts through it.\\n\",\naction, voltage);\nprintf(\"-- Lovely plumage, the %s -- It's %s!\\n\", type, state);\n\nPy_INCREF(Py_None);\n\nreturn Py_None;\n}\n\nstatic PyMethodDef keywdarg_methods[] = {\n/* The cast of the function is necessary since PyCFunction values\n* only take two PyObject* parameters, and keywdarg_parrot() takes\n* three.\n*/\n{\"parrot\", (PyCFunction)keywdarg_parrot, METH_VARARGS|METH_KEYWORDS,\n\"Print a lovely skit to standard output.\"},\n{NULL, NULL, 0, NULL} /* sentinel */\n};\n\nvoid\ninitkeywdarg(void)\n{\n/* Create the module and add the functions */\nPy_InitModule(\"keywdarg\", keywdarg_methods);\n}\n```", "python_version": "2.2", "length": 2174, "url": "https://docs.python.org/2.2/ext/parseTupleAndKeywords.html"} {"title": "5.3 Pure Embedding", "text": "lower-level-embedding.html | embedding.html | extending-with-embedding.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 5.3 Pure Embedding\nThe first program aims to execute a function in a Python\nscript. Like in the section about the very high level interface,\nthe Python interpreter does not directly interact with the\napplication (but that will change in th next section).\nThe code to run a function defined in a Python script is:\n```text\n#include \n\nint\nmain(int argc, char *argv[])\n{\nPyObject *pName, *pModule, *pDict, *pFunc;\nPyObject *pArgs, *pValue;\nint i, result;\n\nif (argc < 3) {\nfprintf(stderr,\"Usage: call pythonfile funcname [args]\\n\");\nreturn 1;\n}\n\nPy_Initialize();\npName = PyString_FromString(argv[1]);\n/* Error checking of pName left out */\n\npModule = PyImport_Import(pName);\nif (pModule != NULL) {\npDict = PyModule_GetDict(pModule);\n/* pDict is a borrowed reference */\n\npFunc = PyDict_GetItemString(pDict, argv[2]);\n/* pFun: Borrowed reference */\n\nif (pFunc && PyCallable_Check(pFunc)) {\npArgs = PyTuple_New(argc - 3);\nfor (i = 0; i < argc - 3; ++i) {\npValue = PyInt_FromLong(atoi(argv[i + 3]));\nif (!pValue) {\nfprintf(stderr, \"Cannot convert argument\\n\");\nreturn 1;\n}\n/* pValue reference stolen here: */\nPyTuple_SetItem(pArgs, i, pValue);\n}\npValue = PyObject_CallObject(pFunc, pArgs);\nif (pValue != NULL) {\nprintf(\"Result of call: %ld\\n\", PyInt_AsLong(pValue));\nPy_DECREF(pValue);\n}\nelse {\nPyErr_Print();\nfprintf(stderr,\"Call failed\\n\");\nreturn 1;\n}\nPy_DECREF(pArgs);\n/* pDict and pFunc are borrowed and must not be Py_DECREF-ed */\n}\nelse {\nPyErr_Print();\nfprintf(stderr, \"Cannot find function \\\"%s\\\"\\n\", argv[2]);\n}\nPy_DECREF(pModule);\n}\nelse {\nPyErr_Print();\nfprintf(stderr, \"Failed to load \\\"%s\\\"\\n\", argv[1]);\nreturn 1;\n}\nPy_DECREF(pName);\nPy_Finalize();\nreturn 0;\n}\n```\nDownload as text. (run-func.txt)\nThis code loads a Python script using `argv[1]`, and calls the\nfunction named in `argv[2]`. Its integer arguments are the other\nvalues of the `argv` array. If you compile and link this\nprogram (let's call the finished executable call), and use\nit to execute a Python script, such as:\n```text\n\ndef multiply(a,b):\nprint \"Thy shall add\", a, \"times\", b\nc = 0\nfor i in range(0, a):\nc = c + b\nreturn c\n```\nthen the result should be:\n```text\n\n$ call multiply 3 2\nThy shall add 3 times 2\nResult of call: 6\n```\nAlthough the program is quite large for its functionality, most of the\ncode is for data conversion between Python and C, and for error\nreporting. The interesting part with respect to embedding Python\nstarts with\n```text\n\nPy_Initialize();\npName = PyString_FromString(argv[1]);\n/* Error checking of pName left out */\npModule = PyImport_Import(pName);\n```\nAfter initializing the interpreter, the script is loaded using\nPyImport_Import(). This routine needs a Python string\nas its argument, which is constructed using the\nPyString_FromString() data conversion routine.\n```text\n\npDict = PyModule_GetDict(pModule);\n/* pDict is a borrowed reference */\n\npFunc = PyDict_GetItemString(pDict, argv[2]);\n/* pFun is a borrowed reference */\n\nif (pFunc && PyCallable_Check(pFunc)) {\n...\n}\n```\nOnce the script is loaded, its dictionary is retrieved with\nPyModule_GetDict(). The dictionary is then searched using\nthe normal dictionary access routines for the function name. If the\nname exists, and the object retunred is callable, you can safely\nassume that it is a function. The program then proceeds by\nconstructing a tuple of arguments as normal. The call to the python\nfunction is then made with:\n```text\n\npValue = PyObject_CallObject(pFunc, pArgs);\n```\nUpon return of the function, `pValue` is either NULL or it\ncontains a reference to the return value of the function. Be sure to\nrelease the reference after examining the value.", "python_version": "2.2", "length": 3780, "url": "https://docs.python.org/2.2/ext/pure-embedding.html"} {"title": "1.10 Reference Counts", "text": "buildValue.html | intro.html | refcountsInPython.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.10 Reference Counts\nIn languages like C or C++, the programmer is responsible for\ndynamic allocation and deallocation of memory on the heap. In C,\nthis is done using the functions malloc() and\nfree(). In C++, the operators new and\ndelete are used with essentially the same meaning; they are\nactually implemented using malloc() and\nfree(), so we'll restrict the following discussion to the\nlatter.\nEvery block of memory allocated with malloc() should\neventually be returned to the pool of available memory by exactly one\ncall to free(). It is important to call\nfree() at the right time. If a block's address is\nforgotten but free() is not called for it, the memory it\noccupies cannot be reused until the program terminates. This is\ncalled a memory leak. On the other hand, if a program calls\nfree() for a block and then continues to use the block, it\ncreates a conflict with re-use of the block through another\nmalloc() call. This is called using freed memory.\nIt has the same bad consequences as referencing uninitialized data --\ncore dumps, wrong results, mysterious crashes.\nCommon causes of memory leaks are unusual paths through the code. For\ninstance, a function may allocate a block of memory, do some\ncalculation, and then free the block again. Now a change in the\nrequirements for the function may add a test to the calculation that\ndetects an error condition and can return prematurely from the\nfunction. It's easy to forget to free the allocated memory block when\ntaking this premature exit, especially when it is added later to the\ncode. Such leaks, once introduced, often go undetected for a long\ntime: the error exit is taken only in a small fraction of all calls,\nand most modern machines have plenty of virtual memory, so the leak\nonly becomes apparent in a long-running process that uses the leaking\nfunction frequently. Therefore, it's important to prevent leaks from\nhappening by having a coding convention or strategy that minimizes\nthis kind of errors.\nSince Python makes heavy use of malloc() and\nfree(), it needs a strategy to avoid memory leaks as well\nas the use of freed memory. The chosen method is called\nreference counting. The principle is simple: every object\ncontains a counter, which is incremented when a reference to the\nobject is stored somewhere, and which is decremented when a reference\nto it is deleted. When the counter reaches zero, the last reference\nto the object has been deleted and the object is freed.\nAn alternative strategy is called automatic garbage collection.\n(Sometimes, reference counting is also referred to as a garbage\ncollection strategy, hence my use of ``automatic'' to distinguish the\ntwo.) The big advantage of automatic garbage collection is that the\nuser doesn't need to call free() explicitly. (Another claimed\nadvantage is an improvement in speed or memory usage -- this is no\nhard fact however.) The disadvantage is that for C, there is no\ntruly portable automatic garbage collector, while reference counting\ncan be implemented portably (as long as the functions malloc()\nand free() are available -- which the C Standard guarantees).\nMaybe some day a sufficiently portable automatic garbage collector\nwill be available for C. Until then, we'll have to live with\nreference counts.\nWhile Python uses the traditional reference counting implementation,\nit also offers a cycle detector that works to detect reference\ncycles. This allows applications to not worry about creating direct\nor indirect circular references; these are the weakness of garbage\ncollection implemented using only reference counting. Reference\ncycles consist of objects which contain (possibly indirect) references\nto themselves, so that each object in the cycle has a reference count\nwhich is non-zero. Typical reference counting implementations are not\nable to reclaim the memory belonging to any objects in a reference\ncycle, or referenced from the objects in the cycle, even though there\nare no further references to the cycle itself.\nThe cycle detector is able to detect garbage cycles and can reclaim\nthem so long as there are no finalizers implemented in Python\n(__del__() methods). When there are such finalizers, the\ndetector exposes the cycles through the gc\nmodule (../lib/module-gc.html) (specifically, the `garbage`\nvariable in that module). The gc module also exposes a way\nto run the detector (the collect() function), as well as\nconfiguration interfaces and the ability to disable the detector at\nruntime. The cycle detector is considered an optional component;\nthough it is included by default, it can be disabled at build time\nusing the --without-cycle-gc option to the\nconfigure script on Unix platforms (including Mac OS X)\nor by removing the definition of `WITH_CYCLE_GC` in the\npyconfig.h header on other platforms. If the cycle detector is\ndisabled in this way, the gc module will not be available.", "python_version": "2.2", "length": 4983, "url": "https://docs.python.org/2.2/ext/refcounts.html"} {"title": "1.10.1 Reference Counting in Python", "text": "refcounts.html | refcounts.html | ownershipRules.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.1 Reference Counting in Python\nThere are two macros, `Py_INCREF(x)` and `Py_DECREF(x)`,\nwhich handle the incrementing and decrementing of the reference count.\nPy_DECREF() also frees the object when the count reaches zero.\nFor flexibility, it doesn't call free() directly -- rather, it\nmakes a call through a function pointer in the object's type\nobject. For this purpose (and others), every object also contains a\npointer to its type object.\nThe big question now remains: when to use `Py_INCREF(x)` and\n`Py_DECREF(x)`? Let's first introduce some terms. Nobody\n``owns'' an object; however, you can own a reference to an\nobject. An object's reference count is now defined as the number of\nowned references to it. The owner of a reference is responsible for\ncalling Py_DECREF() when the reference is no longer\nneeded. Ownership of a reference can be transferred. There are three\nways to dispose of an owned reference: pass it on, store it, or call\nPy_DECREF(). Forgetting to dispose of an owned reference\ncreates a memory leak.\nIt is also possible to borrow1.2 (#foot637) a reference to an object. The borrower\nof a reference should not call Py_DECREF(). The borrower must\nnot hold on to the object longer than the owner from which it was\nborrowed. Using a borrowed reference after the owner has disposed of\nit risks using freed memory and should be avoided\ncompletely.1.3 (#foot779)\nThe advantage of borrowing over owning a reference is that you don't\nneed to take care of disposing of the reference on all possible paths\nthrough the code -- in other words, with a borrowed reference you\ndon't run the risk of leaking when a premature exit is taken. The\ndisadvantage of borrowing over leaking is that there are some subtle\nsituations where in seemingly correct code a borrowed reference can be\nused after the owner from which it was borrowed has in fact disposed\nof it.\nA borrowed reference can be changed into an owned reference by calling\nPy_INCREF(). This does not affect the status of the owner from\nwhich the reference was borrowed -- it creates a new owned reference,\nand gives full owner responsibilities (the new owner must\ndispose of the reference properly, as well as the previous owner).", "python_version": "2.2", "length": 2327, "url": "https://docs.python.org/2.2/ext/refcountsInPython.html"} {"title": "A. Reporting Bugs", "text": "link-reqs.html | ext.html | node46.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# A. Reporting Bugs\nPython is a mature programming language which has established a\nreputation for stability. In order to maintain this reputation, the\ndevelopers would like to know of any deficiencies you find in Python\nor its documentation.\nAll bug reports should be submitted via the Python Bug Tracker on\nSourceForge (http://sourceforge.net/bugs/?group_id=5470). The\nbug tracker offers a Web form which allows pertinent information to be\nentered and submitted to the developers.\nBefore submitting a report, please log into SourceForge if you are a\nmember; this will make it possible for the developers to contact you\nfor additional information if needed. If you are not a SourceForge\nmember but would not mind the developers contacting you, you may\ninclude your email address in your bug description. In this case,\nplease realize that the information is publically available and cannot\nbe protected.\nThe first step in filing a report is to determine whether the problem\nhas already been reported. The advantage in doing so, aside from\nsaving the developers time, is that you learn what has been done to\nfix it; it may be that the problem has already been fixed for the next\nrelease, or additional information is needed (in which case you are\nwelcome to provide it if you can!). To do this, search the bug\ndatabase using the search box near the bottom of the page.\nIf the problem you're reporting is not already in the bug tracker, go\nback to the Python Bug Tracker\n(http://sourceforge.net/bugs/?group_id=5470). Select the\n``Submit a Bug'' link at the top of the page to open the bug reporting\nform.\nThe submission form has a number of fields. The only fields that are\nrequired are the ``Summary'' and ``Details'' fields. For the summary,\nenter a very short description of the problem; less than ten\nwords is good. In the Details field, describe the problem in detail,\nincluding what you expected to happen and what did happen. Be sure to\ninclude the version of Python you used, whether any extension modules\nwere involved, and what hardware and software platform you were using\n(including version information as appropriate).\nThe only other field that you may want to set is the ``Category''\nfield, which allows you to place the bug report into a broad category\n(such as ``Documentation'' or ``Library'').\nEach bug report will be assigned to a developer who will determine\nwhat needs to be done to correct the problem. If you have a\nSourceForge account and logged in to report the problem, you will\nreceive an update each time action is taken on the bug.\nSee Also:", "python_version": "2.2", "length": 2677, "url": "https://docs.python.org/2.2/ext/reporting-bugs.html"} {"title": "1.1 A Simple Example", "text": "intro.html | intro.html | errors.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.1 A Simple Example\nLet's create an extension module called \"spam\" (the favorite food\nof Monty Python fans...) and let's say we want to create a Python\ninterface to the C library function system().1.1 (#foot751)This function takes a null-terminated character string as argument and\nreturns an integer. We want this function to be callable from Python\nas follows:\n```text\n\n>>> import spam\n>>> status = spam.system(\"ls -l\")\n```\nBegin by creating a file spammodule.c. (Historically, if a\nmodule is called \"spam\", the C file containing its implementation\nis called spammodule.c; if the module name is very long, like\n\"spammify\", the module name can be just spammify.c.)\nThe first line of our file can be:\n```text\n\n#include \n```\nwhich pulls in the Python API (you can add a comment describing the\npurpose of the module and a copyright notice if you like).\nSince Python may define some pre-processor definitions which affect\nthe standard headers on some systems, you must include Python.h\nbefore any standard headers are included.\nAll user-visible symbols defined by Python.h have a prefix of\n\"Py\" or \"PY\", except those defined in standard header files.\nFor convenience, and since they are used extensively by the Python\ninterpreter, `\"Python.h\"` includes a few standard header files:\n``, ``, ``, and\n``. If the latter header file does not exist on your\nsystem, it declares the functions malloc(),\nfree() and realloc() directly.\nThe next thing we add to our module file is the C function that will\nbe called when the Python expression \"spam.system(string)\"is evaluated (we'll see shortly how it ends up being called):\n```text\n\nstatic PyObject *\nspam_system(self, args)\nPyObject *self;\nPyObject *args;\n{\nchar *command;\nint sts;\n\nif (!PyArg_ParseTuple(args, \"s\", &command))\nreturn NULL;\nsts = system(command);\nreturn Py_BuildValue(\"i\", sts);\n}\n```\nThere is a straightforward translation from the argument list in\nPython (for example, the single expression `\"ls -l\"`) to the\narguments passed to the C function. The C function always has two\narguments, conventionally named self and args.\nThe self argument is only used when the C function implements a\nbuilt-in method, not a function. In the example, self will\nalways be a NULL pointer, since we are defining a function, not a\nmethod. (This is done so that the interpreter doesn't have to\nunderstand two different types of C functions.)\nThe args argument will be a pointer to a Python tuple object\ncontaining the arguments. Each item of the tuple corresponds to an\nargument in the call's argument list. The arguments are Python\nobjects -- in order to do anything with them in our C function we have\nto convert them to C values. The function PyArg_ParseTuple()\nin the Python API checks the argument types and converts them to C\nvalues. It uses a template string to determine the required types of\nthe arguments as well as the types of the C variables into which to\nstore the converted values. More about this later.\nPyArg_ParseTuple() returns true (nonzero) if all arguments have\nthe right type and its components have been stored in the variables\nwhose addresses are passed. It returns false (zero) if an invalid\nargument list was passed. In the latter case it also raises an\nappropriate exception so the calling function can return\nNULL immediately (as we saw in the example).", "python_version": "2.2", "length": 3476, "url": "https://docs.python.org/2.2/ext/simpleExample.html"} {"title": "1.10.3 Thin Ice", "text": "ownershipRules.html | refcounts.html | nullPointers.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.3 Thin Ice\nThere are a few situations where seemingly harmless use of a borrowed\nreference can lead to problems. These all have to do with implicit\ninvocations of the interpreter, which can cause the owner of a\nreference to dispose of it.\nThe first and most important case to know about is using\nPy_DECREF() on an unrelated object while borrowing a\nreference to a list item. For instance:\n```text\n\nbug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\n\nPyList_SetItem(list, 1, PyInt_FromLong(0L));\nPyObject_Print(item, stdout, 0); /* BUG! */\n}\n```\nThis function first borrows a reference to `list[0]`, then\nreplaces `list[1]` with the value `0`, and finally prints\nthe borrowed reference. Looks harmless, right? But it's not!\nLet's follow the control flow into PyList_SetItem(). The list\nowns references to all its items, so when item 1 is replaced, it has\nto dispose of the original item 1. Now let's suppose the original\nitem 1 was an instance of a user-defined class, and let's further\nsuppose that the class defined a __del__() method. If this\nclass instance has a reference count of 1, disposing of it will call\nits __del__() method.\nSince it is written in Python, the __del__() method can execute\narbitrary Python code. Could it perhaps do something to invalidate\nthe reference to `item` in bug()? You bet! Assuming\nthat the list passed into bug() is accessible to the\n__del__() method, it could execute a statement to the effect of\n\"del list[0]\", and assuming this was the last reference to that\nobject, it would free the memory associated with it, thereby\ninvalidating `item`.\nThe solution, once you know the source of the problem, is easy:\ntemporarily increment the reference count. The correct version of the\nfunction reads:\n```text\n\nno_bug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\n\nPy_INCREF(item);\nPyList_SetItem(list, 1, PyInt_FromLong(0L));\nPyObject_Print(item, stdout, 0);\nPy_DECREF(item);\n}\n```\nThis is a true story. An older version of Python contained variants\nof this bug and someone spent a considerable amount of time in a C\ndebugger to figure out why his __del__() methods would fail...\nThe second case of problems with a borrowed reference is a variant\ninvolving threads. Normally, multiple threads in the Python\ninterpreter can't get in each other's way, because there is a global\nlock protecting Python's entire object space. However, it is possible\nto temporarily release this lock using the macro\n`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using\n`Py_END_ALLOW_THREADS`. This is common around blocking I/O\ncalls, to let other threads use the processor while waiting for the I/O to\ncomplete. Obviously, the following function has the same problem as\nthe previous one:\n```text\n\nbug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\nPy_BEGIN_ALLOW_THREADS\n...some blocking I/O call...\nPy_END_ALLOW_THREADS\nPyObject_Print(item, stdout, 0); /* BUG! */\n}\n```", "python_version": "2.2", "length": 3055, "url": "https://docs.python.org/2.2/ext/thinIce.html"} {"title": "1.12 Providing a C API for an Extension Module", "text": "cplusplus.html | intro.html | defining-new-types.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.12 Providing a C API for an Extension Module\nMany extension modules just provide new functions and types to be\nused from Python, but sometimes the code in an extension module can\nbe useful for other extension modules. For example, an extension\nmodule could implement a type ``collection'' which works like lists\nwithout order. Just like the standard Python list type has a C API\nwhich permits extension modules to create and manipulate lists, this\nnew collection type should have a set of C functions for direct\nmanipulation from other extension modules.\nAt first sight this seems easy: just write the functions (without\ndeclaring them static, of course), provide an appropriate\nheader file, and document the C API. And in fact this would work if\nall extension modules were always linked statically with the Python\ninterpreter. When modules are used as shared libraries, however, the\nsymbols defined in one module may not be visible to another module.\nThe details of visibility depend on the operating system; some systems\nuse one global namespace for the Python interpreter and all extension\nmodules (Windows, for example), whereas others require an explicit\nlist of imported symbols at module link time (AIX is one example), or\noffer a choice of different strategies (most Unices). And even if\nsymbols are globally visible, the module whose functions one wishes to\ncall might not have been loaded yet!\nPortability therefore requires not to make any assumptions about\nsymbol visibility. This means that all symbols in extension modules\nshould be declared static, except for the module's\ninitialization function, in order to avoid name clashes with other\nextension modules (as discussed in section 1.4 (methodTable.html#methodTable)). And it\nmeans that symbols that should be accessible from other\nextension modules must be exported in a different way.\nPython provides a special mechanism to pass C-level information\n(pointers) from one extension module to another one: CObjects.\nA CObject is a Python data type which stores a pointer (void\n*). CObjects can only be created and accessed via their C API, but\nthey can be passed around like any other Python object. In particular,\nthey can be assigned to a name in an extension module's namespace.\nOther extension modules can then import this module, retrieve the\nvalue of this name, and then retrieve the pointer from the CObject.\nThere are many ways in which CObjects can be used to export the C API\nof an extension module. Each name could get its own CObject, or all C\nAPI pointers could be stored in an array whose address is published in\na CObject. And the various tasks of storing and retrieving the pointers\ncan be distributed in different ways between the module providing the\ncode and the client modules.\nThe following example demonstrates an approach that puts most of the\nburden on the writer of the exporting module, which is appropriate\nfor commonly used library modules. It stores all C API pointers\n(just one in the example!) in an array of void pointers which\nbecomes the value of a CObject. The header file corresponding to\nthe module provides a macro that takes care of importing the module\nand retrieving its C API pointers; client modules only have to call\nthis macro before accessing the C API.\nThe exporting module is a modification of the spam module from\nsection 1.1 (simpleExample.html#simpleExample). The function spam.system()\ndoes not call the C library function system() directly,\nbut a function PySpam_System(), which would of course do\nsomething more complicated in reality (such as adding ``spam'' to\nevery command). This function PySpam_System() is also\nexported to other extension modules.\nThe function PySpam_System() is a plain C function,\ndeclared static like everything else:\n```text\n\nstatic int\nPySpam_System(command)\nchar *command;\n{\nreturn system(command);\n}\n```\nThe function spam_system() is modified in a trivial way:\n```text\n\nstatic PyObject *\nspam_system(self, args)\nPyObject *self;\nPyObject *args;\n{\nchar *command;\nint sts;\n\nif (!PyArg_ParseTuple(args, \"s\", &command))\nreturn NULL;\nsts = PySpam_System(command);\nreturn Py_BuildValue(\"i\", sts);\n}\n```\nIn the beginning of the module, right after the line\n```text\n\n#include \"Python.h\"\n```\ntwo more lines must be added:\n```text\n\n#define SPAM_MODULE\n#include \"spammodule.h\"\n```\nThe `#define` is used to tell the header file that it is being\nincluded in the exporting module, not a client module. Finally,\nthe module's initialization function must take care of initializing\nthe C API pointer array:\n```text\n\nvoid\ninitspam(void)\n{\nPyObject *m;\nstatic void *PySpam_API[PySpam_API_pointers];\nPyObject *c_api_object;\n\nm = Py_InitModule(\"spam\", SpamMethods);\n\n/* Initialize the C API pointer array */\nPySpam_API[PySpam_System_NUM] = (void *)PySpam_System;\n\n/* Create a CObject containing the API pointer array's address */\nc_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);\n\nif (c_api_object != NULL) {\n/* Create a name for this object in the module's namespace */\nPyObject *d = PyModule_GetDict(m);\n\nPyDict_SetItemString(d, \"_C_API\", c_api_object);\nPy_DECREF(c_api_object);\n}\n}\n```\nNote that `PySpam_API` is declared static; otherwise\nthe pointer array would disappear when initspam() terminates!\nThe bulk of the work is in the header file spammodule.h,\nwhich looks like this:\n```text\n\n#ifndef Py_SPAMMODULE_H\n#define Py_SPAMMODULE_H\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Header file for spammodule */\n\n/* C API functions */\n#define PySpam_System_NUM 0\n#define PySpam_System_RETURN int\n#define PySpam_System_PROTO (char *command)\n\n/* Total number of C API pointers */\n#define PySpam_API_pointers 1\n\n#ifdef SPAM_MODULE\n/* This section is used when compiling spammodule.c */\n\nstatic PySpam_System_RETURN PySpam_System PySpam_System_PROTO;\n\n#else\n/* This section is used in modules that use spammodule's API */\n\nstatic void **PySpam_API;\n\n#define PySpam_System \\\n(*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])\n\n#define import_spam() \\\n{ \\\nPyObject *module = PyImport_ImportModule(\"spam\"); \\\nif (module != NULL) { \\\nPyObject *module_dict = PyModule_GetDict(module); \\\nPyObject *c_api_object = PyDict_GetItemString(module_dict, \"_C_API\"); \\\nif (PyCObject_Check(c_api_object)) { \\\nPySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \\\n} \\\n} \\\n}\n\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* !defined(Py_SPAMMODULE_H */\n```\nAll that a client module must do in order to have access to the\nfunction PySpam_System() is to call the function (or\nrather macro) import_spam() in its initialization\nfunction:\n```text\n\nvoid\ninitclient(void)\n{\nPyObject *m;\n\nPy_InitModule(\"client\", ClientMethods);\nimport_spam();\n}\n```\nThe main disadvantage of this approach is that the file\nspammodule.h is rather complicated. However, the\nbasic structure is the same for each function that is\nexported, so it has to be learned only once.", "python_version": "2.2", "length": 7023, "url": "https://docs.python.org/2.2/ext/using-cobjects.html"} {"title": "4.1 A Cookbook Approach", "text": "building-on-windows.html | building-on-windows.html | dynamic-linking.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 4.1 A Cookbook Approach\nThere are two approaches to building extension modules on Windows,\njust as there are on Unix: use the distutils (module-distutils.html) package to\ncontrol the build process, or do things manually. The distutils\napproach works well for most extensions; documentation on using\ndistutils (module-distutils.html) to build and package extension modules is\navailable in Distributing Python\nModules (../dist/dist.html). This section describes the manual approach to building\nPython extensions written in C or C++.\nTo build extensions using these instructions, you need to have a copy\nof the Python sources of the same version as your installed Python.\nYou will need Microsoft Visual C++ ``Developer Studio''; project\nfiles are supplied for VC++ version 6, but you can use older\nversions of VC++. The example files described here are distributed\nwith the Python sources in the PC\\\nexample_nt\\ directory.\n1. Copy the example files\nThe example_nt directory is a subdirectory of the PC\ndirectory, in order to keep all the PC-specific files under the\nsame directory in the source distribution. However, the\nexample_nt directory can't actually be used from this\nlocation. You first need to copy or move it up one level, so that\nexample_nt is a sibling of the PC and Include\ndirectories. Do all your work from within this new location.\n2. Open the project\nFrom VC++, use the File > Open Workspace\ndialog (not File > Open!). Navigate to and\nselect the file example.dsw, in the copy of the\nexample_nt directory you made above. Click Open.\n3. Build the example DLL\nIn order to check that everything is set up right, try building:\n1. Select a configuration. This step is optional. Choose\nBuild > Select Active Configuration and\nselect either ``example - Win32 Release'' or ``example - Win32\nDebug.'' If you skip this step, VC++ will use the Debug\nconfiguration by default.\n2. Build the DLL. Choose Build > Build\nexample_d.dll in Debug mode, or Build >\nBuild example.dll in Release mode. This creates all\nintermediate and result files in a subdirectory called either\nDebug or Release, depending on which\nconfiguration you selected in the preceding step.\n4. Testing the debug-mode DLL\nOnce the Debug build has succeeded, bring up a DOS box, and change\nto the example_nt\\Debug directory. You\nshould now be able to repeat the following session (`C>` is\nthe DOS prompt, `> > >` is the Python prompt; note that\nbuild information and various debug output from Python may not\nmatch this screen dump exactly):\n```text\n\nC>..\\..\\PCbuild\\python_d\nAdding parser accelerators ...\nDone.\nPython 2.2 (#28, Dec 19 2001, 23:26:37) [MSC 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license\" for more information.\n>>> import example\n[4897 refs]\n>>> example.foo()\nHello, world\n[4903 refs]\n>>>\n```\nCongratulations! You've successfully built your first Python\nextension module.\n5. Cretating your own project\nChoose a name and create a directory for it. Copy your C sources\ninto it. Note that the module source file name does not\nnecessarily have to match the module name, but the name of the\ninitialization function should match the module name -- you can\nonly import a module spam if its initialization function\nis called initspam(), and it should call\nPy_InitModule() with the string `\"spam\"` as its\nfirst argument (use the minimal example.c in this directory\nas a guide). By convention, it lives in a file called\nspam.c or spammodule.c. The output file should be\ncalled spam.dll or spam.pyd (the latter is supported\nto avoid confusion with a system library spam.dll to which\nyour module could be a Python interface) in Release mode, or\nspam_d.dll or spam_d.pyd in Debug mode.\nNow your options are:\n1. Copy example.dsw and example.dsp, rename\nthem to spam.*, and edit them by hand, or\n2. Create a brand new project; instructions are below.\nIn either case, copy example_nt\\example.def\nto spam\\spam.def, and edit the new\nspam.def so its second line contains the string\n``initspam`'. If you created a new project yourself, add the\nfile spam.def to the project now. (This is an annoying\nlittle file with only two lines. An alternative approach is to\nforget about the .def file, and add the option\n/export:initspam somewhere to the Link settings, by\nmanually editing the setting in Project Options dialog).\n6. Creating a brand new project\nUse the File > New > Projects dialog to\ncreate a new Project Workspace. Select ``Win32 Dynamic-Link\nLibrary,'' enter the name (\"spam\"), and make sure the\nLocation is set to the spam directory you have created\n(which should be a direct subdirectory of the Python build tree, a\nsibling of Include and PC). Select Win32 as the\nplatform (in my version, this is the only choice). Make sure the\nCreate new workspace radio button is selected. Click OK.\nNow open the Project > Settings dialog. You\nonly need to change a few settings. Make sure All Configurations\nis selected from the Settings for: dropdown list. Select the\nC/C++ tab. Choose the Preprocessor category in the popup menu\nat the top. Type the following text in the entry box labeled\nAddditional include directories:\n```text\n\n..\\Include,..\\PC\n```\nThen, choose the Input category in the Link tab, and enter\n```text\n\n..\\PCbuild\n```\nin the text box labelled ``Additional library path.''\nNow you need to add some mode-specific settings:\nSelect ``Win32 Release'' in the ``Settings for'' dropdown list.\nClick the Link tab, choose the Input Category, and append\n`python22.lib` to the list in the ``Object/library modules''\nbox.\nSelect ``Win32 Debug'' in the ``Settings for'' dropdown list, and\nappend `python22_d.lib` to the list in the ``Object/library\nmodules'' box. Then click the C/C++ tab, select ``Code\nGeneration'' from the Category dropdown list, and select ``Debug\nMultithreaded DLL'' from the ``Use run-time library'' dropdown\nlist.\nSelect ``Win32 Release'' again from the ``Settings for'' dropdown\nlist. Select ``Multithreaded DLL'' from the ``Use run-time\nlibrary:'' dropdown list.\nYou should now create the file spam.def as instructed in the\nprevious section. Then chose the Insert > Files\ninto Project dialog. Set the pattern to `*.*` and select\nboth spam.c and spam.def and click OK. (Inserting\nthem one by one is fine too.)\nIf your module creates a new type, you may have trouble with this line:\n```text\n\nPyObject_HEAD_INIT(&PyType_Type)\n```\nChange it to:\n```text\n\nPyObject_HEAD_INIT(NULL)\n```\nand add the following to the module initialization function:\n```text\n\nMyObject_Type.ob_type = &PyType_Type;\n```\nRefer to section 3 of the\nPython FAQ (http://www.python.org/doc/FAQ.html) for details\non why you must do this.", "python_version": "2.2", "length": 6756, "url": "https://docs.python.org/2.2/ext/win-cookbook.html"} {"title": "4.3 Using DLLs in Practice", "text": "dynamic-linking.html | building-on-windows.html | embedding.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 4.3 Using DLLs in Practice\nWindows Python is built in Microsoft Visual C++; using other\ncompilers may or may not work (though Borland seems to). The rest of\nthis section is MSVC++ specific.\nWhen creating DLLs in Windows, you must pass python15.lib to\nthe linker. To build two DLLs, spam and ni (which uses C functions\nfound in spam), you could use these commands:\n```text\n\ncl /LD /I/python/include spam.c ../libs/python15.lib\ncl /LD /I/python/include ni.c spam.lib ../libs/python15.lib\n```\nThe first command created three files: spam.obj,\nspam.dll and spam.lib. Spam.dll does not contain\nany Python functions (such as PyArg_ParseTuple()), but it\ndoes know how to find the Python code thanks to python15.lib.\nThe second command created ni.dll (and .obj and\n.lib), which knows how to find the necessary functions from\nspam, and also from the Python executable.\nNot every identifier is exported to the lookup table. If you want any\nother modules (including Python) to be able to see your identifiers,\nyou have to say \"_declspec(dllexport)\", as in \"void\n_declspec(dllexport) initspam(void)\" or \"PyObject\n_declspec(dllexport) *NiGetSpamData(void)\".", "python_version": "2.2", "length": 1279, "url": "https://docs.python.org/2.2/ext/win-dlls.html"} {"title": "Python 2.2 Documentation - December 21, 2001", "text": "Python Documentation | modindex.html\n---\n# Python Documentation\nRelease 2.2\nDecember 21, 2001\n---\nSee About the Python Documentation (about.html)\nfor information on suggesting changes.", "python_version": "2.2", "length": 184, "url": "https://docs.python.org/2.2/index.html"} {"title": "About this document ...", "text": "config-syntax.html | inst.html | Installing Python Modules\n---\n# About this document ...\nInstalling Python Modules\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nconfig-syntax.html | inst.html | Installing Python Modules\n---", "python_version": "2.2", "length": 1570, "url": "https://docs.python.org/2.2/inst/about.html"} {"title": "4 Alternate Installation", "text": "non-ms-compilers.html | inst.html | custom-install.html | Installing Python Modules\n---\n- 4.1 Alternate installation: Unix (the home scheme) (#SECTION000410000000000000000)\n 4.2 Alternate installation: Unix (the prefix scheme) (#SECTION000420000000000000000)\n 4.3 Alternate installation: Windows (#SECTION000430000000000000000)\n 4.4 Alternate installation: Mac OS (#SECTION000440000000000000000)\n---\n# 4 Alternate Installation\nOften, it is necessary or desirable to install modules to a location\nother than the standard location for third-party Python modules. For\nexample, on a Unix system you might not have permission to write to the\nstandard third-party module directory. Or you might wish to try out a\nmodule before making it a standard part of your local Python\ninstallation; this is especially true when upgrading a distribution\nalready present: you want to make sure your existing base of scripts\nstill works with the new version before actually upgrading.\nThe Distutils `install` command is designed to make installing\nmodule distributions to an alternate location simple and painless. The\nbasic idea is that you supply a base directory for the installation, and\nthe `install` command picks a set of directories (called an\ninstallation scheme) under this base directory in which to\ninstall files. The details differ across platforms, so read whichever\nof the following sections applies to you.\n## 4.1 Alternate installation: Unix (the home scheme)\nUnder Unix, there are two ways to perform an alternate installation.\nThe ``prefix scheme'' is similar to how alternate installation works\nunder Windows and Mac OS, but is not necessarily the most useful way to\nmaintain a personal Python library. Hence, we document the more\nconvenient and commonly useful ``home scheme'' first.\nThe idea behind the ``home scheme'' is that you build and maintain a\npersonal stash of Python modules, probably under your home directory.\nInstalling a new module distribution is as simple as\n```text\n\npython setup.py install --home=\n```\nwhere you can supply any directory you like for the --home\noption. Lazy typists can just type a tilde (); the\n`install` command will expand this to your home directory:\n```text\n\npython setup.py install --home=~\n```\nThe --home option defines the installation base\ndirectory. Files are installed to the following directories under the\ninstallation base as follows:\n## 4.2 Alternate installation: Unix (the prefix scheme)\nThe ``prefix scheme'' is useful when you wish to use one Python\ninstallation to perform the build/install (i.e., to run the setup\nscript), but install modules into the third-party module directory of a\ndifferent Python installation (or something that looks like a different\nPython installation). If this sounds a trifle unusual, it is--that's\nwhy the ``home scheme'' comes first. However, there are at least two\nknown cases where the prefix scheme will be useful.\nFirst, consider that many Linux distributions put Python in /usr,\nrather than the more traditional /usr/local. This is entirely\nappropriate, since in those cases Python is part of ``the system''\nrather than a local add-on. However, if you are installing Python\nmodules from source, you probably want them to go in\n/usr/local/lib/python1.X rather than\n/usr/lib/python1.X. This can be done with\n```text\n\n/usr/bin/python setup.py install --prefix=/usr/local\n```\nAnother possibility is a network filesystem where the name used to write\nto a remote directory is different from the name used to read it: for\nexample, the Python interpreter accessed as /usr/local/bin/python\nmight search for modules in /usr/local/lib/python1.X,\nbut those modules would have to be installed to, say,\n/mnt/@server/export/lib/python1.X. This\ncould be done with\n```text\n\n/usr/local/bin/python setup.py install --prefix=/mnt/@server/export\n```\nIn either case, the --prefix option defines the\ninstallation base, and the --exec-prefix option defines\nthe platform-specific installation base, which is used for\nplatform-specific files. (Currently, this just means non-pure module\ndistributions, but could be expanded to C libraries, binary executables,\netc.) If --exec-prefix is not supplied, it defaults to\n--prefix. Files are installed as follows:\nThere is no requirement that --prefix or\n--exec-prefix actually point to an alternate Python\ninstallation; if the directories listed above do not already exist, they\nare created at installation time.\nIncidentally, the real reason the prefix scheme is important is simply\nthat a standard Unix installation uses the prefix scheme, but with\n--prefix and --exec-prefix supplied by\nPython itself (as `sys.prefix` and `sys.exec_prefix`). Thus,\nyou might think you'll never use the prefix scheme, but every time you\nrun `python setup.py install` without any other options, you're\nusing it.\nNote that installing extensions to an alternate Python installation has\nno effect on how those extensions are built: in particular, the Python\nheader files (Python.h and friends) installed with the Python\ninterpreter used to run the setup script will be used in compiling\nextensions. It is your responsibility to ensure that the interpreter\nused to run extensions installed in this way is compatibile with the\ninterpreter used to build them. The best way to do this is to ensure\nthat the two interpreters are the same version of Python (possibly\ndifferent builds, or possibly copies of the same build). (Of course, if\nyour --prefix and --exec-prefix don't even\npoint to an alternate Python installation, this is immaterial.)\n## 4.3 Alternate installation: Windows\nSince Windows has no conception of a user's home directory, and since\nthe standard Python installation under Windows is simpler than that\nunder Unix, there's no point in having separate --prefix\nand --home options. Just use the --prefix\noption to specify a base directory, e.g.\n```text\n\npython setup.py install --prefix=\"\\Temp\\Python\"\n```\nto install modules to the \\Temp directory on the current\ndrive.\nThe installation base is defined by the --prefix option;\nthe --exec-prefix option is not supported under Windows.\nFiles are installed as follows:\n## 4.4 Alternate installation: Mac OS\nLike Windows, Mac OS has no notion of home directories (or even of\nusers), and a fairly simple standard Python installation. Thus, only a\n--prefix option is needed. It defines the installation\nbase, and files are installed under it as follows:\nSee section 2.1 (standard-install.html#platform-variations) for information on supplying\ncommand-line arguments to the setup script with MacPython.", "python_version": "2.2", "length": 6556, "url": "https://docs.python.org/2.2/inst/alt-install-windows.html"} {"title": "6 Distutils Configuration Files", "text": "custom-install.html | inst.html | about.html | Installing Python Modules\n---\n- 6.1 Location and names of config files (#SECTION000610000000000000000)\n 6.2 Syntax of config files (#SECTION000620000000000000000)\n---\n# 6 Distutils Configuration Files\nAs mentioned above, you can use Distutils configuration files to record\npersonal or site preferences for any Distutils options. That is, any\noption to any command can be stored in one of two or three (depending on\nyour platform) configuration files, which will be consulted before the\ncommand-line is parsed. This means that configuration files will\noverride default values, and the command-line will in turn override\nconfiguration files. Furthermore, if multiple configuration files\napply, values from ``earlier'' files are overridden by ``later'' files.\n## 6.1 Location and names of config files\nThe names and locations of the configuration files vary slightly across\nplatforms. On Unix, the three configuration files (in the order they\nare processed) are:\nOn Windows, the configuration files are:\nAnd on Mac OS, they are:\nNotes:\n(1): Strictly speaking, the system-wide configuration file lives\nin the directory where the Distutils are installed; under Python 1.6\nand later on Unix, this is as shown. For Python 1.5.2, the Distutils\nwill normally be installed to\nprefix/lib/site-packages/python1.5/distutils,\nso the system configuration file should be put there under Python\n1.5.2.\n(2): On Unix, if the HOME environment variable is not\ndefined, the user's home directory will be determined with the\ngetpwuid() function from the standard pwd module.\n(3): I.e., in the current directory (usually the location of the\nsetup script).\n(4): (See also note (1).) Under Python 1.6 and later, Python's\ndefault ``installation prefix'' is C:\\Python, so\nthe system configuration file is normally\nC:\\Python\\Lib\\distutils\\distutils.cfg.\nUnder Python 1.5.2, the default prefix was\nC:\\Program Files\\Python, and the\nDistutils were not part of the standard library--so the system\nconfiguration file would be\nC:\\Program Files\\Python\\distutils\\distutils.cfg\nin a standard Python 1.5.2 installation under Windows.\n(5): On Windows, if the HOME environment variable is not\ndefined, no personal configuration file will be found or used. (In\nother words, the Distutils make no attempt to guess your home\ndirectory on Windows.)\n(6): (See also notes (1) and (4).) The default installation\nprefix is just Python:, so under Python 1.6 and later this is\nnormallyPython:Lib:distutils:distutils.cfg. (The Distutils\ndon't work very well with Python 1.5.2 under Mac OS. ** true? **)\n## 6.2 Syntax of config files\nThe Distutils configuration files all have the same syntax. The config\nfiles are grouped into sections; there is one section for each Distutils\ncommand, plus a `global` section for global options that affect\nevery command. Each section consists of one option per line, specified\nlike `option=value`.\nFor example, the following is a complete config file that just forces\nall commands to run quietly by default:\n```text\n\n[global]\nverbose=0\n```\nIf this is installed as the system config file, it will affect all\nprocessing of any Python module distribution by any user on the current\nsystem. If it is installed as your personal config file (on systems\nthat support them), it will affect only module distributions processed\nby you. And if it is used as the setup.cfg for a particular\nmodule distribution, it affects only that distribution.\nYou could override the default ``build base'' directory and make the\n`build*` commands always forcibly rebuild all files with the\nfollowing:\n```text\n\n[build]\nbuild-base=blib\nforce=1\n```\nwhich corresponds to the command-line arguments\n```text\n\npython setup.py build --build-base=blib --force\n```\nexcept that including the `build` command on the command-line\nmeans that command will be run. Including a particular command in\nconfig files has no such implication; it only means that if the command\nis run, the options in the config file will apply. (Or if other\ncommands that derive values from it are run, they will use the values in\nthe config file.)\nYou can find out the complete list of options for any command using the\n--help option, e.g.:\n```text\n\npython setup.py build --help\n```\nand you can find out the complete list of global options by using\n--help without a command:\n```text\n\npython setup.py --help\n```\nSee also the ``Reference'' section of the ``Distributing Python\nModules'' manual.", "python_version": "2.2", "length": 4459, "url": "https://docs.python.org/2.2/inst/config-syntax.html"} {"title": "5 Custom Installation", "text": "alt-install-windows.html | inst.html | config-syntax.html | Installing Python Modules\n---\n# 5 Custom Installation\nSometimes, the alternate installation schemes described in\nsection 4 (alt-install-windows.html#alt-install) just don't do what you want. You might\nwant to tweak just one or two directories while keeping everything under\nthe same base directory, or you might want to completely redefine the\ninstallation scheme. In either case, you're creating a custom\ninstallation scheme.\nYou probably noticed the column of ``override options'' in the tables\ndescribing the alternate installation schemes above. Those options are\nhow you define a custom installation scheme. These override options can\nbe relative, absolute, or explicitly defined in terms of one of the\ninstallation base directories. (There are two installation base\ndirectories, and they are normally the same--they only differ when you\nuse the Unix ``prefix scheme'' and supply different\n--prefix and --exec-prefix options.)\nFor example, say you're installing a module distribution to your home\ndirectory under Unix--but you want scripts to go in\n /scripts rather than  /bin.\nAs you might expect, you can override this directory with the\n--install-scripts option; in this case, it makes most\nsense to supply a relative path, which will be interpreted relative to\nthe installation base directory (your home directory, in this case):\n```text\n\npython setup.py install --home=~ --install-scripts=scripts\n```\nAnother Unix example: suppose your Python installation was built and\ninstalled with a prefix of /usr/local/python, so under a standard\ninstallation scripts will wind up in /usr/local/python/bin. If\nyou want them in /usr/local/bin instead, you would supply this\nabsolute directory for the --install-scripts option:\n```text\n\npython setup.py install --install-scripts=/usr/local/bin\n```\n(This performs an installation using the ``prefix scheme,'' where the\nprefix is whatever your Python interpreter was installed with--\n/usr/local/python in this case.)\nIf you maintain Python on Windows, you might want third-party modules to\nlive in a subdirectory of prefix, rather than right in\nprefix itself. This is almost as easy as customizing the\nscript installation directory--you just have to remember that there are\ntwo types of modules to worry about, pure modules and non-pure modules\n(i.e., modules from a non-pure distribution). For example:\n```text\n\npython setup.py install --install-purelib=Site --install-platlib=Site\n```\nThe specified installation directories are relative to prefix.\nOf course, you also have to ensure that these directories are in\nPython's module search path, e.g. by putting a .pth file in\nprefix (** should have a section describing .pth files and\ncross-ref it here **).\nIf you want to define an entire installation scheme, you just have to\nsupply all of the installation directory options. The recommended way\nto do this is to supply relative paths; for example, if you want to\nmaintain all Python module-related files under python in your\nhome directory, and you want a separate directory for each platform that\nyou use your home directory from, you might define the following\ninstallation scheme:\n```text\n\npython setup.py install --home=~ \\\n--install-purelib=python/lib \\\n--install-platlib=python/lib.$PLAT \\\n--install-scripts=python/scripts\n--install-data=python/data\n```\nor, equivalently,\n```text\n\npython setup.py install --home=~/python \\\n--install-purelib=lib \\\n--install-platlib='lib.$PLAT' \\\n--install-scripts=scripts\n--install-data=data\n```\n`$PLAT` is not (necessarily) an environment variable--it will be\nexpanded by the Distutils as it parses your command line options (just\nas it does when parsing your configuration file(s)).\nObviously, specifying the entire installation scheme every time you\ninstall a new module distribution would be very tedious. Thus, you can\nput these options into your Distutils config file (see\nsection 6 (config-syntax.html#config-files)):\n```text\n\n[install]\ninstall-base=$HOME\ninstall-purelib=python/lib\ninstall-platlib=python/lib.$PLAT\ninstall-scripts=python/scripts\ninstall-data=python/data\n```\nor, equivalently,\n```text\n\n[install]\ninstall-base=$HOME/python\ninstall-purelib=lib\ninstall-platlib=lib.$PLAT\ninstall-scripts=scripts\ninstall-data=data\n```\nNote that these two are not equivalent if you supply a different\ninstallation base directory when you run the setup script. For example,\n```text\n\npython setup.py --install-base=/tmp\n```\nwould install pure modules to /tmp/python/lib in the first\ncase, and to /tmp/lib in the second case. (For the second\ncase, you probably want to supply an installation base of\n/tmp/python.)\nYou probably noticed the use of `$HOME` and `$PLAT` in the\nsample configuration file input. These are Distutils configuration\nvariables, which bear a strong resemblance to environment variables. In\nfact, you can use environment variables in config files--on platforms\nthat have such a notion--but the Distutils additionally define a few\nextra variables that may not be in your environment, such as\n`$PLAT`. (And of course, you can only use the configuration\nvariables supplied by the Distutils on systems that don't have\nenvironment variables, such as Mac OS (** true? **).) See\nsection 6 (config-syntax.html#config-files) for details.\n** need some Windows and Mac OS examples--when would custom\ninstallation schemes be needed on those platforms? **", "python_version": "2.2", "length": 5408, "url": "https://docs.python.org/2.2/inst/custom-install.html"} {"title": "Installing Python Modules", "text": "../index.html | trivial-install.html | Installing Python Modules\n---\n# Installing Python Modules\nGreg Ward\nEmail: gward@python.net\n### Abstract:\nThis document describes the Python Distribution Utilities\n(``Distutils'') from the end-user's point-of-view, describing how to\nextend the capabilities of a standard Python installation by building\nand installing third-party Python modules and extensions.", "python_version": "2.2", "length": 399, "url": "https://docs.python.org/2.2/inst/index.html"} {"title": "Installing Python Modules", "text": "../index.html | trivial-install.html | Installing Python Modules\n---\n# Installing Python Modules\nGreg Ward\nEmail: gward@python.net\n### Abstract:\nThis document describes the Python Distribution Utilities\n(``Distutils'') from the end-user's point-of-view, describing how to\nextend the capabilities of a standard Python installation by building\nand installing third-party Python modules and extensions.", "python_version": "2.2", "length": 399, "url": "https://docs.python.org/2.2/inst/inst.html"} {"title": "3 Building Extensions: Tips and Tricks", "text": "standard-install.html | inst.html | alt-install-windows.html | Installing Python Modules\n---\n- 3.1 Using non-Microsoft compilers on Windows (#SECTION000310000000000000000)\n - 3.1.1 Borland C++ (#SECTION000311000000000000000)\n 3.1.2 GNU C / Cygwin / MinGW32 (#SECTION000312000000000000000)\n---\n# 3 Building Extensions: Tips and Tricks\n(This is the section to read for people doing any sort of interesting\nbuild. Things to talk about:\n- the Setup file (any platform now, but Unix-biased)\n- CFLAGS and LDFLAGS (must implement them first!)\n- using non-MS compilers on Windows (how to convert\nPython's library, ...)\n## 3.1 Using non-Microsoft compilers on Windows\n### 3.1.1 Borland C++\nThis subsection describes the necessary steps to use Distutils with the\nBorland C++ compiler version 5.5.\nFirst you have to know that the Borland's object file format(OMF) is\ndifferent from what is used by the Python version you can download\nfrom the Python Web site. (Python is built with Microsoft Visual C++,\nwhich uses COFF as object file format.) For this reason you have to\nconvert Python's library python20.lib into the Borland format.\nYou can do this as follows:\n```text\n\ncoff2omf python20.lib python20_bcpp.lib\n```\nThe coff2omf program comes with the Borland compiler. The file\npython20.lib is in the Libs directory of your Python\ninstallation. If your extension uses other libraries (zlib,...) you\nhave to convert them too.\nThe converted files have to reside in the same directories as the\nnormal libraries.\nHow does Distutils manage to use these libraries with their changed\nnames? If the extension needs a library (eg. foo) Distutils\nchecks first if it finds a library with suffix _bcpp\n(eg. foo_bcpp.lib) and then uses this library. In the case it\ndoesn't find such a special library it uses the default name\n(foo.lib.)1 (#foot188)\nTo let Distutils compile your extension with Borland C++ you now have\nto type:\n```text\n\npython setup.py build --compiler=bcpp\n```\nIf you want to use the Borland C++ compiler as default, you should\nconsider to write it in your personal or system-wide configuration\nfile for Distutils (see section 6 (config-syntax.html#config-files).)\nSee Also:\n### 3.1.2 GNU C / Cygwin / MinGW32\nThis section describes the necessary steps to use Distutils with the\nGNU C/C++ compilers in their Cygwin and MinGW32\ndistributions.2 (#foot494)\n** For a Python which was built with Cygwin, all should work without\nany of these following steps. **\nFor these compilers we have to create some special libraries too.\nThis task is more complex as for Borland's C++, because there is no\nprogram to convert the library (inclusive the references on data\nstructures.)\nFirst you have to create a list of symbols which the Python DLL exports.\n(You can find a good program for this task at\nhttp://starship.python.net/crew/kernr/mingw32/Notes.html, see at\nPExports 0.42h there.)\n```text\n\npexports python20.dll >python20.def\n```\nThen you can create from these information an import library for gcc.\n```text\n\ndlltool --dllname python20.dll --def python20.def --output-lib libpython20.a\n```\nThe resulting library has to be placed in the same directory as\npython20.lib. (Should be the libs directory under your\nPython installation directory.)\nIf your extension uses other libraries (zlib,...) you might\nhave to convert them too.\nThe converted files have to reside in the same directories as the normal\nlibraries do.\nTo let Distutils compile your extension with Cygwin you now have to type\n```text\n\npython setup.py build --compiler=cygwin\n```\nand for Cygwin in no-cygwin mode3 (#foot495) or for MinGW32 type:\n```text\n\npython setup.py build --compiler=mingw32\n```\nIf you want to use any of these options/compilers as default, you should\nconsider to write it in your personal or system-wide configuration file\nfor Distutils (see section 6 (config-syntax.html#config-files).)\nSee Also:", "python_version": "2.2", "length": 3870, "url": "https://docs.python.org/2.2/inst/non-ms-compilers.html"} {"title": "About this document ...", "text": "config-syntax.html | inst.html | Installing Python Modules\n---\n# About this document ...\nInstalling Python Modules\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nconfig-syntax.html | inst.html | Installing Python Modules\n---", "python_version": "2.2", "length": 1570, "url": "https://docs.python.org/2.2/inst/pre-distutils.html"} {"title": "2 Standard Build and Install", "text": "trivial-install.html | inst.html | non-ms-compilers.html | Installing Python Modules\n---\n- 2.1 Platform variations (#SECTION000210000000000000000)\n 2.2 Splitting the job up (#SECTION000220000000000000000)\n 2.3 How building works (#SECTION000230000000000000000)\n 2.4 How installation works (#SECTION000240000000000000000)\n---\n# 2 Standard Build and Install\nAs described in section 1.2 (trivial-install.html#new-standard), building and installing\na module distribution using the Distutils is usually one simple command:\n```text\n\npython setup.py install\n```\nOn Unix, you'd run this command from a shell prompt; on Windows, you\nhave to open a command prompt window (``DOS box'') and do it there; on\nMac OS, things are a tad more complicated (see below).\n## 2.1 Platform variations\nYou should always run the setup command from the distribution root\ndirectory, i.e. the top-level subdirectory that the module source\ndistribution unpacks into. For example, if you've just downloaded a\nmodule source distribution foo-1.0.tar.gz onto a\nUnix system, the normal thing to do is:\n```text\n\ngunzip -c foo-1.0.tar.gz | tar xf - # unpacks into directory foo-1.0\ncd foo-1.0\npython setup.py install\n```\nOn Windows, you'd probably download foo-1.0.zip. If you\ndownloaded the archive file to C:\\Temp, then it\nwould unpack into C:\\Temp\\foo-1.0;\nyou can use either a archive manipulator with a grapical user interface\n(such as WinZip) or a command-line tool (such as unzip or\npkunzip) to unpack the archive. Then, open a command prompt\nwindow (``DOS box''), and run:\n```text\n\ncd c:\\Temp\\foo-1.0\npython setup.py install\n```\nOn Mac OS, you have to go through a bit more effort to supply\ncommand-line arguments to the setup script:\n- hit option-double-click on the script's icon (or option-drop it\nonto the Python interpreter's icon)\n- press the ``Set unix-style command line'' button\n- set the ``Keep stdio window open on termination'' if you're\ninterested in seeing the output of the setup script (which is usually\nvoluminous and often useful)\n- when the command-line dialog pops up, enter ``install'' (you\ncan, of course, enter any Distutils command-line as described in this\ndocument or in Distributing Python\nModules (../dist/dist.html): just leave off the initial `python setup.py` and\nyou'll be fine)\n** this should change: every Distutils setup script will need\ncommand-line arguments for every run (and should probably keep stdout\naround), so all this should happen automatically for setup scripts **\n## 2.2 Splitting the job up\nRunning `setup.py install` builds and installs all modules in one\nrun. If you prefer to work incrementally--especially useful if you\nwant to customize the build process, or if things are going wrong--you\ncan use the setup script to do one thing at a time. This is\nparticularly helpful when the build and install will be done by\ndifferent users--e.g., you might want to build a module distribution\nand hand it off to a system administrator for installation (or do it\nyourself, with super-user privileges).\nFor example, you can build everything in one step, and then install\neverything in a second step, by invoking the setup script twice:\n```text\n\npython setup.py build\npython setup.py install\n```\n(If you do this, you will notice that running the `install`\ncommand first runs the `build` command, which--in this\ncase--quickly notices that it has nothing to do, since everything in\nthe build directory is up-to-date.)\nYou may not need this ability to break things down often if all you do\nis install modules downloaded off the 'net, but it's very handy for more\nadvanced tasks. If you get into distributing your own Python modules\nand extensions, you'll run lots of individual Distutils commands on\ntheir own.\n## 2.3 How building works\nAs implied above, the `build` command is responsible for putting\nthe files to install into a build directory. By default, this is\nbuild under the distribution root; if you're excessively\nconcerned with speed, or want to keep the source tree pristine, you can\nchange the build directory with the --build-base option.\nFor example:\n```text\n\npython setup.py build --build-base=/tmp/pybuild/foo-1.0\n```\n(Or you could do this permanently with a directive in your system or\npersonal Distutils configuration file; see\nsection 6 (config-syntax.html#config-files).) Normally, this isn't necessary.\nThe default layout for the build tree is as follows:\n```text\n\n--- build/ --- lib/\nor\n--- build/ --- lib./\ntemp./\n```\nwhere `` expands to a brief description of the current\nOS/hardware platform and Python version. The first form, with just a\nlib directory, is used for ``pure module distributions''--that\nis, module distributions that include only pure Python modules. If a\nmodule distribution contains any extensions (modules written in C/C++),\nthen the second form, with two `` directories, is used. In\nthat case, the temp.plat directory holds temporary\nfiles generated by the compile/link process that don't actually get\ninstalled. In either case, the lib (or\nlib.plat) directory contains all Python modules (pure\nPython and extensions) that will be installed.\nIn the future, more directories will be added to handle Python scripts,\ndocumentation, binary executables, and whatever else is needed to handle\nthe job of installing Python modules and applications.\n## 2.4 How installation works\nAfter the `build` command runs (whether you run it explicitly,\nor the `install` command does it for you), the work of the\n`install` command is relatively simple: all it has to do is copy\neverything under build/lib (or build/lib.plat)\nto your chosen installation directory.\nIf you don't choose an installation directory--i.e., if you just run\n`setup.py install`--then the `install` command installs to\nthe standard location for third-party Python modules. This location\nvaries by platform and by how you built/installed Python itself. On\nUnix and Mac OS, it also depends on whether the module distribution\nbeing installed is pure Python or contains extensions (``non-pure''):\nNotes:\n(1): Most Linux distributions include Python as a standard part of\nthe system, so prefix and exec-prefix are usually\nboth /usr on Linux. If you build Python yourself on Linux (or\nany Unix-like system), the default prefix and\nexec-prefix are /usr/local.\n(2): The default installation directory on Windows was\nC:\\Program Files\\Python under\nPython 1.6a1, 1.5.2, and earlier.\nprefix and exec-prefix stand for the directories\nthat Python is installed to, and where it finds its libraries at\nrun-time. They are always the same under Windows and Mac OS, and very\noften the same under Unix. You can find out what your Python\ninstallation uses for prefix and exec-prefix by\nrunning Python in interactive mode and typing a few simple commands.\nUnder Unix, just type `python` at the shell prompt. Under\nWindows, choose Start > Programs > Python\n2.1 > Python (command line). Under Mac OS, ** ??? **.\nOnce the interpreter is started, you type Python code at the\nprompt. For example, on my Linux system, I type the three Python\nstatements shown below, and get the output as shown, to find out my\nprefix and exec-prefix:\n```text\n\nPython 1.5.2 (#1, Apr 18 1999, 16:03:16) [GCC pgcc-2.91.60 19981201 (egcs-1.1.1 on linux2\nCopyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam\n>>> import sys\n>>> sys.prefix\n'/usr'\n>>> sys.exec_prefix\n'/usr'\n```\nIf you don't want to install modules to the standard location, or if you\ndon't have permission to write there, then you need to read about\nalternate installations in section 4 (alt-install-windows.html#alt-install). If you want to\ncustomize your installation directories more heavily, see\nsection 5 (custom-install.html#custom-install) on custom installations.", "python_version": "2.2", "length": 7732, "url": "https://docs.python.org/2.2/inst/standard-install.html"} {"title": "1 Introduction", "text": "inst.html | inst.html | standard-install.html | Installing Python Modules\n---\n- 1.1 Best case: trivial installation (#SECTION000110000000000000000)\n 1.2 The new standard: Distutils (#SECTION000120000000000000000)\n 1.3 The old way: no standards (#SECTION000130000000000000000)\n---\n# 1 Introduction\nAlthough Python's extensive standard library covers many programming\nneeds, there often comes a time when you need to add some new\nfunctionality to your Python installation in the form of third-party\nmodules. This might be necessary to support your own programming, or to\nsupport an application that you want to use and that happens to be\nwritten in Python.\nIn the past, there has been little support for adding third-party\nmodules to an existing Python installation. With the introduction of\nthe Python Distribution Utilities (Distutils for short) in Python 2.0,\nthis is starting to change. Not everything will change overnight,\nthough, so while this document concentrates on installing module\ndistributions that use the Distutils, we will also spend some time\ndealing with the old ways.\nThis document is aimed primarily at the people who need to install\nthird-party Python modules: end-users and system administrators who just\nneed to get some Python application running, and existing Python\nprogrammers who want to add some new goodies to their toolbox. You\ndon't need to know Python to read this document; there will be some\nbrief forays into using Python's interactive mode to explore your\ninstallation, but that's it. If you're looking for information on how\nto distribute your own Python modules so that others may use them, see\nthe Distributing Python Modules (../dist/dist.html) manual.\n## 1.1 Best case: trivial installation\nIn the best case, someone will have prepared a special version of the\nmodule distribution you want to install that is targeted specifically at\nyour platform and is installed just like any other software on your\nplatform. For example, the module developer might make an executable\ninstaller available for Windows users, an RPM package for users of\nRPM-based Linux systems (Red Hat, SuSE, Mandrake, and many others), a\nDebian package for users of Debian-based Linux systems (Debian proper,\nCaldera, Corel, etc.), and so forth.\nIn that case, you would download the installer appropriate to your\nplatform and do the obvious thing with it: run it if it's an executable\ninstaller, `rpm -install` it if it's an RPM, etc. You don't need\nto run Python or a setup script, you don't need to compile\nanything--you might not even need to read any instructions (although\nit's always a good idea to do so anyways).\nOf course, things will not always be that easy. You might be interested\nin a module distribution that doesn't have an easy-to-use installer for\nyour platform. In that case, you'll have to start with the source\ndistribution released by the module's author/maintainer. Installing\nfrom a source distribution is not too hard, as long as the modules are\npackaged in the standard way. The bulk of this document is about\nbuilding and installing modules from standard source distributions.\n## 1.2 The new standard: Distutils\nIf you download a module source distribution, you can tell pretty\nquickly if it was packaged and distributed in the standard way, i.e.\nusing the Distutils. First, the distribution's name and version number\nwill be featured prominently in the name of the downloaded archive, e.g.\nfoo-1.0.tar.gz or widget-0.9.7.zip. Next, the archive\nwill unpack into a similarly-named directory: foo-1.0 or\nwidget-0.9.7. Additionally, the distribution will contain a\nsetup script setup.py, and a README.txt (or possibly\nREADME), which should explain that building and installing the\nmodule distribution is a simple matter of running\n```text\n\npython setup.py install\n```\nIf all these things are true, then you already know how to build and\ninstall the modules you've just downloaded: run the command above.\nUnless you need to install things in a non-standard way or customize the\nbuild process, you don't really need this manual. Or rather, the above\ncommand is everything you need to get out of this manual.\n## 1.3 The old way: no standards\nBefore the Distutils, there was no infrastructure to support installing\nthird-party modules in a consistent, standardized way. Thus, it's not\nreally possible to write a general manual for installing Python modules\nthat don't use the Distutils; the only truly general statement that can\nbe made is, ``Read the module's own installation instructions.''\nHowever, if such instructions exist at all, they are often woefully\ninadequate and targeted at experienced Python developers. Such users\nare already familiar with how the Python library is laid out on their\nplatform, and know where to copy various files in order for Python to\nfind them. This document makes no such assumptions, and explains how\nthe Python library is laid out on three major platforms (Unix, Windows,\nand Mac OS), so that you can understand what happens when the Distutils\ndo their job and know how to install modules manually when the\nmodule author fails to provide a setup script.\nAdditionally, while there has not previously been a standard\ninstallation mechanism, Python has had some standard machinery for\nbuilding extensions on Unix since Python 1.4. This\nmachinery (the Makefile.pre.in file) is superseded by the\nDistutils, but it will no doubt live on in older module distributions\nfor a while. This Makefile.pre.in mechanism is documented in\nthe Extending & Embedding Python (../ext/ext.html) manual,\nbut that manual is aimed at module developers--hence, we include\ndocumentation for builders/installers here.\nAll of the pre-Distutils material is tucked away in\nsection #pre-distutils.", "python_version": "2.2", "length": 5737, "url": "https://docs.python.org/2.2/inst/trivial-install.html"} {"title": "3 Building Extensions: Tips and Tricks", "text": "standard-install.html | inst.html | alt-install-windows.html | Installing Python Modules\n---\n- 3.1 Using non-Microsoft compilers on Windows (tweak-flags.html#SECTION000310000000000000000)\n - 3.1.1 Borland C++ (tweak-flags.html#SECTION000311000000000000000)\n 3.1.2 GNU C / Cygwin / MinGW32 (tweak-flags.html#SECTION000312000000000000000)\n---\n# 3 Building Extensions: Tips and Tricks\n(This is the section to read for people doing any sort of interesting\nbuild. Things to talk about:\n- the Setup file (any platform now, but Unix-biased)\n- CFLAGS and LDFLAGS (must implement them first!)\n- using non-MS compilers on Windows (how to convert\nPython's library, ...)\n## 3.1 Using non-Microsoft compilers on Windows\n### 3.1.1 Borland C++\nThis subsection describes the necessary steps to use Distutils with the\nBorland C++ compiler version 5.5.1 (#foot486)\nFirst you have to know that the Borland's object file format(OMF) is\ndifferent from what is used by the Python version you can download\nfrom the Python web site. (Python is built with Microsoft Visual C++,\nwhich uses COFF as object file format.) For this reason you have to\nconvert Python's library python20.lib into the Borland format.\nYou can do this as follows:\n```text\n\ncoff2omf python20.lib python20_bcpp.lib\n```\nThe coff2omf program comes with the Borland compiler. The file\npython20.lib is in the Libs directory of your Python\ninstallation. If your extension uses other libraries (zlib,...) you\nhave to convert them too.\nThe converted files have to reside in the same directories as the\nnormal libraries.\nHow does Distutils manage to use these libraries with their changed\nnames? If the extension needs a library (eg. foo) Distutils\nchecks first if it finds a library with suffix _bcpp\n(eg. foo_bcpp.lib) and then uses this library. In the case it\ndoesn't find such a special library it uses the default name\n(foo.lib.)2 (#foot190)\nTo let Distutils compile your extension with Borland C++ you now have\nto type:\n```text\n\npython setup.py build --compiler=bcpp\n```\nIf you want to use the Borland C++ compiler as default, you should\nconsider to write it in your personal or system-wide configuration\nfile for Distutils (see section 6 (config-syntax.html#config-files).)\n** One place to look: http://www.cyberus.ca/~g_will/pyExtenDL.shtml **\n### 3.1.2 GNU C / Cygwin / MinGW32\nThis section describes the necessary steps to use Distutils with the\nGNU C/C++ compilers in their Cygwin and MinGW32\ndistributions.3 (#foot488)\n** For a Python which was built with Cygwin, all should work without\nany of these following steps. **\nFor these compilers we have to create some special libraries too.\nThis task is more complex as for Borland's C++, because there is no\nprogram to convert the library (inclusive the references on data\nstructures.)\nFirst you have to create a list of symbols which the Python DLL exports.\n(You can find a good program for this task at\nhttp://starship.python.net/crew/kernr/mingw32/Notes.html, see at\nPExports 0.42h there.)\n```text\n\npexports python20.dll >python20.def\n```\nThen you can create from these information an import library for gcc.\n```text\n\ndlltool --dllname python20.dll --def python20.def --output-lib libpython20.a\n```\nThe resulting library has to be placed in the same directory as\npython20.lib. (Should be the libs directory under your\nPython installation directory.)\nIf your extension uses other libraries (zlib,...) you might\nhave to convert them too.\nThe converted files have to reside in the same directories as the normal\nlibraries do.\nTo let Distutils compile your extension with Cygwin you now have to type\n```text\n\npython setup.py build --compiler=cygwin\n```\nand for Cygwin in no-cygwin mode4 (#foot489) or for MinGW32 type\n```text\n\npython setup.py build --compiler=mingw32\n```\nIf you want to use any of these options/compilers as default, you should\nconsider to write it in your personal or system-wide configuration file\nfor Distutils (see section 6 (config-syntax.html#config-files).)\n** One place to look: http://www.zope.org/Members/als/tips/win32_mingw_modules **\n** For converted import libraries for python20, tcl83 and tk83 in\ncygwin/mingw32 and bcpp format, see\nhttp://www.htw-dresden.de/~liebschr/PyOpenGL/py2.0-libs.tgzand for the missing header files of the in python2.0 included tcl/tk,\nsee http://www.htw-dresden.de/%7Eliebschr/PyOpenGL/py2.0-tk8.3-header.tgz. **", "python_version": "2.2", "length": 4371, "url": "https://docs.python.org/2.2/inst/tweak-flags.html"} {"title": "About this document ...", "text": "genindex.html | lib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# About this document ...\nPython Library Reference,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | lib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1740, "url": "https://docs.python.org/2.2/lib/about.html"} {"title": "11.5.7 AbstractBasicAuthHandler Objects", "text": "http-password-mgr.html | module-urllib2.html | http-basic-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.7 AbstractBasicAuthHandler Objects", "python_version": "2.2", "length": 197, "url": "https://docs.python.org/2.2/lib/abstract-basic-auth-handler.html"} {"title": "11.5.10 AbstractDigestAuthHandler Objects", "text": "proxy-basic-auth-handler.html | module-urllib2.html | http-digest-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.10 AbstractDigestAuthHandler Objects", "python_version": "2.2", "length": 207, "url": "https://docs.python.org/2.2/lib/abstract-digest-auth-handler.html"} {"title": "12.11.2 AddressList Objects", "text": "message-objects.html | module-rfc822.html | module-base64.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.11.2 AddressList Objects\nAn AddressList instance has the following methods:\nFinally, AddressList instances have one public instance variable:", "python_version": "2.2", "length": 289, "url": "https://docs.python.org/2.2/lib/addresslist-objects.html"} {"title": "20.1.1 Configuration Objects", "text": "module-al.html | module-al.html | al-port-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 20.1.1 Configuration Objects\nConfiguration objects (returned by newconfig() have the\nfollowing methods:", "python_version": "2.2", "length": 240, "url": "https://docs.python.org/2.2/lib/al-config-objects.html"} {"title": "20.1.2 Port Objects", "text": "al-config-objects.html | module-al.html | module-al-constants.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 20.1.2 Port Objects\nPort objects, as returned by openport(), have the following\nmethods:", "python_version": "2.2", "length": 237, "url": "https://docs.python.org/2.2/lib/al-port-objects.html"} {"title": "6. Generic Operating System Services", "text": "shlex-objects.html | lib.html | module-os.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6. Generic Operating System Services\nThe modules described in this chapter provide interfaces to operating\nsystem features that are available on (almost) all operating systems,\nsuch as files and a clock. The interfaces are generally modeled\nafter the Unix or C interfaces, but they are available on most\nother systems as well. Here's an overview:", "python_version": "2.2", "length": 474, "url": "https://docs.python.org/2.2/lib/allos.html"} {"title": "17.1.4 Exceptions and Error Handling", "text": "Querying_ASTs.html | module-parser.html | AST_Objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.4 Exceptions and Error Handling\nThe parser module defines a single exception, but may also pass other\nbuilt-in exceptions from other portions of the Python runtime\nenvironment. See each function for information about the exceptions\nit can raise.\nNote that the functions compileast(), expr(), and\nsuite() may throw exceptions which are normally thrown by the\nparsing and compilation process. These include the built in\nexceptions MemoryError, OverflowError,\nSyntaxError, and SystemError. In these cases, these\nexceptions carry all the meaning normally associated with them. Refer\nto the descriptions of each function for detailed information.", "python_version": "2.2", "length": 787, "url": "https://docs.python.org/2.2/lib/AST_Errors.html"} {"title": "17.1.6 Examples", "text": "AST_Objects.html | module-parser.html | node464.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.6 Examples\nThe parser modules allows operations to be performed on the parse tree\nof Python source code before the bytecode is generated, and provides\nfor inspection of the parse tree for information gathering purposes.\nTwo examples are presented. The simple example demonstrates emulation\nof the compile()built-in function and\nthe complex example shows the use of a parse tree for information\ndiscovery.", "python_version": "2.2", "length": 544, "url": "https://docs.python.org/2.2/lib/AST_Examples.html"} {"title": "17.1.5 AST Objects", "text": "AST_Errors.html | module-parser.html | AST_Examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.5 AST Objects\nOrdered and equality comparisons are supported between AST objects.\nPickling of AST objects (using the pickle (module-pickle.html) module) is also\nsupported.\nAST objects have the following methods:", "python_version": "2.2", "length": 355, "url": "https://docs.python.org/2.2/lib/AST_Objects.html"} {"title": "11.22.1 Example basic HTTP client", "text": "module-asyncore.html | module-asyncore.html | netdata.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.22.1 Example basic HTTP client\nAs a basic example, below is a very basic HTTP client that uses the\ndispatcher class to implement its socket handling:\n```text\n\nclass http_client(asyncore.dispatcher):\ndef __init__(self, host,path):\nasyncore.dispatcher.__init__(self)\nself.path = path\nself.create_socket(socket.AF_INET, socket.SOCK_STREAM)\nself.connect( (host, 80) )\nself.buffer = 'GET %s HTTP/1.0\\r\\n\\r\\n' % self.path\n\ndef handle_connect(self):\npass\n\ndef handle_read(self):\ndata = self.recv(8192)\nprint data\n\ndef writable(self):\nreturn (len(self.buffer) > 0)\n\ndef handle_write(self):\nsent = self.send(self.buffer)\nself.buffer = self.buffer[sent:]\n```", "python_version": "2.2", "length": 792, "url": "https://docs.python.org/2.2/lib/asyncore-example.html"} {"title": "3.5.1 atexit Example", "text": "module-atexit.html | module-atexit.html | module-types.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.5.1 atexit Example\nThe following simple example demonstrates how a module can initialize\na counter from a file when it is imported and save the counter's\nupdated value automatically when the program terminates without\nrelying on the application making an explicit call into this module at\ntermination.", "python_version": "2.2", "length": 445, "url": "https://docs.python.org/2.2/lib/atexit-example.html"} {"title": "13.12.5 AttributesImpl Objects", "text": "input-source-objects.html | module-xml.sax.xmlreader.html | attributes-ns-impl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.12.5 AttributesImpl Objects\nAttributesImpl objects implement a portion of the mapping\nprotocol, and the methods copy(), get(),\nhas_key(), items(), keys(), and\nvalues(). The following methods are also provided:", "python_version": "2.2", "length": 386, "url": "https://docs.python.org/2.2/lib/attributes-impl-objects.html"} {"title": "13.12.6 AttributesNSImpl Objects", "text": "attributes-impl-objects.html | module-xml.sax.xmlreader.html | module-xmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.12.6 AttributesNSImpl Objects", "python_version": "2.2", "length": 196, "url": "https://docs.python.org/2.2/lib/attributes-ns-impl-objects.html"} {"title": "14.4.1 AU_read Objects", "text": "module-sunau.html | module-sunau.html | au-write-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 14.4.1 AU_read Objects\nAU_read objects, as returned by open() above, have the\nfollowing methods:\nThe following two methods define a term ``position'' which is compatible\nbetween them, and is otherwise implementation dependent.\nThe following two functions are defined for compatibility with the\naifc (module-aifc.html), and don't do anything interesting.", "python_version": "2.2", "length": 497, "url": "https://docs.python.org/2.2/lib/au-read-objects.html"} {"title": "14.4.2 AU_write Objects", "text": "au-read-objects.html | module-sunau.html | module-wave.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 14.4.2 AU_write Objects\nAU_write objects, as returned by open() above, have the\nfollowing methods:", "python_version": "2.2", "length": 240, "url": "https://docs.python.org/2.2/lib/au-write-objects.html"} {"title": "21.1.1 Audio Device Objects", "text": "module-sunaudiodev.html | module-sunaudiodev.html | module-sunaudiodev-constants.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 21.1.1 Audio Device Objects\nThe audio device objects are returned by open() define the\nfollowing methods (except `control` objects which only provide\ngetinfo(), setinfo(), fileno(), and\ndrain()):\nThe audio device supports asynchronous notification of various events,\nthrough the SIGPOLL signal. Here's an example of how you might enable\nthis in Python:\n```text\n\ndef handle_sigpoll(signum, frame):\nprint 'I got a SIGPOLL update'\n\nimport fcntl, signal, STROPTS\n\nsignal.signal(signal.SIGPOLL, handle_sigpoll)\nfcntl.ioctl(audio_obj.fileno(), STROPTS.I_SETSIG, STROPTS.S_MSG)\n```", "python_version": "2.2", "length": 742, "url": "https://docs.python.org/2.2/lib/audio-device-objects.html"} {"title": "11.5.3 BaseHandler Objects", "text": "opener-director-objects.html | module-urllib2.html | http-redirect-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.3 BaseHandler Objects\nBaseHandler objects provide a couple of methods that are\ndirectly useful, and others that are meant to be used by derived\nclasses. These are intended for direct use:\nThe following members and methods should only be used by classes\nderived from BaseHandler:", "python_version": "2.2", "length": 445, "url": "https://docs.python.org/2.2/lib/base-handler-objects.html"} {"title": "11.20.4 Binary Objects", "text": "datetime-objects.html | module-xmlrpclib.html | fault-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.4 Binary Objects\nThis class may initialized from string data (which may include NULs).\nIt has the following methods, supported mainly for internal use by the\nmarshalling/unmarshalling code:\nIt also supports certain of Python's built-in operators through a\n_cmp__ method.", "python_version": "2.2", "length": 425, "url": "https://docs.python.org/2.2/lib/binary-objects.html"} {"title": "12.14.1 Notes", "text": "module-binhex.html | module-binhex.html | module-quopri.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.14.1 Notes\nThere is an alternative, more powerful interface to the coder and\ndecoder, see the source for details.\nIf you code or decode textfiles on non-Macintosh platforms they will\nstill use the Macintosh newline convention (carriage-return as end of\nline).", "python_version": "2.2", "length": 405, "url": "https://docs.python.org/2.2/lib/binhex-notes.html"} {"title": "5.8.1 Example", "text": "module-bisect.html | module-bisect.html | module-array.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.8.1 Example\nThe bisect() function is generally useful for categorizing\nnumeric data. This example uses bisect() to look up a\nletter grade for an exam total (say) based on a set of ordered numeric\nbreakpoints: 85 and up is an `A', 75..84 is a `B', etc.", "python_version": "2.2", "length": 395, "url": "https://docs.python.org/2.2/lib/bisect-example.html"} {"title": "2.2.4.1 Bit-string Operations on Integer Types", "text": "typesnumeric.html | typesnumeric.html | typeiter.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.4.1 Bit-string Operations on Integer Types\nPlain and long integer types support additional operations that make\nsense only for bit-strings. Negative numbers are treated as their 2's\ncomplement value (for long integers, this assumes a sufficiently large\nnumber of bits that no overflow occurs during the operation).\nThe priorities of the binary bit-wise operations are all lower than\nthe numeric operations and higher than the comparisons; the unary\noperation \"~\" has the same priority as the other unary numeric\noperations (\"+\" and \"-\").\nThis table lists the bit-string operations sorted in ascending\npriority (operations in the same box have the same priority):\nNotes:\n(1): Negative shift counts are illegal and cause a\nValueError to be raised.\n(2): A left shift by n bits is equivalent to\nmultiplication by `pow(2, n )` without overflow check.\n(3): A right shift by n bits is equivalent to\ndivision by `pow(2, n )` without overflow check.", "python_version": "2.2", "length": 1081, "url": "https://docs.python.org/2.2/lib/bitstring-ops.html"} {"title": "2.2.9.5 Code Objects", "text": "typesmethods.html | typesother.html | bltin-type-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.5 Code Objects\nCode objects are used by the implementation to represent\n``pseudo-compiled'' executable Python code such as a function body.\nThey differ from function objects because they don't contain a\nreference to their global execution environment. Code objects are\nreturned by the built-in compile() function and can be\nextracted from function objects through their func_code\nattribute.\nA code object can be executed or evaluated by passing it (instead of a\nsource string) to the exec statement or the built-in\neval() function.\nSee the Python Reference Manual (../ref/ref.html) for more\ninformation.", "python_version": "2.2", "length": 754, "url": "https://docs.python.org/2.2/lib/bltin-code-objects.html"} {"title": "2.2.9.8 The Ellipsis Object", "text": "bltin-null-object.html | typesother.html | typesinternal.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.8 The Ellipsis Object\nThis object is used by extended slice notation (see the\nPython Reference Manual (../ref/ref.html)). It supports no\nspecial operations. There is exactly one ellipsis object, named\nEllipsis (a built-in name).\nIt is written as `Ellipsis`.", "python_version": "2.2", "length": 408, "url": "https://docs.python.org/2.2/lib/bltin-ellipsis-object.html"} {"title": "2.2.8 File Objects", "text": "typesmapping.html | types.html | typesother.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.8 File Objects\nFile objectsare implemented using C's `stdio`\npackage and can be created with the built-in constructor\nfile()described in section\n2.1 (built-in-funcs.html#built-in-funcs), ``Built-in Functions.''2.10 (#foot2691)They are also returned\nby some other built-in functions and methods, such as\nos.popen() and os.fdopen() and the\nmakefile() method of socket objects.\nWhen a file operation fails for an I/O-related reason, the exception\nIOError is raised. This includes situations where the\noperation is not defined for some reason, like seek() on a tty\ndevice or writing a file opened for reading.\nFiles have the following methods:\nFiles support the iterator protocol. Each iteration returns the same\nresult as `file .readline()`, and iteration ends when the\nreadline() method returns an empty string.\nFile objects also offer a number of other interesting attributes.\nThese are not required for file-like objects, but should be\nimplemented if they make sense for the particular object.", "python_version": "2.2", "length": 1128, "url": "https://docs.python.org/2.2/lib/bltin-file-objects.html"} {"title": "2.2.9.7 The Null Object", "text": "bltin-type-objects.html | typesother.html | bltin-ellipsis-object.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.7 The Null Object\nThis object is returned by functions that don't explicitly return a\nvalue. It supports no special operations. There is exactly one null\nobject, named `None` (a built-in name).\nIt is written as `None`.", "python_version": "2.2", "length": 378, "url": "https://docs.python.org/2.2/lib/bltin-null-object.html"} {"title": "2.2.9.6 Type Objects", "text": "bltin-code-objects.html | typesother.html | bltin-null-object.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.6 Type Objects\nType objects represent the various object types. An object's type is\naccessed by the built-in function type(). There are no special\noperations on types. The standard module types defines names\nfor all standard built-in types.\nTypes are written like this: ``.", "python_version": "2.2", "length": 441, "url": "https://docs.python.org/2.2/lib/bltin-type-objects.html"} {"title": "11.20.2 Boolean Objects", "text": "server-objects.html | module-xmlrpclib.html | datetime-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.2 Boolean Objects\nThis class may be initialized from any Python value; the instance\nreturned depends only on its truth value. It supports various Python\noperators through __cmp__(), __repr__(),\n__int__(), and __nonzero__() methods, all\nimplemented in the obvious ways.\nIt also has the following method, supported mainly for internal use by\nthe unmarshalling code:", "python_version": "2.2", "length": 519, "url": "https://docs.python.org/2.2/lib/boolean-objects.html"} {"title": "2.2.2 Boolean Operations", "text": "truth.html | types.html | comparisons.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.2 Boolean Operations\nThese are the Boolean operations, ordered by ascending priority:\nNotes:\n(1): These only evaluate their second argument if needed for their outcome.\n(2): \"not\" has a lower priority than non-Boolean operators, so\n`not a == b` is interpreted as `not ( a == b )`, and `a == not b` is a syntax error.", "python_version": "2.2", "length": 445, "url": "https://docs.python.org/2.2/lib/boolean.html"} {"title": "11.1.1 Browser Controller Objects", "text": "module-webbrowser.html | module-webbrowser.html | module-cgi.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.1.1 Browser Controller Objects\nBrowser controllers provide two methods which parallel two of the\nmodule-level convenience functions:", "python_version": "2.2", "length": 283, "url": "https://docs.python.org/2.2/lib/browser-controllers.html"} {"title": "7.12.1 Hash, BTree and Record Objects", "text": "module-bsddb.html | module-bsddb.html | module-zlib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.12.1 Hash, BTree and Record Objects\nOnce instantiated, hash, btree and record objects support the following\nmethods:\nExample:", "python_version": "2.2", "length": 266, "url": "https://docs.python.org/2.2/lib/bsddb-objects.html"} {"title": "2.1 Built-in Functions", "text": "builtin.html | builtin.html | types.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 2.1 Built-in Functions\nThe Python interpreter has a number of functions built into it that\nare always available. They are listed here in alphabetical order.", "python_version": "2.2", "length": 278, "url": "https://docs.python.org/2.2/lib/built-in-funcs.html"} {"title": "2. Built-in Functions, Types, and Exceptions", "text": "intro.html | lib.html | built-in-funcs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 2. Built-in Functions, Types, and Exceptions\nNames for built-in exceptions and functions are found in a separate\nsymbol table. This table is searched last when the interpreter looks\nup the meaning of a name, so local and global\nuser-defined names can override built-in names. Built-in types are\ndescribed together here for easy reference.2.1 (#foot91)\nThe tables in this chapter document the priorities of operators by\nlisting them in order of ascending priority (within a table) and\ngrouping operators that have the same priority in the same box.\nBinary operators of the same priority group from left to right.\n(Unary operators group from right to left, but there you have no real\nchoice.) See chapter 5 of the Python\nReference Manual (../ref/ref.html) for the complete picture on operator priorities.\n---\n#### Footnotes", "python_version": "2.2", "length": 946, "url": "https://docs.python.org/2.2/lib/builtin.html"} {"title": "18.10.1 Python Byte Code Instructions", "text": "module-dis.html | module-dis.html | module-distutils.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.10.1 Python Byte Code Instructions\nThe Python compiler currently generates the following byte code\ninstructions.\nUnary Operations take the top of the stack, apply the operation, and\npush the result back on the stack.\nBinary operations remove the top of the stack (TOS) and the second top-most\nstack item (TOS1) from the stack. They perform the operation, and put the\nresult back on the stack.\nIn-place operations are like binary operations, in that they remove TOS and\nTOS1, and push the result back on the stack, but the operation is done\nin-place when TOS1 supports it, and the resulting TOS may be (but does not\nhave to be) the original TOS1.\nThe slice opcodes take up to three parameters.\nSlice assignment needs even an additional parameter. As any statement,\nthey put nothing on the stack.\nAll of the following opcodes expect arguments. An argument is two\nbytes, with the more significant byte last.", "python_version": "2.2", "length": 1047, "url": "https://docs.python.org/2.2/lib/bytecodes.html"} {"title": "11.5.17 CacheFTPHandler Objects", "text": "ftp-handler-objects.html | module-urllib2.html | gopher-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.17 CacheFTPHandler Objects\nCacheFTPHandler objects are FTPHandler objects with\nthe following additional methods:", "python_version": "2.2", "length": 268, "url": "https://docs.python.org/2.2/lib/cacheftp-handler-objects.html"} {"title": "20.3.2 Parser Objects", "text": "player-objects.html | module-cd.html | module-fl.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 20.3.2 Parser Objects\nParser objects (returned by createparser()) have the\nfollowing methods:", "python_version": "2.2", "length": 229, "url": "https://docs.python.org/2.2/lib/cd-parser-objects.html"} {"title": "11.2.1 Introduction", "text": "module-cgi.html | module-cgi.html | node295.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.1 Introduction\nA CGI script is invoked by an HTTP server, usually to process user\ninput submitted through an HTML `
` or `` element.\nMost often, CGI scripts live in the server's special cgi-bin\ndirectory. The HTTP server places all sorts of information about the\nrequest (such as the client's hostname, the requested URL, the query\nstring, and lots of other goodies) in the script's shell environment,\nexecutes the script, and sends the script's output back to the client.\nThe script's input is connected to the client too, and sometimes the\nform data is read this way; at other times the form data is passed via\nthe ``query string'' part of the URL. This module is intended\nto take care of the different cases and provide a simpler interface to\nthe Python script. It also provides a number of utilities that help\nin debugging scripts, and the latest addition is support for file\nuploads from a form (if your browser supports it -- Grail 0.3 and\nNetscape 2.0 do).\nThe output of a CGI script should consist of two sections, separated\nby a blank line. The first section contains a number of headers,\ntelling the client what kind of data is following. Python code to\ngenerate a minimal header section looks like this:\n```text\n\nprint \"Content-Type: text/html\" # HTML is following\nprint # blank line, end of headers\n```\nThe second section is usually HTML, which allows the client software\nto display nicely formatted text with header, in-line images, etc.\nHere's Python code that prints a simple piece of HTML:\n```text\n\nprint \"CGI script output\"\nprint \"

This is my first CGI script

\"\nprint \"Hello, world!\"\n```", "python_version": "2.2", "length": 1776, "url": "https://docs.python.org/2.2/lib/cgi-intro.html"} {"title": "11.2.6 Caring about security", "text": "node298.html | module-cgi.html | node300.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.6 Caring about security\nThere's one important rule: if you invoke an external program (via the\nos.system() or os.popen() functions. or others\nwith similar functionality), make very sure you don't pass arbitrary\nstrings received from the client to the shell. This is a well-known\nsecurity hole whereby clever hackers anywhere on the Web can exploit a\ngullible CGI script to invoke arbitrary shell commands. Even parts of\nthe URL or field names cannot be trusted, since the request doesn't\nhave to come from your form!\nTo be on the safe side, if you must pass a string gotten from a form\nto a shell command, you should make sure the string contains only\nalphanumeric characters, dashes, underscores, and periods.", "python_version": "2.2", "length": 843, "url": "https://docs.python.org/2.2/lib/cgi-security.html"} {"title": "5.14.1 Cmd Objects", "text": "module-cmd.html | module-cmd.html | module-shlex.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.14.1 Cmd Objects\nA Cmd instance has the following methods:\nInstances of Cmd subclasses have some public instance variables:", "python_version": "2.2", "length": 261, "url": "https://docs.python.org/2.2/lib/Cmd-objects.html"} {"title": "4.8.1.1 Codec Objects", "text": "node113.html | node113.html | stream-writer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 4.8.1.1 Codec Objects\nThe Codec class defines these methods which also define the\nfunction interfaces of the stateless encoder and decoder:\nThe StreamWriter and StreamReader classes provide\ngeneric working interfaces which can be used to implement new\nencodings submodules very easily. See encodings.utf_8 for an\nexample on how this is done.", "python_version": "2.2", "length": 481, "url": "https://docs.python.org/2.2/lib/codec-objects.html"} {"title": "2.2.3 Comparisons", "text": "boolean.html | types.html | typesnumeric.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.3 Comparisons\nComparison operations are supported by all objects. They all have the\nsame priority (which is higher than that of the Boolean operations).\nComparisons can be chained arbitrarily; for example, `x < y <= z` is equivalent to `x < y and y <= z`, except that y is evaluated only once (but\nin both cases z is not evaluated at all when `x < y` is found to be false).\nThis table summarizes the comparison operations:\nNotes:\n(1): `<>` and `!=` are alternate spellings for the same operator.\n(I couldn't choose between ABC and C! :-)\n`!=` is the preferred spelling; `<>` is obsolescent.\nObjects of different types, except different numeric types, never\ncompare equal; such objects are ordered consistently but arbitrarily\n(so that sorting a heterogeneous array yields a consistent result).\nFurthermore, some types (for example, file objects) support only a\ndegenerate notion of comparison where any two objects of that type are\nunequal. Again, such objects are ordered arbitrarily but\nconsistently.\nInstances of a class normally compare as non-equal unless the class\ndefines the __cmp__() method. Refer to the\nPython Reference Manual (../ref/customization.html) for\ninformation on the use of this method to effect object comparisons.\nImplementation note: Objects of different types except\nnumbers are ordered by their type names; objects of the same types\nthat don't support proper comparison are ordered by their address.\nTwo more operations with the same syntactic priority,\n\"in\"and \"not in\", are supported\nonly by sequence types (below).", "python_version": "2.2", "length": 1676, "url": "https://docs.python.org/2.2/lib/comparisons.html"} {"title": "19. Python compiler package", "text": "module-distutils.html | lib.html | module-compiler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 19. Python compiler package\nThe Python compiler package is a tool for analyzing Python source code\nand generating Python bytecode. The compiler contains libraries to\ngenerate an abstract syntax tree from Python source code and to\ngenerate Python bytecode from the tree.\nThe compiler (module-compiler.html) package is a Python source to bytecode\ntranslator written in Python. It uses the built-in parser and\nstandard parser (module-parser.html) module to generated a concrete syntax\ntree. This tree is used to generate an abstract syntax tree (AST) and\nthen Python bytecode.\nThe full functionality of the package duplicates the builtin compiler\nprovided with the Python interpreter. It is intended to match its\nbehavior almost exactly. Why implement another compiler that does the\nsame thing? The package is useful for a variety of purposes. It can\nbe modified more easily than the builtin compiler. The AST it\ngenerates is useful for analyzing Python source code.\nThis chapter explains how the various components of the\ncompiler (module-compiler.html) package work. It blends reference material with\na tutorial.\nThe following modules are part of the compiler (module-compiler.html) package:\ncompiler (module-compiler.html)\ncompiler.ast (module-compiler.ast.html)\ncompiler.visitor (module-compiler.visitor.html)", "python_version": "2.2", "length": 1447, "url": "https://docs.python.org/2.2/lib/compiler.html"} {"title": "7.17.1 Completer Objects", "text": "module-rlcompleter.html | module-rlcompleter.html | unix.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.17.1 Completer Objects\nCompleter objects have the following method:", "python_version": "2.2", "length": 213, "url": "https://docs.python.org/2.2/lib/completer-objects.html"} {"title": "7.5.3 Condition Objects", "text": "rlock-objects.html | module-threading.html | semaphore-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.5.3 Condition Objects\nA condition variable is always associated with some kind of lock;\nthis can be passed in or one will be created by default. (Passing\none in is useful when several condition variables must share the\nsame lock.)\nA condition variable has acquire() and release()\nmethods that call the corresponding methods of the associated lock.\nIt also has a wait() method, and notify() and\nnotifyAll() methods. These three must only be called when\nthe calling thread has acquired the lock.\nThe wait() method releases the lock, and then blocks until it\nis awakened by a notify() or notifyAll() call for\nthe same condition variable in another thread. Once awakened, it\nre-acquires the lock and returns. It is also possible to specify a\ntimeout.\nThe notify() method wakes up one of the threads waiting for\nthe condition variable, if any are waiting. The notifyAll()\nmethod wakes up all threads waiting for the condition variable.\nNote: the notify() and notifyAll() methods don't\nrelease the lock; this means that the thread or threads awakened will\nnot return from their wait() call immediately, but only when\nthe thread that called notify() or notifyAll()\nfinally relinquishes ownership of the lock.\nTip: the typical programming style using condition variables uses the\nlock to synchronize access to some shared state; threads that are\ninterested in a particular change of state call wait()\nrepeatedly until they see the desired state, while threads that modify\nthe state call notify() or notifyAll() when they\nchange the state in such a way that it could possibly be a desired\nstate for one of the waiters. For example, the following code is a\ngeneric producer-consumer situation with unlimited buffer capacity:\n```text\n\n# Consume one item\ncv.acquire()\nwhile not an_item_is_available():\ncv.wait()\nget_an_available_item()\ncv.release()\n\n# Produce one item\ncv.acquire()\nmake_an_item_available()\ncv.notify()\ncv.release()\n```\nTo choose between notify() and notifyAll(), consider\nwhether one state change can be interesting for only one or several\nwaiting threads. E.g. in a typical producer-consumer situation,\nadding one item to the buffer only needs to wake up one consumer\nthread.", "python_version": "2.2", "length": 2333, "url": "https://docs.python.org/2.2/lib/condition-objects.html"} {"title": "5.10.1 ConfigParser Objects", "text": "module-ConfigParser.html | module-ConfigParser.html | module-fileinput.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.10.1 ConfigParser Objects\nConfigParser instances have the following methods:", "python_version": "2.2", "length": 236, "url": "https://docs.python.org/2.2/lib/ConfigParser-objects.html"} {"title": "3.22.2 Interactive Console Objects", "text": "interpreter-objects.html | module-code.html | module-codeop.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.22.2 Interactive Console Objects\nThe InteractiveConsole class is a subclass of\nInteractiveInterpreter, and so offers all the methods of the\ninterpreter objects as well as the following additions.", "python_version": "2.2", "length": 344, "url": "https://docs.python.org/2.2/lib/console-objects.html"} {"title": "13.10.1 ContentHandler Objects", "text": "module-xml.sax.handler.html | module-xml.sax.handler.html | dtd-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.10.1 ContentHandler Objects\nUsers are expected to subclass ContentHandler to support their\napplication. The following methods are called by the parser on the\nappropriate events in the input document:", "python_version": "2.2", "length": 369, "url": "https://docs.python.org/2.2/lib/content-handler-objects.html"} {"title": "Contents", "text": "front.html | lib.html | intro.html | Python Library Reference | modindex.html | genindex.html\n---\n## Contents\nTable of Contents\n- Front Matter (front.html)\n 1. Introduction (intro.html)\n 2. Built-in Functions, Types, and Exceptions (builtin.html)\n - 2.1 Built-in Functions (built-in-funcs.html)\n 2.2 Built-in Types (types.html)\n - 2.2.1 Truth Value Testing (truth.html)\n 2.2.2 Boolean Operations (boolean.html)\n 2.2.3 Comparisons (comparisons.html)\n 2.2.4 Numeric Types (typesnumeric.html)\n 2.2.5 Iterator Types (typeiter.html)\n 2.2.6 Sequence Types (typesseq.html)\n 2.2.7 Mapping Types (typesmapping.html)\n 2.2.8 File Objects (bltin-file-objects.html)\n 2.2.9 Other Built-in Types (typesother.html)\n 2.2.10 Special Attributes (specialattrs.html)\n 2.3 Built-in Exceptions (module-exceptions.html)\n 3. Python Runtime Services (python.html)\n - 3.1 sys -- System-specific parameters and functions (module-sys.html)\n 3.2 gc -- Garbage Collector interface (module-gc.html)\n 3.3 weakref -- Weak references (module-weakref.html)\n - 3.3.1 Weak Reference Objects (weakref-objects.html)\n 3.3.2 Example (weakref-example.html)\n 3.3.3 Weak References in Extension Types (weakref-extension.html)\n 3.4 fpectl -- Floating point exception control (module-fpectl.html)\n - 3.4.1 Example (fpectl-example.html)\n 3.4.2 Limitations and other considerations (node41.html)\n 3.5 atexit -- Exit handlers (module-atexit.html)\n - 3.5.1 atexit Example (atexit-example.html)\n 3.6 types -- Names for all built-in types (module-types.html)\n 3.7 UserDict -- Class wrapper for dictionary objects (module-UserDict.html)\n 3.8 UserList -- Class wrapper for list objects (module-UserList.html)\n 3.9 UserString -- Class wrapper for string objects (module-UserString.html)\n 3.10 operator -- Standard operators as functions. (module-operator.html)\n - 3.10.1 Mapping Operators to Functions (operator-map.html)\n 3.11 inspect -- Inspect live objects (module-inspect.html)\n - 3.11.1 Types and members (inspect-types.html)\n 3.11.2 Retrieving source code (inspect-source.html)\n 3.11.3 Classes and functions (inspect-classes-functions.html)\n 3.11.4 The interpreter stack (inspect-stack.html)\n 3.12 traceback -- Print or retrieve a stack traceback (module-traceback.html)\n - 3.12.1 Traceback Example (traceback-example.html)\n 3.13 linecache -- Random access to text lines (module-linecache.html)\n 3.14 pickle -- Python object serialization (module-pickle.html)\n - 3.14.1 Relationship to other Python modules (node59.html)\n 3.14.2 Data stream format (node60.html)\n 3.14.3 Usage (node61.html)\n 3.14.4 What can be pickled and unpickled? (node62.html)\n 3.14.5 The pickle protocol (pickle-protocol.html)\n 3.14.6 Security (pickle-sec.html)\n 3.14.7 Example (pickle-example.html)\n 3.15 cPickle -- A faster pickle (module-cPickle.html)\n 3.16 copy_reg -- Register pickle support functions (module-copyreg.html)\n 3.17 shelve -- Python object persistence (module-shelve.html)\n 3.18 copy -- Shallow and deep copy operations (module-copy.html)\n 3.19 marshal -- Internal Python object serialization (module-marshal.html)\n 3.20 warnings -- Warning control (module-warnings.html)\n - 3.20.1 Warning Categories (warning-categories.html)\n 3.20.2 The Warnings Filter (warning-filter.html)\n 3.20.3 Available Functions (warning-functions.html)\n 3.21 imp -- Access the import internals (module-imp.html)\n - 3.21.1 Examples (examples-imp.html)\n 3.22 code -- Interpreter base classes (module-code.html)\n - 3.22.1 Interactive Interpreter Objects (interpreter-objects.html)\n 3.22.2 Interactive Console Objects (console-objects.html)\n 3.23 codeop -- Compile Python code (module-codeop.html)\n 3.24 pprint -- Data pretty printer (module-pprint.html)\n - 3.24.1 PrettyPrinter Objects (node85.html)\n 3.25 repr -- Alternate repr() implementation (module-repr.html)\n - 3.25.1 Repr Objects (Repr-objects.html)\n 3.25.2 Subclassing Repr Objects (subclassing-reprs.html)\n 3.26 new -- Creation of runtime internal objects (module-new.html)\n 3.27 site -- Site-specific configuration hook (module-site.html)\n 3.28 user -- User-specific configuration hook (module-user.html)\n 3.29 __builtin__ -- Built-in functions (module-builtin.html)\n 3.30 __main__ -- Top-level script environment (module-main.html)\n 4. String Services (strings.html)\n - 4.1 string -- Common string operations (module-string.html)\n 4.2 re -- Regular expression operations (module-re.html)\n - 4.2.1 Regular Expression Syntax (re-syntax.html)\n 4.2.2 Matching vs. Searching (matching-searching.html)\n 4.2.3 Module Contents (node99.html)\n 4.2.4 Regular Expression Objects (re-objects.html)\n 4.2.5 Match Objects (match-objects.html)\n 4.2.6 Examples (node102.html)\n 4.3 struct -- Interpret strings as packed binary data (module-struct.html)\n 4.4 difflib -- Helpers for computing deltas (module-difflib.html)\n - 4.4.1 SequenceMatcher Objects (sequence-matcher.html)\n 4.4.2 SequenceMatcher Examples (sequencematcher-examples.html)\n 4.4.3 Differ Objects (differ-objects.html)\n 4.4.4 Differ Example (differ-examples.html)\n 4.5 fpformat -- Floating point conversions (module-fpformat.html)\n 4.6 StringIO -- Read and write strings as files (module-StringIO.html)\n 4.7 cStringIO -- Faster version of StringIO (module-cStringIO.html)\n 4.8 codecs -- Codec registry and base classes (module-codecs.html)\n - 4.8.1 Codec Base Classes (node113.html)\n 4.9 unicodedata -- Unicode Database (module-unicodedata.html)\n 5. Miscellaneous Services (misc.html)\n - 5.1 pydoc -- Documentation generator and online help system (module-pydoc.html)\n 5.2 doctest -- Test docstrings represent reality (module-doctest.html)\n - 5.2.1 Normal Usage (node123.html)\n 5.2.2 Which Docstrings Are Examined? (node124.html)\n 5.2.3 What's the Execution Context? (node125.html)\n 5.2.4 What About Exceptions? (node126.html)\n 5.2.5 Advanced Usage (node127.html)\n 5.2.6 How are Docstring Examples Recognized? (node128.html)\n 5.2.7 Warnings (node129.html)\n 5.2.8 Soapbox (node130.html)\n 5.3 unittest -- Unit testing framework (module-unittest.html)\n - 5.3.1 Organizing test code (organizing-tests.html)\n 5.3.2 Re-using old test code (legacy-unit-tests.html)\n 5.3.3 Classes and functions (unittest-contents.html)\n 5.3.4 TestCase Objects (testcase-objects.html)\n 5.3.5 TestSuite Objects (testsuite-objects.html)\n 5.3.6 TestResult Objects (testresult-objects.html)\n 5.3.7 TestLoader Objects (testloader-objects.html)\n 5.4 math -- Mathematical functions (module-math.html)\n 5.5 cmath -- Mathematical functions for complex numbers (module-cmath.html)\n 5.6 random -- Generate pseudo-random numbers (module-random.html)\n 5.7 whrandom -- Pseudo-random number generator (module-whrandom.html)\n 5.8 bisect -- Array bisection algorithm (module-bisect.html)\n - 5.8.1 Example (bisect-example.html)\n 5.9 array -- Efficient arrays of numeric values (module-array.html)\n 5.10 ConfigParser -- Configuration file parser (module-ConfigParser.html)\n - 5.10.1 ConfigParser Objects (ConfigParser-objects.html)\n 5.11 fileinput -- Iterate over lines from multiple input streams (module-fileinput.html)\n 5.12 xreadlines -- Efficient iteration over a file (module-xreadlines.html)\n 5.13 calendar -- General calendar-related functions (module-calendar.html)\n 5.14 cmd -- Support for line-oriented command interpreters (module-cmd.html)\n - 5.14.1 Cmd Objects (Cmd-objects.html)\n 5.15 shlex -- Simple lexical analysis (module-shlex.html)\n - 5.15.1 shlex Objects (shlex-objects.html)\n 6. Generic Operating System Services (allos.html)\n - 6.1 os -- Miscellaneous operating system interfaces (module-os.html)\n - 6.1.1 Process Parameters (os-procinfo.html)\n 6.1.2 File Object Creation (os-newstreams.html)\n 6.1.3 File Descriptor Operations (os-fd-ops.html)\n 6.1.4 Files and Directories (os-file-dir.html)\n 6.1.5 Process Management (os-process.html)\n 6.1.6 Miscellaneous System Information (os-path.html)\n 6.2 os.path -- Common pathname manipulations (module-os.path.html)\n 6.3 dircache -- Cached directory listings (module-dircache.html)\n 6.4 stat -- Interpreting stat() results (module-stat.html)\n 6.5 statcache -- An optimization of os.stat() (module-statcache.html)\n 6.6 statvfs -- Constants used with os.statvfs() (module-statvfs.html)\n 6.7 filecmp -- File and Directory Comparisons (module-filecmp.html)\n - 6.7.1 The dircmp class (dircmp-objects.html)\n 6.8 popen2 -- Subprocesses with accessible I/O streams (module-popen2.html)\n - 6.8.1 Popen3 and Popen4 Objects (popen3-objects.html)\n 6.9 time -- Time access and conversions (module-time.html)\n 6.10 sched -- Event scheduler (module-sched.html)\n - 6.10.1 Scheduler Objects (scheduler-objects.html)\n 6.11 mutex -- Mutual exclusion support (module-mutex.html)\n - 6.11.1 Mutex Objects (mutex-objects.html)\n 6.12 getpass -- Portable password input (module-getpass.html)\n 6.13 curses -- Terminal handling for character-cell displays (module-curses.html)\n - 6.13.1 Functions (curses-functions.html)\n 6.13.2 Window Objects (curses-window-objects.html)\n 6.13.3 Constants (node181.html)\n 6.14 curses.textpad -- Text input widget for curses programs (module-curses.textpad.html)\n - 6.14.1 Textbox objects (curses-textpad-objects.html)\n 6.15 curses.wrapper -- Terminal handler for curses programs (module-curses.wrapper.html)\n 6.16 curses.ascii -- Utilities for ASCII characters (module-curses.ascii.html)\n 6.17 curses.panel -- A panel stack extension for curses. (module-curses.panel.html)\n - 6.17.1 Functions (cursespanel-functions.html)\n 6.17.2 Panel Objects (curses-panel-objects.html)\n 6.18 getopt -- Parser for command line options (module-getopt.html)\n 6.19 tempfile -- Generate temporary file names (module-tempfile.html)\n 6.20 errno -- Standard errno system symbols (module-errno.html)\n 6.21 glob -- Unix style pathname pattern expansion (module-glob.html)\n 6.22 fnmatch -- Unix filename pattern matching (module-fnmatch.html)\n 6.23 shutil -- High-level file operations (module-shutil.html)\n - 6.23.1 Example (shutil-example.html)\n 6.24 locale -- Internationalization services (module-locale.html)\n - 6.24.1 Background, details, hints, tips and caveats (node197.html)\n 6.24.2 For extension writers and programs that embed Python (embedding-locale.html)\n 6.25 gettext -- Multilingual internationalization services (module-gettext.html)\n - 6.25.1 GNU gettext API (node200.html)\n 6.25.2 Class-based API (node201.html)\n 6.25.3 Internationalizing your programs and modules (node206.html)\n 6.25.4 Acknowledgements (node211.html)\n 7. Optional Operating System Services (someos.html)\n - 7.1 signal -- Set handlers for asynchronous events (module-signal.html)\n - 7.1.1 Example (node214.html)\n 7.2 socket -- Low-level networking interface (module-socket.html)\n - 7.2.1 Socket Objects (socket-objects.html)\n 7.2.2 SSL Objects (ssl-objects.html)\n 7.2.3 Example (socket-example.html)\n 7.3 select -- Waiting for I/O completion (module-select.html)\n - 7.3.1 Polling Objects (poll-objects.html)\n 7.4 thread -- Multiple threads of control (module-thread.html)\n 7.5 threading -- Higher-level threading interface (module-threading.html)\n - 7.5.1 Lock Objects (lock-objects.html)\n 7.5.2 RLock Objects (rlock-objects.html)\n 7.5.3 Condition Objects (condition-objects.html)\n 7.5.4 Semaphore Objects (semaphore-objects.html)\n 7.5.5 Event Objects (event-objects.html)\n 7.5.6 Thread Objects (thread-objects.html)\n 7.5.7 Timer Objects (timer-objects.html)\n 7.6 Queue -- A synchronized queue class (module-Queue.html)\n - 7.6.1 Queue Objects (QueueObjects.html)\n 7.7 mmap --\n Memory-mapped file support (module-mmap.html)\n 7.8 anydbm -- Generic access to DBM-style databases (module-anydbm.html)\n 7.9 dumbdbm -- Portable DBM implementation (module-dumbdbm.html)\n 7.10 dbhash -- DBM-style interface to the BSD database library (module-dbhash.html)\n - 7.10.1 Database Objects (dbhash-objects.html)\n 7.11 whichdb -- Guess which DBM module created a database (module-whichdb.html)\n 7.12 bsddb -- Interface to Berkeley DB library (module-bsddb.html)\n - 7.12.1 Hash, BTree and Record Objects (bsddb-objects.html)\n 7.13 zlib -- Compression compatible with gzip (module-zlib.html)\n 7.14 gzip -- Support for gzip files (module-gzip.html)\n 7.15 zipfile -- Work with ZIP archives (module-zipfile.html)\n - 7.15.1 ZipFile Objects (zipfile-objects.html)\n 7.15.2 PyZipFile Objects (pyzipfile-objects.html)\n 7.15.3 ZipInfo Objects (zipinfo-objects.html)\n 7.16 readline -- GNU readline interface (module-readline.html)\n - 7.16.1 Example (readline-example.html)\n 7.17 rlcompleter -- Completion function for GNU readline (module-rlcompleter.html)\n - 7.17.1 Completer Objects (completer-objects.html)\n 8. Unix Specific Services (unix.html)\n - 8.1 posix -- The most common POSIX system calls (module-posix.html)\n - 8.1.1 Large File Support (posix-large-files.html)\n 8.1.2 Module Contents (posix-contents.html)\n 8.2 pwd -- The password database (module-pwd.html)\n 8.3 grp -- The group database (module-grp.html)\n 8.4 crypt -- Function to check Unix passwords (module-crypt.html)\n 8.5 dl -- Call C functions in shared objects (module-dl.html)\n - 8.5.1 Dl Objects (dl-objects.html)\n 8.6 dbm -- Simple ``database'' interface (module-dbm.html)\n 8.7 gdbm -- GNU's reinterpretation of dbm (module-gdbm.html)\n 8.8 termios -- POSIX style tty control (module-termios.html)\n - 8.8.1 Example (node263.html)\n 8.9 TERMIOS -- Constants used with the termios module (module-TERMIOSuppercase.html)\n 8.10 tty -- Terminal control functions (module-tty.html)\n 8.11 pty -- Pseudo-terminal utilities (module-pty.html)\n 8.12 fcntl -- The fcntl() and ioctl() system calls (module-fcntl.html)\n 8.13 pipes -- Interface to shell pipelines (module-pipes.html)\n - 8.13.1 Template Objects (template-objects.html)\n 8.14 posixfile -- File-like objects with locking support (module-posixfile.html)\n 8.15 resource -- Resource usage information (module-resource.html)\n - 8.15.1 Resource Limits (node272.html)\n 8.15.2 Resource Usage (node273.html)\n 8.16 nis -- Interface to Sun's NIS (Yellow Pages) (module-nis.html)\n 8.17 syslog -- Unix syslog library routines (module-syslog.html)\n 8.18 commands -- Utilities for running commands (module-commands.html)\n 9. The Python Debugger (module-pdb.html)\n - 9.1 Debugger Commands (debugger-commands.html)\n 9.2 How It Works (debugger-hooks.html)\n 10. The Python Profiler (profile.html)\n - 10.1 Introduction to the profiler (node281.html)\n 10.2 How Is This Profiler Different From The Old Profiler? (node282.html)\n 10.3 Instant Users Manual (profile-instant.html)\n 10.4 What Is Deterministic Profiling? (node284.html)\n 10.5 Reference Manual (module-profile.html)\n - 10.5.1 The Stats Class (profile-stats.html)\n 10.6 Limitations (profile-limits.html)\n 10.7 Calibration (profile-calibration.html)\n 10.8 Extensions -- Deriving Better Profilers (node289.html)\n 11. Internet Protocols and Support (internet.html)\n - 11.1 webbrowser -- Convenient Web-browser controller (module-webbrowser.html)\n - 11.1.1 Browser Controller Objects (browser-controllers.html)\n 11.2 cgi -- Common Gateway Interface support. (module-cgi.html)\n - 11.2.1 Introduction (cgi-intro.html)\n 11.2.2 Using the cgi module (node295.html)\n 11.2.3 Higher Level Interface (node296.html)\n 11.2.4 Old classes (node297.html)\n 11.2.5 Functions (node298.html)\n 11.2.6 Caring about security (cgi-security.html)\n 11.2.7 Installing your CGI script on a Unix system (node300.html)\n 11.2.8 Testing your CGI script (node301.html)\n 11.2.9 Debugging CGI scripts (node302.html)\n 11.2.10 Common problems and solutions (node303.html)\n 11.3 cgitb -- Traceback manager for CGI scripts (module-cgitb.html)\n 11.4 urllib -- Open arbitrary resources by URL (module-urllib.html)\n - 11.4.1 URLopener Objects (urlopener-objs.html)\n 11.4.2 Examples (node307.html)\n 11.5 urllib2 -- extensible library for opening URLs (module-urllib2.html)\n - 11.5.1 Request Objects (request-objects.html)\n 11.5.2 OpenerDirector Objects (opener-director-objects.html)\n 11.5.3 BaseHandler Objects (base-handler-objects.html)\n 11.5.4 HTTPRedirectHandler Objects (http-redirect-handler.html)\n 11.5.5 ProxyHandler Objects (proxy-handler.html)\n 11.5.6 HTTPPasswordMgr Objects (http-password-mgr.html)\n 11.5.7 AbstractBasicAuthHandler Objects (abstract-basic-auth-handler.html)\n 11.5.8 HTTPBasicAuthHandler Objects (http-basic-auth-handler.html)\n 11.5.9 ProxyBasicAuthHandler Objects (proxy-basic-auth-handler.html)\n 11.5.10 AbstractDigestAuthHandler Objects (abstract-digest-auth-handler.html)\n 11.5.11 HTTPDigestAuthHandler Objects (http-digest-auth-handler.html)\n 11.5.12 ProxyDigestAuthHandler Objects (proxy-digest-auth-handler.html)\n 11.5.13 HTTPHandler Objects (http-handler-objects.html)\n 11.5.14 HTTPSHandler Objects (https-handler-objects.html)\n 11.5.15 FileHandler Objects (file-handler-objects.html)\n 11.5.16 FTPHandler Objects (ftp-handler-objects.html)\n 11.5.17 CacheFTPHandler Objects (cacheftp-handler-objects.html)\n 11.5.18 GopherHandler Objects (gopher-handler.html)\n 11.5.19 UnknownHandler Objects (unknown-handler-objects.html)\n 11.6 httplib -- HTTP protocol client (module-httplib.html)\n - 11.6.1 HTTPConnection Objects (httpconnection-objects.html)\n 11.6.2 HTTPResponse Objects (httpresponse-objects.html)\n 11.6.3 Examples (httplib-examples.html)\n 11.7 ftplib -- FTP protocol client (module-ftplib.html)\n - 11.7.1 FTP Objects (ftp-objects.html)\n 11.8 gopherlib -- Gopher protocol client (module-gopherlib.html)\n 11.9 poplib -- POP3 protocol client (module-poplib.html)\n - 11.9.1 POP3 Objects (pop3-objects.html)\n 11.9.2 POP3 Example (pop3-example.html)\n 11.10 imaplib -- IMAP4 protocol client (module-imaplib.html)\n - 11.10.1 IMAP4 Objects (imap4-objects.html)\n 11.10.2 IMAP4 Example (imap4-example.html)\n 11.11 nntplib -- NNTP protocol client (module-nntplib.html)\n - 11.11.1 NNTP Objects (nntp-objects.html)\n 11.12 smtplib -- SMTP protocol client (module-smtplib.html)\n - 11.12.1 SMTP Objects (SMTP-objects.html)\n 11.12.2 SMTP Example (SMTP-example.html)\n 11.13 telnetlib -- Telnet client (module-telnetlib.html)\n - 11.13.1 Telnet Objects (telnet-objects.html)\n 11.13.2 Telnet Example (telnet-example.html)\n 11.14 urlparse -- Parse URLs into components (module-urlparse.html)\n 11.15 SocketServer -- A framework for network servers (module-SocketServer.html)\n 11.16 BaseHTTPServer -- Basic HTTP server (module-BaseHTTPServer.html)\n 11.17 SimpleHTTPServer -- Simple HTTP request handler (module-SimpleHTTPServer.html)\n 11.18 CGIHTTPServer -- CGI-capable HTTP request handler (module-CGIHTTPServer.html)\n 11.19 Cookie -- HTTP state management (module-Cookie.html)\n - 11.19.1 Cookie Objects (cookie-objects.html)\n 11.19.2 Morsel Objects (morsel-objects.html)\n 11.19.3 Example (cookie-example.html)\n 11.20 xmlrpclib -- XML-RPC client access (module-xmlrpclib.html)\n - 11.20.1 Server Objects (server-objects.html)\n 11.20.2 Boolean Objects (boolean-objects.html)\n 11.20.3 DateTime Objects (datetime-objects.html)\n 11.20.4 Binary Objects (binary-objects.html)\n 11.20.5 Fault Objects (fault-objects.html)\n 11.20.6 ProtocolError Objects (protocol-error-objects.html)\n 11.20.7 Convenience Functions (node365.html)\n 11.20.8 Example of Client Usage (xmlrpc-client-example.html)\n 11.21 SimpleXMLRPCServer -- Basic XML-RPC server (module-SimpleXMLRPCServer.html)\n - 11.21.1 SimpleXMLRPCServer Objects (simple-xmlrpc-servers.html)\n 11.22 asyncore -- Asynchronous socket handler (module-asyncore.html)\n - 11.22.1 Example basic HTTP client (asyncore-example.html)\n 12. Internet Data Handling (netdata.html)\n - 12.1 formatter -- Generic output formatting (module-formatter.html)\n - 12.1.1 The Formatter Interface (formatter-interface.html)\n 12.1.2 Formatter Implementations (formatter-impls.html)\n 12.1.3 The Writer Interface (writer-interface.html)\n 12.1.4 Writer Implementations (writer-impls.html)\n 12.2 email -- An email and MIME handling package (module-email.html)\n - 12.2.1 Representing an email message (module-email.Message.html)\n 12.2.2 Parsing email messages (module-email.Parser.html)\n 12.2.3 Generating MIME documents (module-email.Generator.html)\n 12.2.4 Creating email and MIME objects from scratch (node383.html)\n 12.2.5 Encoders (module-email.Encoders.html)\n 12.2.6 Exception classes (module-email.Errors.html)\n 12.2.7 Miscellaneous utilities (module-email.Utils.html)\n 12.2.8 Iterators (module-email.Iterators.html)\n 12.2.9 Differences from mimelib (node388.html)\n 12.2.10 Examples (node389.html)\n 12.3 mailcap -- Mailcap file handling. (module-mailcap.html)\n 12.4 mailbox -- Read various mailbox formats (module-mailbox.html)\n - 12.4.1 Mailbox Objects (mailbox-objects.html)\n 12.5 mhlib -- Access to MH mailboxes (module-mhlib.html)\n - 12.5.1 MH Objects (mh-objects.html)\n 12.5.2 Folder Objects (mh-folder-objects.html)\n 12.5.3 Message Objects (mh-message-objects.html)\n 12.6 mimetools -- Tools for parsing MIME messages (module-mimetools.html)\n - 12.6.1 Additional Methods of Message Objects (mimetools-message-objects.html)\n 12.7 mimetypes -- Map filenames to MIME types (module-mimetypes.html)\n - 12.7.1 MimeTypes Objects (mimetypes-objects.html)\n 12.8 MimeWriter -- Generic MIME file writer (module-MimeWriter.html)\n - 12.8.1 MimeWriter Objects (MimeWriter-objects.html)\n 12.9 mimify -- MIME processing of mail messages (module-mimify.html)\n 12.10 multifile -- Support for files containing distinct parts (module-multifile.html)\n - 12.10.1 MultiFile Objects (MultiFile-objects.html)\n 12.10.2 MultiFile Example (multifile-example.html)\n 12.11 rfc822 -- Parse RFC 2822 mail headers (module-rfc822.html)\n - 12.11.1 Message Objects (message-objects.html)\n 12.11.2 AddressList Objects (addresslist-objects.html)\n 12.12 base64 -- Encode and decode MIME base64 data (module-base64.html)\n 12.13 binascii -- Convert between binary and ASCII (module-binascii.html)\n 12.14 binhex -- Encode and decode binhex4 files (module-binhex.html)\n - 12.14.1 Notes (binhex-notes.html)\n 12.15 quopri -- Encode and decode MIME quoted-printable data (module-quopri.html)\n 12.16 uu -- Encode and decode uuencode files (module-uu.html)\n 12.17 xdrlib -- Encode and decode XDR data (module-xdrlib.html)\n - 12.17.1 Packer Objects (xdr-packer-objects.html)\n 12.17.2 Unpacker Objects (xdr-unpacker-objects.html)\n 12.17.3 Exceptions (xdr-exceptions.html)\n 12.18 netrc -- netrc file processing (module-netrc.html)\n - 12.18.1 netrc Objects (netrc-objects.html)\n 12.19 robotparser -- Parser for robots.txt (module-robotparser.html)\n 13. Structured Markup Processing Tools (markup.html)\n - 13.1 HTMLParser -- Simple HTML and XHTML parser (module-HTMLParser.html)\n - 13.1.1 Example HTML Parser (htmlparser-example.html)\n 13.2 sgmllib -- Simple SGML parser (module-sgmllib.html)\n 13.3 htmllib -- A parser for HTML documents (module-htmllib.html)\n - 13.3.1 HTMLParser Objects (html-parser-objects.html)\n 13.4 htmlentitydefs -- Definitions of HTML general entities (module-htmlentitydefs.html)\n 13.5 xml.parsers.expat -- Fast XML parsing using Expat (module-xml.parsers.expat.html)\n - 13.5.1 XMLParser Objects (xmlparser-objects.html)\n 13.5.2 ExpatError Exceptions (expaterror-objects.html)\n 13.5.3 Example (expat-example.html)\n 13.5.4 Content Model Descriptions (expat-content-models.html)\n 13.5.5 Expat error constants (expat-errors.html)\n 13.6 xml.dom -- The Document Object Model API (module-xml.dom.html)\n - 13.6.1 Module Contents (node437.html)\n 13.6.2 Objects in the DOM (node438.html)\n 13.6.3 Conformance (dom-conformance.html)\n 13.7 xml.dom.minidom -- Lightweight DOM implementation (module-xml.dom.minidom.html)\n - 13.7.1 DOM objects (dom-objects.html)\n 13.7.2 DOM Example (dom-example.html)\n 13.7.3 minidom and the DOM standard (minidom-and-dom.html)\n 13.8 xml.dom.pulldom -- Support for building partial DOM trees (module-xml.dom.pulldom.html)\n - 13.8.1 DOMEventStream Objects (domeventstream-objects.html)\n 13.9 xml.sax -- Support for SAX2 parsers (module-xml.sax.html)\n - 13.9.1 SAXException Objects (sax-exception-objects.html)\n 13.10 xml.sax.handler -- Base classes for SAX handlers (module-xml.sax.handler.html)\n - 13.10.1 ContentHandler Objects (content-handler-objects.html)\n 13.10.2 DTDHandler Objects (dtd-handler-objects.html)\n 13.10.3 EntityResolver Objects (entity-resolver-objects.html)\n 13.10.4 ErrorHandler Objects (sax-error-handler.html)\n 13.11 xml.sax.saxutils -- SAX Utilities (module-xml.sax.saxutils.html)\n 13.12 xml.sax.xmlreader -- Interface for XML parsers (module-xml.sax.xmlreader.html)\n - 13.12.1 XMLReader Objects (xmlreader-objects.html)\n 13.12.2 IncrementalParser Objects (incremental-parser-objects.html)\n 13.12.3 Locator Objects (locator-objects.html)\n 13.12.4 InputSource Objects (input-source-objects.html)\n 13.12.5 AttributesImpl Objects (attributes-impl-objects.html)\n 13.12.6 AttributesNSImpl Objects (attributes-ns-impl-objects.html)\n 13.13 xmllib -- A parser for XML documents (module-xmllib.html)\n - 13.13.1 XML Namespaces (xml-namespace.html)\n 14. Multimedia Services (mmedia.html)\n - 14.1 audioop -- Manipulate raw audio data (module-audioop.html)\n 14.2 imageop -- Manipulate raw image data (module-imageop.html)\n 14.3 aifc -- Read and write AIFF and AIFC files (module-aifc.html)\n 14.4 sunau -- Read and write Sun AU files (module-sunau.html)\n - 14.4.1 AU_read Objects (au-read-objects.html)\n 14.4.2 AU_write Objects (au-write-objects.html)\n 14.5 wave -- Read and write WAV files (module-wave.html)\n - 14.5.1 Wave_read Objects (Wave-read-objects.html)\n 14.5.2 Wave_write Objects (Wave-write-objects.html)\n 14.6 chunk -- Read IFF chunked data (module-chunk.html)\n 14.7 colorsys -- Conversions between color systems (module-colorsys.html)\n 14.8 rgbimg -- Read and write ``SGI RGB'' files (module-rgbimg.html)\n 14.9 imghdr -- Determine the type of an image (module-imghdr.html)\n 14.10 sndhdr -- Determine type of sound file (module-sndhdr.html)\n 15. Cryptographic Services (crypto.html)\n - 15.1 hmac -- Keyed-Hashing for Message Authentication (module-hmac.html)\n 15.2 md5 -- MD5 message digest algorithm (module-md5.html)\n 15.3 sha -- SHA message digest algorithm (module-sha.html)\n 15.4 mpz -- GNU arbitrary magnitude integers (module-mpz.html)\n 15.5 rotor -- Enigma-like encryption and decryption (module-rotor.html)\n 16. Graphical User Interfaces with Tk (tkinter.html)\n - 16.1 Tkinter -- Python interface to Tcl/Tk (module-Tkinter.html)\n - 16.1.1 Tkinter Modules (node500.html)\n 16.1.2 Tkinter Life Preserver (node501.html)\n 16.1.3 A (Very) Quick Look at Tcl/Tk (node504.html)\n 16.1.4 Mapping Basic Tk into Tkinter (tkinter-basic-mapping.html)\n 16.1.5 How Tk and Tkinter are Related (node506.html)\n 16.1.6 Handy Reference (node507.html)\n 16.2 Tix -- Extension widgets for Tk (module-Tix.html)\n - 16.2.1 Using Tix (node517.html)\n 16.2.2 Tix Widgets (node518.html)\n 16.2.3 Tix Commands (node527.html)\n 16.3 ScrolledText -- Scrolled Text Widget (module-ScrolledText.html)\n 16.4 turtle -- Turtle graphics for Tk (module-turtle.html)\n - 16.4.1 Pen and RawPen Objects (pen-rawpen-objects.html)\n 16.5 Idle (idle.html)\n - 16.5.1 Menus (node532.html)\n 16.5.2 Basic editing and navigation (node537.html)\n 16.5.3 Syntax colors (node540.html)\n 16.6 Other Graphical User Interface Packages (other-gui-packages.html)\n 17. Restricted Execution (restricted.html)\n - 17.1 rexec -- Restricted execution framework (module-rexec.html)\n - 17.1.1 RExec Objects (rexec-objects.html)\n 17.1.2 Defining restricted environments (rexec-extension.html)\n 17.1.3 An example (node547.html)\n 17.2 Bastion -- Restricting access to objects (module-Bastion.html)\n 18. Python Language Services (language.html)\n - 18.1 parser -- Access Python parse trees (module-parser.html)\n - 18.1.1 Creating AST Objects (node551.html)\n 18.1.2 Converting AST Objects (node552.html)\n 18.1.3 Queries on AST Objects (node553.html)\n 18.1.4 Exceptions and Error Handling (node554.html)\n 18.1.5 AST Objects (node555.html)\n 18.1.6 Examples (node556.html)\n 18.2 symbol -- Constants used with Python parse trees (module-symbol.html)\n 18.3 token -- Constants used with Python parse trees (module-token.html)\n 18.4 keyword -- Testing for Python keywords (module-keyword.html)\n 18.5 tokenize -- Tokenizer for Python source (module-tokenize.html)\n 18.6 tabnanny -- Detection of ambiguous indentation (module-tabnanny.html)\n 18.7 pyclbr -- Python class browser support (module-pyclbr.html)\n - 18.7.1 Class Descriptor Objects (pyclbr-class-objects.html)\n 18.8 py_compile -- Compile Python source files (module-pycompile.html)\n 18.9 compileall -- Byte-compile Python libraries (module-compileall.html)\n 18.10 dis -- Disassembler for Python byte code (module-dis.html)\n - 18.10.1 Python Byte Code Instructions (bytecodes.html)\n 18.11 distutils -- Building and installing Python modules (module-distutils.html)\n 19. Python compiler package (compiler.html)\n - 19.1 The basic interface (module-compiler.html)\n 19.2 Limitations (node573.html)\n 19.3 Python Abstract Syntax (node574.html)\n - 19.3.1 AST Nodes (module-compiler.ast.html)\n 19.3.2 Assignment nodes (node576.html)\n 19.3.3 Examples (node577.html)\n 19.4 Using Visitors to Walk ASTs (module-compiler.visitor.html)\n 19.5 Bytecode Generation (node579.html)\n 20. SGI IRIX Specific Services (sgi.html)\n - 20.1 al -- Audio functions on the SGI (module-al.html)\n - 20.1.1 Configuration Objects (al-config-objects.html)\n 20.1.2 Port Objects (al-port-objects.html)\n 20.2 AL -- Constants used with the al module (module-al-constants.html)\n 20.3 cd -- CD-ROM access on SGI systems (module-cd.html)\n - 20.3.1 Player Objects (player-objects.html)\n 20.3.2 Parser Objects (cd-parser-objects.html)\n 20.4 fl -- FORMS library for graphical user interfaces (module-fl.html)\n - 20.4.1 Functions Defined in Module fl (node589.html)\n 20.4.2 Form Objects (form-objects.html)\n 20.4.3 FORMS Objects (forms-objects.html)\n 20.5 FL -- Constants used with the fl module (module-fl-constants.html)\n 20.6 flp -- Functions for loading stored FORMS designs (module-flp.html)\n 20.7 fm -- Font Manager interface (module-fm.html)\n 20.8 gl -- Graphics Library interface (module-gl.html)\n 20.9 DEVICE -- Constants used with the gl module (module-DEVICE.html)\n 20.10 GL -- Constants used with the gl module (module-gl-constants.html)\n 20.11 imgfile -- Support for SGI imglib files (module-imgfile.html)\n 20.12 jpeg -- Read and write JPEG files (module-jpeg.html)\n 21. SunOS Specific Services (sunos.html)\n - 21.1 sunaudiodev -- Access to Sun audio hardware (module-sunaudiodev.html)\n - 21.1.1 Audio Device Objects (audio-device-objects.html)\n 21.2 SUNAUDIODEV -- Constants used with sunaudiodev (module-sunaudiodev-constants.html)\n 22. MS Windows Specific Services (node604.html)\n - 22.1 msvcrt - Useful routines from the MS VC++ runtime (module-msvcrt.html)\n - 22.1.1 File Operations (msvcrt-files.html)\n 22.1.2 Console I/O (msvcrt-console.html)\n 22.1.3 Other Functions (msvcrt-other.html)\n 22.2 _winreg - Windows registry access (module--winreg.html)\n - 22.2.1 Registry Handle Objects (handle-object.html)\n 22.3 winsound -- Sound-playing interface for Windows (module-winsound.html)\n A. Undocumented Modules (undoc.html)\n - A.1 Frameworks (node613.html)\n A.2 Miscellaneous useful utilities (node614.html)\n A.3 Platform specific modules (node615.html)\n A.4 Multimedia (node616.html)\n A.5 Obsolete (obsolete-modules.html)\n A.6 SGI-specific Extension modules (node618.html)\n B. Reporting Bugs (reporting-bugs.html)\n C. History and License (node620.html)\n - C.1 History of the software (node621.html)\n C.2 Terms and conditions for accessing or otherwise using Python (node622.html)\n Module Index (modindex.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.2", "length": 31921, "url": "https://docs.python.org/2.2/lib/contents.html"} {"title": "4.2.3 Module Contents", "text": "matching-searching.html | module-re.html | re-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.2.3 Module Contents\nThe module defines the following functions and constants, and an exception:", "python_version": "2.2", "length": 238, "url": "https://docs.python.org/2.2/lib/Contents_of_Module_re.html"} {"title": "17.1.2 Converting AST Objects", "text": "Creating_ASTs.html | module-parser.html | Querying_ASTs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.2 Converting AST Objects\nAST objects, regardless of the input used to create them, may be\nconverted to parse trees represented as list- or tuple- trees, or may\nbe compiled into executable code objects. Parse trees may be\nextracted with or without line numbering information.", "python_version": "2.2", "length": 422, "url": "https://docs.python.org/2.2/lib/Converting_ASTs.html"} {"title": "11.19.3 Example", "text": "morsel-objects.html | module-Cookie.html | module-xmlrpclib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.19.3 Example\nThe following example demonstrates how to use the Cookie module.", "python_version": "2.2", "length": 227, "url": "https://docs.python.org/2.2/lib/cookie-example.html"} {"title": "11.19.1 Cookie Objects", "text": "module-Cookie.html | module-Cookie.html | morsel-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.19.1 Cookie Objects", "python_version": "2.2", "length": 166, "url": "https://docs.python.org/2.2/lib/cookie-objects.html"} {"title": "17.1.1 Creating AST Objects", "text": "module-parser.html | module-parser.html | Converting_ASTs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.1 Creating AST Objects\nAST objects may be created from source code or from a parse tree.\nWhen creating an AST object from source, different functions are used\nto create the `'eval'` and `'exec'` forms.", "python_version": "2.2", "length": 351, "url": "https://docs.python.org/2.2/lib/Creating_ASTs.html"} {"title": "15. Cryptographic Services", "text": "module-sndhdr.html | lib.html | module-hmac.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 15. Cryptographic Services\nThe modules described in this chapter implement various algorithms of\na cryptographic nature. They are available at the discretion of the\ninstallation. Here's an overview:\nhmac (module-hmac.html) | Keyed-Hashing for Message Authentication (HMAC)\nimplementation for Python.\nmd5 (module-md5.html) | RSA's MD5 message digest algorithm.\nsha (module-sha.html) | NIST's secure hash algorithm, SHA.\nmpz (module-mpz.html) | Interface to the GNU MP library for arbitrary\nprecision arithmetic.\nrotor (module-rotor.html) | Enigma-like encryption and decryption.", "python_version": "2.2", "length": 707, "url": "https://docs.python.org/2.2/lib/crypto.html"} {"title": "6.13.1 Functions", "text": "module-curses.html | module-curses.html | curses-window-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.13.1 Functions\nThe module curses defines the following exception:\nNote:\nWhenever x or y arguments to a function\nor a method are optional, they default to the current cursor location.\nWhenever attr is optional, it defaults to A_NORMAL.\nThe module curses defines the following functions:", "python_version": "2.2", "length": 438, "url": "https://docs.python.org/2.2/lib/curses-functions.html"} {"title": "6.17.2 Panel Objects", "text": "cursespanel-functions.html | module-curses.panel.html | module-getopt.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.17.2 Panel Objects\nPanel objects, as returned by new_panel() above, are windows\nwith a stacking order. There's always a window associated with a\npanel which determines the content, while the panel methods are\nresponsible for the window's depth in the panel stack.\nPanel objects have the following methods:", "python_version": "2.2", "length": 464, "url": "https://docs.python.org/2.2/lib/curses-panel-objects.html"} {"title": "6.14.1 Textbox objects", "text": "module-curses.textpad.html | module-curses.textpad.html | module-curses.wrapper.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.14.1 Textbox objects\nYou can instantiate a Textbox object as follows:\nTextbox objects have the following methods:", "python_version": "2.2", "length": 282, "url": "https://docs.python.org/2.2/lib/curses-textpad-objects.html"} {"title": "6.13.2 Window Objects", "text": "curses-functions.html | module-curses.html | node181.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.13.2 Window Objects\nWindow objects, as returned by initscr() and\nnewwin() above, have the\nfollowing methods:", "python_version": "2.2", "length": 250, "url": "https://docs.python.org/2.2/lib/curses-window-objects.html"} {"title": "6.17.1 Functions", "text": "module-curses.panel.html | module-curses.panel.html | curses-panel-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.17.1 Functions\nThe module curses.panel defines the following functions:", "python_version": "2.2", "length": 235, "url": "https://docs.python.org/2.2/lib/cursespanel-functions.html"} {"title": "11.20.3 DateTime Objects", "text": "boolean-objects.html | module-xmlrpclib.html | binary-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.3 DateTime Objects\nThis class may initialized from date in seconds since the epoch, a\ntime tuple, or an ISO 8601 time/date string. It has the following\nmethods, supported mainly for internal use by the\nmarshalling/unmarshalling code:\nIt also supports certain of Python's built-in operators through\n_cmp__ and __repr__ methods.", "python_version": "2.2", "length": 481, "url": "https://docs.python.org/2.2/lib/datetime-objects.html"} {"title": "7.10.1 Database Objects", "text": "module-dbhash.html | module-dbhash.html | module-whichdb.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.10.1 Database Objects\nThe database objects returned by open() provide the methods\ncommon to all the DBM-style databases. The following methods are\navailable in addition to the standard methods.", "python_version": "2.2", "length": 339, "url": "https://docs.python.org/2.2/lib/dbhash-objects.html"} {"title": "9.1 Debugger Commands", "text": "module-pdb.html | module-pdb.html | debugger-hooks.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 9.1 Debugger Commands\nThe debugger recognizes the following commands. Most commands can be\nabbreviated to one or two letters; e.g. \"h(elp)\" means that\neither \"h\" or \"help\" can be used to enter the help\ncommand (but not \"he\" or \"hel\", nor \"H\" or\n\"Help\" or \"HELP\"). Arguments to commands must be\nseparated by whitespace (spaces or tabs). Optional arguments are\nenclosed in square brackets (\"[]\") in the command syntax; the\nsquare brackets must not be typed. Alternatives in the command syntax\nare separated by a vertical bar (\"|\").\nEntering a blank line repeats the last command entered. Exception: if\nthe last command was a \"list\" command, the next 11 lines are\nlisted.\nCommands that the debugger doesn't recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged. Python statements can also be prefixed with an exclamation\npoint (\"!\"). This is a powerful way to inspect the program\nbeing debugged; it is even possible to change a variable or call a\nfunction. When an\nexception occurs in such a statement, the exception name is printed\nbut the debugger's state is not changed.\nMultiple commands may be entered on a single line, separated by\n\";;\". (A single \";\" is not used as it is\nthe separator for multiple commands in a line that is passed to\nthe Python parser.)\nNo intelligence is applied to separating the commands;\nthe input is split at the first \";;\" pair, even if it is in\nthe middle of a quoted string.\nThe debugger supports aliases. Aliases can have parameters which\nallows one a certain level of adaptability to the context under\nexamination.\nIf a file .pdbrc\nexists in the user's home directory or in the current directory, it is\nread in and executed as if it had been typed at the debugger prompt.\nThis is particularly useful for aliases. If both files exist, the one\nin the home directory is read first and aliases defined there can be\noverridden by the local file.\nh(elp) [command]: Without argument, print the list of available commands. With a\ncommand as argument, print help about that command. \"help\npdb\" displays the full documentation file; if the environment variable\nPAGER is defined, the file is piped through that command\ninstead. Since the command argument must be an identifier,\n\"help exec\" must be entered to get help on the \"!\" command.\nw(here): Print a stack trace, with the most recent frame at the bottom. An\narrow indicates the current frame, which determines the context of\nmost commands.\nd(own): Move the current frame one level down in the stack trace\n(to an newer frame).\nu(p): Move the current frame one level up in the stack trace\n(to a older frame).\nb(reak) [[filename:]lineno`|`function[, condition]]: With a lineno argument, set a break there in the current\nfile. With a function argument, set a break at the first\nexecutable statement within that function.\nThe line number may be prefixed with a filename and a colon,\nto specify a breakpoint in another file (probably one that\nhasn't been loaded yet). The file is searched on `sys.path`.\nNote that each breakpoint is assigned a number to which all the other\nbreakpoint commands refer.\nIf a second argument is present, it is an expression which must\nevaluate to true before the breakpoint is honored.\nWithout argument, list all breaks, including for each breakpoint,\nthe number of times that breakpoint has been hit, the current\nignore count, and the associated condition if any.\ntbreak [[filename:]lineno`|`function[, condition]]: Temporary breakpoint, which is removed automatically when it is\nfirst hit. The arguments are the same as break.\ncl(ear) [bpnumber [bpnumber ...]]: With a space separated list of breakpoint numbers, clear those\nbreakpoints. Without argument, clear all breaks (but first\nask confirmation).\ndisable [bpnumber [bpnumber ...]]: Disables the breakpoints given as a space separated list of\nbreakpoint numbers. Disabling a breakpoint means it cannot cause\nthe program to stop execution, but unlike clearing a breakpoint, it\nremains in the list of breakpoints and can be (re-)enabled.\nenable [bpnumber [bpnumber ...]]: Enables the breakpoints specified.\nignore bpnumber [count]: Sets the ignore count for the given breakpoint number. If\ncount is omitted, the ignore count is set to 0. A breakpoint\nbecomes active when the ignore count is zero. When non-zero,\nthe count is decremented each time the breakpoint is reached\nand the breakpoint is not disabled and any associated condition\nevaluates to true.\ncondition bpnumber [condition]: Condition is an expression which must evaluate to true before\nthe breakpoint is honored. If condition is absent, any existing\ncondition is removed; i.e., the breakpoint is made unconditional.\ns(tep): Execute the current line, stop at the first possible occasion\n(either in a function that is called or on the next line in the\ncurrent function).\nn(ext): Continue execution until the next line in the current function\nis reached or it returns. (The difference between \"next\" and\n\"step\" is that \"step\" stops inside a called function, while\n\"next\" executes called functions at (nearly) full speed, only\nstopping at the next line in the current function.)\nr(eturn): Continue execution until the current function returns.\nc(ont(inue)): Continue execution, only stop when a breakpoint is encountered.\nl(ist) [first[, last]]: List source code for the current file. Without arguments, list 11\nlines around the current line or continue the previous listing. With\none argument, list 11 lines around at that line. With two arguments,\nlist the given range; if the second argument is less than the first,\nit is interpreted as a count.\na(rgs): Print the argument list of the current function.\np expression: Evaluate the expression in the current context and print its\nvalue. (Note: \"print\" can also be used, but is not a debugger\ncommand -- this executes the Python print statement.)\nalias [name [command]]: Creates an alias called name that executes command. The\ncommand must not be enclosed in quotes. Replaceable parameters\ncan be indicated by \"%1\", \"%2\", and so on, while \"%*\" is\nreplaced by all the parameters. If no command is given, the current\nalias for name is shown. If no arguments are given, all\naliases are listed.\nAliases may be nested and can contain anything that can be\nlegally typed at the pdb prompt. Note that internal pdb commands\ncan be overridden by aliases. Such a command is\nthen hidden until the alias is removed. Aliasing is recursively\napplied to the first word of the command line; all other words\nin the line are left alone.\nAs an example, here are two useful aliases (especially when placed\nin the .pdbrc file):\n```text\n\n#Print instance variables (usage \"pi classInst\")\nalias pi for k in %1.__dict__.keys(): print \"%1.\",k,\"=\",%1.__dict__[k]\n#Print instance variables in self\nalias ps pi self\n```\nunalias name: Deletes the specified alias.\n[!]statement: Execute the (one-line) statement in the context of\nthe current stack frame.\nThe exclamation point can be omitted unless the first word\nof the statement resembles a debugger command.\nTo set a global variable, you can prefix the assignment\ncommand with a \"global\" command on the same line, e.g.:\n```text\n\n(Pdb) global list_options; list_options = ['-l']\n(Pdb)\n```\nq(uit): Quit from the debugger.\nThe program being executed is aborted.", "python_version": "2.2", "length": 7436, "url": "https://docs.python.org/2.2/lib/debugger-commands.html"} {"title": "9.2 How It Works", "text": "debugger-commands.html | module-pdb.html | profile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 9.2 How It Works\nSome changes were made to the interpreter:\n- `sys.settrace( func )` sets the global trace function\n- there can also a local trace function (see later)\nTrace functions have three arguments: frame, event, and\narg. frame is the current stack frame. event is a\nstring: `'call'`, `'line'`, `'return'` or\n`'exception'`. arg depends on the event type.\nThe global trace function is invoked (with event set to\n`'call'`) whenever a new local scope is entered; it should return\na reference to the local trace function to be used that scope, or\n`None` if the scope shouldn't be traced.\nThe local trace function should return a reference to itself (or to\nanother function for further tracing in that scope), or `None` to\nturn off tracing in that scope.\nInstance methods are accepted (and very useful!) as trace functions.\nThe events have the following meaning:\n`'call'`: A function is called (or some other code block entered). The global\ntrace function is called; arg is `None`;\nthe return value specifies the local trace function.\n`'line'`: The interpreter is about to execute a new line of code (sometimes\nmultiple line events on one line exist). The local trace function is\ncalled; arg is `None`; the return value specifies the new\nlocal trace function.\n`'return'`: A function (or other code block) is about to return. The local trace\nfunction is called; arg is the value that will be returned. The\ntrace function's return value is ignored.\n`'exception'`: An exception has occurred. The local trace function is called;\narg is a triple `( exception , value , traceback )`; the return value specifies the new local trace\nfunction.\nNote that as an exception is propagated down the chain of callers, an\n`'exception'` event is generated at each level.\nFor more information on code and frame objects, refer to the\nPython Reference Manual (../ref/ref.html).", "python_version": "2.2", "length": 1995, "url": "https://docs.python.org/2.2/lib/debugger-hooks.html"} {"title": "10.4 What Is Deterministic Profiling?", "text": "profile-instant.html | profile.html | module-profile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.4 What Is Deterministic Profiling?\nDeterministic profiling is meant to reflect the fact that all\nfunction call, function return, and exception events\nare monitored, and precise timings are made for the intervals between\nthese events (during which time the user's code is executing). In\ncontrast, statistical profiling (which is not done by this\nmodule) randomly samples the effective instruction pointer, and\ndeduces where time is being spent. The latter technique traditionally\ninvolves less overhead (as the code does not need to be instrumented),\nbut provides only relative indications of where time is being spent.\nIn Python, since there is an interpreter active during execution, the\npresence of instrumented code is not required to do deterministic\nprofiling. Python automatically provides a hook (optional\ncallback) for each event. In addition, the interpreted nature of\nPython tends to add so much overhead to execution, that deterministic\nprofiling tends to only add small processing overhead in typical\napplications. The result is that deterministic profiling is not that\nexpensive, yet provides extensive run time statistics about the\nexecution of a Python program.\nCall count statistics can be used to identify bugs in code (surprising\ncounts), and to identify possible inline-expansion points (high call\ncounts). Internal time statistics can be used to identify ``hot\nloops'' that should be carefully optimized. Cumulative time\nstatistics should be used to identify high level errors in the\nselection of algorithms. Note that the unusual handling of cumulative\ntimes in this profiler allows statistics for recursive implementations\nof algorithms to be directly compared to iterative implementations.", "python_version": "2.2", "length": 1854, "url": "https://docs.python.org/2.2/lib/Deterministic_Profiling.html"} {"title": "4.4.4 Differ Example", "text": "differ-objects.html | module-difflib.html | module-fpformat.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.4.4 Differ Example\nThis example compares two texts. First we set up the texts, sequences\nof individual single-line strings ending with newlines (such sequences\ncan also be obtained from the readlines() method of file-like\nobjects):\n```text\n\n>>> text1 = ''' 1. Beautiful is better than ugly.\n... 2. Explicit is better than implicit.\n... 3. Simple is better than complex.\n... 4. Complex is better than complicated.\n... '''.splitlines(1)\n>>> len(text1)\n4\n>>> text1[0][-1]\n'\\n'\n>>> text2 = ''' 1. Beautiful is better than ugly.\n... 3. Simple is better than complex.\n... 4. Complicated is better than complex.\n... 5. Flat is better than nested.\n... '''.splitlines(1)\n```\nNext we instantiate a Differ object:\n```text\n\n>>> d = Differ()\n```\nNote that when instantiating a Differ object we may pass\nfunctions to filter out line and character ``junk.'' See the\nDiffer() constructor for details.\nFinally, we compare the two:\n```text\n\n>>> result = list(d.compare(text1, text2))\n```\n`result` is a list of strings, so let's pretty-print it:\n```text\n\n>>> from pprint import pprint\n>>> pprint(result)\n[' 1. Beautiful is better than ugly.\\n',\n'- 2. Explicit is better than implicit.\\n',\n'- 3. Simple is better than complex.\\n',\n'+ 3. Simple is better than complex.\\n',\n'? ++ \\n',\n'- 4. Complex is better than complicated.\\n',\n'? ^ ---- ^ \\n',\n'+ 4. Complicated is better than complex.\\n',\n'? ++++ ^ ^ \\n',\n'+ 5. Flat is better than nested.\\n']\n```\nAs a single multi-line string it looks like this:", "python_version": "2.2", "length": 1629, "url": "https://docs.python.org/2.2/lib/differ-examples.html"} {"title": "4.4.3 Differ Objects", "text": "sequencematcher-examples.html | module-difflib.html | differ-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.4.3 Differ Objects\nNote that Differ-generated deltas make no claim to be\nminimal diffs. To the contrary, minimal diffs are often\ncounter-intuitive, because they synch up anywhere possible, sometimes\naccidental matches 100 pages apart. Restricting synch points to\ncontiguous matches preserves some notion of locality, at the\noccasional cost of producing a longer diff.\nThe Differ class has this constructor:\nDiffer objects are used (deltas generated) via a single\nmethod:", "python_version": "2.2", "length": 629, "url": "https://docs.python.org/2.2/lib/differ-objects.html"} {"title": "4.4.2 Examples", "text": "sequence-matcher.html | module-difflib.html | module-fpformat.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.4.2 Examples\nThis example compares two strings, considering blanks to be ``junk:''\n```text\n\n>>> s = SequenceMatcher(lambda x: x == \" \",\n... \"private Thread currentThread;\",\n... \"private volatile Thread currentThread;\")\n```\nratio() returns a float in [0, 1], measuring the similarity\nof the sequences. As a rule of thumb, a ratio() value over\n0.6 means the sequences are close matches:\n```text\n\n>>> print round(s.ratio(), 3)\n0.866\n```\nIf you're only interested in where the sequences match,\nget_matching_blocks() is handy:\n```text\n\n>>> for block in s.get_matching_blocks():\n... print \"a[%d] and b[%d] match for %d elements\" % block\na[0] and b[0] match for 8 elements\na[8] and b[17] match for 6 elements\na[14] and b[23] match for 15 elements\na[29] and b[38] match for 0 elements\n```\nNote that the last tuple returned by get_matching_blocks() is\nalways a dummy, `(len( a ), len( b ), 0)`, and this is\nthe only case in which the last tuple element (number of elements\nmatched) is `0`.\nIf you want to know how to change the first sequence into the second,\nuse get_opcodes():\n```text\n\n>>> for opcode in s.get_opcodes():\n... print \"%6s a[%d:%d] b[%d:%d]\" % opcode\nequal a[0:8] b[0:8]\ninsert a[8:8] b[8:17]\nequal a[8:14] b[17:23]\nequal a[14:29] b[23:38]\n```\nSee Tools/scripts/ndiff.py from the Python source distribution\nfor a fancy human-friendly file differencer, which uses\nSequenceMatcher both to view files as sequences of lines, and\nlines as sequences of characters.", "python_version": "2.2", "length": 1615, "url": "https://docs.python.org/2.2/lib/difflib-examples.html"} {"title": "6.7.1 The dircmp class", "text": "module-filecmp.html | module-filecmp.html | module-popen2.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.7.1 The dircmp class\ndircmp instances are built using this constructor:\nThe dircmp class provides the following methods:\nThe dircmp offers a number of interesting attributes that may\nbe used to get various bits of information about the directory trees\nbeing compared.\nNote that via __getattr__() hooks, all attributes are\ncomputed lazilly, so there is no speed penalty if only those\nattributes which are lightweight to compute are used.", "python_version": "2.2", "length": 583, "url": "https://docs.python.org/2.2/lib/dircmp-objects.html"} {"title": "8.5.1 Dl Objects", "text": "module-dl.html | module-dl.html | module-dbm.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.5.1 Dl Objects\nDl objects, as returned by open() above, have the\nfollowing methods:", "python_version": "2.2", "length": 217, "url": "https://docs.python.org/2.2/lib/dl-objects.html"} {"title": "13.6.3.2 Accessor Methods", "text": "dom-type-mapping.html | dom-conformance.html | module-xml.dom.minidom.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.3.2 Accessor Methods\nThe mapping from OMG IDL to Python defines accessor functions for IDL\nattribute declarations in much the way the Java mapping\ndoes. Mapping the IDL declarations\n```text\n\nreadonly attribute string someValue;\nattribute string anotherValue;\n```\nyields three accessor functions: a ``get'' method for\nsomeValue (_get_someValue()), and ``get'' and\n``set'' methods for\nanotherValue (_get_anotherValue() and\n_set_anotherValue()). The mapping, in particular, does not\nrequire that the IDL attributes are accessible as normal Python\nattributes: `object .someValue` is not required to\nwork, and may raise an AttributeError.\nThe Python DOM API, however, does require that normal attribute\naccess work. This means that the typical surrogates generated by\nPython IDL compilers are not likely to work, and wrapper objects may\nbe needed on the client if the DOM objects are accessed via CORBA.\nWhile this does require some additional consideration for CORBA DOM\nclients, the implementers with experience using DOM over CORBA from\nPython do not consider this a problem. Attributes that are declared\nreadonly may not restrict write access in all DOM\nimplementations.", "python_version": "2.2", "length": 1332, "url": "https://docs.python.org/2.2/lib/dom-accessor-methods.html"} {"title": "13.6.2.7 Attr Objects", "text": "dom-element-objects.html | node438.html | dom-attributelist-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.7 Attr Objects\nAttr inherits from Node, so inherits all its\nattributes.", "python_version": "2.2", "length": 234, "url": "https://docs.python.org/2.2/lib/dom-attr-objects.html"} {"title": "13.6.2.8 NamedNodeMap Objects", "text": "dom-attr-objects.html | node438.html | dom-comment-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.8 NamedNodeMap Objects\nNamedNodeMap does not inherit from Node.\nThere are also experimental methods that give this class more mapping\nbehavior. You can use them or you can use the standardized\ngetAttribute*() family of methods on the Element\nobjects.", "python_version": "2.2", "length": 404, "url": "https://docs.python.org/2.2/lib/dom-attributelist-objects.html"} {"title": "13.6.2.9 Comment Objects", "text": "dom-attributelist-objects.html | node438.html | dom-text-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.9 Comment Objects\nComment represents a comment in the XML document. It is a\nsubclass of Node, but cannot have child nodes.", "python_version": "2.2", "length": 282, "url": "https://docs.python.org/2.2/lib/dom-comment-objects.html"} {"title": "13.6.3 Conformance", "text": "dom-exceptions.html | module-xml.dom.html | dom-type-mapping.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.6.3 Conformance\nThis section describes the conformance requirements and relationships\nbetween the Python DOM API, the W3C DOM recommendations, and the OMG\nIDL mapping for Python.", "python_version": "2.2", "length": 329, "url": "https://docs.python.org/2.2/lib/dom-conformance.html"} {"title": "13.6.2.5 Document Objects", "text": "dom-documenttype-objects.html | node438.html | dom-element-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.5 Document Objects\nA Document represents an entire XML document, including its\nconstituent elements, attributes, processing instructions, comments\netc. Remeber that it inherits properties from Node.", "python_version": "2.2", "length": 360, "url": "https://docs.python.org/2.2/lib/dom-document-objects.html"} {"title": "13.6.2.4 DocumentType Objects", "text": "dom-nodelist-objects.html | node438.html | dom-document-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.4 DocumentType Objects\nInformation about the notations and entities declared by a document\n(including the external subset if the parser uses it and can provide\nthe information) is available from a DocumentType object. The\nDocumentType for a document is available from the\nDocument object's doctype attribute; if there is no\n`DOCTYPE` declaration for the document, the document's\ndoctype attribute will be set to `None` instead of an\ninstance of this interface.\nDocumentType is a specialization of Node, and adds the\nfollowing attributes:", "python_version": "2.2", "length": 696, "url": "https://docs.python.org/2.2/lib/dom-documenttype-objects.html"} {"title": "13.6.2.6 Element Objects", "text": "dom-document-objects.html | node438.html | dom-attr-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.6 Element Objects\nElement is a subclass of Node, so inherits all the\nattributes of that class.", "python_version": "2.2", "length": 249, "url": "https://docs.python.org/2.2/lib/dom-element-objects.html"} {"title": "13.7.2 DOM Example", "text": "dom-objects.html | module-xml.dom.minidom.html | minidom-and-dom.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.7.2 DOM Example\nThis example program is a fairly realistic example of a simple\nprogram. In this particular case, we do not take much advantage\nof the flexibility of the DOM.\n```text\nimport xml.dom.minidom\n\ndocument = \"\"\"\\\n\nDemo slideshow\nSlide title\nThis is a demo\nOf a program for processing slides\n\n\nAnother demo slide\nIt is important\nTo have more than\none slide\n\n\n\"\"\"\n\ndom = xml.dom.minidom.parseString(document)\n\ndef getText(nodelist):\nrc = \"\"\nfor node in nodelist:\nif node.nodeType == node.TEXT_NODE:\nrc = rc + node.data\nreturn rc\n\ndef handleSlideshow(slideshow):\nprint \"\"\nhandleSlideshowTitle(slideshow.getElementsByTagName(\"title\")[0])\nslides = slideshow.getElementsByTagName(\"slide\")\nhandleToc(slides)\nhandleSlides(slides)\nprint \"\"\n\ndef handleSlides(slides):\nfor slide in slides:\nhandleSlide(slide)\n\ndef handleSlide(slide):\nhandleSlideTitle(slide.getElementsByTagName(\"title\")[0])\nhandlePoints(slide.getElementsByTagName(\"point\"))\n\ndef handleSlideshowTitle(title):\nprint \"%s\" % getText(title.childNodes)\n\ndef handleSlideTitle(title):\nprint \"

%s

\" % getText(title.childNodes)\n\ndef handlePoints(points):\nprint \"
    \"\nfor point in points:\nhandlePoint(point)\nprint \"
\"\n\ndef handlePoint(point):\nprint \"
  • %s
  • \" % getText(point.childNodes)\n\ndef handleToc(slides):\nfor slide in slides:\ntitle = slide.getElementsByTagName(\"title\")[0]\nprint \"

    %s

    \" % getText(title.childNodes)\n\nhandleSlideshow(dom)\n```\nDownload as text. (minidom-example.txt)", "python_version": "2.2", "length": 1816, "url": "https://docs.python.org/2.2/lib/dom-example.html"} {"title": "13.6.2.12 Exceptions", "text": "dom-pi-objects.html | node438.html | dom-conformance.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.12 Exceptions\nNew in version 2.1.\nThe DOM Level 2 recommendation defines a single exception,\nDOMException, and a number of constants that allow\napplications to determine what sort of error occurred.\nDOMException instances carry a code attribute\nthat provides the appropriate value for the specific exception.\nThe Python DOM interface provides the constants, but also expands the\nset of exceptions so that a specific exception exists for each of the\nexception codes defined by the DOM. The implementations must raise\nthe appropriate specific exception, each of which carries the\nappropriate value for the code attribute.\nThe exception codes defined in the DOM recommendation map to the\nexceptions described above according to this table:", "python_version": "2.2", "length": 884, "url": "https://docs.python.org/2.2/lib/dom-exceptions.html"} {"title": "13.6.2.1 DOMImplementation Objects", "text": "node438.html | node438.html | dom-node-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.1 DOMImplementation Objects\nThe DOMImplementation interface provides a way for\napplications to determine the availability of particular features in\nthe DOM they are using. DOM Level 2 added the ability to create new\nDocument and DocumentType objects using the\nDOMImplementation as well.", "python_version": "2.2", "length": 428, "url": "https://docs.python.org/2.2/lib/dom-implementation-objects.html"} {"title": "13.6.2.2 Node Objects", "text": "dom-implementation-objects.html | node438.html | dom-nodelist-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.2 Node Objects\nAll of the components of an XML document are subclasses of\nNode.", "python_version": "2.2", "length": 244, "url": "https://docs.python.org/2.2/lib/dom-node-objects.html"} {"title": "13.6.2.3 NodeList Objects", "text": "dom-node-objects.html | node438.html | dom-documenttype-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.3 NodeList Objects\nA NodeList represents a sequence of nodes. These objects are\nused in two ways in the DOM Core recommendation: the\nElement objects provides one as it's list of child nodes, and\nthe getElementsByTagName() and\ngetElementsByTagNameNS() methods of Node return\nobjects with this interface to represent query results.\nThe DOM Level 2 recommendation defines one method and one attribute\nfor these objects:\nIn addition, the Python DOM interface requires that some additional\nsupport is provided to allow NodeList objects to be used as\nPython sequences. All NodeList implementations must include\nsupport for __len__() and __getitem__(); this allows\niteration over the NodeList in for statements and\nproper support for the len() built-in function.\nIf a DOM implementation supports modification of the document, the\nNodeList implementation must also support the\n__setitem__() and __delitem__() methods.", "python_version": "2.2", "length": 1068, "url": "https://docs.python.org/2.2/lib/dom-nodelist-objects.html"} {"title": "13.7.1 DOM objects", "text": "module-xml.dom.minidom.html | module-xml.dom.minidom.html | dom-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.7.1 DOM objects\nThe definition of the DOM API for Python is given as part of the\nxml.dom (module-xml.dom.html) module documentation. This section lists the\ndifferences between the API and xml.dom.minidom (module-xml.dom.minidom.html).\nThe following standard DOM methods have special considerations with\nxml.dom.minidom (module-xml.dom.minidom.html):", "python_version": "2.2", "length": 511, "url": "https://docs.python.org/2.2/lib/dom-objects.html"} {"title": "13.6.2.11 ProcessingInstruction Objects", "text": "dom-text-objects.html | node438.html | dom-exceptions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.11 ProcessingInstruction Objects\nRepresents a processing instruction in the XML document; this inherits\nfrom the Node interface and cannot have child nodes.", "python_version": "2.2", "length": 305, "url": "https://docs.python.org/2.2/lib/dom-pi-objects.html"} {"title": "13.6.2.10 Text and CDATASection Objects", "text": "dom-comment-objects.html | node438.html | dom-pi-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.2.10 Text and CDATASection Objects\nThe Text interface represents text in the XML document. If\nthe parser and DOM implementation support the DOM's XML extension,\nportions of the text enclosed in CDATA marked sections are stored in\nCDATASection objects. These two interfaces are identical, but\nprovide different values for the nodeType attribute.\nThese interfaces extend the Node interface. They cannot have\nchild nodes.\nNote:\nThe use of a CDATASection node does not\nindicate that the node represents a complete CDATA marked section,\nonly that the content of the node was part of a CDATA section. A\nsingle CDATA section may be represented by more than one node in the\ndocument tree. There is no way to determine whether two adjacent\nCDATASection nodes represent different CDATA marked sections.", "python_version": "2.2", "length": 942, "url": "https://docs.python.org/2.2/lib/dom-text-objects.html"} {"title": "13.6.3.1 Type Mapping", "text": "dom-conformance.html | dom-conformance.html | dom-accessor-methods.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 13.6.3.1 Type Mapping\nThe primitive IDL types used in the DOM specification are mapped to\nPython types according to the following table.\nAdditionally, the DOMString defined in the recommendation is\nmapped to a Python string or Unicode string. Applications should\nbe able to handle Unicode whenever a string is returned from the DOM.\nThe IDL null value is mapped to `None`, which may be\naccepted or provided by the implementation whenever null is\nallowed by the API.", "python_version": "2.2", "length": 620, "url": "https://docs.python.org/2.2/lib/dom-type-mapping.html"} {"title": "13.8.1 DOMEventStream Objects", "text": "module-xml.dom.pulldom.html | module-xml.dom.pulldom.html | module-xml.sax.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.8.1 DOMEventStream Objects", "python_version": "2.2", "length": 191, "url": "https://docs.python.org/2.2/lib/domeventstream-objects.html"} {"title": "13.10.2 DTDHandler Objects", "text": "content-handler-objects.html | module-xml.sax.handler.html | entity-resolver-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.10.2 DTDHandler Objects\nDTDHandler instances provide the following methods:", "python_version": "2.2", "length": 250, "url": "https://docs.python.org/2.2/lib/dtd-handler-objects.html"} {"title": "6.24.2 For extension writers and programs that embed Python", "text": "node197.html | module-locale.html | module-gettext.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.24.2 For extension writers and programs that embed Python\nExtension modules should never call setlocale(), except to\nfind out what the current locale is. But since the return value can\nonly be used portably to restore it, that is not very useful (except\nperhaps to find out whether or not the locale is \"C\").\nWhen Python is embedded in an application, if the application sets the\nlocale to something specific before initializing Python, that is\ngenerally okay, and Python will use whatever locale is set,\nexcept that the LC_NUMERIC locale should always be\n\"C\".\nThe setlocale() function in the locale module\ngives the Python programmer the impression that you can manipulate the\nLC_NUMERIC locale setting, but this not the case at the C\nlevel: C code will always find that the LC_NUMERIC locale\nsetting is \"C\". This is because too much would break when the\ndecimal point character is set to something else than a period\n(e.g. the Python parser would break). Caveat: threads that run\nwithout holding Python's global interpreter lock may occasionally find\nthat the numeric locale setting differs; this is because the only\nportable way to implement this feature is to set the numeric locale\nsettings to what the user requests, extract the relevant\ncharacteristics, and then restore the \"C\" numeric locale.", "python_version": "2.2", "length": 1441, "url": "https://docs.python.org/2.2/lib/embedding-locale.html"} {"title": "13.10.3 EntityResolver Objects", "text": "dtd-handler-objects.html | module-xml.sax.handler.html | sax-error-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.10.3 EntityResolver Objects", "python_version": "2.2", "length": 192, "url": "https://docs.python.org/2.2/lib/entity-resolver-objects.html"} {"title": "7.5.5 Event Objects", "text": "semaphore-examples.html | module-threading.html | thread-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.5.5 Event Objects\nThis is one of the simplest mechanisms for communication between\nthreads: one thread signals an event and one or more other threads\nare waiting for it.\nAn event object manages an internal flag that can be set to true with\nthe set() method and reset to false with the clear() method. The\nwait() method blocks until the flag is true.", "python_version": "2.2", "length": 503, "url": "https://docs.python.org/2.2/lib/event-objects.html"} {"title": "3.21.1 Examples", "text": "module-imp.html | module-imp.html | module-code.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.21.1 Examples\nThe following function emulates what was the standard import statement\nup to Python 1.4 (no hierarchical module names). (This\nimplementation wouldn't work in that version, since\nfind_module() has been extended and\nload_module() has been added in 1.4.)\n```text\n\nimport imp\nimport sys\n\ndef __import__(name, globals=None, locals=None, fromlist=None):\n# Fast path: see if the module has already been imported.\ntry:\nreturn sys.modules[name]\nexcept KeyError:\npass\n\n# If any of the following calls raises an exception,\n# there's a problem we can't handle -- let the caller handle it.\n\nfp, pathname, description = imp.find_module(name)\n\ntry:\nreturn imp.load_module(name, fp, pathname, description)\nfinally:\n# Since we may exit via an exception, close fp explicitly.\nif fp:\nfp.close()\n```", "python_version": "2.2", "length": 930, "url": "https://docs.python.org/2.2/lib/examples-imp.html"} {"title": "13.5.4 Content Model Descriptions", "text": "expat-example.html | module-xml.parsers.expat.html | expat-errors.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.5.4 Content Model Descriptions\nContent modules are described using nested tuples. Each tuple\ncontains four values: the type, the quantifier, the name, and a tuple\nof children. Children are simply additional content module\ndescriptions.\nThe values of the first two fields are constants defined in the\n`model` object of the xml.parsers.expat module. These\nconstants can be collected in two groups: the model type group and the\nquantifier group.\nThe constants in the model type group are:\nThe constants in the quantifier group are:", "python_version": "2.2", "length": 684, "url": "https://docs.python.org/2.2/lib/expat-content-models.html"} {"title": "13.5.5 Expat error constants", "text": "expat-content-models.html | module-xml.parsers.expat.html | module-xml.dom.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.5.5 Expat error constants\nThe following constants are provided in the `errors` object of\nthe xml.parsers.expat (module-xml.parsers.expat.html) module. These constants are useful\nin interpreting some of the attributes of the ExpatError\nexception objects raised when an error has occurred.\nThe `errors` object has the following attributes:", "python_version": "2.2", "length": 502, "url": "https://docs.python.org/2.2/lib/expat-errors.html"} {"title": "13.5.3 Example", "text": "expaterror-objects.html | module-xml.parsers.expat.html | expat-content-models.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.5.3 Example\nThe following program defines three handlers that just print out their\narguments.\n```text\n\nimport xml.parsers.expat\n\n# 3 handler functions\ndef start_element(name, attrs):\nprint 'Start element:', name, attrs\ndef end_element(name):\nprint 'End element:', name\ndef char_data(data):\nprint 'Character data:', repr(data)\n\np = xml.parsers.expat.ParserCreate()\n\np.StartElementHandler = start_element\np.EndElementHandler = end_element\np.CharacterDataHandler = char_data\n\np.Parse(\"\"\"\nText goes here\nMore text\n\"\"\")\n```\nThe output from this program is:\n```text\n\nStart element: parent {'id': 'top'}\nStart element: child1 {'name': 'paul'}\nCharacter data: 'Text goes here'\nEnd element: child1\nCharacter data: '\\n'\nStart element: child2 {'name': 'fred'}\nCharacter data: 'More text'\nEnd element: child2\nCharacter data: '\\n'\nEnd element: parent\n```", "python_version": "2.2", "length": 1115, "url": "https://docs.python.org/2.2/lib/expat-example.html"} {"title": "13.5.2 ExpatError Exceptions", "text": "xmlparser-objects.html | module-xml.parsers.expat.html | expat-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.5.2 ExpatError Exceptions\nExpatError exceptions have a number of interesting\nattributes:", "python_version": "2.2", "length": 249, "url": "https://docs.python.org/2.2/lib/expaterror-objects.html"} {"title": "11.20.5 Fault Objects", "text": "binary-objects.html | module-xmlrpclib.html | protocol-error-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.5 Fault Objects\nA Fault object encapsulates the content of an XML-RPC fault tag.\nFault objects have the following members:", "python_version": "2.2", "length": 284, "url": "https://docs.python.org/2.2/lib/fault-objects.html"} {"title": "11.5.15 FileHandler Objects", "text": "https-handler-objects.html | module-urllib2.html | ftp-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.15 FileHandler Objects", "python_version": "2.2", "length": 185, "url": "https://docs.python.org/2.2/lib/file-handler-objects.html"} {"title": "18.4.1 Functions Defined in Module fl", "text": "module-fl.html | module-fl.html | form-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.4.1 Functions Defined in Module fl\nModule fl defines the following functions. For more\ninformation about what they do, see the description of the equivalent\nC function in the FORMS documentation:", "python_version": "2.2", "length": 332, "url": "https://docs.python.org/2.2/lib/FL_Functions.html"} {"title": "20.4.2 Form Objects", "text": "node589.html | module-fl.html | forms-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 20.4.2 Form Objects\nForm objects (returned by make_form() above) have the\nfollowing methods. Each method corresponds to a C function whose\nname is prefixed with \"fl_\"; and whose first argument is a form\npointer; please refer to the official FORMS documentation for\ndescriptions.\nAll the add_*() methods return a Python object representing\nthe FORMS object. Methods of FORMS objects are described below. Most\nkinds of FORMS object also have some methods specific to that kind;\nthese methods are listed here.\nForm objects have the following data attributes; see the FORMS\ndocumentation:", "python_version": "2.2", "length": 717, "url": "https://docs.python.org/2.2/lib/form-objects.html"} {"title": "12.1.2 Formatter Implementations", "text": "formatter-interface.html | module-formatter.html | writer-interface.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.1.2 Formatter Implementations\nTwo implementations of formatter objects are provided by this module.\nMost applications may use one of these classes without modification or\nsubclassing.", "python_version": "2.2", "length": 341, "url": "https://docs.python.org/2.2/lib/formatter-impls.html"} {"title": "12.1.1 The Formatter Interface", "text": "module-formatter.html | module-formatter.html | formatter-impls.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.1.1 The Formatter Interface\nInterfaces to create formatters are dependent on the specific\nformatter class being instantiated. The interfaces described below\nare the required interfaces which all formatters must support once\ninitialized.\nOne data element is defined at the module level:\nThe following attributes are defined for formatter instance objects:", "python_version": "2.2", "length": 508, "url": "https://docs.python.org/2.2/lib/formatter-interface.html"} {"title": "20.4.3 FORMS Objects", "text": "form-objects.html | module-fl.html | module-fl-constants.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 20.4.3 FORMS Objects\nBesides methods specific to particular kinds of FORMS objects, all\nFORMS objects also have the following methods:\nFORMS objects have these data attributes; see the FORMS documentation:", "python_version": "2.2", "length": 349, "url": "https://docs.python.org/2.2/lib/forms-objects.html"} {"title": "3.4.1 Example", "text": "module-fpectl.html | module-fpectl.html | node41.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.4.1 Example\nThe following example demonstrates how to start up and test operation of\nthe fpectl module.\n```text\n\n>>> import fpectl\n>>> import fpetest\n>>> fpectl.turnon_sigfpe()\n>>> fpetest.test()\noverflow PASS\nFloatingPointError: Overflow\n\ndiv by 0 PASS\nFloatingPointError: Division by zero\n[ more output from test elided ]\n>>> import math\n>>> math.exp(1000)\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nFloatingPointError: in math_1\n```", "python_version": "2.2", "length": 594, "url": "https://docs.python.org/2.2/lib/fpectl-example.html"} {"title": "Front Matter", "text": "lib.html | lib.html | contents.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# Front Matter\nCopyright © 2001 Python Software Foundation.\nAll rights reserved.\nCopyright © 2000 BeOpen.com.\nAll rights reserved.\nCopyright © 1995-2000 Corporation for National Research Initiatives.\nAll rights reserved.\nCopyright © 1991-1995 Stichting Mathematisch Centrum.\nAll rights reserved.\nSee the end of this document for complete license and permissions\ninformation.\n### Abstract:\nPython is an extensible, interpreted, object-oriented programming\nlanguage. It supports a wide range of applications, from simple text\nprocessing scripts to interactive Web browsers.\nWhile the Python Reference Manual (../ref/ref.html)\ndescribes the exact syntax and semantics of the language, it does not\ndescribe the standard library that is distributed with the language,\nand which greatly enhances its immediate usability. This library\ncontains built-in modules (written in C) that provide access to system\nfunctionality such as file I/O that would otherwise be inaccessible to\nPython programmers, as well as modules written in Python that provide\nstandardized solutions for many problems that occur in everyday\nprogramming. Some of these modules are explicitly designed to\nencourage and enhance the portability of Python programs.\nThis library reference manual documents Python's standard library, as\nwell as many optional library modules (which may or may not be\navailable, depending on whether the underlying platform supports them\nand on the configuration choices made at compile time). It also\ndocuments the standard types of the language and its built-in\nfunctions and exceptions, many of which are not or incompletely\ndocumented in the Reference Manual.\nThis manual assumes basic knowledge about the Python language. For an\ninformal introduction to Python, see the\nPython Tutorial (../tut/tut.html); the\nPython Reference Manual (../ref/ref.html) remains the\nhighest authority on syntactic and semantic questions. Finally, the\nmanual entitled Extending and Embedding\nthe Python Interpreter (../ext/ext.html) describes how to add new extensions to Python\nand how to embed it in other applications.", "python_version": "2.2", "length": 2209, "url": "https://docs.python.org/2.2/lib/front.html"} {"title": "11.5.16 FTPHandler Objects", "text": "file-handler-objects.html | module-urllib2.html | cacheftp-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.16 FTPHandler Objects", "python_version": "2.2", "length": 188, "url": "https://docs.python.org/2.2/lib/ftp-handler-objects.html"} {"title": "11.7.1 FTP Objects", "text": "module-ftplib.html | module-ftplib.html | module-gopherlib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.7.1 FTP Objects\nSeveral methods are available in two flavors: one for handling text\nfiles and another for binary files. These are named for the command\nwhich is used followed by \"lines\" for the text version or\n\"binary\" for the binary version.\nFTP instances have the following methods:", "python_version": "2.2", "length": 433, "url": "https://docs.python.org/2.2/lib/ftp-objects.html"} {"title": "11.2.4 Functions", "text": "node281.html | module-cgi.html | node283.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.4 Functions\nThese are useful if you want more control, or if you want to employ\nsome of the algorithms implemented in this module in other\ncircumstances.", "python_version": "2.2", "length": 286, "url": "https://docs.python.org/2.2/lib/Functions_in_cgi_module.html"} {"title": "Index", "text": "modindex.html | lib.html | about.html | Python Library Reference | contents.html | modindex.html\n---\n## Index\n---\n. (#letter-.) |\n< (#letter-<) |\n= (#letter-=) |\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\nj (#letter-j) |\nk (#letter-k) |\nl (#letter-l) |\nm (#letter-m) |\nn (#letter-n) |\no (#letter-o) |\np (#letter-p) |\nq (#letter-q) |\nr (#letter-r) |\ns (#letter-s) |\nt (#letter-t) |\nu (#letter-u) |\nv (#letter-v) |\nw (#letter-w) |\nx (#letter-x) |\ny (#letter-y) |\nz (#letter-z)\n---\n## . (dot)\n---\n## <\n---\n## =\n---\n## _ (underscore)\n---\n## A\n---\n## B\n---\n## C\n---\n## D\n---\n## E\n---\n## F\n---\n## G\n---\n## H\n---\n## I\n---\n## J\n---\n## K\n---\n## L\n---\n## M\n---\n## N\n---\n## O\n---\n## P\n---\n## Q\n---\n## R\n---\n## S\n---\n## T\n---\n## U\n---\n## V\n---\n## W\n---\n## X\n---\n## Y\n---\n## Z", "python_version": "2.2", "length": 880, "url": "https://docs.python.org/2.2/lib/genindex.html"} {"title": "11.5.18 GopherHandler Objects", "text": "cacheftp-handler-objects.html | module-urllib2.html | unknown-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.18 GopherHandler Objects", "python_version": "2.2", "length": 194, "url": "https://docs.python.org/2.2/lib/gopher-handler.html"} {"title": "22.2.1 Registry Handle Objects", "text": "module--winreg.html | module--winreg.html | module-winsound.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 22.2.1 Registry Handle Objects\nThis object wraps a Windows HKEY object, automatically closing it when\nthe object is destroyed. To guarantee cleanup, you can call either\nthe Close() method on the object, or the\nCloseKey() function.\nAll registry functions in this module return one of these objects.\nAll registry functions in this module which accept a handle object\nalso accept an integer, however, use of the handle object is\nencouraged.\nHandle objects provide semantics for __nonzero__() - thus\n```text\n\nif handle:\nprint \"Yes\"\n```\nwill print `Yes` if the handle is currently valid (has not been\nclosed or detached).\nThe object also support comparison semantics, so handle\nobjects will compare true if they both reference the same\nunderlying Windows handle value.\nHandle objects can be converted to an integer (eg, using the\nbuiltin int() function, in which case the underlying\nWindows handle value is returned. You can also use the\nDetach() method to return the integer handle, and\nalso disconnect the Windows handle from the handle object.", "python_version": "2.2", "length": 1188, "url": "https://docs.python.org/2.2/lib/handle-object.html"} {"title": "13.3.1 HTMLParser Objects", "text": "module-htmllib.html | module-htmllib.html | module-htmlentitydefs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.3.1 HTMLParser Objects\nIn addition to tag methods, the HTMLParser class provides some\nadditional methods and instance variables for use within tag methods.", "python_version": "2.2", "length": 311, "url": "https://docs.python.org/2.2/lib/html-parser-objects.html"} {"title": "13.1.1 Example HTML Parser", "text": "module-HTMLParser.html | module-HTMLParser.html | module-sgmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.1.1 Example HTML Parser\nAs a basic example, below is a very basic HTML parser that uses the\nHTMLParser class to print out tags as they are encountered:", "python_version": "2.2", "length": 306, "url": "https://docs.python.org/2.2/lib/htmlparser-example.html"} {"title": "11.5.8 HTTPBasicAuthHandler Objects", "text": "abstract-basic-auth-handler.html | module-urllib2.html | proxy-basic-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.8 HTTPBasicAuthHandler Objects", "python_version": "2.2", "length": 204, "url": "https://docs.python.org/2.2/lib/http-basic-auth-handler.html"} {"title": "11.5.11 HTTPDigestAuthHandler Objects", "text": "abstract-digest-auth-handler.html | module-urllib2.html | proxy-digest-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.11 HTTPDigestAuthHandler Objects", "python_version": "2.2", "length": 208, "url": "https://docs.python.org/2.2/lib/http-digest-auth-handler.html"} {"title": "11.5.13 HTTPHandler Objects", "text": "proxy-digest-auth-handler.html | module-urllib2.html | https-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.13 HTTPHandler Objects", "python_version": "2.2", "length": 191, "url": "https://docs.python.org/2.2/lib/http-handler-objects.html"} {"title": "11.5.6 HTTPPasswordMgr Objects", "text": "proxy-handler.html | module-urllib2.html | abstract-basic-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.6 HTTPPasswordMgr Objects\nThese methods are available on HTTPPasswordMgr and\nHTTPPasswordMgrWithDefaultRealm objects.", "python_version": "2.2", "length": 280, "url": "https://docs.python.org/2.2/lib/http-password-mgr.html"} {"title": "11.5.4 HTTPRedirectHandler Objects", "text": "base-handler-objects.html | module-urllib2.html | proxy-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.4 HTTPRedirectHandler Objects\nNote:\n303 redirection is not supported by this version of\nurllib2.", "python_version": "2.2", "length": 252, "url": "https://docs.python.org/2.2/lib/http-redirect-handler.html"} {"title": "11.6.1 HTTPConnection Objects", "text": "module-httplib.html | module-httplib.html | httpresponse-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.6.1 HTTPConnection Objects\nHTTPConnection instances have the following methods:", "python_version": "2.2", "length": 234, "url": "https://docs.python.org/2.2/lib/httpconnection-objects.html"} {"title": "11.6.3 Examples", "text": "httpresponse-objects.html | module-httplib.html | module-ftplib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.6.3 Examples\nHere is an example session that uses the \"GET\" method:\n```text\n\n>>> import httplib\n>>> conn = httplib.HTTPConnection(\"www.python.org\")\n>>> conn.request(\"GET\", \"/index.html\")\n>>> r1 = conn.getresponse()\n>>> print r1.status, r1.reason\n200 OK\n>>> data1 = r1.read()\n>>> conn.request(\"GET\", \"/parrot.spam\")\n>>> r2 = conn.getresponse()\n>>> print r2.status, r2.reason\n404 Not Found\n>>> data2 = r2.read()\n>>> conn.close()\n```\nHere is an example session that shows how to \"POST\" requests:", "python_version": "2.2", "length": 646, "url": "https://docs.python.org/2.2/lib/httplib-examples.html"} {"title": "11.6.2 HTTPResponse Objects", "text": "httpconnection-objects.html | module-httplib.html | httplib-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.6.2 HTTPResponse Objects\nHTTPResponse instances have the following methods and attributes:", "python_version": "2.2", "length": 249, "url": "https://docs.python.org/2.2/lib/httpresponse-objects.html"} {"title": "11.5.14 HTTPSHandler Objects", "text": "http-handler-objects.html | module-urllib2.html | file-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.14 HTTPSHandler Objects", "python_version": "2.2", "length": 186, "url": "https://docs.python.org/2.2/lib/https-handler-objects.html"} {"title": "16.5 Idle", "text": "pen-rawpen-objects.html | tkinter.html | node532.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 16.5 Idle\nIdle is the Python IDE built with the Tkinter (module-Tkinter.html) GUI toolkit.\nIDLE has the following features:\n- coded in 100% pure Python, using the Tkinter (module-Tkinter.html) GUI toolkit\n- cross-platform: works on Windows and Unix (on Mac OS, there are\ncurrently problems with Tcl/Tk)\n- multi-window text editor with multiple undo, Python colorizing\nand many other features, e.g. smart indent and call tips\n- Python shell window (a.k.a. interactive interpreter)\n- debugger (not complete, but you can set breakpoints, view and step)", "python_version": "2.2", "length": 684, "url": "https://docs.python.org/2.2/lib/idle.html"} {"title": "11.10.2 IMAP4 Example", "text": "imap4-objects.html | module-imaplib.html | module-nntplib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.10.2 IMAP4 Example\nHere is a minimal example (without error checking) that opens a\nmailbox and retrieves and prints all messages:", "python_version": "2.2", "length": 277, "url": "https://docs.python.org/2.2/lib/imap4-example.html"} {"title": "11.10.1 IMAP4 Objects", "text": "module-imaplib.html | module-imaplib.html | imap4-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.10.1 IMAP4 Objects\nAll IMAP4rev1 commands are represented by methods of the same name,\neither upper-case or lower-case.\nAll arguments to commands are converted to strings, except for\n\"AUTHENTICATE\", and the last argument to \"APPEND\" which is\npassed as an IMAP4 literal. If necessary (the string contains IMAP4\nprotocol-sensitive characters and isn't enclosed with either\nparentheses or double quotes) each string is quoted. However, the\npassword argument to the \"LOGIN\" command is always quoted.\nIf you want to avoid having an argument string quoted\n(eg: the flags argument to \"STORE\") then enclose the string in\nparentheses (eg: `r'(\\Deleted)'`).\nEach command returns a tuple: `( type , [ data ,\n...])` where type is usually `'OK'` or `'NO'`,\nand data is either the text from the command response, or\nmandated results from the command.\nAn IMAP4 instance has the following methods:\nThe following attributes are defined on instances of IMAP4:", "python_version": "2.2", "length": 1089, "url": "https://docs.python.org/2.2/lib/imap4-objects.html"} {"title": "13.12.2 IncrementalParser Objects", "text": "xmlreader-objects.html | module-xml.sax.xmlreader.html | locator-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.12.2 IncrementalParser Objects\nInstances of IncrementalParser offer the following additional\nmethods:", "python_version": "2.2", "length": 264, "url": "https://docs.python.org/2.2/lib/incremental-parser-objects.html"} {"title": "Python Library Reference", "text": "../index.html | front.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# Python Library Reference\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 247, "url": "https://docs.python.org/2.2/lib/index.html"} {"title": "13.12.4 InputSource Objects", "text": "locator-objects.html | module-xml.sax.xmlreader.html | attributes-impl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.12.4 InputSource Objects", "python_version": "2.2", "length": 193, "url": "https://docs.python.org/2.2/lib/input-source-objects.html"} {"title": "3.11.3 Classes and functions", "text": "inspect-source.html | module-inspect.html | inspect-stack.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.11.3 Classes and functions", "python_version": "2.2", "length": 173, "url": "https://docs.python.org/2.2/lib/inspect-classes-functions.html"} {"title": "3.11.2 Retrieving source code", "text": "inspect-types.html | module-inspect.html | inspect-classes-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.11.2 Retrieving source code", "python_version": "2.2", "length": 185, "url": "https://docs.python.org/2.2/lib/inspect-source.html"} {"title": "3.11.4 The interpreter stack", "text": "inspect-classes-functions.html | module-inspect.html | module-traceback.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.11.4 The interpreter stack\nWhen the following functions return ``frame records,'' each record\nis a tuple of six items: the frame object, the filename,\nthe line number of the current line, the function name, a list of\nlines of context from the source code, and the index of the current\nline within that list.\nThe optional context argument specifies the number of lines of\ncontext to return, which are centered around the current line.\nWarning:\nKeeping references to frame objects, as found in\nthe first element of the frame records these functions return, can\ncause your program to create reference cycles. Once a reference cycle\nhas been created, the lifespan of all objects which can be accessed\nfrom the objects which form the cycle can become much longer even if\nPython's optional cycle detector is enabled. If such cycles must be\ncreated, it is important to ensure they are explicitly broken to avoid\nthe delayed destruction of objects and increased memory consumption\nwhich occurs.", "python_version": "2.2", "length": 1147, "url": "https://docs.python.org/2.2/lib/inspect-stack.html"} {"title": "3.11.1 Types and members", "text": "module-inspect.html | module-inspect.html | inspect-source.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.11.1 Types and members\nThe getmembers() function retrieves the members\nof an object such as a class or module.\nThe nine functions whose names begin with ``is'' are mainly\nprovided as convenient choices for the second argument to\ngetmembers(). They also help you determine when\nyou can expect to find the following special attributes:\nNote:\n(1): Changed in version 2.2:\nim_class used to refer to the class that\ndefined the method.", "python_version": "2.2", "length": 577, "url": "https://docs.python.org/2.2/lib/inspect-types.html"} {"title": "11. Internet Protocols and Support", "text": "node289.html | lib.html | module-webbrowser.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11. Internet Protocols and Support\nThe modules described in this chapter implement Internet protocols and\nsupport for related technology. They are all implemented in Python.\nMost of these modules require the presence of the system-dependent\nmodule socket (module-socket.html), which is currently\nsupported on most popular platforms. Here is an overview:", "python_version": "2.2", "length": 483, "url": "https://docs.python.org/2.2/lib/internet.html"} {"title": "3.22.1 Interactive Interpreter Objects", "text": "module-code.html | module-code.html | console-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.22.1 Interactive Interpreter Objects", "python_version": "2.2", "length": 179, "url": "https://docs.python.org/2.2/lib/interpreter-objects.html"} {"title": "1. Introduction", "text": "contents.html | lib.html | builtin.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 1. Introduction\nThe ``Python library'' contains several different kinds of components.\nIt contains data types that would normally be considered part of the\n``core'' of a language, such as numbers and lists. For these types,\nthe Python language core defines the form of literals and places some\nconstraints on their semantics, but does not fully define the\nsemantics. (On the other hand, the language core does define\nsyntactic properties like the spelling and priorities of operators.)\nThe library also contains built-in functions and exceptions --\nobjects that can be used by all Python code without the need of an\nimport statement. Some of these are defined by the core\nlanguage, but many are not essential for the core semantics and are\nonly described here.\nThe bulk of the library, however, consists of a collection of modules.\nThere are many ways to dissect this collection. Some modules are\nwritten in C and built in to the Python interpreter; others are\nwritten in Python and imported in source form. Some modules provide\ninterfaces that are highly specific to Python, like printing a stack\ntrace; some provide interfaces that are specific to particular\noperating systems, such as access to specific hardware; others provide\ninterfaces that are\nspecific to a particular application domain, like the World Wide Web.\nSome modules are available in all versions and ports of Python; others\nare only available when the underlying system supports or requires\nthem; yet others are available only when a particular configuration\noption was chosen at the time when Python was compiled and installed.\nThis manual is organized ``from the inside out:'' it first describes\nthe built-in data types, then the built-in functions and exceptions,\nand finally the modules, grouped in chapters of related modules. The\nordering of the chapters as well as the ordering of the modules within\neach chapter is roughly from most relevant to least important.\nThis means that if you start reading this manual from the start, and\nskip to the next chapter when you get bored, you will get a reasonable\noverview of the available modules and application areas that are\nsupported by the Python library. Of course, you don't have to\nread it like a novel -- you can also browse the table of contents (in\nfront of the manual), or look for a specific function, module or term\nin the index (in the back). And finally, if you enjoy learning about\nrandom subjects, you choose a random page number (see module\nrandom (module-random.html)) and read a section or two. Regardless of the\norder in which you read the sections of this manual, it helps to start\nwith chapter 2 (builtin.html#builtin), ``Built-in Types, Exceptions and\nFunctions,'' as the remainder of the manual assumes familiarity with\nthis material.\nLet the show begin!", "python_version": "2.2", "length": 2917, "url": "https://docs.python.org/2.2/lib/intro.html"} {"title": "18. Python Language Services", "text": "module-Bastion.html | lib.html | module-parser.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18. Python Language Services\nPython provides a number of modules to assist in working with the\nPython language. These module support tokenizing, parsing, syntax\nanalysis, bytecode disassembly, and various other facilities.\nThese modules include:", "python_version": "2.2", "length": 378, "url": "https://docs.python.org/2.2/lib/language.html"} {"title": "5.3.2 Re-using old test code", "text": "organizing-tests.html | module-unittest.html | unittest-contents.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.3.2 Re-using old test code\nSome users will find that they have existing test code that they would\nlike to run from PyUnit, without converting every old test function to\na TestCase subclass.\nFor this reason, PyUnit provides a FunctionTestCase class.\nThis subclass of TestCase can be used to wrap an existing test\nfunction. Set-up and tear-down functions can also optionally be\nwrapped.\nGiven the following test function:\n```text\n\ndef testSomething():\nsomething = makeSomething()\nassert something.name is not None\n# ...\n```\none can create an equivalent test case instance as follows:\n```text\n\ntestcase = unittest.FunctionTestCase(testSomething)\n```\nIf there are additional set-up and tear-down methods that should be\ncalled as part of the test case's operation, they can also be provided:\n```text\n\ntestcase = unittest.FunctionTestCase(testSomething,\nsetUp=makeSomethingDB,\ntearDown=deleteSomethingDB)\n```\nNote:\nPyUnit supports the use of AssertionError\nas an indicator of test failure, but does not recommend it. Future\nversions may treat AssertionError differently.", "python_version": "2.2", "length": 1218, "url": "https://docs.python.org/2.2/lib/legacy-unit-tests.html"} {"title": "Python Library Reference", "text": "../index.html | front.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# Python Library Reference\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 247, "url": "https://docs.python.org/2.2/lib/lib.html"} {"title": "13.12.3 Locator Objects", "text": "incremental-parser-objects.html | module-xml.sax.xmlreader.html | input-source-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.12.3 Locator Objects\nInstances of Locator provide these methods:", "python_version": "2.2", "length": 241, "url": "https://docs.python.org/2.2/lib/locator-objects.html"} {"title": "7.5.1 Lock Objects", "text": "module-threading.html | module-threading.html | rlock-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.5.1 Lock Objects\nA primitive lock is a synchronization primitive that is not owned\nby a particular thread when locked. In Python, it is currently\nthe lowest level synchronization primitive available, implemented\ndirectly by the thread (module-thread.html) extension module.\nA primitive lock is in one of two states, ``locked'' or ``unlocked''.\nIt is created in the unlocked state. It has two basic methods,\nacquire() and release(). When the state is\nunlocked, acquire() changes the state to locked and returns\nimmediately. When the state is locked, acquire() blocks\nuntil a call to release() in another thread changes it to\nunlocked, then the acquire() call resets it to locked and\nreturns. The release() method should only be called in the\nlocked state; it changes the state to unlocked and returns\nimmediately. When more than one thread is blocked in\nacquire() waiting for the state to turn to unlocked, only one\nthread proceeds when a release() call resets the state to\nunlocked; which one of the waiting threads proceeds is not defined,\nand may vary across implementations.\nAll methods are executed atomically.", "python_version": "2.2", "length": 1265, "url": "https://docs.python.org/2.2/lib/lock-objects.html"} {"title": "12.4.1 Mailbox Objects", "text": "module-mailbox.html | module-mailbox.html | module-mhlib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.4.1 Mailbox Objects\nAll implementations of mailbox objects are iterable objects, and\nhave one externally visible method. This method is used by iterators\ncreated from mailbox objects and may also be used directly.", "python_version": "2.2", "length": 360, "url": "https://docs.python.org/2.2/lib/mailbox-objects.html"} {"title": "13. Structured Markup Processing Tools", "text": "module-robotparser.html | lib.html | module-HTMLParser.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13. Structured Markup Processing Tools\nPython supports a variety of modules to work with various forms of\nstructured data markup. This includes modules to work with the\nStandard Generalized Markup Language (SGML) and the Hypertext Markup\nLanguage (HTML), and several interfaces for working with the\nExtensible Markup Language (XML).", "python_version": "2.2", "length": 473, "url": "https://docs.python.org/2.2/lib/markup.html"} {"title": "4.2.5 Match Objects", "text": "re-objects.html | module-re.html | node102.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.2.5 Match Objects\nMatchObject instances support the following methods and\nattributes:", "python_version": "2.2", "length": 217, "url": "https://docs.python.org/2.2/lib/match-objects.html"} {"title": "4.2.2 Matching vs. Searching", "text": "re-syntax.html | module-re.html | node99.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.2.2 Matching vs. Searching\nPython offers two different primitive operations based on regular\nexpressions: match and search. If you are accustomed to Perl's\nsemantics, the search operation is what you're looking for. See the\nsearch() function and corresponding method of compiled\nregular expression objects.\nNote that match may differ from search using a regular expression\nbeginning with \"^\": \"^\" matches only at the\nstart of the string, or in MULTILINE mode also immediately\nfollowing a newline. The ``match'' operation succeeds only if the\npattern matches at the start of the string regardless of mode, or at\nthe starting position given by the optional pos argument\nregardless of whether a newline precedes it.\n```text\n\nre.compile(\"a\").match(\"ba\", 1) # succeeds\nre.compile(\"^a\").search(\"ba\", 1) # fails; 'a' not at start\nre.compile(\"^a\").search(\"\\na\", 1) # fails; 'a' not at start\nre.compile(\"^a\", re.M).search(\"\\na\", 1) # succeeds\nre.compile(\"^a\", re.M).search(\"ba\", 1) # fails; no preceding \\n\n```", "python_version": "2.2", "length": 1131, "url": "https://docs.python.org/2.2/lib/matching-searching.html"} {"title": "12.11.1 Message Objects", "text": "module-rfc822.html | module-rfc822.html | addresslist-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.11.1 Message Objects\nA Message instance has the following methods:\nMessage instances also support a limited mapping interface.\nIn particular: `m [name]` is like\n`m .getheader(name)` but raises KeyError if\nthere is no matching header; and `len( m )`,\n`m .get(name [ , deafult ] )`,\n`m .has_key(name)`, `m .keys()`,\n`m .values()` `m .items()`, and\n`m .setdefault(name [ , default ] )` act as expected,\nwith the one difference that get() and setdefault()\nuse an empty string as the default value. Message instances\nalso support the mapping writable interface `m [name] =\nvalue` and `del m [name]`. Message objects do not\nsupport the clear(), copy(), popitem(), or\nupdate() methods of the mapping interface. (Support for\nget() and setdefault() was only added in Python\n2.2.)\nFinally, Message instances have some public instance variables:", "python_version": "2.2", "length": 986, "url": "https://docs.python.org/2.2/lib/message-objects.html"} {"title": "12.5.2 Folder Objects", "text": "mh-objects.html | module-mhlib.html | mh-message-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.5.2 Folder Objects\nFolder instances represent open folders and have the following\nmethods:", "python_version": "2.2", "length": 237, "url": "https://docs.python.org/2.2/lib/mh-folder-objects.html"} {"title": "12.5.3 Message Objects", "text": "mh-folder-objects.html | module-mhlib.html | module-mimetools.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.5.3 Message Objects\nThe Message class adds one method to those of\nmimetools.Message:", "python_version": "2.2", "length": 236, "url": "https://docs.python.org/2.2/lib/mh-message-objects.html"} {"title": "12.5.1 MH Objects", "text": "module-mhlib.html | module-mhlib.html | mh-folder-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.5.1 MH Objects\nMH instances have the following methods:", "python_version": "2.2", "length": 203, "url": "https://docs.python.org/2.2/lib/mh-objects.html"} {"title": "12.6.1 Additional Methods of Message Objects", "text": "module-mimetools.html | module-mimetools.html | module-mimetypes.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.6.1 Additional Methods of Message Objects\nThe Message class defines the following methods in\naddition to the rfc822.Message methods:", "python_version": "2.2", "length": 287, "url": "https://docs.python.org/2.2/lib/mimetools-message-objects.html"} {"title": "12.7.1 MimeTypes Objects", "text": "module-mimetypes.html | module-mimetypes.html | module-MimeWriter.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.7.1 MimeTypes Objects\nMimeTypes instances provide an interface which is very like\nthat of the mimetypes (module-mimetypes.html) module.", "python_version": "2.2", "length": 291, "url": "https://docs.python.org/2.2/lib/mimetypes-objects.html"} {"title": "12.8.1 MimeWriter Objects", "text": "module-MimeWriter.html | module-MimeWriter.html | module-mimify.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.8.1 MimeWriter Objects\nMimeWriter instances have the following methods:", "python_version": "2.2", "length": 225, "url": "https://docs.python.org/2.2/lib/MimeWriter-objects.html"} {"title": "13.7.3 minidom and the DOM standard", "text": "dom-example.html | module-xml.dom.minidom.html | module-xml.dom.pulldom.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.7.3 minidom and the DOM standard\nThe xml.dom.minidom (module-xml.dom.minidom.html) module is essentially a DOM\n1.0-compatible DOM with some DOM 2 features (primarily namespace\nfeatures).\nUsage of the DOM interface in Python is straight-forward. The\nfollowing mapping rules apply:\n- Interfaces are accessed through instance objects. Applications\nshould not instantiate the classes themselves; they should use\nthe creator functions available on the Document object.\nDerived interfaces support all operations (and attributes) from\nthe base interfaces, plus any new operations.\n- Operations are used as methods. Since the DOM uses only\nin parameters, the arguments are passed in normal\norder (from left to right). There are no optional\narguments. void operations return `None`.\n- IDL attributes map to instance attributes. For compatibility\nwith the OMG IDL language mapping for Python, an attribute\n`foo` can also be accessed through accessor methods\n_get_foo() and _set_foo(). readonly\nattributes must not be changed; this is not enforced at\nruntime.\n- The types `short int`, `unsigned int`, `unsigned\nlong long`, and `boolean` all map to Python integer\nobjects.\n- The type `DOMString` maps to Python strings.\nxml.dom.minidom (module-xml.dom.minidom.html) supports either byte or Unicode\nstrings, but will normally produce Unicode strings. Values\nof type `DOMString` may also be `None` where allowed\nto have the IDL `null` value by the DOM specification from\nthe W3C.\n- const declarations map to variables in their\nrespective scope\n(e.g. `xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE`);\nthey must not be changed.\n- `DOMException` is currently not supported in\nxml.dom.minidom (module-xml.dom.minidom.html). Instead,\nxml.dom.minidom (module-xml.dom.minidom.html) uses standard Python exceptions such\nas TypeError and AttributeError.\n- NodeList objects are implemented using Python's built-in\nlist type. Starting with Python 2.2, these objects provide the\ninterface defined in the DOM specification, but with earlier\nversions of Python they do not support the official API. They\nare, however, much more ``Pythonic'' than the interface defined\nin the W3C recommendations.\nThe following interfaces have no implementation in\nxml.dom.minidom (module-xml.dom.minidom.html):\n- DOMTimeStamp\n- DocumentType (added in Python 2.1)\n- DOMImplementation (added in Python 2.1)\n- CharacterData\n- CDATASection\n- Notation\n- Entity\n- EntityReference\n- DocumentFragment", "python_version": "2.2", "length": 2612, "url": "https://docs.python.org/2.2/lib/minidom-and-dom.html"} {"title": "5. Miscellaneous Services", "text": "module-unicodedata.html | lib.html | module-pydoc.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5. Miscellaneous Services\nThe modules described in this chapter provide miscellaneous services\nthat are available in all Python versions. Here's an overview:", "python_version": "2.2", "length": 293, "url": "https://docs.python.org/2.2/lib/misc.html"} {"title": "14. Multimedia Services", "text": "xml-namespace.html | lib.html | module-audioop.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14. Multimedia Services\nThe modules described in this chapter implement various algorithms or\ninterfaces that are mainly useful for multimedia applications. They\nare available at the discretion of the installation. Here's an overview:", "python_version": "2.2", "length": 367, "url": "https://docs.python.org/2.2/lib/mmedia.html"} {"title": "Module Index", "text": "node622.html | lib.html | genindex.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## Module Index\nThis index only lists modules documented in this manual.\nThe Global Module\nIndex (../modindex.html) lists all modules that are documented in this set\nof manuals.\nSome module names are followed by an annotation indicating what\nplatform they are available on.", "python_version": "2.2", "length": 392, "url": "https://docs.python.org/2.2/lib/modindex.html"} {"title": "22.2 _winreg - Windows registry access", "text": "msvcrt-other.html | node604.html | handle-object.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 22.2 _winreg -\nWindows registry access\nAvailability: Windows.\nNew in version 2.0.\nThese functions expose the Windows registry API to Python. Instead of\nusing an integer as the registry handle, a handle object is used to\nensure that the handles are closed correctly, even if the programmer\nneglects to explicitly close them.\nThis module exposes a very low-level interface to the Windows\nregistry; it is expected that in the future a new `winreg`\nmodule will be created offering a higher-level interface to the\nregistry API.\nThis module offers the following functions:", "python_version": "2.2", "length": 701, "url": "https://docs.python.org/2.2/lib/module--winreg.html"} {"title": "14.3 aifc -- Read and write AIFF and AIFC files", "text": "module-imageop.html | mmedia.html | module-sunau.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.3 aifc --\nRead and write AIFF and AIFC files\nThis module provides support for reading and writing AIFF and AIFF-C\nfiles. AIFF is Audio Interchange File Format, a format for storing\ndigital audio samples in a file. AIFF-C is a newer version of the\nformat that includes the ability to compress the audio data.\nCaveat: Some operations may only work under IRIX; these will\nraise ImportError when attempting to import the\ncl module, which is only available on IRIX.\nAudio files have a number of parameters that describe the audio data.\nThe sampling rate or frame rate is the number of times per second the\nsound is sampled. The number of channels indicate if the audio is\nmono, stereo, or quadro. Each frame consists of one sample per\nchannel. The sample size is the size in bytes of each sample. Thus a\nframe consists of nchannels*samplesize bytes, and a\nsecond's worth of audio consists of\nnchannels*samplesize*framerate bytes.\nFor example, CD quality audio has a sample size of two bytes (16\nbits), uses two channels (stereo) and has a frame rate of 44,100\nframes/second. This gives a frame size of 4 bytes (2*2), and a\nsecond's worth occupies 2*2*44100 bytes (176,400 bytes).\nModule aifc defines the following function:\nObjects returned by open() when a file is opened for\nreading have the following methods:\nObjects returned by open() when a file is opened for\nwriting have all the above methods, except for readframes() and\nsetpos(). In addition the following methods exist. The\nget*() methods can only be called after the corresponding\nset*() methods have been called. Before the first\nwriteframes() or writeframesraw(), all parameters\nexcept for the number of frames must be filled in.", "python_version": "2.2", "length": 1826, "url": "https://docs.python.org/2.2/lib/module-aifc.html"} {"title": "20.2 AL -- Constants used with the al module", "text": "al-port-objects.html | sgi.html | module-cd.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.2 AL --\nConstants used with the al module\nAvailability: IRIX.\nThis module defines symbolic constants needed to use the built-in\nmodule al (module-al.html) (see above); they are equivalent to those defined\nin the C header file `` except that the name prefix\n\"AL_\" is omitted. Read the module source for a complete list of\nthe defined names. Suggested use:", "python_version": "2.2", "length": 496, "url": "https://docs.python.org/2.2/lib/module-al-constants.html"} {"title": "20.1 al -- Audio functions on the SGI", "text": "sgi.html | sgi.html | al-config-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.1 al --\nAudio functions on the SGI\nAvailability: IRIX.\nThis module provides access to the audio facilities of the SGI Indy\nand Indigo workstations. See section 3A of the IRIX man pages for\ndetails. You'll need to read those man pages to understand what these\nfunctions do! Some of the functions are not available in IRIX\nreleases before 4.0.5. Again, see the manual to check whether a\nspecific function is available on your platform.\nAll functions and methods defined in this module are equivalent to\nthe C functions with \"AL\" prefixed to their name.\nSymbolic constants from the C header file `` are\ndefined in the standard module\nAL (module-al-constants.html), see below.\nWarning:\nThe current version of the audio library may dump core\nwhen bad argument values are passed rather than returning an error\nstatus. Unfortunately, since the precise circumstances under which\nthis may happen are undocumented and hard to check, the Python\ninterface can provide no protection against this kind of problems.\n(One example is specifying an excessive queue size -- there is no\ndocumented upper limit.)\nThe module defines the following functions:", "python_version": "2.2", "length": 1273, "url": "https://docs.python.org/2.2/lib/module-al.html"} {"title": "7.8 anydbm -- Generic access to DBM-style databases", "text": "module-mmap.html | someos.html | module-dumbdbm.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.8 anydbm --\nGeneric access to DBM-style databases\nanydbm is a generic interface to variants of the DBM\ndatabase -- dbhash (module-dbhash.html)(requires\nbsddb (module-bsddb.html)),\ngdbm (module-gdbm.html), or\ndbm (module-dbm.html). If none of these modules is\ninstalled, the slow-but-simple implementation in module\ndumbdbm (module-dumbdbm.html)will be used.\nThe object returned by open() supports most of the same\nfunctionality as dictionaries; keys and their corresponding values can\nbe stored, retrieved, and deleted, and the has_key() and\nkeys() methods are available. Keys and values must always be\nstrings.\nSee Also:", "python_version": "2.2", "length": 757, "url": "https://docs.python.org/2.2/lib/module-anydbm.html"} {"title": "5.9 array -- Efficient arrays of numeric values", "text": "bisect-example.html | misc.html | module-ConfigParser.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.9 array --\nEfficient arrays of numeric values\nThis module defines a new object type which can efficiently represent\nan array of basic values: characters, integers, floating point\nnumbers. Arraysare sequence types and behave very much\nlike lists, except that the type of objects stored in them is\nconstrained. The type is specified at object creation time by using a\ntype code, which is a single character. The following type\ncodes are defined:\nThe actual representation of values is determined by the machine\narchitecture (strictly speaking, by the C implementation). The actual\nsize can be accessed through the itemsize attribute. The values\nstored for `'L'` and `'I'` items will be represented as\nPython long integers when retrieved, because Python's plain integer\ntype cannot represent the full range of C's unsigned (long) integers.\nThe module defines the following function and type object:\nArray objects support the following data items and methods:\nWhen an array object is printed or converted to a string, it is\nrepresented as `array( typecode , initializer )`. The\ninitializer is omitted if the array is empty, otherwise it is a\nstring if the typecode is `'c'`, otherwise it is a list of\nnumbers. The string is guaranteed to be able to be converted back to\nan array with the same type and value using reverse quotes\n(````), so long as the array() function has been\nimported using `from array import array`. Examples:\n```text\n\narray('l')\narray('c', 'hello world')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.14])\n```", "python_version": "2.2", "length": 1674, "url": "https://docs.python.org/2.2/lib/module-array.html"} {"title": "11.22 asyncore -- Asynchronous socket handler", "text": "simple-xmlrpc-servers.html | internet.html | asyncore-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.22 asyncore --\nAsynchronous socket handler\nThis module provides the basic infrastructure for writing asynchronous\nsocket service clients and servers.\nThere are only two ways to have a program on a single processor do\n``more than one thing at a time.'' Multi-threaded programming is the\nsimplest and most popular way to do it, but there is another very\ndifferent technique, that lets you have nearly all the advantages of\nmulti-threading, without actually using multiple threads. It's really\nonly practical if your program is largely I/O bound. If your program\nis processor bound, then pre-emptive scheduled threads are probably what\nyou really need. Network servers are rarely processor bound, however.\nIf your operating system supports the select() system call\nin its I/O library (and nearly all do), then you can use it to juggle\nmultiple communication channels at once; doing other work while your\nI/O is taking place in the ``background.'' Although this strategy can\nseem strange and complex, especially at first, it is in many ways\neasier to understand and control than multi-threaded programming.\nThe module documented here solves many of the difficult problems for\nyou, making the task of building sophisticated high-performance\nnetwork servers and clients a snap.\nThis set of user-level events is larger than the basics. The\nfull set of methods that can be overridden in your subclass are:\nIn addition, there are the basic methods needed to construct and\nmanipulate ``channels,'' which are what we will call the socket\nconnections in this context. Note that most of these are nearly\nidentical to their socket partners.", "python_version": "2.2", "length": 1777, "url": "https://docs.python.org/2.2/lib/module-asyncore.html"} {"title": "3.5 atexit -- Exit handlers", "text": "node41.html | python.html | atexit-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.5 atexit --\nExit handlers\nNew in version 2.0.\nThe atexit module defines a single function to register\ncleanup functions. Functions thus registered are automatically\nexecuted upon normal interpreter termination.\nNote: the functions registered via this module are not called when the program is killed by a\nsignal, when a Python fatal internal error is detected, or when\nos._exit() is called.\nThis is an alternate interface to the functionality provided by the\n`sys.exitfunc` variable.\nNote: This module is unlikely to work correctly when used with other code\nthat sets `sys.exitfunc`. In particular, other core Python modules are\nfree to use atexit without the programmer's knowledge. Authors who\nuse `sys.exitfunc` should convert their code to use\natexit instead. The simplest way to convert code that sets\n`sys.exitfunc` is to import atexit and register the function\nthat had been bound to `sys.exitfunc`.\nSee Also:", "python_version": "2.2", "length": 1047, "url": "https://docs.python.org/2.2/lib/module-atexit.html"} {"title": "14.1 audioop -- Manipulate raw audio data", "text": "mmedia.html | mmedia.html | module-imageop.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.1 audioop --\nManipulate raw audio data\nThe audioop module contains some useful operations on sound\nfragments. It operates on sound fragments consisting of signed\ninteger samples 8, 16 or 32 bits wide, stored in Python strings. This\nis the same format as used by the al (module-al.html) and sunaudiodev (module-sunaudiodev.html)\nmodules. All scalar items are integers, unless specified otherwise.\nThis module provides support for u-LAW and Intel/DVI ADPCM encodings.\nA few of the more complicated operations only take 16-bit samples,\notherwise the sample size (in bytes) is always a parameter of the\noperation.\nThe module defines the following variables and functions:\nNote that operations such as mul() or max() make\nno distinction between mono and stereo fragments, i.e. all samples\nare treated equal. If this is a problem the stereo fragment should be\nsplit into two mono fragments first and recombined later. Here is an\nexample of how to do that:\n```text\n\ndef mul_stereo(sample, width, lfactor, rfactor):\nlsample = audioop.tomono(sample, width, 1, 0)\nrsample = audioop.tomono(sample, width, 0, 1)\nlsample = audioop.mul(sample, width, lfactor)\nrsample = audioop.mul(sample, width, rfactor)\nlsample = audioop.tostereo(lsample, width, 1, 0)\nrsample = audioop.tostereo(rsample, width, 0, 1)\nreturn audioop.add(lsample, rsample, width)\n```\nIf you use the ADPCM coder to build network packets and you want your\nprotocol to be stateless (i.e. to be able to tolerate packet loss)\nyou should not only transmit the data but also the state. Note that\nyou should send the initial state (the one you passed to\nlin2adpcm()) along to the decoder, not the final state (as\nreturned by the coder). If you want to use struct.struct()\nto store the state in binary you can code the first element (the\npredicted value) in 16 bits and the second (the delta index) in 8.\nThe ADPCM coders have never been tried against other ADPCM coders,\nonly against themselves. It could well be that I misinterpreted the\nstandards in which case they will not be interoperable with the\nrespective standards.\nThe find*() routines might look a bit funny at first sight.\nThey are primarily meant to do echo cancellation. A reasonably\nfast way to do this is to pick the most energetic piece of the output\nsample, locate that in the input sample and subtract the whole output\nsample from the input sample:", "python_version": "2.2", "length": 2495, "url": "https://docs.python.org/2.2/lib/module-audioop.html"} {"title": "12.12 base64 -- Encode and decode MIME base64 data", "text": "addresslist-objects.html | netdata.html | module-binascii.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.12 base64 --\nEncode and decode MIME base64 data\nThis module performs base64 encoding and decoding of arbitrary binary\nstrings into text strings that can be safely sent by email or included\nas part of an HTTP POST request. The\nencoding scheme is defined in RFC 1521 (http://www.faqs.org/rfcs/rfc1521.html) (MIME\n(Multipurpose Internet Mail Extensions) Part One: Mechanisms for\nSpecifying and Describing the Format of Internet Message Bodies,\nsection 5.2, ``Base64 Content-Transfer-Encoding'') and is used for\nMIME email and various other Internet-related applications; it is not\nthe same as the output produced by the uuencode program.\nFor example, the string `'www.python.org'` is encoded as the\nstring `'d3d3LnB5dGhvbi5vcmc=\\n'`.", "python_version": "2.2", "length": 877, "url": "https://docs.python.org/2.2/lib/module-base64.html"} {"title": "11.16 BaseHTTPServer -- Basic HTTP server", "text": "module-SocketServer.html | internet.html | module-SimpleHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.16 BaseHTTPServer --\nBasic HTTP server\nThis module defines two classes for implementing HTTP servers\n(Web servers). Usually, this module isn't used directly, but is used\nas a basis for building functioning Web servers. See the\nSimpleHTTPServerand\nCGIHTTPServer (module-CGIHTTPServer.html)modules.\nThe first class, HTTPServer, is a\nSocketServer.TCPServer subclass. It creates and listens at the\nHTTP socket, dispatching the requests to a handler. Code to create and\nrun the server looks like this:\n```text\n\ndef run(server_class=BaseHTTPServer.HTTPServer,\nhandler_class=BaseHTTPServer.BaseHTTPRequestHandler):\nserver_address = ('', 8000)\nhttpd = server_class(server_address, handler_class)\nhttpd.serve_forever()\n```\nBaseHTTPRequestHandler has the following instance variables:\nBaseHTTPRequestHandler has the following class variables:\nA BaseHTTPRequestHandler instance has the following methods:", "python_version": "2.2", "length": 1049, "url": "https://docs.python.org/2.2/lib/module-BaseHTTPServer.html"} {"title": "17.2 Bastion -- Restricting access to objects", "text": "node547.html | restricted.html | language.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 17.2 Bastion --\nRestricting access to objects\nAccording to the dictionary, a bastion is ``a fortified area or\nposition'', or ``something that is considered a stronghold.'' It's a\nsuitable name for this module, which provides a way to forbid access\nto certain attributes of an object. It must always be used with the\nrexec (module-rexec.html) module, in order to allow restricted-mode programs\naccess to certain safe attributes of an object, while denying access\nto other, unsafe attributes.", "python_version": "2.2", "length": 618, "url": "https://docs.python.org/2.2/lib/module-Bastion.html"} {"title": "12.13 binascii -- Convert between binary and ASCII", "text": "module-base64.html | netdata.html | module-binhex.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.13 binascii --\nConvert between binary and ASCII\nThe binascii module contains a number of methods to convert\nbetween binary and various ASCII-encoded binary\nrepresentations. Normally, you will not use these functions directly\nbut use wrapper modules like uu (module-uu.html)or\nbinhex (module-binhex.html)instead, this module solely\nexists because bit-manipulation of large amounts of data is slow in\nPython.\nThe binascii module defines the following functions:", "python_version": "2.2", "length": 598, "url": "https://docs.python.org/2.2/lib/module-binascii.html"} {"title": "12.14 binhex -- Encode and decode binhex4 files", "text": "module-binascii.html | netdata.html | binhex-notes.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.14 binhex --\nEncode and decode binhex4 files\nThis module encodes and decodes files in binhex4 format, a format\nallowing representation of Macintosh files in ASCII. On the Macintosh,\nboth forks of a file and the finder information are encoded (or\ndecoded), on other platforms only the data fork is handled.\nThe binhex module defines the following functions:\nSee Also:", "python_version": "2.2", "length": 506, "url": "https://docs.python.org/2.2/lib/module-binhex.html"} {"title": "5.8 bisect -- Array bisection algorithm", "text": "module-whrandom.html | misc.html | bisect-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.8 bisect --\nArray bisection algorithm\nThis module provides support for maintaining a list in sorted order\nwithout having to sort the list after each insertion. For long lists\nof items with expensive comparison operations, this can be an\nimprovement over the more common approach. The module is called\nbisect because it uses a basic bisection algorithm to do its\nwork. The source code may be most useful as a working example of the\nalgorithm (the boundary conditions are already right!).\nThe following functions are provided:", "python_version": "2.2", "length": 662, "url": "https://docs.python.org/2.2/lib/module-bisect.html"} {"title": "7.12 bsddb -- Interface to Berkeley DB library", "text": "module-whichdb.html | someos.html | bsddb-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.12 bsddb --\nInterface to Berkeley DB library\nAvailability: Unix, Windows.\nThe bsddb module provides an interface to the Berkeley DB\nlibrary. Users can create hash, btree or record based library files\nusing the appropriate open call. Bsddb objects behave generally like\ndictionaries. Keys and values must be strings, however, so to use\nother objects as keys or to store other kinds of objects the user must\nserialize them somehow, typically using marshal.dumps or pickle.dumps.\nThere are two incompatible versions of the underlying library.\nVersion 1.85 is widely available, but has some known bugs. Version 2\nis not quite as widely used, but does offer some improvements. The\nbsddb module uses the 1.85 interface. Starting with Python\n2.0, the configure script can usually determine the\nversion of the library which is available and build it correctly. If\nyou have difficulty getting configure to do the right thing,\nrun it with the --help option to get information about\nadditional options that can help. On Windows, you will need to define\nthe `HAVE_DB_185_H` macro if you are building Python from source\nand using version 2 of the DB library.\nThe bsddb module defines the following functions that create\nobjects that access the appropriate type of Berkeley DB file. The\nfirst two arguments of each function are the same. For ease of\nportability, only the first two arguments should be used in most\ninstances.\nSee Also:", "python_version": "2.2", "length": 1559, "url": "https://docs.python.org/2.2/lib/module-bsddb.html"} {"title": "3.29 __builtin__ -- Built-in functions", "text": "module-user.html | python.html | module-main.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.29 __builtin__ --\nBuilt-in functions", "python_version": "2.2", "length": 169, "url": "https://docs.python.org/2.2/lib/module-builtin.html"} {"title": "5.13 calendar -- General calendar-related functions", "text": "module-xreadlines.html | misc.html | module-cmd.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.13 calendar --\nGeneral calendar-related functions\nThis module allows you to output calendars like the Unix\ncal program, and provides additional useful functions\nrelated to the calendar. By default, these calendars have Monday as\nthe first day of the week, and Sunday as the last (the European\nconvention). Use setfirstweekday() to set the first day of the\nweek to Sunday (6) or to any other weekday. Parameters that specify\ndates are given as integers.", "python_version": "2.2", "length": 588, "url": "https://docs.python.org/2.2/lib/module-calendar.html"} {"title": "20.3 cd -- CD-ROM access on SGI systems", "text": "module-al-constants.html | sgi.html | player-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.3 cd --\nCD-ROM access on SGI systems\nAvailability: IRIX.\nThis module provides an interface to the Silicon Graphics CD library.\nIt is available only on Silicon Graphics systems.\nThe way the library works is as follows. A program opens the CD-ROM\ndevice with open() and creates a parser to parse the data\nfrom the CD with createparser(). The object returned by\nopen() can be used to read data from the CD, but also to get\nstatus information for the CD-ROM device, and to get information about\nthe CD, such as the table of contents. Data from the CD is passed to\nthe parser, which parses the frames, and calls any callback\nfunctions that have previously been added.\nAn audio CD is divided into tracks or programs (the terms\nare used interchangeably). Tracks can be subdivided into\nindices. An audio CD contains a table of contents which\ngives the starts of the tracks on the CD. Index 0 is usually the\npause before the start of a track. The start of the track as given by\nthe table of contents is normally the start of index 1.\nPositions on a CD can be represented in two ways. Either a frame\nnumber or a tuple of three values, minutes, seconds and frames. Most\nfunctions use the latter representation. Positions can be both\nrelative to the beginning of the CD, and to the beginning of the\ntrack.\nModule cd defines the following functions and constants:\nThe module defines the following variables:\nThe following variables are states as returned by\ngetstatus():", "python_version": "2.2", "length": 1599, "url": "https://docs.python.org/2.2/lib/module-cd.html"} {"title": "11.2 cgi -- Common Gateway Interface support.", "text": "browser-controllers.html | internet.html | cgi-intro.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.2 cgi --\nCommon Gateway Interface support.\nSupport module for Common Gateway Interface (CGI) scripts.\nThis module defines a number of utilities for use by CGI scripts\nwritten in Python.", "python_version": "2.2", "length": 327, "url": "https://docs.python.org/2.2/lib/module-cgi.html"} {"title": "11.18 CGIHTTPServer -- CGI-capable HTTP request handler", "text": "module-SimpleHTTPServer.html | internet.html | module-Cookie.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.18 CGIHTTPServer --\nCGI-capable HTTP request handler\nThe CGIHTTPServer module defines a request-handler class,\ninterface compatible with\nBaseHTTPServer.BaseHTTPRequestHandler and inherits behavior\nfrom SimpleHTTPServer.SimpleHTTPRequestHandler but can also\nrun CGI scripts.\nNote:\nThis module can run CGI scripts on Unix and Windows systems;\non Mac OS it will only be able to run Python scripts within the same\nprocess as itself.\nThe CGIHTTPServer module defines the following class:\nThe CGIHTTPRequestHandler defines the following data member:\nThe CGIHTTPRequestHandler defines the following methods:\nNote that CGI scripts will be run with UID of user nobody, for security\nreasons. Problems with the CGI script will be translated to error 403.\nFor example usage, see the implementation of the test()\nfunction.", "python_version": "2.2", "length": 959, "url": "https://docs.python.org/2.2/lib/module-CGIHTTPServer.html"} {"title": "11.3 cgitb -- Traceback manager for CGI scripts", "text": "node303.html | internet.html | module-urllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.3 cgitb --\nTraceback manager for CGI scripts\nNew in version 2.2.\nThe cgitb module provides a special exception handler for CGI\nscripts. After this module is activated, if an uncaught exception occurs,\na detailed, formatted report will be sent to the Web browser. The report\nincludes a traceback showing excerpts of the source code for each level,\nas well as the values of the arguments and local variables to currently\nrunning functions, to help you debug the problem. Optionally, you can\nsave this information to a file instead of sending it to the browser.\nTo enable this feature, simply add one line to the top of your CGI script:\n```text\n\nimport cgitb; cgitb.enable()\n```\nThe options to the enable() function control whether the\nreport is displayed in the browser and whether the report is logged\nto a file for later analysis.", "python_version": "2.2", "length": 964, "url": "https://docs.python.org/2.2/lib/module-cgitb.html"} {"title": "14.6 chunk -- Read IFF chunked data", "text": "Wave-write-objects.html | mmedia.html | module-colorsys.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.6 chunk --\nRead IFF chunked data\nThis module provides an interface for reading files that use EA IFF 85\nchunks.14.1 (#foot44678) This format is used\nin at least the AudioInterchange File Format\n(AIFF/AIFF-C) and the RealMedia File\nFormat(RMFF). The WAVE audio file format is closely\nrelated and can also be read using this module.\nA chunk has the following structure:\nThe ID is a 4-byte string which identifies the type of chunk.\nThe size field (a 32-bit value, encoded using big-endian byte order)\ngives the size of the chunk data, not including the 8-byte header.\nUsually an IFF-type file consists of one or more chunks. The proposed\nusage of the Chunk class defined here is to instantiate an\ninstance at the start of each chunk and read from the instance until\nit reaches the end, after which a new instance can be instantiated.\nAt the end of the file, creating a new instance will fail with a\nEOFError exception.\nA Chunk object supports the following methods:\nThe remaining methods will raise IOError if called after\nthe close() method has been called.", "python_version": "2.2", "length": 1201, "url": "https://docs.python.org/2.2/lib/module-chunk.html"} {"title": "5.5 cmath -- Mathematical functions for complex numbers", "text": "module-math.html | misc.html | module-random.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.5 cmath --\nMathematical functions for complex numbers\nThis module is always available. It provides access to mathematical\nfunctions for complex numbers. The functions are:\nThe module also defines two mathematical constants:\nNote that the selection of functions is similar, but not identical, to\nthat in module math (module-math.html). The reason for having\ntwo modules is that some users aren't interested in complex numbers,\nand perhaps don't even know what they are. They would rather have\n`math.sqrt(-1)` raise an exception than return a complex number.\nAlso note that the functions defined in cmath always return a\ncomplex number, even if the answer can be expressed as a real number\n(in which case the complex number has an imaginary part of zero).\nA note on branch cuts: They are curves along which the given function\nfails to be continuous. They are a necessary feature of many complex\nfunctions. It is assumed that if you need to compute with complex\nfunctions, you will understand about branch cuts. Consult almost any\n(not too elementary) book on complex variables for enlightenment. For\ninformation of the proper choice of branch cuts for numerical\npurposes, a good reference should be the following:", "python_version": "2.2", "length": 1344, "url": "https://docs.python.org/2.2/lib/module-cmath.html"} {"title": "5.14 cmd -- Support for line-oriented command interpreters", "text": "module-calendar.html | misc.html | Cmd-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.14 cmd --\nSupport for line-oriented command interpreters\nThe Cmd class provides a simple framework for writing\nline-oriented command interpreters. These are often useful for\ntest harnesses, administrative tools, and prototypes that will\nlater be wrapped in a more sophisticated interface.", "python_version": "2.2", "length": 423, "url": "https://docs.python.org/2.2/lib/module-cmd.html"} {"title": "3.22 code -- Interpreter base classes", "text": "examples-imp.html | python.html | interpreter-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.22 code --\nInterpreter base classes\nThe `code` module provides facilities to implement\nread-eval-print loops in Python. Two classes and convenience\nfunctions are included which can be used to build applications which\nprovide an interactive interpreter prompt.", "python_version": "2.2", "length": 401, "url": "https://docs.python.org/2.2/lib/module-code.html"} {"title": "4.8 codecs -- Codec registry and base classes", "text": "module-cStringIO.html | strings.html | node113.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.8 codecs --\nCodec registry and base classes\nThis module defines base classes for standard Python codecs (encoders\nand decoders) and provides access to the internal Python codec\nregistry which manages the codec lookup process.\nIt defines the following functions:\nTo simply access to the various codecs, the module provides these\nadditional functions which use lookup() for the codec\nlookup:\nTo simplify working with encoded files or stream, the module\nalso defines these utility functions:\nThe module also provides the following constants which are useful\nfor reading and writing to platform dependent files:\nSee Also:", "python_version": "2.2", "length": 752, "url": "https://docs.python.org/2.2/lib/module-codecs.html"} {"title": "3.23 codeop -- Compile Python code", "text": "console-objects.html | python.html | module-pprint.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.23 codeop --\nCompile Python code\nThe codeop module provides utilities upon which the Python\nread-eval-print loop can be emulated, as is done in the\ncode (module-code.html) module. As a result, you probably don't want to use\nthe module directly; if you want to include such a loop in your\nprogram you probably want to use the code (module-code.html) module instead.\nThere are two parts to this job:\n1. Being able to tell if a line of input completes a Python\nstatement: in short, telling whether to print\n``> > >` or ``...`' next.\n2. Remembering which future statements the user has entered, so\nsubsequent input can be compiled with these in effect.\nThe codeop module provides a way of doing each of these\nthings, and a way of doing them both.\nTo do just the former:\nA note on version compatibility: the Compile and\nCommandCompiler are new in Python 2.2. If you want to enable\nthe future-tracking features of 2.2 but also retain compatibility with\n2.1 and earlier versions of Python you can either write\n```text\n\ntry:\nfrom codeop import CommandCompiler\ncompile_command = CommandCompiler()\ndel CommandCompiler\nexcept ImportError:\nfrom codeop import compile_command\n```\nwhich is a low-impact change, but introduces possibly unwanted global\nstate into your program, or you can write:\n```text\n\ntry:\nfrom codeop import CommandCompiler\nexcept ImportError:\ndef CommandCompiler():\nfrom codeop import compile_command\nreturn compile_comamnd\n```", "python_version": "2.2", "length": 1572, "url": "https://docs.python.org/2.2/lib/module-codeop.html"} {"title": "14.7 colorsys -- Conversions between color systems", "text": "module-chunk.html | mmedia.html | module-rgbimg.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.7 colorsys --\nConversions between color systems\nThe colorsys module defines bidirectional conversions of\ncolor values between colors expressed in the RGB (Red Green Blue)\ncolor space used in computer monitors and three other coordinate\nsystems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation\nValue). Coordinates in all of these color spaces are floating point\nvalues. In the YIQ space, the Y coordinate is between 0 and 1, but\nthe I and Q coordinates can be positive or negative. In all other\nspaces, the coordinates are all between 0 and 1.\nMore information about color spaces can be found at\nhttp://www.inforamp.net/%7epoynton/ColorFAQ.html.\nThe colorsys module defines the following functions:\nExample:", "python_version": "2.2", "length": 855, "url": "https://docs.python.org/2.2/lib/module-colorsys.html"} {"title": "8.18 commands -- Utilities for running commands", "text": "module-syslog.html | unix.html | module-pdb.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.18 commands --\nUtilities for running commands\nAvailability: Unix.\nThe commands module contains wrapper functions for\nos.popen() which take a system command as a string and\nreturn any output generated by the command and, optionally, the exit\nstatus.\nThe commands module defines the following functions:\nExample:\n```text\n\n>>> import commands\n>>> commands.getstatusoutput('ls /bin/ls')\n(0, '/bin/ls')\n>>> commands.getstatusoutput('cat /bin/junk')\n(256, 'cat: /bin/junk: No such file or directory')\n>>> commands.getstatusoutput('/bin/junk')\n(256, 'sh: /bin/junk: not found')\n>>> commands.getoutput('ls /bin/ls')\n'/bin/ls'\n>>> commands.getstatus('/bin/ls')\n'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'\n```", "python_version": "2.2", "length": 833, "url": "https://docs.python.org/2.2/lib/module-commands.html"} {"title": "18.9 compileall -- Byte-compile Python libraries", "text": "module-pycompile.html | language.html | module-dis.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.9 compileall --\nByte-compile Python libraries\nThis module provides some utility functions to support installing\nPython libraries. These functions compile Python source files in a\ndirectory tree, allowing users without permission to write to the\nlibraries to take advantage of cached byte-code files.\nThe source file for this module may also be used as a script to\ncompile Python sources in directories named on the command line or in\n`sys.path`.", "python_version": "2.2", "length": 585, "url": "https://docs.python.org/2.2/lib/module-compileall.html"} {"title": "19.3.1 AST Nodes", "text": "node574.html | node574.html | node576.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 19.3.1 AST Nodes\nThe compiler.ast module is generated from a text file that\ndescribes each node type and its elements. Each node type is\nrepresented as a class that inherits from the abstract base class\ncompiler.ast.Node and defines a set of named attributes for\nchild nodes.\nAll Node objects offer the following methods:\nTwo examples illustrate the general structure of Node\nclasses. The while statement is defined by the following\ngrammar production:\n```text\n\nwhile_stmt: \"while\" expression \":\" suite\n[\"else\" \":\" suite]\n```\nThe While node has three attributes: test,\nbody, and else_. (If the natural name for an\nattribute is also a Python reserved word, it can't be used as an\nattribute name. An underscore is appended to the word to make it a\nlegal identifier, hence else_ instead of else.)\nThe if statement is more complicated because it can include\nseveral tests.\n```text\n\nif_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]\n```\nThe If node only defines two attributes: tests and\nelse_. The tests attribute is a sequence of test\nexpression, consequent body pairs. There is one pair for each\nif/elif clause. The first element of the pair is\nthe test expression. The second elements is a Stmt node that\ncontains the code to execute if the test is true.\nThe getChildren() method of If returns a flat list of\nchild nodes. If there are three if/elif clauses\nand no else clause, then getChildren() will return\na list of six elements: the first test expression, the first\nStmt, the second text expression, etc.\nThe following table lists each of the Node subclasses defined\nin compiler.ast and each of the public attributes available\non their instances. The values of most of the attributes are\nthemselves Node instances or sequences of instances. When the\nvalue is something other than an instance, the type is noted in the\ncomment. The attributes are listed in the order in which they are\nreturned by getChildren() and getChildNodes().", "python_version": "2.2", "length": 2080, "url": "https://docs.python.org/2.2/lib/module-compiler.ast.html"} {"title": "19.1 The basic interface", "text": "compiler.html | compiler.html | node573.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 19.1 The basic interface\nThe top-level of the package defines four functions. If you import\ncompiler, you will get these functions and a collection of\nmodules contained in the package.\nThe compiler package contains the following modules:\nast (module-compiler.ast.html), consts, future,\nmisc, pyassem, pycodegen, symbols,\ntransformer, and visitor (module-compiler.visitor.html).", "python_version": "2.2", "length": 503, "url": "https://docs.python.org/2.2/lib/module-compiler.html"} {"title": "19.4 Using Visitors to Walk ASTs", "text": "node577.html | compiler.html | node579.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 19.4 Using Visitors to Walk ASTs\nThe visitor pattern is ... The compiler (module-compiler.html) package uses a\nvariant on the visitor pattern that takes advantage of Python's\nintrospection features to elminiate the need for much of the visitor's\ninfrastructure.\nThe classes being visited do not need to be programmed to accept\nvisitors. The visitor need only define visit methods for classes it\nis specifically interested in; a default visit method can handle the\nrest.\nXXX The magic visit() method for visitors.\nASTVisitor objects have the following methods:\nXXX describe extra arguments", "python_version": "2.2", "length": 713, "url": "https://docs.python.org/2.2/lib/module-compiler.visitor.html"} {"title": "5.10 ConfigParser -- Configuration file parser", "text": "module-array.html | misc.html | ConfigParser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.10 ConfigParser --\nConfiguration file parser\nThis module defines the class ConfigParser.\nThe ConfigParser class implements a basic configuration file\nparser language which provides a structure similar to what you would\nfind on Microsoft Windows INI files. You can use this to write Python\nprograms which can be customized by end users easily.\nThe configuration file consists of sections, lead by a\n\"[section]\" header and followed by \"name: value\" entries,\nwith continuations in the style of RFC 822 (http://www.faqs.org/rfcs/rfc822.html); \"name=value\" is\nalso accepted. Note that leading whitespace is removed from values.\nThe optional values can contain format strings which refer to other\nvalues in the same section, or values in a special\n`DEFAULT` section. Additional defaults can be provided upon\ninitialization and retrieval. Lines beginning with \"#\" or\n\";\" are ignored and may be used to provide comments.\nFor example:\n```text\n\nfoodir: %(dir)s/whatever\ndir=frob\n```\nwould resolve the \"%(dir)s\" to the value of\n\"dir\" (\"frob\" in this case). All reference expansions are\ndone on demand.\nDefault values can be specified by passing them into the\nConfigParser constructor as a dictionary. Additional defaults\nmay be passed into the get() method which will override all\nothers.\nSee Also:", "python_version": "2.2", "length": 1428, "url": "https://docs.python.org/2.2/lib/module-ConfigParser.html"} {"title": "11.19 Cookie -- HTTP state management", "text": "module-CGIHTTPServer.html | internet.html | cookie-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.19 Cookie --\nHTTP state management\nThe Cookie module defines classes for abstracting the concept of\ncookies, an HTTP state management mechanism. It supports both simple\nstring-only cookies, and provides an abstraction for having any serializable\ndata-type as cookie value.\nThe module formerly strictly applied the parsing rules described in in\nthe RFC 2109 (http://www.faqs.org/rfcs/rfc2109.html) and RFC 2068 (http://www.faqs.org/rfcs/rfc2068.html) specifications. It has since been discovered\nthat MSIE 3.0x doesn't follow the character rules outlined in those\nspecs. As a result, the parsing rules used are a bit less strict.\nA further security note is warranted. For backwards compatibility,\nthe Cookie module exports a class named Cookie which\nis just an alias for SmartCookie. This is probably a mistake\nand will likely be removed in a future version. You should not use\nthe Cookie class in your applications, for the same reason why\nyou should not use the SerialCookie class.\nSee Also:", "python_version": "2.2", "length": 1140, "url": "https://docs.python.org/2.2/lib/module-Cookie.html"} {"title": "3.18 copy -- Shallow and deep copy operations", "text": "module-shelve.html | python.html | module-marshal.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.18 copy --\nShallow and deep copy operations\nThis module provides generic (shallow and deep) copying operations.\nInterface summary:\n```text\n\nimport copy\n\nx = copy.copy(y) # make a shallow copy of y\nx = copy.deepcopy(y) # make a deep copy of y\n```\nFor module specific errors, copy.error is raised.\nThe difference between shallow and deep copying is only relevant for\ncompound objects (objects that contain other objects, like lists or\nclass instances):\n- A shallow copy constructs a new compound object and then (to the\nextent possible) inserts references into it to the objects found\nin the original.\n- A deep copy constructs a new compound object and then,\nrecursively, inserts copies into it of the objects found in the\noriginal.\nTwo problems often exist with deep copy operations that don't exist\nwith shallow copy operations:\n- Recursive objects (compound objects that, directly or indirectly,\ncontain a reference to themselves) may cause a recursive loop.\n- Because deep copy copies everything it may copy too much,\ne.g., administrative data structures that should be shared even\nbetween copies.\nThe deepcopy() function avoids these problems by:\n- keeping a ``memo'' dictionary of objects already copied during the current\ncopying pass; and\n- letting user-defined classes override the copying operation or the\nset of components copied.\nThis version does not copy types like module, class, function, method,\nstack trace, stack frame, file, socket, window, array, or any similar\ntypes.\nClasses can use the same interfaces to control copying that they use\nto control pickling: they can define methods called\n__getinitargs__(), __getstate__() and\n__setstate__(). See the description of module\npickle (module-pickle.html)for information on these\nmethods. The copy module does not use the\ncopy_reg (module-copyreg.html) registration module.\nIn order for a class to define its own copy implementation, it can\ndefine special methods __copy__() and\n__deepcopy__(). The former is called to implement the\nshallow copy operation; no additional arguments are passed. The\nlatter is called to implement the deep copy operation; it is passed\none argument, the memo dictionary. If the __deepcopy__()\nimplementation needs to make a deep copy of a component, it should\ncall the deepcopy() function with the component as first\nargument and the memo dictionary as second argument.", "python_version": "2.2", "length": 2501, "url": "https://docs.python.org/2.2/lib/module-copy.html"} {"title": "3.16 copy_reg -- Register pickle support functions", "text": "module-cPickle.html | python.html | module-shelve.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.16 copy_reg --\nRegister pickle support functions\nThe copy_reg module provides support for the\npickle (module-pickle.html)and\ncPickle (module-cPickle.html)modules. The\ncopy (module-copy.html)module is likely to use this in the\nfuture as well. It provides configuration information about object\nconstructors which are not classes. Such constructors may be factory\nfunctions or class instances.", "python_version": "2.2", "length": 529, "url": "https://docs.python.org/2.2/lib/module-copyreg.html"} {"title": "3.15 cPickle -- A faster pickle", "text": "pickle-example.html | python.html | module-copyreg.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.15 cPickle -- A faster pickle\nThe cPickle module supports serialization and\nde-serialization of Python objects, providing an interface and\nfunctionality nearly identical to the\npickle (module-pickle.html)module. There are several\ndifferences, the most important being performance and subclassability.\nFirst, cPickle can be up to 1000 times faster than\npickle because the former is implemented in C. Second, in\nthe cPickle module the callables Pickler() and\nUnpickler() are functions, not classes. This means that\nyou cannot use them to derive custom pickling and unpickling\nsubclasses. Most applications have no need for this functionality and\nshould benefit from the greatly improved performance of the\ncPickle module.\nThe pickle data stream produced by pickle and\ncPickle are identical, so it is possible to use\npickle and cPickle interchangeably with existing\npickles3.13 (#foot6907).\nThere are additional minor differences in API between cPickle\nand pickle, however for most applications, they are\ninterchangable. More documentation is provided in the\npickle module documentation, which\nincludes a list of the documented differences.", "python_version": "2.2", "length": 1276, "url": "https://docs.python.org/2.2/lib/module-cPickle.html"} {"title": "8.4 crypt -- Function to check Unix passwords", "text": "module-grp.html | unix.html | module-dl.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.4 crypt --\nFunction to check Unix passwords\nAvailability: Unix.\nThis module implements an interface to the\ncrypt(3)routine, which is a one-way hash\nfunction based upon a modified DESalgorithm; see\nthe Unix man page for further details. Possible uses include\nallowing Python scripts to accept typed passwords from the user, or\nattempting to crack Unix passwords with a dictionary.\nA simple example illustrating typical use:", "python_version": "2.2", "length": 550, "url": "https://docs.python.org/2.2/lib/module-crypt.html"} {"title": "4.7 cStringIO -- Faster version of StringIO", "text": "module-StringIO.html | strings.html | module-codecs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.7 cStringIO --\nFaster version of StringIO\nThe module cStringIO provides an interface similar to that of\nthe StringIO (module-StringIO.html) module. Heavy use of StringIO.StringIO\nobjects can be made more efficient by using the function\nStringIO() from this module instead.\nSince this module provides a factory function which returns objects of\nbuilt-in types, there's no way to build your own version using\nsubclassing. Use the original StringIO (module-StringIO.html) module in that case.\nUnlike the memory files implemented by the StringIO (module-StringIO.html)\nmodule, those provided by this module are not able to accept Unicode\nstrings that cannot be encoded as plain ASCII strings.\nThe following data objects are provided as well:", "python_version": "2.2", "length": 877, "url": "https://docs.python.org/2.2/lib/module-cStringIO.html"} {"title": "6.16 curses.ascii -- Utilities for ASCII characters", "text": "module-curses.wrapper.html | allos.html | module-curses.panel.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.16 curses.ascii --\nUtilities for ASCII characters\nNew in version 1.6.\nThe curses.ascii module supplies name constants for\nASCII characters and functions to test membership in various\nASCII character classes. The constants supplied are names for\ncontrol characters as follows:\nNote that many of these have little practical significance in modern\nusage. The mnemonics derive from teleprinter conventions that predate\ndigital computers.\nThe module supplies the following functions, patterned on those in the\nstandard C library:\nThese functions accept either integers or strings; when the argument\nis a string, it is first converted using the built-in function\nord().\nNote that all these functions check ordinal bit values derived from the\nfirst character of the string you pass in; they do not actually know\nanything about the host machine's character encoding. For functions\nthat know about the character encoding (and handle\ninternationalization properly) see the string (module-string.html) module.\nThe following two functions take either a single-character string or\ninteger byte value; they return a value of the same type.\nThe following function takes either a single-character string or\ninteger value; it returns a string.", "python_version": "2.2", "length": 1376, "url": "https://docs.python.org/2.2/lib/module-curses.ascii.html"} {"title": "6.13 curses -- Terminal handling for character-cell displays", "text": "module-getpass.html | allos.html | curses-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.13 curses --\nTerminal handling for character-cell displays\nChanged in version 1.6:\nAdded support for the `ncurses` library and\nconverted to a package.\nThe curses module provides an interface to the curses\nlibrary, the de-facto standard for portable advanced terminal\nhandling.\nWhile curses is most widely used in the Unix environment, versions\nare available for DOS, OS/2, and possibly other systems as well. This\nextension module is designed to match the API of ncurses, an\nopen-source curses library hosted on Linux and the BSD variants of\nUnix.\nSee Also:\nThe Demo/curses/ directory in the Python source\ndistribution contains some example programs using the\ncurses bindings provided by this module.", "python_version": "2.2", "length": 840, "url": "https://docs.python.org/2.2/lib/module-curses.html"} {"title": "6.17 curses.panel -- A panel stack extension for curses.", "text": "module-curses.ascii.html | allos.html | cursespanel-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.17 curses.panel --\nA panel stack extension for curses.\nPanels are windows with the added feature of depth, so they can be\nstacked on top of each other, and only the visible portions of\neach window will be displayed. Panels can be added, moved up\nor down in the stack, and removed.", "python_version": "2.2", "length": 430, "url": "https://docs.python.org/2.2/lib/module-curses.panel.html"} {"title": "6.14 curses.textpad -- Text input widget for curses programs", "text": "node181.html | allos.html | curses-textpad-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.14 curses.textpad --\nText input widget for curses programs\nNew in version 1.6.\nThe curses.textpad module provides a Textbox class\nthat handles elementary text editing in a curses window, supporting a\nset of keybindings resembling those of Emacs (thus, also of Netscape\nNavigator, BBedit 6.x, FrameMaker, and many other programs). The\nmodule also provides a rectangle-drawing function useful for framing\ntext boxes or for other purposes.\nThe module curses.textpad defines the following function:", "python_version": "2.2", "length": 633, "url": "https://docs.python.org/2.2/lib/module-curses.textpad.html"} {"title": "6.15 curses.wrapper -- Terminal handler for curses programs", "text": "curses-textpad-objects.html | allos.html | module-curses.ascii.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.15 curses.wrapper --\nTerminal handler for curses programs\nNew in version 1.6.\nThis module supplies one function, wrapper(), which runs\nanother function which should be the rest of your curses-using\napplication. If the application raises an exception,\nwrapper() will restore the terminal to a sane state before\npassing it further up the stack and generating a traceback.", "python_version": "2.2", "length": 520, "url": "https://docs.python.org/2.2/lib/module-curses.wrapper.html"} {"title": "7.10 dbhash -- DBM-style interface to the BSD database library", "text": "module-dumbdbm.html | someos.html | dbhash-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.10 dbhash --\nDBM-style interface to the BSD database library\nAvailability: Unix, Windows.\nThe dbhash module provides a function to open databases using\nthe BSD `db` library. This module mirrors the interface of the\nother Python database modules that provide access to DBM-style\ndatabases. The bsddb (module-bsddb.html)module is required\nto use dbhash.\nThis module provides an exception and a function:\nSee Also:", "python_version": "2.2", "length": 550, "url": "https://docs.python.org/2.2/lib/module-dbhash.html"} {"title": "8.6 dbm -- Simple ``database'' interface", "text": "dl-objects.html | unix.html | module-gdbm.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.6 dbm --\nSimple ``database'' interface\nAvailability: Unix.\nThe dbm module provides an interface to the Unix\n(`n`)`dbm` library. Dbm objects behave like mappings\n(dictionaries), except that keys and values are always strings.\nPrinting a dbm object doesn't print the keys and values, and the\nitems() and values() methods are not supported.\nThis module can be used with the ``classic'' ndbm interface, the BSD\nDB compatibility interface, or the GNU GDBM compatibility interface.\nOn Unix, the configure script will attempt to locate the\nappropriate header file to simplify building this module.\nThe module defines the following:", "python_version": "2.2", "length": 754, "url": "https://docs.python.org/2.2/lib/module-dbm.html"} {"title": "20.9 DEVICE -- Constants used with the gl module", "text": "module-gl.html | sgi.html | module-gl-constants.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.9 DEVICE --\nConstants used with the gl module\nAvailability: IRIX.\nThis modules defines the constants used by the Silicon Graphics\nGraphics Library that C programmers find in the header file\n``.\nRead the module source file for details.", "python_version": "2.2", "length": 384, "url": "https://docs.python.org/2.2/lib/module-DEVICE.html"} {"title": "4.4 difflib -- Helpers for computing deltas", "text": "module-struct.html | strings.html | sequence-matcher.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.4 difflib --\nHelpers for computing deltas\nNew in version 2.1.\nSee Also:", "python_version": "2.2", "length": 212, "url": "https://docs.python.org/2.2/lib/module-difflib.html"} {"title": "6.3 dircache -- Cached directory listings", "text": "module-os.path.html | allos.html | module-stat.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.3 dircache --\nCached directory listings\nThe dircache module defines a function for reading directory listing\nusing a cache, and cache invalidation using the mtime of the directory.\nAdditionally, it defines a function to annotate directories by appending\na slash.\nThe dircache module defines the following functions:", "python_version": "2.2", "length": 450, "url": "https://docs.python.org/2.2/lib/module-dircache.html"} {"title": "18.10 dis -- Disassembler for Python byte code", "text": "module-compileall.html | language.html | bytecodes.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.10 dis --\nDisassembler for Python byte code\nThe dis module supports the analysis of Python byte code by\ndisassembling it. Since there is no Python assembler, this module\ndefines the Python assembly language. The Python byte code which\nthis module takes as an input is defined in the file\nInclude/opcode.h and used by the compiler and the interpreter.\nExample: Given the function myfunc:\n```text\n\ndef myfunc(alist):\nreturn len(alist)\n```\nthe following command can be used to get the disassembly of\nmyfunc():\n```text\n\n>>> dis.dis(myfunc)\n0 SET_LINENO 1\n\n3 SET_LINENO 2\n6 LOAD_GLOBAL 0 (len)\n9 LOAD_FAST 0 (alist)\n12 CALL_FUNCTION 1\n15 RETURN_VALUE\n16 LOAD_CONST 0 (None)\n19 RETURN_VALUE\n```\nThe dis module defines the following functions and constants:", "python_version": "2.2", "length": 890, "url": "https://docs.python.org/2.2/lib/module-dis.html"} {"title": "18.11 distutils -- Building and installing Python modules", "text": "bytecodes.html | language.html | compiler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.11 distutils --\nBuilding and installing Python modules\nThe distutils package provides support for building and\ninstalling additional modules into a Python installation. The new\nmodules may be either 100%-pure Python, or may be extension modules\nwritten in C, or may be collections of Python packages which include\nmodules coded in both Python and C.\nThis package is discussed in two separate documents which are included\nin the Python documentation package. To learn about distributing new\nmodules using the distutils facilities, read\nDistributing Python Modules (../dist/dist.html). To learn\nabout installing Python modules, whether or not the author made use of\nthe distutils package, read\nInstalling Python Modules (../inst/inst.html).\nSee Also:", "python_version": "2.2", "length": 879, "url": "https://docs.python.org/2.2/lib/module-distutils.html"} {"title": "8.5 dl -- Call C functions in shared objects", "text": "module-crypt.html | unix.html | dl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.5 dl --\nCall C functions in shared objects\nAvailability: Unix.\nThe dl module defines an interface to the\ndlopen() function, which is the most common interface on\nUnix platforms for handling dynamically linked libraries. It allows\nthe program to call arbitrary functions in such a library.\nNote:\nThis module will not work unless\n`sizeof(int) == sizeof(long) == sizeof(char *)`\nIf this is not the case, SystemError will be raised on\nimport.\nThe dl module defines the following function:\nThe dl module defines the following constants:\nThe dl module defines the following exception:\nExample:\n```text\n\n>>> import dl, time\n>>> a=dl.open('/lib/libc.so.6')\n>>> a.call('time'), time.time()\n(929723914, 929723914.498)\n```\nThis example was tried on a Debian GNU/Linux system, and is a good\nexample of the fact that using this module is usually a bad alternative.", "python_version": "2.2", "length": 982, "url": "https://docs.python.org/2.2/lib/module-dl.html"} {"title": "5.2 doctest -- Test docstrings represent reality", "text": "module-pydoc.html | misc.html | node123.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.2 doctest --\nTest docstrings represent reality\nThe doctest module searches a module's docstrings for text that looks\nlike an interactive Python session, then executes all such sessions to verify\nthey still work exactly as shown. Here's a complete but small example:\n```text\n\n\"\"\"\nThis is module example.\n\nExample supplies one function, factorial. For example,\n\n>>> factorial(5)\n120\n\"\"\"\n\ndef factorial(n):\n\"\"\"Return the factorial of n, an exact integer >= 0.\n\nIf the result is small enough to fit in an int, return an int.\nElse return a long.\n\n>>> [factorial(n) for n in range(6)]\n[1, 1, 2, 6, 24, 120]\n>>> [factorial(long(n)) for n in range(6)]\n[1, 1, 2, 6, 24, 120]\n>>> factorial(30)\n265252859812191058636308480000000L\n>>> factorial(30L)\n265252859812191058636308480000000L\n>>> factorial(-1)\nTraceback (most recent call last):\n...\nValueError: n must be >= 0\n\nFactorials of floats are OK, but the float must be an exact integer:\n>>> factorial(30.1)\nTraceback (most recent call last):\n...\nValueError: n must be exact integer\n>>> factorial(30.0)\n265252859812191058636308480000000L\n\nIt must also not be ridiculously large:\n>>> factorial(1e100)\nTraceback (most recent call last):\n...\nOverflowError: n too large\n\"\"\"\n```\n```text\n\nimport math\nif not n >= 0:\nraise ValueError(\"n must be >= 0\")\nif math.floor(n) != n:\nraise ValueError(\"n must be exact integer\")\nif n+1 == n: # e.g., 1e300\nraise OverflowError(\"n too large\")\nresult = 1\nfactor = 2\nwhile factor <= n:\ntry:\nresult *= factor\nexcept OverflowError:\nresult *= long(factor)\nfactor += 1\nreturn result\n\ndef _test():\nimport doctest, example\nreturn doctest.testmod(example)\n\nif __name__ == \"__main__\":\n_test()\n```\nIf you run example.py directly from the command line, doctest works\nits magic:\n```text\n\n$ python example.py\n$\n```\nThere's no output! That's normal, and it means all the examples worked.\nPass -v to the script, and doctest prints a detailed log\nof what it's trying, and prints a summary at the end:\n```text\n\n$ python example.py -v\nRunning example.__doc__\nTrying: factorial(5)\nExpecting: 120\nok\n0 of 1 examples failed in example.__doc__\nRunning example.factorial.__doc__\nTrying: [factorial(n) for n in range(6)]\nExpecting: [1, 1, 2, 6, 24, 120]\nok\nTrying: [factorial(long(n)) for n in range(6)]\nExpecting: [1, 1, 2, 6, 24, 120]\nok\nTrying: factorial(30)\nExpecting: 265252859812191058636308480000000L\nok\n```\nAnd so on, eventually ending with:\n```text\n\nTrying: factorial(1e100)\nExpecting:\nTraceback (most recent call last):\n...\nOverflowError: n too large\nok\n0 of 8 examples failed in example.factorial.__doc__\n2 items passed all tests:\n1 tests in example\n8 tests in example.factorial\n9 tests in 2 items.\n9 passed and 0 failed.\nTest passed.\n$\n```\nThat's all you need to know to start making productive use of doctest! Jump\nin. The docstrings in doctest.py contain detailed information about all\naspects of doctest, and we'll just cover the more important points here.", "python_version": "2.2", "length": 3045, "url": "https://docs.python.org/2.2/lib/module-doctest.html"} {"title": "7.9 dumbdbm -- Portable DBM implementation", "text": "module-anydbm.html | someos.html | module-dbhash.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.9 dumbdbm --\nPortable DBM implementation\nA simple and slow database implemented entirely in Python. This\nshould only be used when no other DBM-style database is available.", "python_version": "2.2", "length": 308, "url": "https://docs.python.org/2.2/lib/module-dumbdbm.html"} {"title": "12.2.5 Encoders", "text": "node383.html | module-email.html | module-email.Errors.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.5 Encoders\nWhen creating Message objects from scratch, you often need to\nencode the payloads for transport through compliant mail servers.\nThis is especially true for image/* and text/*\ntype messages containing binary data.\nThe email package provides some convenient encodings in its\nEncoders module. These encoders are actually used by the\nMIMEImage and MIMEText class constructors to provide default\nencodings. All encoder functions take exactly one argument, the\nmessage object to encode. They usually extract the payload, encode\nit, and reset the payload to this newly encoded value. They should also\nset the Content-Transfer-Encoding: header as appropriate.\nHere are the encoding functions provided:", "python_version": "2.2", "length": 851, "url": "https://docs.python.org/2.2/lib/module-email.Encoders.html"} {"title": "12.2.6 Exception classes", "text": "module-email.Encoders.html | module-email.html | module-email.Utils.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.6 Exception classes\nThe following exception classes are defined in the\nemail.Errors module:", "python_version": "2.2", "length": 251, "url": "https://docs.python.org/2.2/lib/module-email.Errors.html"} {"title": "12.2.3 Generating MIME documents", "text": "node381.html | module-email.html | node383.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.3 Generating MIME documents\nOne of the most common tasks is to generate the flat text of the email\nmessage represented by a message object tree. You will need to do\nthis if you want to send your message via the smtplib (module-smtplib.html)\nmodule or the nntplib (module-nntplib.html) module, or print the message on the\nconsole. Taking a message object tree and producing a flat text\ndocument is the job of the Generator class.\nAgain, as with the email.Parser (module-email.Parser.html) module, you aren't limited\nto the functionality of the bundled generator; you could write one\nfrom scratch yourself. However the bundled generator knows how to\ngenerate most email in a standards-compliant way, should handle MIME\nand non-MIME email messages just fine, and is designed so that the\ntransformation from flat text, to an object tree via the\nParser class,\nand back to flat text, is idempotent (the input is identical to the\noutput).\nHere are the public methods of the Generator class:\nThe other public Generator methods are:\nAs a convenience, see the methods Message.as_string() and\n`str(aMessage)`, a.k.a. Message.__str__(), which\nsimplify the generation of a formatted string representation of a\nmessage object. For more detail, see email.Message (module-email.Message.html).", "python_version": "2.2", "length": 1411, "url": "https://docs.python.org/2.2/lib/module-email.Generator.html"} {"title": "12.2 email -- An email and MIME handling package", "text": "writer-impls.html | netdata.html | module-email.Message.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.2 email --\nAn email and MIME handling package\nNew in version 2.2.\nThe email package is a library for managing email messages,\nincluding MIME and other RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html)-based message documents. It\nsubsumes most of the functionality in several older standard modules\nsuch as rfc822 (module-rfc822.html), mimetools (module-mimetools.html),\nmultifile (module-multifile.html), and other non-standard packages such as\nmimecntl. It is specifically not designed to do any\nsending of email messages to SMTP (RFC 2821 (http://www.faqs.org/rfcs/rfc2821.html)) servers; that is the\nfunction of the smtplib (module-smtplib.html) module12.1 (#foot35502).\nThe primary distinguishing feature of the email package is\nthat it splits the parsing and generating of email messages from the\ninternal object model representation of email. Applications\nusing the email package deal primarily with objects; you can\nadd sub-objects to messages, remove sub-objects from messages,\ncompletely re-arrange the contents, etc. There is a separate parser\nand a separate generator which handles the transformation from flat\ntext to the object model, and then back to flat text again. There\nare also handy subclasses for some common MIME object types, and a few\nmiscellaneous utilities that help with such common tasks as extracting\nand parsing message field values, creating RFC-compliant dates, etc.\nThe following sections describe the functionality of the\nemail package. The ordering follows a progression that\nshould be common in applications: an email message is read as flat\ntext from a file or other source, the text is parsed to produce an\nobject model representation of the email message, this model is\nmanipulated, and finally the model is rendered back into\nflat text.\nIt is perfectly feasible to create the object model out of whole cloth\n-- i.e. completely from scratch. From there, a similar progression\ncan be taken as above.\nAlso included are detailed specifications of all the classes and\nmodules that the email package provides, the exception\nclasses you might encounter while using the email package,\nsome auxiliary utilities, and a few examples. For users of the older\nmimelib package, from which the email package is\ndescended, a section on differences and porting is provided.\nSee Also:\n---\n#### Footnotes", "python_version": "2.2", "length": 2468, "url": "https://docs.python.org/2.2/lib/module-email.html"} {"title": "12.2.8 Iterators", "text": "module-email.Utils.html | module-email.html | node388.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.8 Iterators\nIterating over a message object tree is fairly easy with the\nMessage.walk() method. The email.Iterators module\nprovides some useful higher level iterations over message object\ntrees.", "python_version": "2.2", "length": 340, "url": "https://docs.python.org/2.2/lib/module-email.Iterators.html"} {"title": "12.2.1 Representing an email message", "text": "module-email.html | module-email.html | module-email.Parser.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.1 Representing an email message\nThe central class in the email package is the\nMessage class; it is the base class for the email\nobject model. Message provides the core functionality for\nsetting and querying header fields, and for accessing message bodies.\nConceptually, a Message object consists of headers and\npayloads. Headers are RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) style field names and\nvalues where the field name and value are separated by a colon. The\ncolon is not part of either the field name or the field value.\nHeaders are stored and returned in case-preserving form but are\nmatched case-insensitively. There may also be a single\nUnix-From header, also known as the envelope header or the\n`From_` header. The payload is either a string in the case of\nsimple message objects, a list of Message objects for\nmultipart MIME documents, or a single Message instance for\nmessage/rfc822 type objects.\nMessage objects provide a mapping style interface for\naccessing the message headers, and an explicit interface for accessing\nboth the headers and the payload. It provides convenience methods for\ngenerating a flat text representation of the message object tree, for\naccessing commonly used header parameters, and for recursively walking\nover the object tree.\nHere are the methods of the Message class:\nThe following methods implement a mapping-like interface for accessing\nthe message object's RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) headers. Note that there are some\nsemantic differences between these methods and a normal mapping\n(i.e. dictionary) interface. For example, in a dictionary there are\nno duplicate keys, but here there may be duplicate message headers. Also,\nin dictionaries there is no guaranteed order to the keys returned by\nkeys(), but in a Message object, there is an explicit\norder. These semantic differences are intentional and are biased\ntoward maximal convenience.\nNote that in all cases, any optional Unix-From header the message\nmay have is not included in the mapping interface.\nHere are some additional useful methods:\nMessage objects can also optionally contain two instance\nattributes, which can be used when generating the plain text of a MIME\nmessage.", "python_version": "2.2", "length": 2361, "url": "https://docs.python.org/2.2/lib/module-email.Message.html"} {"title": "12.2.2 Parsing email messages", "text": "module-email.Message.html | module-email.html | node380.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.2 Parsing email messages\nMessage object trees can be created in one of two ways: they can be\ncreated from whole cloth by instantiating Message objects and\nstringing them together via add_payload() and\nset_payload() calls, or they can be created by parsing a flat text\nrepresentation of the email message.\nThe email package provides a standard parser that understands\nmost email document structures, including MIME documents. You can\npass the parser a string or a file object, and the parser will return\nto you the root Message instance of the object tree. For\nsimple, non-MIME messages the payload of this root object will likely\nbe a string containing the text of the message. For MIME\nmessages, the root object will return true from its\nis_multipart() method, and the subparts can be accessed via\nthe get_payload() and walk() methods.\nNote that the parser can be extended in limited ways, and of course\nyou can implement your own parser completely from scratch. There is\nno magical connection between the email package's bundled\nparser and the Message class, so your custom parser can create\nmessage object trees in any way it find necessary.\nThe primary parser class is Parser which parses both the\nheaders and the payload of the message. In the case of\nmultipart messages, it will recursively parse the body of\nthe container message. The email.Parser module also provides\na second class, called HeaderParser which can be used if\nyou're only interested in the headers of the message.\nHeaderParser can be much faster in this situations, since it\ndoes not attempt to parse the message body, instead setting the\npayload to the raw body as a string. HeaderParser has the\nsame API as the Parser class.", "python_version": "2.2", "length": 1847, "url": "https://docs.python.org/2.2/lib/module-email.Parser.html"} {"title": "12.2.7 Miscellaneous utilities", "text": "module-email.Errors.html | module-email.html | module-email.Iterators.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.7 Miscellaneous utilities\nThere are several useful utilities provided with the email\npackage.", "python_version": "2.2", "length": 255, "url": "https://docs.python.org/2.2/lib/module-email.Utils.html"} {"title": "6.20 errno -- Standard errno system symbols", "text": "module-tempfile.html | allos.html | module-glob.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.20 errno --\nStandard errno system symbols\nThis module makes available standard `errno` system symbols.\nThe value of each symbol is the corresponding integer value.\nThe names and descriptions are borrowed from linux/include/errno.h,\nwhich should be pretty all-inclusive.\nTo translate a numeric error code to an error message, use\nos.strerror().\nOf the following list, symbols that are not used on the current\nplatform are not defined by the module. The specific list of defined\nsymbols is available as `errno.errorcode.keys()`. Symbols\navailable can include:", "python_version": "2.2", "length": 693, "url": "https://docs.python.org/2.2/lib/module-errno.html"} {"title": "2.3 Built-in Exceptions", "text": "specialattrs.html | builtin.html | python.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 2.3 Built-in Exceptions\nExceptions can be class objects or string objects. Though most\nexceptions have been string objects in past versions of Python, in\nPython 1.5 and newer versions, all standard exceptions have been\nconverted to class objects, and users are encouraged to do the same.\nThe exceptions are defined in the module exceptions. This\nmodule never needs to be imported explicitly: the exceptions are\nprovided in the built-in namespace as well as the exceptions\nmodule.\nTwo distinct string objects with the same value are considered different\nexceptions. This is done to force programmers to use exception names\nrather than their string value when specifying exception handlers.\nThe string value of all built-in exceptions is their name, but this is\nnot a requirement for user-defined exceptions or exceptions defined by\nlibrary modules.\nFor class exceptions, in a trystatement with\nan exceptclause that mentions a particular\nclass, that clause also handles any exception classes derived from\nthat class (but not exception classes from which it is\nderived). Two exception classes that are not related via subclassing\nare never equivalent, even if they have the same name.\nThe built-in exceptions listed below can be generated by the\ninterpreter or built-in functions. Except where mentioned, they have\nan ``associated value'' indicating the detailed cause of the error.\nThis may be a string or a tuple containing several items of\ninformation (e.g., an error code and a string explaining the code).\nThe associated value is the second argument to the\nraisestatement. For string exceptions, the\nassociated value itself will be stored in the variable named as the\nsecond argument of the except clause (if any). For class\nexceptions, that variable receives the exception instance. If the\nexception class is derived from the standard root class\nException, the associated value is present as the\nexception instance's args attribute, and possibly on other\nattributes as well.\nUser code can raise built-in exceptions. This can be used to test an\nexception handler or to report an error condition ``just like'' the\nsituation in which the interpreter raises the same exception; but\nbeware that there is nothing to prevent user code from raising an\ninappropriate error.\nThe built-in exception classes can be sub-classed to define new\nexceptions; programmers are encouraged to at least derive new\nexceptions from the Exception base class. More\ninformation on defining exceptions is available in the\nPython Tutorial (../tut/tut.html) under the heading\n``User-defined Exceptions.''\nThe following exceptions are only used as base classes for other\nexceptions.\nThe following exceptions are the exceptions that are actually raised.\nThe following exceptions are used as warning categories; see the\nwarnings module for more information.", "python_version": "2.2", "length": 2954, "url": "https://docs.python.org/2.2/lib/module-exceptions.html"} {"title": "8.12 fcntl -- The fcntl() and ioctl() system calls", "text": "module-pty.html | unix.html | module-pipes.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.12 fcntl --\nThe fcntl() and ioctl() system calls\nAvailability: Unix.\nThis module performs file control and I/O control on file descriptors.\nIt is an interface to the fcntl() and ioctl()\nUnix routines.\nAll functions in this module take a file descriptor fd as their\nfirst argument. This can be an integer file descriptor, such as\nreturned by `sys.stdin.fileno()`, or a file object, such as\n`sys.stdin` itself, which provides a fileno() which\nreturns a genuine file descriptor.\nThe module defines the following functions:\nExamples (all on a SVR4 compliant system):\n```text\n\nimport struct, fcntl\n\nfile = open(...)\nrv = fcntl(file, fcntl.F_SETFL, os.O_NDELAY)\n\nlockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)\nrv = fcntl.fcntl(file, fcntl.F_SETLKW, lockdata)\n```", "python_version": "2.2", "length": 903, "url": "https://docs.python.org/2.2/lib/module-fcntl.html"} {"title": "6.7 filecmp -- File and Directory Comparisons", "text": "module-statvfs.html | allos.html | dircmp-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.7 filecmp --\nFile and Directory Comparisons\nThe filecmp module defines functions to compare files and\ndirectories, with various optional time/correctness trade-offs.\nThe filecmp module defines the following functions:\nExample:\n```text\n\n>>> import filecmp\n>>> filecmp.cmp('libundoc.tex', 'libundoc.tex')\n1\n>>> filecmp.cmp('libundoc.tex', 'lib.tex')\n0\n```", "python_version": "2.2", "length": 491, "url": "https://docs.python.org/2.2/lib/module-filecmp.html"} {"title": "5.11 fileinput -- Iterate over lines from multiple input streams", "text": "ConfigParser-objects.html | misc.html | module-xreadlines.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.11 fileinput --\nIterate over lines from multiple input streams\nThis module implements a helper class and functions to quickly write a\nloop over standard input or a list of files.\nThe typical use is:\n```text\n\nimport fileinput\nfor line in fileinput.input():\nprocess(line)\n```\nThis iterates over the lines of all files listed in\n`sys.argv[1:]`, defaulting to `sys.stdin` if the list is\nempty. If a filename is `'-'`, it is also replaced by\n`sys.stdin`. To specify an alternative list of filenames, pass\nit as the first argument to input(). A single file name is\nalso allowed.\nAll files are opened in text mode. If an I/O error occurs during\nopening or reading a file, IOError is raised.\nIf `sys.stdin` is used more than once, the second and further use\nwill return no lines, except perhaps for interactive use, or if it has\nbeen explicitly reset (e.g. using `sys.stdin.seek(0)`).\nEmpty files are opened and immediately closed; the only time their\npresence in the list of filenames is noticeable at all is when the\nlast file opened is empty.\nIt is possible that the last line of a file does not end in a newline\ncharacter; lines are returned including the trailing newline when it\nis present.\nThe following function is the primary interface of this module:\nThe following functions use the global state created by\ninput(); if there is no active state,\nRuntimeError is raised.\nThe class which implements the sequence behavior provided by the\nmodule is available for subclassing as well:\nOptional in-place filtering: if the keyword argument\n`inplace =1` is passed to input() or to the\nFileInput constructor, the file is moved to a backup file and\nstandard output is directed to the input file (if a file of the same\nname as the backup file already exists, it will be replaced silently).\nThis makes it possible to write a filter that rewrites its input file\nin place. If the keyword argument `backup ='.'` is also given, it specifies the extension for the backup\nfile, and the backup file remains around; by default, the extension is\n`'.bak'` and it is deleted when the output file is closed. In-place\nfiltering is disabled when standard input is read.", "python_version": "2.2", "length": 2306, "url": "https://docs.python.org/2.2/lib/module-fileinput.html"} {"title": "20.5 FL -- Constants used with the fl module", "text": "forms-objects.html | sgi.html | module-flp.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.5 FL --\nConstants used with the fl module\nAvailability: IRIX.\nThis module defines symbolic constants needed to use the built-in\nmodule fl (module-fl.html) (see above); they are equivalent to those defined in\nthe C header file `` except that the name prefix\n\"FL_\" is omitted. Read the module source for a complete list of\nthe defined names. Suggested use:\n```text\n\nimport fl\nfrom FL import *\n```", "python_version": "2.2", "length": 535, "url": "https://docs.python.org/2.2/lib/module-fl-constants.html"} {"title": "20.4 fl -- FORMS library for graphical user interfaces", "text": "cd-parser-objects.html | sgi.html | node589.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.4 fl --\nFORMS library for graphical user interfaces\nAvailability: IRIX.\nThis module provides an interface to the FORMS Libraryby Mark Overmars. The source for the\nlibrary can be retrieved by anonymous ftp from host\n\"ftp.cs.ruu.nl\", directory SGI/FORMS. It was last tested\nwith version 2.0b.\nMost functions are literal translations of their C equivalents,\ndropping the initial \"fl_\" from their name. Constants used by\nthe library are defined in module FL (module-fl-constants.html)\ndescribed below.\nThe creation of objects is a little different in Python than in C:\ninstead of the `current form' maintained by the library to which new\nFORMS objects are added, all functions that add a FORMS object to a\nform are methods of the Python object representing the form.\nConsequently, there are no Python equivalents for the C functions\nfl_addto_form() and fl_end_form(), and the\nequivalent of fl_bgn_form() is called\nfl.make_form().\nWatch out for the somewhat confusing terminology: FORMS uses the word\nobject for the buttons, sliders etc. that you can place in a form.\nIn Python, `object' means any value. The Python interface to FORMS\nintroduces two new Python object types: form objects (representing an\nentire form) and FORMS objects (representing one button, slider etc.).\nHopefully this isn't too confusing.\nThere are no `free objects' in the Python interface to FORMS, nor is\nthere an easy way to add object classes written in Python. The FORMS\ninterface to GL event handling is available, though, so you can mix\nFORMS with pure GL windows.\nPlease note: importing fl implies a call to the GL\nfunction foreground() and to the FORMS routine\nfl_init().", "python_version": "2.2", "length": 1782, "url": "https://docs.python.org/2.2/lib/module-fl.html"} {"title": "20.6 flp -- Functions for loading stored FORMS designs", "text": "module-fl-constants.html | sgi.html | module-fm.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.6 flp --\nFunctions for loading stored FORMS designs\nAvailability: IRIX.\nThis module defines functions that can read form definitions created\nby the `form designer' (fdesign) program that comes with the\nFORMS library (see module fl (module-fl.html) above).\nFor now, see the file flp.doc in the Python library source\ndirectory for a description.", "python_version": "2.2", "length": 480, "url": "https://docs.python.org/2.2/lib/module-flp.html"} {"title": "20.7 fm -- Font Manager interface", "text": "module-flp.html | sgi.html | module-gl.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.7 fm --\nFont Manager interface\nAvailability: IRIX.\nThis module provides access to the IRIS Font Manager library.\nIt is available only on Silicon Graphics machines.\nSee also: 4Sight User's Guide, section 1, chapter 5: ``Using\nthe IRIS Font Manager.''\nThis is not yet a full interface to the IRIS Font Manager.\nAmong the unsupported features are: matrix operations; cache\noperations; character operations (use string operations instead); some\ndetails of font info; individual glyph metrics; and printer matching.\nIt supports the following operations:\nFont handle objects support the following operations:", "python_version": "2.2", "length": 730, "url": "https://docs.python.org/2.2/lib/module-fm.html"} {"title": "6.22 fnmatch -- Unix filename pattern matching", "text": "module-glob.html | allos.html | module-shutil.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.22 fnmatch --\nUnix filename pattern matching\nThis module provides support for Unix shell-style wildcards, which\nare not the same as regular expressions (which are documented\nin the re (module-re.html)module). The special\ncharacters used in shell-style wildcards are:\nNote that the filename separator (`'/'` on Unix) is not\nspecial to this module. See module\nglob (module-glob.html)for pathname expansion\n(glob (module-glob.html) uses fnmatch() to match pathname\nsegments). Similarly, filenames starting with a period are\nnot special for this module, and are matched by the `*` and\n`?` patterns.", "python_version": "2.2", "length": 728, "url": "https://docs.python.org/2.2/lib/module-fnmatch.html"} {"title": "12.1 formatter -- Generic output formatting", "text": "netdata.html | netdata.html | formatter-interface.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.1 formatter --\nGeneric output formatting\nThis module supports two interface definitions, each with multiple\nimplementations. The formatter interface is used by the\nHTMLParser class of the htmllib (module-htmllib.html) module, and the\nwriter interface is required by the formatter interface.\nFormatter objects transform an abstract flow of formatting events into\nspecific output events on writer objects. Formatters manage several\nstack structures to allow various properties of a writer object to be\nchanged and restored; writers need not be able to handle relative\nchanges nor any sort of ``change back'' operation. Specific writer\nproperties which may be controlled via formatter objects are\nhorizontal alignment, font, and left margin indentations. A mechanism\nis provided which supports providing arbitrary, non-exclusive style\nsettings to a writer as well. Additional interfaces facilitate\nformatting events which are not reversible, such as paragraph\nseparation.\nWriter objects encapsulate device interfaces. Abstract devices, such\nas file formats, are supported as well as physical devices. The\nprovided implementations all work with abstract devices. The\ninterface makes available mechanisms for setting the properties which\nformatter objects manage and inserting data into the output.", "python_version": "2.2", "length": 1432, "url": "https://docs.python.org/2.2/lib/module-formatter.html"} {"title": "3.4 fpectl -- Floating point exception control", "text": "weakref-extension.html | python.html | fpectl-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.4 fpectl --\nFloating point exception control\nAvailability: Unix.\nMost computers carry out floating point operationsin conformance with the so-called IEEE-754 standard.\nOn any real computer,\nsome floating point operations produce results that cannot\nbe expressed as a normal floating point value.\nFor example, try\n```text\n\n>>> import math\n>>> math.exp(1000)\ninf\n>>> math.exp(1000) / math.exp(1000)\nnan\n```\n(The example above will work on many platforms.\nDEC Alpha may be one exception.)\n\"Inf\" is a special, non-numeric value in IEEE-754 that\nstands for \"infinity\", and \"nan\" means \"not a number.\"\nNote that,\nother than the non-numeric results,\nnothing special happened when you asked Python\nto carry out those calculations.\nThat is in fact the default behaviour prescribed in the IEEE-754 standard,\nand if it works for you,\nstop reading now.\nIn some circumstances,\nit would be better to raise an exception and stop processing\nat the point where the faulty operation was attempted.\nThe fpectl module\nis for use in that situation.\nIt provides control over floating point\nunits from several hardware manufacturers,\nallowing the user to turn on the generation\nof SIGFPE whenever any of the\nIEEE-754 exceptions Division by Zero, Overflow, or\nInvalid Operation occurs.\nIn tandem with a pair of wrapper macros that are inserted\ninto the C code comprising your python system,\nSIGFPE is trapped and converted into the Python\nFloatingPointError exception.\nThe fpectl module defines the following functions and\nmay raise the given exception:", "python_version": "2.2", "length": 1671, "url": "https://docs.python.org/2.2/lib/module-fpectl.html"} {"title": "4.5 fpformat -- Floating point conversions", "text": "differ-examples.html | strings.html | module-StringIO.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.5 fpformat --\nFloating point conversions\nThe fpformat module defines functions for dealing with\nfloating point numbers representations in 100% pure\nPython. Note:\nThis module is unneeded: everything here could\nbe done via the `%` string interpolation operator.\nThe fpformat module defines the following functions and an\nexception:\nExample:", "python_version": "2.2", "length": 480, "url": "https://docs.python.org/2.2/lib/module-fpformat.html"} {"title": "11.7 ftplib -- FTP protocol client", "text": "httplib-examples.html | internet.html | ftp-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.7 ftplib --\nFTP protocol client\nThis module defines the class FTP and a few related items.\nThe FTP class implements the client side of the FTP\nprotocol. You can use this to write Python\nprograms that perform a variety of automated FTP jobs, such as\nmirroring other ftp servers. It is also used by the module\nurllib (module-urllib.html) to handle URLs that use FTP. For more information\non FTP (File Transfer Protocol), see Internet RFC 959 (http://www.faqs.org/rfcs/rfc959.html).\nHere's a sample session using the ftplib module:\n```text\n\n>>> from ftplib import FTP\n>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port\n>>> ftp.login() # user anonymous, passwd user@hostname\n>>> ftp.retrlines('LIST') # list directory contents\ntotal 24418\ndrwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .\ndr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..\n-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX\n.\n.\n.\n>>> ftp.retrbinary('RETR README', open('README', 'wb').write)\n'226 Transfer complete.'\n>>> ftp.quit()\n```\nThe module defines the following items:\nSee Also:\nThe file Tools/scripts/ftpmirror.py in the Python source distribution is a script that can mirror\nFTP sites, or portions thereof, using the ftplib module.\nIt can be used as an extended example that applies this module.", "python_version": "2.2", "length": 1419, "url": "https://docs.python.org/2.2/lib/module-ftplib.html"} {"title": "3.2 gc -- Garbage Collector interface", "text": "module-sys.html | python.html | module-weakref.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.2 gc --\nGarbage Collector interface\nThe gc module is only available if the interpreter was built\nwith the optional cyclic garbage detector (enabled by default). If\nthis was not enabled, an ImportError is raised by attempts\nto import this module.\nThis module provides an interface to the optional garbage collector. It\nprovides the ability to disable the collector, tune the collection\nfrequency, and set debugging options. It also provides access to\nunreachable objects that the collector found but cannot free. Since the\ncollector supplements the reference counting already used in Python, you\ncan disable the collector if you are sure your program does not create\nreference cycles. Automatic collection can be disabled by calling\n`gc.disable()`. To debug a leaking program call\n`gc.set_debug(gc.DEBUG_LEAK)`.\nThe gc module provides the following functions:\nThe following variable is provided for read-only access (you can\nmutate its value but should not rebind it):\nThe following constants are provided for use with\nset_debug():", "python_version": "2.2", "length": 1165, "url": "https://docs.python.org/2.2/lib/module-gc.html"} {"title": "8.7 gdbm -- GNU's reinterpretation of dbm", "text": "module-dbm.html | unix.html | module-termios.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.7 gdbm --\nGNU's reinterpretation of dbm\nAvailability: Unix.\nThis module is quite similar to the dbm (module-dbm.html)module, but uses `gdbm` instead to provide some additional\nfunctionality. Please note that the file formats created by\n`gdbm` and `dbm` are incompatible.\nThe gdbm module provides an interface to the GNU DBM\nlibrary. `gdbm` objects behave like mappings\n(dictionaries), except that keys and values are always strings.\nPrinting a `gdbm` object doesn't print the keys and values, and\nthe items() and values() methods are not supported.\nThe module defines the following constant and functions:\nIn addition to the dictionary-like methods, `gdbm` objects have the\nfollowing methods:", "python_version": "2.2", "length": 825, "url": "https://docs.python.org/2.2/lib/module-gdbm.html"} {"title": "6.18 getopt -- Parser for command line options", "text": "curses-panel-objects.html | allos.html | module-tempfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.18 getopt --\nParser for command line options\nThis module helps scripts to parse the command line arguments in\n`sys.argv`.\nIt supports the same conventions as the Unix getopt()\nfunction (including the special meanings of arguments of the form\n``-`' and ``-``-`').\nLong options similar to those supported by\nGNU software may be used as well via an optional third argument.\nThis module provides a single function and an exception:\nAn example using only Unix style options:\n```text\n\n>>> import getopt\n>>> args = '-a -b -cfoo -d bar a1 a2'.split()\n>>> args\n['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']\n>>> optlist, args = getopt.getopt(args, 'abc:d:')\n>>> optlist\n[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]\n>>> args\n['a1', 'a2']\n```\nUsing long option names is equally easy:\n```text\n\n>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'\n>>> args = s.split()\n>>> args\n['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']\n>>> optlist, args = getopt.getopt(args, 'x', [\n... 'condition=', 'output-file=', 'testing'])\n>>> optlist\n[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x',\n'')]\n>>> args\n['a1', 'a2']\n```\nIn a script, typical usage is something like this:", "python_version": "2.2", "length": 1380, "url": "https://docs.python.org/2.2/lib/module-getopt.html"} {"title": "6.12 getpass -- Portable password input", "text": "mutex-objects.html | allos.html | module-curses.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.12 getpass\n-- Portable password input\nThe getpass module provides two functions:", "python_version": "2.2", "length": 216, "url": "https://docs.python.org/2.2/lib/module-getpass.html"} {"title": "6.25 gettext -- Multilingual internationalization services", "text": "embedding-locale.html | allos.html | node200.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.25 gettext --\nMultilingual internationalization services\nThe gettext module provides internationalization (I18N) and\nlocalization (L10N) services for your Python modules and applications.\nIt supports both the GNU `gettext` message catalog API and a\nhigher level, class-based API that may be more appropriate for Python\nfiles. The interface described below allows you to write your\nmodule and application messages in one natural language, and provide a\ncatalog of translated messages for running under different natural\nlanguages.\nSome hints on localizing your Python modules and applications are also\ngiven.", "python_version": "2.2", "length": 740, "url": "https://docs.python.org/2.2/lib/module-gettext.html"} {"title": "20.10 GL -- Constants used with the gl module", "text": "module-DEVICE.html | sgi.html | module-imgfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.10 GL --\nConstants used with the gl module\nAvailability: IRIX.", "python_version": "2.2", "length": 198, "url": "https://docs.python.org/2.2/lib/module-gl-constants.html"} {"title": "20.8 gl -- Graphics Library interface", "text": "module-fm.html | sgi.html | module-DEVICE.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.8 gl --\nGraphics Library interface\nAvailability: IRIX.\nThis module provides access to the Silicon Graphics\nGraphics Library.\nIt is available only on Silicon Graphics machines.\nWarning:\nSome illegal calls to the GL library cause the Python\ninterpreter to dump core.\nIn particular, the use of most GL calls is unsafe before the first\nwindow is opened.\nThe module is too large to document here in its entirety, but the\nfollowing should help you to get started.\nThe parameter conventions for the C functions are translated to Python as\nfollows:\n- All (short, long, unsigned) int values are represented by Python\nintegers.\n- All float and double values are represented by Python floating point\nnumbers.\nIn most cases, Python integers are also allowed.\n- All arrays are represented by one-dimensional Python lists.\nIn most cases, tuples are also allowed.\n- All string and character arguments are represented by Python strings,\nfor instance,\n`winopen('Hi There!')`\nand\n`rotate(900, 'z')`.\n- All (short, long, unsigned) integer arguments or return values that are\nonly used to specify the length of an array argument are omitted.\nFor example, the C call\n```text\n\nlmdef(deftype, index, np, props)\n```\nis translated to Python as\n```text\n\nlmdef(deftype, index, props)\n```\n- Output arguments are omitted from the argument list; they are\ntransmitted as function return values instead.\nIf more than one value must be returned, the return value is a tuple.\nIf the C function has both a regular return value (that is not omitted\nbecause of the previous rule) and an output argument, the return value\ncomes first in the tuple.\nExamples: the C call\n```text\n\ngetmcolor(i, &red, &green, &blue)\n```\nis translated to Python as\n```text\n\nred, green, blue = getmcolor(i)\n```\nThe following functions are non-standard or have special argument\nconventions:\nHere is a tiny but complete example GL program in Python:\n```text\n\nimport gl, GL, time\n\ndef main():\ngl.foreground()\ngl.prefposition(500, 900, 500, 900)\nw = gl.winopen('CrissCross')\ngl.ortho2(0.0, 400.0, 0.0, 400.0)\ngl.color(GL.WHITE)\ngl.clear()\ngl.color(GL.RED)\ngl.bgnline()\ngl.v2f(0.0, 0.0)\ngl.v2f(400.0, 400.0)\ngl.endline()\ngl.bgnline()\ngl.v2f(400.0, 0.0)\ngl.v2f(0.0, 400.0)\ngl.endline()\ntime.sleep(5)\n\nmain()\n```\nSee Also:", "python_version": "2.2", "length": 2385, "url": "https://docs.python.org/2.2/lib/module-gl.html"} {"title": "6.21 glob -- Unix style pathname pattern expansion", "text": "module-errno.html | allos.html | module-fnmatch.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.21 glob --\nUnix style pathname pattern expansion\nThe glob module finds all the pathnames matching a specified\npattern according to the rules used by the Unix shell. No tilde\nexpansion is done, but `*`, `?`, and character ranges\nexpressed with `[]` will be correctly matched. This is done by\nusing the os.listdir() and fnmatch.fnmatch()\nfunctions in concert, and not by actually invoking a subshell. (For\ntilde and shell variable expansion, use os.path.expanduser()\nand os.path.expandvars().)\nFor example, consider a directory containing only the following files:\n1.gif, 2.txt, and card.gif. glob()\nwill produce the following results. Notice how any leading components\nof the path are preserved.\n```text\n\n>>> import glob\n>>> glob.glob('./[0-9].*')\n['./1.gif', './2.txt']\n>>> glob.glob('*.gif')\n['1.gif', 'card.gif']\n>>> glob.glob('?.gif')\n['1.gif']\n```", "python_version": "2.2", "length": 987, "url": "https://docs.python.org/2.2/lib/module-glob.html"} {"title": "11.8 gopherlib -- Gopher protocol client", "text": "ftp-objects.html | internet.html | module-poplib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.8 gopherlib --\nGopher protocol client\nThis module provides a minimal implementation of client side of the\nthe Gopher protocol. It is used by the module urllib (module-urllib.html) to\nhandle URLs that use the Gopher protocol.\nThe module defines the following functions:", "python_version": "2.2", "length": 406, "url": "https://docs.python.org/2.2/lib/module-gopherlib.html"} {"title": "8.3 grp -- The group database", "text": "module-pwd.html | unix.html | module-crypt.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.3 grp --\nThe group database\nAvailability: Unix.\nThis module provides access to the Unix group database.\nIt is available on all Unix versions.\nGroup database entries are reported as 4-tuples containing the\nfollowing items from the group database (see ``), in order:\nThe gid is an integer, name and password are strings, and the member\nlist is a list of strings.\n(Note that most users are not explicitly listed as members of the\ngroup they are in according to the password database. Check both\ndatabases to get complete membership information.)\nIt defines the following items:", "python_version": "2.2", "length": 712, "url": "https://docs.python.org/2.2/lib/module-grp.html"} {"title": "7.14 gzip -- Support for gzip files", "text": "module-zlib.html | someos.html | module-zipfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.14 gzip --\nSupport for gzip files\nThe data compression provided by the `zlib` module is compatible\nwith that used by the GNU compression program gzip.\nAccordingly, the gzip module provides the GzipFile\nclass to read and write gzip-format files, automatically\ncompressing or decompressing the data so it looks like an ordinary\nfile object. Note that additional file formats which can be\ndecompressed by the gzip and gunzip programs, such\nas those produced by compress and pack, are not\nsupported by this module.\nThe module defines the following items:", "python_version": "2.2", "length": 686, "url": "https://docs.python.org/2.2/lib/module-gzip.html"} {"title": "15.1 hmac -- Keyed-Hashing for Message Authentication", "text": "crypto.html | crypto.html | module-md5.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 15.1 hmac --\nKeyed-Hashing for Message Authentication\nNew in version 2.2.\nThis module implements the HMAC algorithm as described by RFC 2104 (http://www.faqs.org/rfcs/rfc2104.html).\nAn HMAC object has the following methods:", "python_version": "2.2", "length": 348, "url": "https://docs.python.org/2.2/lib/module-hmac.html"} {"title": "13.4 htmlentitydefs -- Definitions of HTML general entities", "text": "html-parser-objects.html | markup.html | module-xml.parsers.expat.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.4 htmlentitydefs --\nDefinitions of HTML general entities\nThis module defines a single dictionary, `entitydefs`, which is\nused by the htmllib (module-htmllib.html) module to provide the\nentitydefs member of the HTMLParser class. The\ndefinition provided here contains all the entities defined by HTML 2.0\nthat can be handled using simple textual substitution in the Latin-1\ncharacter set (ISO-8859-1).", "python_version": "2.2", "length": 554, "url": "https://docs.python.org/2.2/lib/module-htmlentitydefs.html"} {"title": "13.3 htmllib -- A parser for HTML documents", "text": "module-sgmllib.html | markup.html | html-parser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.3 htmllib --\nA parser for HTML documents\nThis module defines a class which can serve as a base for parsing text\nfiles formatted in the HyperText Mark-up Language (HTML). The class\nis not directly concerned with I/O -- it must be provided with input\nin string form via a method, and makes calls to methods of a\n``formatter'' object in order to produce output. The\nHTMLParser class is designed to be used as a base class for\nother classes in order to add functionality, and allows most of its\nmethods to be extended or overridden. In turn, this class is derived\nfrom and extends the SGMLParser class defined in module\nsgmllib (module-sgmllib.html). The HTMLParser\nimplementation supports the HTML 2.0 language as described in\nRFC 1866 (http://www.faqs.org/rfcs/rfc1866.html). Two implementations of formatter objects are provided in\nthe formatter (module-formatter.html)module; refer to the\ndocumentation for that module for information on the formatter\ninterface.\nThe following is a summary of the interface defined by\nsgmllib.SGMLParser:\n- The interface to feed data to an instance is through the feed()\nmethod, which takes a string argument. This can be called with as\nlittle or as much text at a time as desired; \"p.feed(a);\np.feed(b)\" has the same effect as \"p.feed(a+b)\". When the data\ncontains complete HTML tags, these are processed immediately;\nincomplete elements are saved in a buffer. To force processing of all\nunprocessed data, call the close() method.\nFor example, to parse the entire contents of a file, use:\n```text\n\nparser.feed(open('myfile.html').read())\nparser.close()\n```\n- The interface to define semantics for HTML tags is very simple: derive\na class and define methods called start_tag(),\nend_tag(), or do_tag(). The parser will\ncall these at appropriate moments: start_tag or\ndo_tag() is called when an opening tag of the form\n`< tag ...>` is encountered; end_tag() is called\nwhen a closing tag of the form `< tag >` is encountered. If\nan opening tag requires a corresponding closing tag, like `

    `\n... `

    `, the class should define the start_tag()\nmethod; if a tag requires no closing tag, like `

    `, the class\nshould define the do_tag() method.\nThe module defines a single class:\nSee Also:", "python_version": "2.2", "length": 2365, "url": "https://docs.python.org/2.2/lib/module-htmllib.html"} {"title": "13.1 HTMLParser -- Simple HTML and XHTML parser", "text": "markup.html | markup.html | htmlparser-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.1 HTMLParser --\nSimple HTML and XHTML parser\nThis module defines a class HTMLParser which serves as the\nbasis for parsing text files formatted in HTML(HyperText\nMark-up Language) and XHTML. Unlike the parser in\nhtmllib (module-htmllib.html), this parser is not based on the SGML parser in\nsgmllib (module-sgmllib.html).\nHTMLParser instances have the following methods:", "python_version": "2.2", "length": 504, "url": "https://docs.python.org/2.2/lib/module-HTMLParser.html"} {"title": "11.6 httplib -- HTTP protocol client", "text": "unknown-handler-objects.html | internet.html | httpconnection-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.6 httplib --\nHTTP protocol client\nThis module defines classes which implement the client side of the\nHTTP and HTTPS protocols. It is normally not used directly -- the\nmodule urllib (module-urllib.html)uses it to handle URLs\nthat use HTTP and HTTPS. Note:\nHTTPS support is only\navailable if the socket (module-socket.html) module was compiled with SSL\nsupport.\nThe constants defined in this module are:\nThe module provides the following classes:\nThe following exceptions are raised as appropriate:", "python_version": "2.2", "length": 655, "url": "https://docs.python.org/2.2/lib/module-httplib.html"} {"title": "14.2 imageop -- Manipulate raw image data", "text": "module-audioop.html | mmedia.html | module-aifc.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.2 imageop --\nManipulate raw image data\nThe imageop module contains some useful operations on images.\nIt operates on images consisting of 8 or 32 bit pixels stored in\nPython strings. This is the same format as used by\ngl.lrectwrite() and the imgfile (module-imgfile.html) module.\nThe module defines the following variables and functions:", "python_version": "2.2", "length": 473, "url": "https://docs.python.org/2.2/lib/module-imageop.html"} {"title": "11.10 imaplib -- IMAP4 protocol client", "text": "pop3-example.html | internet.html | imap4-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.10 imaplib --\nIMAP4 protocol client\nThis module defines a class, IMAP4, which encapsulates a\nconnection to an IMAP4 server and implements a large subset of the\nIMAP4rev1 client protocol as defined in RFC 2060 (http://www.faqs.org/rfcs/rfc2060.html). It is backward\ncompatible with IMAP4 (RFC 1730 (http://www.faqs.org/rfcs/rfc1730.html)) servers, but note that the\n\"STATUS\" command is not supported in IMAP4.\nA single class is provided by the imaplib module:\nTwo exceptions are defined as attributes of the IMAP4 class:\nThe following utility functions are defined:\nNote that IMAP4 message numbers change as the mailbox changes; in\nparticular, after an \"EXPUNGE\" command performs deletions the\nremaining messages are renumbered. So it is highly advisable to use\nUIDs instead, with the UID command.\nAt the end of the module, there is a test section that contains a more\nextensive example of usage.\nSee Also:\nDocuments describing the protocol, and sources and binaries\nfor servers implementing it, can all be found at the\nUniversity of Washington's IMAP Information Center\n(http://www.cac.washington.edu/imap/).", "python_version": "2.2", "length": 1247, "url": "https://docs.python.org/2.2/lib/module-imaplib.html"} {"title": "20.11 imgfile -- Support for SGI imglib files", "text": "module-gl-constants.html | sgi.html | module-jpeg.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.11 imgfile --\nSupport for SGI imglib files\nAvailability: IRIX.\nThe imgfile module allows Python programs to access SGI imglib image\nfiles (also known as .rgb files). The module is far from\ncomplete, but is provided anyway since the functionality that there is\nis enough in some cases. Currently, colormap files are not supported.\nThe module defines the following variables and functions:", "python_version": "2.2", "length": 526, "url": "https://docs.python.org/2.2/lib/module-imgfile.html"} {"title": "14.9 imghdr -- Determine the type of an image", "text": "module-rgbimg.html | mmedia.html | module-sndhdr.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.9 imghdr --\nDetermine the type of an image\nThe imghdr module determines the type of image contained in a\nfile or byte stream.\nThe imghdr module defines the following function:\nThe following image types are recognized, as listed below with the\nreturn value from what():\nYou can extend the list of file types imghdr can recognize by\nappending to this variable:\nExample:", "python_version": "2.2", "length": 505, "url": "https://docs.python.org/2.2/lib/module-imghdr.html"} {"title": "3.21 imp -- Access the import internals", "text": "warning-functions.html | python.html | examples-imp.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.21 imp --\nAccess the import internals\nThismodule provides an interface to the mechanisms\nused to implement the import statement. It defines the\nfollowing constants and functions:\nThe following constants with integer values, defined in this module,\nare used to indicate the search result of find_module().\nThe following constant and functions are obsolete; their functionality\nis available through find_module() or load_module().\nThey are kept around for backward compatibility:", "python_version": "2.2", "length": 617, "url": "https://docs.python.org/2.2/lib/module-imp.html"} {"title": "3.11 inspect -- Inspect live objects", "text": "operator-map.html | python.html | inspect-types.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.11 inspect --\nInspect live objects\nNew in version 2.1.\nThe inspect module provides several useful functions\nto help get information about live objects such as modules,\nclasses, methods, functions, tracebacks, frame objects, and\ncode objects. For example, it can help you examine the\ncontents of a class, retrieve the source code of a method,\nextract and format the argument list for a function, or\nget all the information you need to display a detailed traceback.\nThere are four main kinds of services provided by this module:\ntype checking, getting source code, inspecting classes\nand functions, and examining the interpreter stack.", "python_version": "2.2", "length": 769, "url": "https://docs.python.org/2.2/lib/module-inspect.html"} {"title": "20.12 jpeg -- Read and write JPEG files", "text": "module-imgfile.html | sgi.html | sunos.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20.12 jpeg --\nRead and write JPEG files\nAvailability: IRIX.\nThe module jpeg provides access to the jpeg compressor and\ndecompressor written by the Independent JPEG Group\n(IJG). JPEG is a standard for\ncompressing pictures; it is defined in ISO 10918. For details on JPEG\nor the Independent JPEG Group software refer to the JPEG standard or\nthe documentation provided with the software.\nA portable interface to JPEG image files is available with the Python\nImaging Library (PIL) by Fredrik Lundh. Information on PIL is\navailable at http://www.pythonware.com/products/pil/.\nThe jpeg module defines an exception and some functions.\nSee Also:", "python_version": "2.2", "length": 762, "url": "https://docs.python.org/2.2/lib/module-jpeg.html"} {"title": "18.4 keyword -- Testing for Python keywords", "text": "module-token.html | language.html | module-tokenize.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.4 keyword --\nTesting for Python keywords\nThis module allows a Python program to determine if a string is a\nkeyword. A single function is provided:", "python_version": "2.2", "length": 287, "url": "https://docs.python.org/2.2/lib/module-keyword.html"} {"title": "3.13 linecache -- Random access to text lines", "text": "traceback-example.html | python.html | module-pickle.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.13 linecache --\nRandom access to text lines\nThe linecache module allows one to get any line from any file,\nwhile attempting to optimize internally, using a cache, the common case\nwhere many lines are read from a single file. This is used by the\ntraceback (module-traceback.html) module to retrieve source lines for inclusion in\nthe formatted traceback.\nThe linecache module defines the following functions:\nExample:", "python_version": "2.2", "length": 556, "url": "https://docs.python.org/2.2/lib/module-linecache.html"} {"title": "6.24 locale -- Internationalization services", "text": "shutil-example.html | allos.html | node197.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.24 locale --\nInternationalization services\nThe locale module opens access to the POSIX locale\ndatabase and functionality. The POSIX locale mechanism allows\nprogrammers to deal with certain cultural issues in an application,\nwithout requiring the programmer to know all the specifics of each\ncountry where the software is executed.\nThe locale module is implemented on top of the\n_localemodule, which in turn uses an\nANSI C locale implementation if available.\nThe locale module defines the following exception and\nfunctions:\nThe nl_langinfo function accepts one of the following keys.\nMost descriptions are taken from the corresponding description in the\nGNU C library.\nExample:\n```text\n\n>>> import locale\n>>> loc = locale.setlocale(locale.LC_ALL) # get current locale\n>>> locale.setlocale(locale.LC_ALL, 'de') # use German locale\n>>> locale.strcoll('f\\xe4n', 'foo') # compare a string containing an umlaut\n>>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale\n>>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale\n>>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale\n```", "python_version": "2.2", "length": 1239, "url": "https://docs.python.org/2.2/lib/module-locale.html"} {"title": "12.4 mailbox -- Read various mailbox formats", "text": "module-mailcap.html | netdata.html | mailbox-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.4 mailbox --\nRead various mailbox formats\nThis module defines a number of classes that allow easy and uniform\naccess to mail messages in a (Unix) mailbox.\nSee Also:", "python_version": "2.2", "length": 306, "url": "https://docs.python.org/2.2/lib/module-mailbox.html"} {"title": "12.3 mailcap -- Mailcap file handling.", "text": "node389.html | netdata.html | module-mailbox.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.3 mailcap --\nMailcap file handling.\nMailcap files are used to configure how MIME-aware applications such\nas mail readers and Web browsers react to files with different MIME\ntypes. (The name ``mailcap'' is derived from the phrase ``mail\ncapability''.) For example, a mailcap file might contain a line like\n\"video/mpeg; xmpeg %s\". Then, if the user encounters an email\nmessage or Web document with the MIME type video/mpeg,\n\"%s\" will be replaced by a filename (usually one belonging to a\ntemporary file) and the xmpeg program can be automatically\nstarted to view the file.\nThe mailcap format is documented in RFC 1524 (http://www.faqs.org/rfcs/rfc1524.html), ``A User Agent\nConfiguration Mechanism For Multimedia Mail Format Information,'' but\nis not an Internet standard. However, mailcap files are supported on\nmost Unix systems.", "python_version": "2.2", "length": 963, "url": "https://docs.python.org/2.2/lib/module-mailcap.html"} {"title": "3.30 __main__ -- Top-level script environment", "text": "module-builtin.html | python.html | strings.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.30 __main__ --\nTop-level script environment\nThis module represents the (otherwise anonymous) scope in which the\ninterpreter's main program executes -- commands read either from\nstandard input, from a script file, or from an interactive prompt. It\nis this environment in which the idiomatic ``conditional script''\nstanza causes a script to run:\n```text\n\nif __name__ == \"__main__\":\nmain()\n```", "python_version": "2.2", "length": 522, "url": "https://docs.python.org/2.2/lib/module-main.html"} {"title": "3.19 marshal -- Internal Python object serialization", "text": "module-copy.html | python.html | module-warnings.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.19 marshal --\nInternal Python object serialization\nThis module contains functions that can read and write Python\nvalues in a binary format. The format is specific to Python, but\nindependent of machine architecture issues (e.g., you can write a\nPython value to a file on a PC, transport the file to a Sun, and read\nit back there). Details of the format are undocumented on purpose;\nit may change between Python versions (although it rarely\ndoes).3.14 (#foot7455)\nThis is not a general ``persistence'' module. For general persistence\nand transfer of Python objects through RPC calls, see the modules\npickle (module-pickle.html) and shelve (module-shelve.html). The marshal module exists\nmainly to support reading and writing the ``pseudo-compiled'' code for\nPython modules of .pyc files. Therefore, the Python\nmaintainers reserve the right to modify the marshal format in backward\nincompatible ways should the need arise. If you're serializing and\nde-serializing Python objects, use the pickle module. There\nmay also be unknown security problems with\nmarshal3.15 (#foot7508).\nNot all Python object types are supported; in general, only objects\nwhose value is independent from a particular invocation of Python can\nbe written and read by this module. The following types are supported:\n`None`, integers, long integers, floating point numbers,\nstrings, Unicode objects, tuples, lists, dictionaries, and code\nobjects, where it should be understood that tuples, lists and\ndictionaries are only supported as long as the values contained\ntherein are themselves supported; and recursive lists and dictionaries\nshould not be written (they will cause infinite loops).\nCaveat: On machines where C's `long int` type has more than\n32 bits (such as the DEC Alpha), it is possible to create plain Python\nintegers that are longer than 32 bits.\nIf such an integer is marshaled and read back in on a machine where\nC's `long int` type has only 32 bits, a Python long integer object\nis returned instead. While of a different type, the numeric value is\nthe same. (This behavior is new in Python 2.2. In earlier versions,\nall but the least-significant 32 bits of the value were lost, and a\nwarning message was printed.)\nThere are functions that read/write files as well as functions\noperating on strings.\nThe module defines these functions:", "python_version": "2.2", "length": 2454, "url": "https://docs.python.org/2.2/lib/module-marshal.html"} {"title": "5.4 math -- Mathematical functions", "text": "testloader-objects.html | misc.html | module-cmath.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.4 math --\nMathematical functions\nThis module is always available. It provides access to the\nmathematical functions defined by the C standard.\nThese functions cannot be used with complex numbers; use the functions\nof the same name from the cmath (module-cmath.html) module if you require\nsupport for complex numbers. The distinction between functions which\nsupport complex numbers and those which don't is made since most users\ndo not want to learn quite as much mathematics as required to\nunderstand complex numbers. Receiving an exception instead of a\ncomplex result allows earlier detection of the unexpected complex\nnumber used as a parameter, so that the programmer can determine how\nand why it was generated in the first place.\nThe following functions provided by this module:\nNote that frexp() and modf() have a different\ncall/return pattern than their C equivalents: they take a single\nargument and return a pair of values, rather than returning their\nsecond return value through an `output parameter' (there is no such\nthing in Python).\nThe module also defines two mathematical constants:", "python_version": "2.2", "length": 1235, "url": "https://docs.python.org/2.2/lib/module-math.html"} {"title": "15.2 md5 -- MD5 message digest algorithm", "text": "module-hmac.html | crypto.html | module-sha.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 15.2 md5 --\nMD5 message digest algorithm\nThis module implements the interface to RSA's MD5 message digest\nalgorithm (see also Internet RFC 1321 (http://www.faqs.org/rfcs/rfc1321.html)). Its use is quite\nstraightforward: use new() to create an md5 object.\nYou can now feed this object with arbitrary strings using the\nupdate() method, and at any point you can ask it for the\ndigest (a strong kind of 128-bit checksum,\na.k.a. ``fingerprint'') of the concatenation of the strings fed to it\nso far using the digest() method.\nFor example, to obtain the digest of the string `'Nobody inspects\nthe spammish repetition'`:\n```text\n\n>>> import md5\n>>> m = md5.new()\n>>> m.update(\"Nobody inspects\")\n>>> m.update(\" the spammish repetition\")\n>>> m.digest()\n'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'\n```\nMore condensed:\n```text\n\n>>> md5.new(\"Nobody inspects the spammish repetition\").digest()\n'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'\n```\nThe following values are provided as constants in the module and as\nattributes of the md5 objects returned by new():\nmd5 objects support the following methods:\nAn md5 object has the following methods:", "python_version": "2.2", "length": 1299, "url": "https://docs.python.org/2.2/lib/module-md5.html"} {"title": "12.5 mhlib -- Access to MH mailboxes", "text": "mailbox-objects.html | netdata.html | mh-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.5 mhlib --\nAccess to MH mailboxes\nThe mhlib module provides a Python interface to MH folders and\ntheir contents.\nThe module contains three basic classes, MH, which represents a\nparticular collection of folders, Folder, which represents a single\nfolder, and Message, which represents a single message.", "python_version": "2.2", "length": 438, "url": "https://docs.python.org/2.2/lib/module-mhlib.html"} {"title": "12.6 mimetools -- Tools for parsing MIME messages", "text": "mh-message-objects.html | netdata.html | mimetools-message-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.6 mimetools --\nTools for parsing MIME messages\nThis module defines a subclass of the\nrfc822 (module-rfc822.html)module's\nMessage class and a number of utility functions that are\nuseful for the manipulation for MIME multipart or encoded message.\nIt defines the following items:\nSee Also:", "python_version": "2.2", "length": 442, "url": "https://docs.python.org/2.2/lib/module-mimetools.html"} {"title": "12.7 mimetypes -- Map filenames to MIME types", "text": "mimetools-message-objects.html | netdata.html | mimetypes-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.7 mimetypes --\nMap filenames to MIME types\nThe mimetypes module converts between a filename or URL and\nthe MIME type associated with the filename extension. Conversions are\nprovided from filename to MIME type and from MIME type to filename\nextension; encodings are not supported for the latter conversion.\nThe module provides one class and a number of convenience functions.\nThe functions are the normal interface to this module, but some\napplications may be interested in the class as well.\nThe functions described below provide the primary interface for this\nmodule. If the module has not been initialized, they will call\ninit() if they rely on the information init()\nsets up.\nSome additional functions and data items are available for controlling\nthe behavior of the module.\nThe MimeTypes class may be useful for applications which may\nwant more than one MIME-type database:", "python_version": "2.2", "length": 1032, "url": "https://docs.python.org/2.2/lib/module-mimetypes.html"} {"title": "12.8 MimeWriter -- Generic MIME file writer", "text": "mimetypes-objects.html | netdata.html | MimeWriter-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.8 MimeWriter --\nGeneric MIME file writer\nThis module defines the class MimeWriter. The\nMimeWriter class implements a basic formatter for creating\nMIME multi-part files. It doesn't seek around the output file nor\ndoes it use large amounts of buffer space. You must write the parts\nout in the order that they should occur in the final\nfile. MimeWriter does buffer the headers you add, allowing you\nto rearrange their order.", "python_version": "2.2", "length": 569, "url": "https://docs.python.org/2.2/lib/module-MimeWriter.html"} {"title": "12.9 mimify -- MIME processing of mail messages", "text": "MimeWriter-objects.html | netdata.html | module-multifile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.9 mimify --\nMIME processing of mail messages\nThe mimify module defines two functions to convert mail messages to\nand from MIME format. The mail message can be either a simple message\nor a so-called multipart message. Each part is treated separately.\nMimifying (a part of) a message entails encoding the message as\nquoted-printable if it contains any characters that cannot be\nrepresented using 7-bit ASCII. Unmimifying (a part of) a message\nentails undoing the quoted-printable encoding. Mimify and unmimify\nare especially useful when a message has to be edited before being\nsent. Typical use would be:\n```text\n\nunmimify message\nedit message\nmimify message\nsend message\n```\nThe modules defines the following user-callable functions and\nuser-settable variables:\nThis module can also be used from the command line. Usage is as\nfollows:\n```text\n\nmimify.py -e [-l length] [infile [outfile]]\nmimify.py -d [-b] [infile [outfile]]\n```\nto encode (mimify) and decode (unmimify) respectively. infile\ndefaults to standard input, outfile defaults to standard output.\nThe same file can be specified for input and output.\nIf the -l option is given when encoding, if there are any lines\nlonger than the specified length, the containing part will be\nencoded.\nIf the -b option is given when decoding, any base64 parts will\nbe decoded as well.", "python_version": "2.2", "length": 1472, "url": "https://docs.python.org/2.2/lib/module-mimify.html"} {"title": "7.7 mmap --\nMemory-mapped file support", "text": "QueueObjects.html | someos.html | module-anydbm.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.7 mmap --\nMemory-mapped file support\nMemory-mapped file objects behave like both strings and like\nfile objects. Unlike normal string objects, however, these are\nmutable. You can use mmap objects in most places where strings\nare expected; for example, you can use the re module to\nsearch through a memory-mapped file. Since they're mutable, you can\nchange a single character by doing `obj[ index ] = 'a'`, or\nchange a substring by assigning to a slice:\n`obj[ i1 : i2 ] = '...'`. You can also read and write\ndata starting at the current file position, and seek()\nthrough the file to different positions.\nA memory-mapped file is created by the mmap() function,\nwhich is different on Unix and on Windows. In either case you must\nprovide a file descriptor for a file opened for update.\nIf you wish to map an existing Python file object, use its\nfileno() method to obtain the correct value for the\nfileno parameter. Otherwise, you can open the file using the\nos.open() function, which returns a file descriptor\ndirectly (the file still needs to be closed when done).\nFor both the Unix and Windows versions of the function,\naccess may be specified as an optional keyword parameter.\naccess accepts one of three values: ACCESS_READ,\nACCESS_WRITE, or ACCESS_COPY to specify\nreadonly, write-through or copy-on-write memory respectively.\naccess can be used on both Unix and Windows. If\naccess is not specified, Windows mmap returns a write-through\nmapping. The initial memory values for all three access types are\ntaken from the specified file. Assignment to an\nACCESS_READ memory map raises a TypeError\nexception. Assignment to an ACCESS_WRITE memory map\naffects both memory and the underlying file. Assigment to an\nACCESS_COPY memory map affects memory but does not update\nthe underlying file.\nMemory-mapped file objects support the following methods:", "python_version": "2.2", "length": 1977, "url": "https://docs.python.org/2.2/lib/module-mmap.html"} {"title": "15.4 mpz -- GNU arbitrary magnitude integers", "text": "module-sha.html | crypto.html | module-rotor.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 15.4 mpz --\nGNU arbitrary magnitude integers\nDeprecated since release 2.2.\nSee the references at the end of this section for\ninformation about packages which provide similar\nfunctionality. This module will be removed in Python\n2.3.\nThis is an optional module. It is only available when Python is\nconfigured to include it, which requires that the GNU MP software is\ninstalled.\nThis module implements the interface to part of the GNU MP library,\nwhich defines arbitrary precision integer and rational number\narithmetic routines. Only the interfaces to the integer\n(mpz_*()) routines are provided. If not stated\notherwise, the description in the GNU MP documentation can be applied.\nSupport for rational numberscan be\nimplemented in Python. For an example, see the\nRat module, provided as\nDemos/classes/Rat.py in the Python source distribution.\nIn general, mpz-numbers can be used just like other standard\nPython numbers, e.g., you can use the built-in operators like `+`,\n`*`, etc., as well as the standard built-in functions like\nabs(), int(), ..., divmod(),\npow(). Please note: the bitwise-xor\noperation has been implemented as a bunch of ands,\ninverts and ors, because the library lacks an\nmpz_xor() function, and I didn't need one.\nYou create an mpz-number by calling the function mpz() (see\nbelow for an exact description). An mpz-number is printed like this:\n`mpz( value )`.\nA number of extra functions are defined in this module. Non\nmpz-arguments are converted to mpz-values first, and the functions\nreturn mpz-numbers.\nAn mpz-number has one method:", "python_version": "2.2", "length": 1686, "url": "https://docs.python.org/2.2/lib/module-mpz.html"} {"title": "22.1 msvcrt - Useful routines from the MS VC++ runtime", "text": "node604.html | node604.html | msvcrt-files.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 22.1 msvcrt -\nUseful routines from the MS VC++ runtime\nAvailability: Windows.\nThese functions provide access to some useful capabilities on Windows\nplatforms. Some higher-level modules use these functions to build the\nWindows implementations of their services. For example, the\ngetpass (module-getpass.html) module uses this in the implementation of the\ngetpass() function.\nFurther documentation on these functions can be found in the Platform\nAPI documentation.", "python_version": "2.2", "length": 591, "url": "https://docs.python.org/2.2/lib/module-msvcrt.html"} {"title": "12.10 multifile -- Support for files containing distinct parts", "text": "module-mimify.html | netdata.html | MultiFile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.10 multifile --\nSupport for files containing distinct parts\nThe MultiFile object enables you to treat sections of a text\nfile as file-like input objects, with `''` being returned by\nreadline() when a given delimiter pattern is encountered. The\ndefaults of this class are designed to make it useful for parsing\nMIME multipart messages, but by subclassing it and overriding methods\nit can be easily adapted for more general use.\nIt will be useful to know that in MultiFile's view of the world, text\nis composed of three kinds of lines: data, section-dividers, and\nend-markers. MultiFile is designed to support parsing of\nmessages that may have multiple nested message parts, each with its\nown pattern for section-divider and end-marker lines.", "python_version": "2.2", "length": 883, "url": "https://docs.python.org/2.2/lib/module-multifile.html"} {"title": "6.11 mutex -- Mutual exclusion support", "text": "scheduler-objects.html | allos.html | mutex-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.11 mutex --\nMutual exclusion support\nThe mutex module defines a class that allows mutual-exclusion\nvia acquiring and releasing locks. It does not require (or imply)\nthreading or multi-tasking, though it could be useful for\nthose purposes.\nThe mutex module defines the following class:", "python_version": "2.2", "length": 424, "url": "https://docs.python.org/2.2/lib/module-mutex.html"} {"title": "12.18 netrc -- netrc file processing", "text": "xdr-exceptions.html | netdata.html | netrc-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.18 netrc --\nnetrc file processing\nNew in version 1.5.2.\nThe netrc class parses and encapsulates the netrc file format\nused by the Unix ftp program and other FTP clients.", "python_version": "2.2", "length": 309, "url": "https://docs.python.org/2.2/lib/module-netrc.html"} {"title": "3.26 new -- Creation of runtime internal objects", "text": "subclassing-reprs.html | python.html | module-site.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.26 new --\nCreation of runtime internal objects\nThe new module allows an interface to the interpreter object\ncreation functions. This is for use primarily in marshal-type functions,\nwhen a new object needs to be created ``magically'' and not by using the\nregular creation functions. This module provides a low-level interface\nto the interpreter, so care must be exercised when using this module.\nThe new module defines the following functions:", "python_version": "2.2", "length": 581, "url": "https://docs.python.org/2.2/lib/module-new.html"} {"title": "8.16 nis -- Interface to Sun's NIS (Yellow Pages)", "text": "node273.html | unix.html | module-syslog.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.16 nis --\nInterface to Sun's NIS (Yellow Pages)\nAvailability: UNIX.\nThe nis module gives a thin wrapper around the NIS library, useful\nfor central administration of several hosts.\nBecause NIS exists only on Unix systems, this module is\nonly available for Unix.\nThe nis module defines the following functions:\nThe nis module defines the following exception:", "python_version": "2.2", "length": 485, "url": "https://docs.python.org/2.2/lib/module-nis.html"} {"title": "11.11 nntplib -- NNTP protocol client", "text": "imap4-example.html | internet.html | nntp-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.11 nntplib --\nNNTP protocol client\nThis module defines the class NNTP which implements the client\nside of the NNTP protocol. It can be used to implement a news reader\nor poster, or automated news processors. For more information on NNTP\n(Network News Transfer Protocol), see Internet RFC 977 (http://www.faqs.org/rfcs/rfc977.html).\nHere are two small examples of how it can be used. To list some\nstatistics about a newsgroup and print the subjects of the last 10\narticles:\n```text\n\n>>> s = NNTP('news.cwi.nl')\n>>> resp, count, first, last, name = s.group('comp.lang.python')\n>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last\nGroup comp.lang.python has 59 articles, range 3742 to 3803\n>>> resp, subs = s.xhdr('subject', first + '-' + last)\n>>> for id, sub in subs[-10:]: print id, sub\n...\n3792 Re: Removing elements from a list while iterating...\n3793 Re: Who likes Info files?\n3794 Emacs and doc strings\n3795 a few questions about the Mac implementation\n3796 Re: executable python scripts\n3797 Re: executable python scripts\n3798 Re: a few questions about the Mac implementation\n3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules\n3802 Re: executable python scripts\n3803 Re: \\POSIX{} wait and SIGCHLD\n>>> s.quit()\n'205 news.cwi.nl closing connection. Goodbye.'\n```\nTo post an article from a file (this assumes that the article has\nvalid headers):\n```text\n\n>>> s = NNTP('news.cwi.nl')\n>>> f = open('/tmp/article')\n>>> s.post(f)\n'240 Article posted successfully.'\n>>> s.quit()\n'205 news.cwi.nl closing connection. Goodbye.'\n```\nThe module itself defines the following items:", "python_version": "2.2", "length": 1758, "url": "https://docs.python.org/2.2/lib/module-nntplib.html"} {"title": "3.10 operator -- Standard operators as functions.", "text": "module-UserString.html | python.html | operator-map.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.10 operator --\nStandard operators as functions.\nThe operator module exports a set of functions implemented in C\ncorresponding to the intrinsic operators of Python. For example,\n`operator.add(x, y)` is equivalent to the expression `x+y`. The\nfunction names are those used for special class methods; variants without\nleading and trailing \"__\" are also provided for convenience.\nThe functions fall into categories that perform object comparisons,\nlogical operations, mathematical operations, sequence operations, and\nabstract type tests.\nThe object comparison functions are useful for all objects, and are\nnamed after the rich comparison operators they support:\nThe logical operations are also generally applicable to all objects,\nand support truth tests and Boolean operations:\nThe mathematical and bitwise operations are the most numerous:\nOperations which work with sequences include:\nThe operator module also defines a few predicates to test the\ntype of objects. Note:\nBe careful not to misinterpret the\nresults of these functions; only isCallable() has any\nmeasure of reliability with instance objects. For example:\n```text\n\n>>> class C:\n... pass\n...\n>>> import operator\n>>> o = C()\n>>> operator.isMappingType(o)\n1\n```\nExample: Build a dictionary that maps the ordinals from `0` to\n`256` to their character equivalents.\n```text\n\n>>> import operator\n>>> d = {}\n>>> keys = range(256)\n>>> vals = map(chr, keys)\n>>> map(operator.setitem, [d]*len(keys), keys, vals)\n```", "python_version": "2.2", "length": 1606, "url": "https://docs.python.org/2.2/lib/module-operator.html"} {"title": "6.1 os -- Miscellaneous operating system interfaces", "text": "allos.html | allos.html | os-procinfo.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.1 os --\nMiscellaneous operating system interfaces\nThis module provides a more portable way of using operating system\ndependent functionality than importing a operating system dependent\nbuilt-in module like posix (module-posix.html) or nt.\nThis module searches for an operating system dependent built-in module like\nmac or posix (module-posix.html) and exports the same functions and data\nas found there. The design of all Python's built-in operating system dependent\nmodules is such that as long as the same functionality is available,\nit uses the same interface; for example, the function\n`os.stat( path )` returns stat information about path in\nthe same format (which happens to have originated with the\nPOSIX interface).\nExtensions peculiar to a particular operating system are also\navailable through the os module, but using them is of course a\nthreat to portability!\nNote that after the first time os is imported, there is\nno performance penalty in using functions from os\ninstead of directly from the operating system dependent built-in module,\nso there should be no reason not to use os!\nThe os module contains many functions and data values.\nThe items below and in the following sub-sections are all available\ndirectly from the os module.", "python_version": "2.2", "length": 1372, "url": "https://docs.python.org/2.2/lib/module-os.html"} {"title": "6.2 os.path -- Common pathname manipulations", "text": "os-path.html | allos.html | module-dircache.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.2 os.path --\nCommon pathname manipulations\nThis module implements some useful functions on pathnames.\nWarning:\nOn Windows, many of these functions do not properly\nsupport UNC pathnames. splitunc() and ismount()\ndo handle them correctly.", "python_version": "2.2", "length": 368, "url": "https://docs.python.org/2.2/lib/module-os.path.html"} {"title": "18.1 parser -- Access Python parse trees", "text": "language.html | language.html | node551.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.1 parser --\nAccess Python parse trees\nThe parser module provides an interface to Python's internal\nparser and byte-code compiler. The primary purpose for this interface\nis to allow Python code to edit the parse tree of a Python expression\nand create executable code from this. This is better than trying\nto parse and modify an arbitrary Python code fragment as a string\nbecause parsing is performed in a manner identical to the code\nforming the application. It is also faster.\nThere are a few things to note about this module which are important\nto making use of the data structures created. This is not a tutorial\non editing the parse trees for Python code, but some examples of using\nthe parser module are presented.\nMost importantly, a good understanding of the Python grammar processed\nby the internal parser is required. For full information on the\nlanguage syntax, refer to the Python\nLanguage Reference (../ref/ref.html). The parser itself is created from a grammar\nspecification defined in the file Grammar/Grammar in the\nstandard Python distribution. The parse trees stored in the AST\nobjects created by this module are the actual output from the internal\nparser when created by the expr() or suite()\nfunctions, described below. The AST objects created by\nsequence2ast() faithfully simulate those structures. Be\naware that the values of the sequences which are considered\n``correct'' will vary from one version of Python to another as the\nformal grammar for the language is revised. However, transporting\ncode from one Python version to another as source text will always\nallow correct parse trees to be created in the target version, with\nthe only restriction being that migrating to an older version of the\ninterpreter will not support more recent language constructs. The\nparse trees are not typically compatible from one version to another,\nwhereas source code has always been forward-compatible.\nEach element of the sequences returned by ast2list() or\nast2tuple() has a simple form. Sequences representing\nnon-terminal elements in the grammar always have a length greater than\none. The first element is an integer which identifies a production in\nthe grammar. These integers are given symbolic names in the C header\nfile Include/graminit.h and the Python module\nsymbol (module-symbol.html). Each additional element of the sequence represents\na component of the production as recognized in the input string: these\nare always sequences which have the same form as the parent. An\nimportant aspect of this structure which should be noted is that\nkeywords used to identify the parent node type, such as the keyword\nif in an if_stmt, are included in the node tree without\nany special treatment. For example, the if keyword is\nrepresented by the tuple `(1, 'if')`, where `1` is the\nnumeric value associated with all NAME tokens, including\nvariable and function names defined by the user. In an alternate form\nreturned when line number information is requested, the same token\nmight be represented as `(1, 'if', 12)`, where the `12`\nrepresents the line number at which the terminal symbol was found.\nTerminal elements are represented in much the same way, but without\nany child elements and the addition of the source text which was\nidentified. The example of the if keyword above is\nrepresentative. The various types of terminal symbols are defined in\nthe C header file Include/token.h and the Python module\ntoken (module-token.html).\nThe AST objects are not required to support the functionality of this\nmodule, but are provided for three purposes: to allow an application\nto amortize the cost of processing complex parse trees, to provide a\nparse tree representation which conserves memory space when compared\nto the Python list or tuple representation, and to ease the creation\nof additional modules in C which manipulate parse trees. A simple\n``wrapper'' class may be created in Python to hide the use of AST\nobjects.\nThe parser module defines functions for a few distinct\npurposes. The most important purposes are to create AST objects and\nto convert AST objects to other representations such as parse trees\nand compiled code objects, but there are also functions which serve to\nquery the type of parse tree represented by an AST object.\nSee Also:", "python_version": "2.2", "length": 4388, "url": "https://docs.python.org/2.2/lib/module-parser.html"} {"title": "9. The Python Debugger", "text": "module-commands.html | lib.html | debugger-commands.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 9. The Python Debugger\nThe module pdb defines an interactive source code\ndebuggerfor Python programs. It supports setting\n(conditional) breakpoints and single stepping at the source line\nlevel, inspection of stack frames, source code listing, and evaluation\nof arbitrary Python code in the context of any stack frame. It also\nsupports post-mortem debugging and can be called under program\ncontrol.\nThe debugger is extensible -- it is actually defined as the class\nPdb.\nThis is currently undocumented but easily understood by reading the\nsource. The extension interface uses the modules\nbdb(undocumented) and\ncmd (module-cmd.html).\nThe debugger's prompt is \"(Pdb) \".\nTypical usage to run a program under control of the debugger is:\n```text\n\n>>> import pdb\n>>> import mymodule\n>>> pdb.run('mymodule.test()')\n> (0)?()\n(Pdb) continue\n> (1)?()\n(Pdb) continue\nNameError: 'spam'\n> (1)?()\n(Pdb)\n```\npdb.py can also be invoked as\na script to debug other scripts. For example:\n```text\n\npython /usr/local/lib/python1.5/pdb.py myscript.py\n```\nTypical usage to inspect a crashed program is:\n```text\n\n>>> import pdb\n>>> import mymodule\n>>> mymodule.test()\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nFile \"./mymodule.py\", line 4, in test\ntest2()\nFile \"./mymodule.py\", line 3, in test2\nprint spam\nNameError: spam\n>>> pdb.pm()\n> ./mymodule.py(3)test2()\n-> print spam\n(Pdb)\n```\nThe module defines the following functions; each enters the debugger\nin a slightly different way:", "python_version": "2.2", "length": 1640, "url": "https://docs.python.org/2.2/lib/module-pdb.html"} {"title": "3.14 pickle -- Python object serialization", "text": "module-linecache.html | python.html | node59.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.14 pickle -- Python object serialization\nThe pickle module implements a fundamental, but powerful\nalgorithm for serializing and de-serializing a Python object\nstructure. ``Pickling'' is the process whereby a Python object\nhierarchy is converted into a byte stream, and ``unpickling'' is the\ninverse operation, whereby a byte stream is converted back into an\nobject hierarchy. Pickling (and unpickling) is alternatively known as\n``serialization'', ``marshalling,''3.2 (#foot6912) or ``flattening'',\nhowever the preferred term used here is ``pickling'' and\n``unpickling'' to avoid confusing.\nThis documentation describes both the pickle module and the\ncPickle (module-cPickle.html) module.\n---\n#### Footnotes", "python_version": "2.2", "length": 839, "url": "https://docs.python.org/2.2/lib/module-pickle.html"} {"title": "8.13 pipes -- Interface to shell pipelines", "text": "module-fcntl.html | unix.html | template-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.13 pipes --\nInterface to shell pipelines\nAvailability: Unix.\nThe pipes module defines a class to abstract the concept of\na pipeline -- a sequence of convertors from one file to\nanother.\nBecause the module uses /bin/sh command lines, a POSIX or\ncompatible shell for os.system() and os.popen()\nis required.\nThe pipes module defines the following class:\nExample:\n```text\n\n>>> import pipes\n>>> t=pipes.Template()\n>>> t.append('tr a-z A-Z', '--')\n>>> f=t.open('/tmp/1', 'w')\n>>> f.write('hello world')\n>>> f.close()\n>>> open('/tmp/1').read()\n'HELLO WORLD'\n```", "python_version": "2.2", "length": 691, "url": "https://docs.python.org/2.2/lib/module-pipes.html"} {"title": "6.8 popen2 -- Subprocesses with accessible I/O streams", "text": "dircmp-objects.html | allos.html | popen3-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.8 popen2 --\nSubprocesses with accessible I/O streams\nAvailability: Unix, Windows.\nThis module allows you to spawn processes and connect to their\ninput/output/error pipes and obtain their return codes under\nUnix and Windows.\nNote that starting with Python 2.0, this functionality is available\nusing functions from the os (module-os.html) module which have the same\nnames as the factory functions here, but the order of the return\nvalues is more intuitive in the os (module-os.html) module variants.\nThe primary interface offered by this module is a trio of factory\nfunctions. For each of these, if bufsize is specified,\nit specifies the buffer size for the I/O pipes. mode, if\nprovided, should be the string `'b'` or `'t'`; on Windows\nthis is needed to determine whether the file objects should be opened\nin binary or text mode. The default value for mode is\n`'t'`.\nThe only way to retrieve the return codes for the child processes is\nby using the poll() or wait() methods on the\nPopen3 and Popen4 classes; these are only available on\nUnix. This information is not available when using the\npopen2(), popen3(), and popen4()\nfunctions, or the equivalent functions in the os (module-os.html) module.\nOn Unix, a class defining the objects returned by the factory\nfunctions is also available. These are not used for the Windows\nimplementation, and are not available on that platform.", "python_version": "2.2", "length": 1515, "url": "https://docs.python.org/2.2/lib/module-popen2.html"} {"title": "11.9 poplib -- POP3 protocol client", "text": "module-gopherlib.html | internet.html | pop3-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.9 poplib --\nPOP3 protocol client\nThis module defines a class, POP3, which encapsulates a\nconnection to an POP3 server and implements the protocol as defined in\nRFC 1725 (http://www.faqs.org/rfcs/rfc1725.html). The POP3 class supports both the minimal and\noptional command sets.\nNote that POP3, though widely supported, is obsolescent. The\nimplementation quality of POP3 servers varies widely, and too many are\nquite poor. If your mailserver supports IMAP, you would be better off\nusing the `imaplib . IMAP4` class, as IMAP\nservers tend to be better implemented.\nA single class is provided by the poplib module:\nOne exception is defined as an attribute of the poplib module:\nSee Also:", "python_version": "2.2", "length": 825, "url": "https://docs.python.org/2.2/lib/module-poplib.html"} {"title": "8.1 posix -- The most common POSIX system calls", "text": "unix.html | unix.html | posix-large-files.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.1 posix --\nThe most common POSIX system calls\nAvailability: Unix.\nThis module provides access to operating system functionality that is\nstandardized by the C Standard and the POSIX standard (a thinly\ndisguised Unix interface).\nDo not import this module directly. Instead, import the\nmodule os (module-os.html), which provides a portable version of this\ninterface. On Unix, the os (module-os.html) module provides a superset of\nthe posix interface. On non-Unix operating systems the\nposix module is not available, but a subset is always\navailable through the os (module-os.html) interface. Once os (module-os.html) is\nimported, there is no performance penalty in using it instead\nof posix. In addition, os (module-os.html)provides some additional functionality, such as automatically calling\nputenv() when an entry in `os.environ` is changed.\nThe descriptions below are very terse; refer to the corresponding\nUnix manual (or POSIX documentation) entry for more information.\nArguments called path refer to a pathname given as a string.\nErrors are reported as exceptions; the usual exceptions are given for\ntype errors, while errors reported by the system calls raise\nerror (a synonym for the standard exception\nOSError), described below.", "python_version": "2.2", "length": 1365, "url": "https://docs.python.org/2.2/lib/module-posix.html"} {"title": "8.14 posixfile -- File-like objects with locking support", "text": "template-objects.html | unix.html | module-resource.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.14 posixfile --\nFile-like objects with locking support\nAvailability: Unix.\nDeprecated since release 1.5.\nThe locking operation that this module provides is\ndone better and more portably by the\nfcntl (module-fcntl.html).lockf() call.\nThis module implements some additional functionality over the built-in\nfile objects. In particular, it implements file locking, control over\nthe file flags, and an easy interface to duplicate the file object.\nThe module defines a new file object, the posixfile object. It\nhas all the standard file object methods and adds the methods\ndescribed below. This module only works for certain flavors of\nUnix, since it uses fcntl.fcntl() for file locking.\nTo instantiate a posixfile object, use the open() function\nin the posixfile module. The resulting object looks and\nfeels roughly the same as a standard file object.\nThe posixfile module defines the following constants:\nThe posixfile module defines the following functions:\nThe posixfile object defines the following additional methods:\nAll methods raise IOError when the request fails.\nFormat characters for the lock() method have the following\nmeaning:\nIn addition the following modifiers can be added to the format:\nNote:\n(1): The lock returned is in the format `( mode , len , start , whence , pid )` where mode is a character\nrepresenting the type of lock ('r' or 'w'). This modifier prevents a\nrequest from being granted; it is for query purposes only.\nFormat characters for the flags() method have the following\nmeanings:\nIn addition the following modifiers can be added to the format:\nNotes:\n(1): The \"!\" and \"=\" modifiers are mutually exclusive.\n(2): This string represents the flags after they may have been altered\nby the same call.\nExamples:", "python_version": "2.2", "length": 1874, "url": "https://docs.python.org/2.2/lib/module-posixfile.html"} {"title": "3.24 pprint -- Data pretty printer", "text": "module-codeop.html | python.html | node85.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.24 pprint --\nData pretty printer\nThe pprint module provides a capability to ``pretty-print''\narbitrary Python data structures in a form which can be used as input\nto the interpreter. If the formatted structures include objects which\nare not fundamental Python types, the representation may not be\nloadable. This may be the case if objects such as files, sockets,\nclasses, or instances are included, as well as many other builtin\nobjects which are not representable as Python constants.\nThe formatted representation keeps objects on a single line if it can,\nand breaks them onto multiple lines if they don't fit within the\nallowed width. Construct PrettyPrinter objects explicitly if\nyou need to adjust the width constraint.\nThe pprint module defines one class:\nThe PrettyPrinter class supports several derivative functions:\nOne more support function is also defined:\n```text\n\n>>> pprint.saferepr(stuff)\n\"[, '', '/usr/local/lib/python1.5', '/usr/loca\nl/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python\n1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']\"\n```", "python_version": "2.2", "length": 1255, "url": "https://docs.python.org/2.2/lib/module-pprint.html"} {"title": "10.5 Reference Manual", "text": "node284.html | profile.html | profile-stats.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.5 Reference Manual\nThe primary entry point for the profiler is the global function\nprofile.run(). It is typically used to create any profile\ninformation. The reports are formatted and printed using methods of\nthe class pstats.Stats. The following is a description of all\nof these standard entry points and functions. For a more in-depth\nview of some of the code, consider reading the later section on\nProfiler Extensions, which includes discussion of how to derive\n``better'' profilers from the classes presented, or reading the source\ncode for these modules.\nAnalysis of the profiler data is done using this class from the\npstats module:", "python_version": "2.2", "length": 771, "url": "https://docs.python.org/2.2/lib/module-profile.html"} {"title": "8.11 pty -- Pseudo-terminal utilities", "text": "module-tty.html | unix.html | module-fcntl.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.11 pty --\nPseudo-terminal utilities\nAvailability: IRIX, Linux.\nThe pty module defines operations for handling the\npseudo-terminal concept: starting another process and being able to\nwrite to and read from its controlling terminal programmatically.\nBecause pseudo-terminal handling is highly platform dependant, there\nis code to do it only for SGI and Linux. (The Linux code is supposed\nto work on other platforms, but hasn't been tested yet.)\nThe pty module defines the following functions:", "python_version": "2.2", "length": 621, "url": "https://docs.python.org/2.2/lib/module-pty.html"} {"title": "8.2 pwd -- The password database", "text": "posix-contents.html | unix.html | module-grp.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.2 pwd --\nThe password database\nAvailability: Unix.\nThis module provides access to the Unix user account and password\ndatabase. It is available on all Unix versions.\nPassword database entries are reported as 7-tuples containing the\nfollowing items from the password database (see ``), in order:\nThe uid and gid items are integers, all others are strings.\nKeyError is raised if the entry asked for cannot be found.\nNote:\nIn traditional Unix the field `pw_passwd` usually\ncontains a password encrypted with a DES derived algorithm (see module\ncrypt (module-crypt.html)). However most modern unices\nuse a so-called shadow password system. On those unices the\nfield `pw_passwd` only contains a asterisk (`'*'`) or the\nletter \"x\" where the encrypted password is stored in a file\n/etc/shadow which is not world readable.\nIt defines the following items:", "python_version": "2.2", "length": 985, "url": "https://docs.python.org/2.2/lib/module-pwd.html"} {"title": "18.7 pyclbr -- Python class browser support", "text": "module-tabnanny.html | language.html | pyclbr-class-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.7 pyclbr --\nPython class browser support\nThe pyclbr can be used to determine some limited information\nabout the classes and methods defined in a module. The information\nprovided is sufficient to implement a traditional three-pane class\nbrowser. The information is extracted from the source code rather\nthan from an imported module, so this module is safe to use with\nuntrusted source code. This restriction makes it impossible to use\nthis module with modules not implemented in Python, including many\nstandard and optional extension modules.", "python_version": "2.2", "length": 690, "url": "https://docs.python.org/2.2/lib/module-pyclbr.html"} {"title": "18.8 py_compile -- Compile Python source files", "text": "pyclbr-class-objects.html | language.html | module-compileall.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.8 py_compile --\nCompile Python source files\nThe py_compile module provides a single function to generate\na byte-code file from a source file.\nThough not often needed, this function can be useful when installing\nmodules for shared use, especially if some of the users may not have\npermission to write the byte-code cache files in the directory\ncontaining the source code.", "python_version": "2.2", "length": 521, "url": "https://docs.python.org/2.2/lib/module-pycompile.html"} {"title": "5.1 pydoc -- Documentation generator and online help system", "text": "misc.html | misc.html | module-doctest.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.1 pydoc --\nDocumentation generator and online help system\nNew in version 2.1.\nThe pydoc module automatically generates documentation from\nPython modules. The documentation can be presented as pages of text\non the console, served to a Web browser, or saved to HTML files.\nThe built-in function help() invokes the online help system\nin the interactive interpreter, which uses pydoc to generate\nits documentation as text on the console. The same text documentation\ncan also be viewed from outside the Python interpreter by running\npydoc as a script at the operating system's command prompt.\nFor example, running\n```text\n\npydoc sys\n```\nat a shell prompt will display documentation on the sys (module-sys.html)\nmodule, in a style similar to the manual pages shown by the Unix\nman command. The argument to pydoc can be the name\nof a function, module, or package, or a dotted reference to a class,\nmethod, or function within a module or module in a package. If the\nargument to pydoc looks like a path (that is, it contains the\npath separator for your operating system, such as a slash in Unix),\nand refers to an existing Python source file, then documentation is\nproduced for that file.\nSpecifying a -w flag before the argument will cause HTML\ndocumentation to be written out to a file in the current directory,\ninstead of displaying text on the console.\nSpecifying a -k flag before the argument will search the\nsynopsis lines of all available modules for the keyword given as the\nargument, again in a manner similar to the Unix man\ncommand. The synopsis line of a module is the first line of its\ndocumentation string.\nYou can also use pydoc to start an HTTP server on the local\nmachine that will serve documentation to visiting Web browsers.\npydoc -p 1234 will start a HTTP server on port\n1234, allowing you to browse the documentation at\n`http://localhost:1234/` in your preferred Web browser.\npydoc -g will start the server and additionally\nbring up a small Tkinter (module-Tkinter.html)-based graphical interface to help\nyou search for documentation pages.", "python_version": "2.2", "length": 2180, "url": "https://docs.python.org/2.2/lib/module-pydoc.html"} {"title": "7.6 Queue -- A synchronized queue class", "text": "timer-objects.html | someos.html | QueueObjects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.6 Queue --\nA synchronized queue class\nThe Queue module implements a multi-producer, multi-consumer\nFIFO queue. It is especially useful in threads programming when\ninformation must be exchanged safely between multiple threads. The\nQueue class in this module implements all the required locking\nsemantics. It depends on the availability of thread support in\nPython.\nThe Queue module defines the following class and exception:", "python_version": "2.2", "length": 559, "url": "https://docs.python.org/2.2/lib/module-Queue.html"} {"title": "12.15 quopri -- Encode and decode MIME quoted-printable data", "text": "binhex-notes.html | netdata.html | module-uu.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.15 quopri --\nEncode and decode MIME quoted-printable data\nThis module performs quoted-printable transport encoding and decoding,\nas defined in RFC 1521 (http://www.faqs.org/rfcs/rfc1521.html): ``MIME (Multipurpose Internet Mail\nExtensions) Part One: Mechanisms for Specifying and Describing the\nFormat of Internet Message Bodies''. The quoted-printable encoding is\ndesigned for data where there are relatively few nonprintable\ncharacters; the base64 encoding scheme available via the\nbase64 (module-base64.html) module is more compact if there are many such\ncharacters, as when sending a graphics file.", "python_version": "2.2", "length": 736, "url": "https://docs.python.org/2.2/lib/module-quopri.html"} {"title": "5.6 random -- Generate pseudo-random numbers", "text": "module-cmath.html | misc.html | module-whrandom.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.6 random --\nGenerate pseudo-random numbers\nThis module implements pseudo-random number generators for various\ndistributions.\nFor integers, uniform selection from a range.\nFor sequences, uniform selection of a random element, and a function to\ngenerate a random permutation of a list in-place.\nOn the real line, there are functions to compute uniform, normal (Gaussian),\nlognormal, negative exponential, gamma, and beta distributions.\nFor generating distribution of angles, the circular uniform and\nvon Mises distributions are available.\nAlmost all module functions depend on the basic function\nrandom(), which generates a random float uniformly in\nthe semi-open range [0.0, 1.0). Python uses the standard Wichmann-Hill\ngenerator, combining three pure multiplicative congruential\ngenerators of modulus 30269, 30307 and 30323. Its period (how many\nnumbers it generates before repeating the sequence exactly) is\n6,953,607,871,644. While of much higher quality than the rand()\nfunction supplied by most C libraries, the theoretical properties\nare much the same as for a single linear congruential generator of\nlarge modulus. It is not suitable for all purposes, and is completely\nunsuitable for cryptographic purposes.\nThe functions in this module are not threadsafe: if you want to call these\nfunctions from multiple threads, you should explicitly serialize the calls.\nElse, because no critical sections are implemented internally, calls\nfrom different threads may see the same return values.\nThe functions supplied by this module are actually bound methods of a\nhidden instance of the random.Random class. You can\ninstantiate your own instances of Random to get generators\nthat don't share state. This is especially useful for multi-threaded\nprograms, creating a different instance of Random for each\nthread, and using the jumpahead() method to ensure that the\ngenerated sequences seen by each thread don't overlap (see example\nbelow).\nClass Random can also be subclassed if you want to use a\ndifferent basic generator of your own devising: in that case, override\nthe random(), seed(), getstate(),\nsetstate() and jumpahead() methods.\nHere's one way to create threadsafe distinct and non-overlapping generators:\n```text\n\ndef create_generators(num, delta, firstseed=None):\n\"\"\"Return list of num distinct generators.\nEach generator has its own unique segment of delta elements\nfrom Random.random()'s full period.\nSeed the first generator with optional arg firstseed (default\nis None, to seed from current time).\n\"\"\"\n\nfrom random import Random\ng = Random(firstseed)\nresult = [g]\nfor i in range(num - 1):\nlaststate = g.getstate()\ng = Random()\ng.setstate(laststate)\ng.jumpahead(delta)\nresult.append(g)\nreturn result\n\ngens = create_generators(10, 1000000)\n```\nThat creates 10 distinct generators, which can be passed out to 10\ndistinct threads. The generators don't share state so can be called\nsafely in parallel. So long as no thread calls its `g.random()`\nmore than a million times (the second argument to\ncreate_generators(), the sequences seen by each thread will\nnot overlap. The period of the underlying Wichmann-Hill generator\nlimits how far this technique can be pushed.\nJust for fun, note that since we know the period, jumpahead()\ncan also be used to ``move backward in time:''\n```text\n\n>>> g = Random(42) # arbitrary\n>>> g.random()\n0.25420336316883324\n>>> g.jumpahead(6953607871644L - 1) # move *back* one\n>>> g.random()\n0.25420336316883324\n```\nBookkeeping functions:\nFunctions for integers:\nFunctions for sequences:\nThe following functions generate specific real-valued distributions.\nFunction parameters are named after the corresponding variables in the\ndistribution's equation, as used in common mathematical practice; most of\nthese equations can be found in any statistics text.", "python_version": "2.2", "length": 3922, "url": "https://docs.python.org/2.2/lib/module-random.html"} {"title": "4.2 re -- Regular expression operations", "text": "module-string.html | strings.html | re-syntax.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.2 re --\nRegular expression operations\nThis module provides regular expression matching operations similar to\nthose found in Perl. Regular expression pattern strings may not\ncontain null bytes, but can specify the null byte using the\n`\\ number` notation. Both patterns and strings to be\nsearched can be Unicode strings as well as 8-bit strings. The\nre module is always available.\nRegular expressions use the backslash character (\"\\\") to\nindicate special forms or to allow special characters to be used\nwithout invoking their special meaning. This collides with Python's\nusage of the same character for the same purpose in string literals;\nfor example, to match a literal backslash, one might have to write\n`'\\\\\\\\'` as the pattern string, because the regular expression\nmust be \"\\\\\", and each backslash must be expressed as\n\"\\\\\" inside a regular Python string literal.\nThe solution is to use Python's raw string notation for regular\nexpression patterns; backslashes are not handled in any special way in\na string literal prefixed with \"r\". So `r\"\\n\"` is a\ntwo-character string containing \"\\\" and \"n\",\nwhile `\"\\n\"` is a one-character string containing a newline.\nUsually patterns will be expressed in Python code using this raw\nstring notation.\nImplementation note:\nThe remodule has two distinct\nimplementations: sre is the default implementation and\nincludes Unicode support, but may run into stack limitations for some\npatterns. Though this will be fixed for a future release of Python,\nthe older implementation (without Unicode support) is still available\nas the premodule.\nSee Also:", "python_version": "2.2", "length": 1717, "url": "https://docs.python.org/2.2/lib/module-re.html"} {"title": "7.16 readline -- GNU readline interface", "text": "zipinfo-objects.html | someos.html | readline-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.16 readline --\nGNU readline interface\nAvailability: Unix.\nThe readline module defines a number of functions used either\ndirectly or from the rlcompleter (module-rlcompleter.html) module to facilitate\ncompletion and history file read and write from the Python\ninterpreter.\nThe readline module defines the following functions:\nSee Also:", "python_version": "2.2", "length": 476, "url": "https://docs.python.org/2.2/lib/module-readline.html"} {"title": "3.25 repr -- Alternate repr() implementation", "text": "node85.html | python.html | Repr-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.25 repr --\nAlternate repr() implementation\nThe repr module provides a means for producing object\nrepresentations with limits on the size of the resulting strings.\nThis is used in the Python debugger and may be useful in other\ncontexts as well.\nThis module provides a class, an instance, and a function:", "python_version": "2.2", "length": 431, "url": "https://docs.python.org/2.2/lib/module-repr.html"} {"title": "8.15 resource -- Resource usage information", "text": "module-posixfile.html | unix.html | node272.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.15 resource --\nResource usage information\nAvailability: Unix.\nThis module provides basic mechanisms for measuring and controlling\nsystem resources utilized by a program.\nSymbolic constants are used to specify particular system resources and\nto request usage information about either the current process or its\nchildren.\nA single exception is defined for errors:", "python_version": "2.2", "length": 493, "url": "https://docs.python.org/2.2/lib/module-resource.html"} {"title": "17.1 rexec -- Restricted execution framework", "text": "restricted.html | restricted.html | rexec-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 17.1 rexec --\nRestricted execution framework\nThis module contains the RExec class, which supports\nr_eval(), r_execfile(), r_exec(), and\nr_import() methods, which are restricted versions of the standard\nPython functions eval(), execfile() and\nthe exec and import statements.\nCode executed in this restricted environment will\nonly have access to modules and functions that are deemed safe; you\ncan subclass RExec to add or remove capabilities as desired.\nNote:\nThe RExec class can prevent code from performing\nunsafe operations like reading or writing disk files, or using TCP/IP\nsockets. However, it does not protect against code using extremely\nlarge amounts of memory or processor time.\nIt is important to be aware that code running in a restricted\nenvironment can still call the sys.exit() function. To\ndisallow restricted code from exiting the interpreter, always protect\ncalls that cause restricted code to run with a\ntry/except statement that catches the\nSystemExit exception. Removing the sys.exit()\nfunction from the restricted environment is not sufficient -- the\nrestricted code could still use `raise SystemExit`. Removing\nSystemExit is not a reasonable option; some library code\nmakes use of this and would break were it not available.\nSee Also:", "python_version": "2.2", "length": 1392, "url": "https://docs.python.org/2.2/lib/module-rexec.html"} {"title": "12.11 rfc822 -- Parse RFC 2822 mail headers", "text": "multifile-example.html | netdata.html | message-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.11 rfc822 --\nParse RFC 2822 mail headers\nThis module defines a class, Message, which represents an\n``email message'' as defined by the Internet standard\nRFC 2822 (http://www.faqs.org/rfcs/rfc2822.html).12.6 (#foot38387) Such messages\nconsist of a collection of message headers, and a message body. This\nmodule also defines a helper class\nAddressList for parsing RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) addresses. Please refer to\nthe RFC for information on the specific syntax of RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) messages.\nThe mailbox (module-mailbox.html)module provides classes\nto read mailboxes produced by various end-user mail programs.\nSee Also:\n---\n#### Footnotes", "python_version": "2.2", "length": 839, "url": "https://docs.python.org/2.2/lib/module-rfc822.html"} {"title": "14.8 rgbimg -- Read and write ``SGI RGB'' files", "text": "module-colorsys.html | mmedia.html | module-imghdr.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.8 rgbimg --\nRead and write ``SGI RGB'' files\nThe rgbimg module allows Python programs to access SGI imglib image\nfiles (also known as .rgb files). The module is far from\ncomplete, but is provided anyway since the functionality that there is\nenough in some cases. Currently, colormap files are not supported.\nNote:\nThis module is only built by default for 32-bit platforms; it is\nnot expected to work properly on other systems.\nThe module defines the following variables and functions:", "python_version": "2.2", "length": 624, "url": "https://docs.python.org/2.2/lib/module-rgbimg.html"} {"title": "7.17 rlcompleter -- Completion function for GNU readline", "text": "readline-example.html | someos.html | completer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.17 rlcompleter --\nCompletion function for GNU readline\nAvailability: Unix.\nThe rlcompleter module defines a completion function for\nthe readline (module-readline.html) module by completing valid Python identifiers\nand keywords.\nThis module is Unix-specific due to its dependence on the\nreadline (module-readline.html) module.\nThe rlcompleter module defines the Completer class.\nExample:\n```text\n\n>>> import rlcompleter\n>>> import readline\n>>> readline.parse_and_bind(\"tab: complete\")\n>>> readline. \nreadline.__doc__ readline.get_line_buffer readline.read_init_file\nreadline.__file__ readline.insert_text readline.set_completer\nreadline.__name__ readline.parse_and_bind\n>>> readline.\n```\nThe rlcompleter module is designed for use with Python's\ninteractive mode. A user can add the following lines to his or her\ninitialization file (identified by the PYTHONSTARTUP\nenvironment variable) to get automatic Tab completion:\n```text\n\ntry:\nimport readline\nexcept ImportError:\nprint \"Module readline not available.\"\nelse:\nimport rlcompleter\nreadline.parse_and_bind(\"tab: complete\")\n```", "python_version": "2.2", "length": 1234, "url": "https://docs.python.org/2.2/lib/module-rlcompleter.html"} {"title": "12.19 robotparser -- Parser for robots.txt", "text": "netrc-objects.html | netdata.html | markup.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.19 robotparser --\nParser for robots.txt\nThis module provides a single class, RobotFileParser, which answers\nquestions about whether or not a particular user agent can fetch a URL on\nthe Web site that published the robots.txt file. For more details on\nthe structure of robots.txt files, see\nhttp://info.webcrawler.com/mak/projects/robots/norobots.html.\nThe following example demonstrates basic use of the RobotFileParser class.\n```text\n\n>>> import robotparser\n>>> rp = robotparser.RobotFileParser()\n>>> rp.set_url(\"http://www.musi-cal.com/robots.txt\")\n>>> rp.read()\n>>> rp.can_fetch(\"*\", \"http://www.musi-cal.com/cgi-bin/search?city=San+Francisco\")\n0\n>>> rp.can_fetch(\"*\", \"http://www.musi-cal.com/\")\n1\n```", "python_version": "2.2", "length": 837, "url": "https://docs.python.org/2.2/lib/module-robotparser.html"} {"title": "15.5 rotor -- Enigma-like encryption and decryption", "text": "module-mpz.html | crypto.html | tkinter.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 15.5 rotor --\nEnigma-like encryption and decryption\nThis module implements a rotor-based encryption algorithm, contributed by\nLance Ellinghouse. The design is derived\nfrom the Enigma device, a machine\nused during World War II to encipher messages. A rotor is simply a\npermutation. For example, if the character `A' is the origin of the rotor,\nthen a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on.\nTo encrypt, we choose several different rotors, and set the origins of the\nrotors to known positions; their initial position is the ciphering key. To\nencipher a character, we permute the original character by the first rotor,\nand then apply the second rotor's permutation to the result. We continue\nuntil we've applied all the rotors; the resulting character is our\nciphertext. We then change the origin of the final rotor by one position,\nfrom `A' to `B'; if the final rotor has made a complete revolution, then we\nrotate the next-to-last rotor by one position, and apply the same procedure\nrecursively. In other words, after enciphering one character, we advance\nthe rotors in the same fashion as a car's odometer. Decoding works in the\nsame way, except we reverse the permutations and apply them in the opposite\norder.\nThe available functions in this module are:\nRotor objects have the following methods:\nAn example usage:\n```text\n\n>>> import rotor\n>>> rt = rotor.newrotor('key', 12)\n>>> rt.encrypt('bar')\n'\\xab4\\xf3'\n>>> rt.encryptmore('bar')\n'\\xef\\xfd$'\n>>> rt.encrypt('bar')\n'\\xab4\\xf3'\n>>> rt.decrypt('\\xab4\\xf3')\n'bar'\n>>> rt.decryptmore('\\xef\\xfd$')\n'bar'\n>>> rt.decrypt('\\xef\\xfd$')\n'l(\\xcd'\n>>> del rt\n```\nThe module's code is not an exact simulation of the original Enigma\ndevice; it implements the rotor encryption scheme differently from the\noriginal. The most important difference is that in the original\nEnigma, there were only 5 or 6 different rotors in existence, and they\nwere applied twice to each character; the cipher key was the order in\nwhich they were placed in the machine. The Python rotor\nmodule uses the supplied key to initialize a random number generator;\nthe rotor permutations and their initial positions are then randomly\ngenerated. The original device only enciphered the letters of the\nalphabet, while this module can handle any 8-bit binary data; it also\nproduces binary output. This module can also operate with an\narbitrary number of rotors.\nThe original Enigma cipher was broken in 1944. The version implemented here is probably a good deal more difficult to crack\n(especially if you use many rotors), but it won't be impossible for\na truly skillful and determined attacker to break the cipher. So if you want\nto keep the NSA out of your files, this rotor cipher may well be unsafe, but\nfor discouraging casual snooping through your files, it will probably be\njust fine, and may be somewhat safer than using the Unix crypt\ncommand.", "python_version": "2.2", "length": 3016, "url": "https://docs.python.org/2.2/lib/module-rotor.html"} {"title": "6.10 sched -- Event scheduler", "text": "module-time.html | allos.html | scheduler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.10 sched --\nEvent scheduler\nThe sched module defines a class which implements a general\npurpose event scheduler:\nExample:\n```text\n\n>>> import sched, time\n>>> s=sched.scheduler(time.time, time.sleep)\n>>> def print_time(): print \"From print_time\", time.time()\n...\n>>> def print_some_times():\n... print time.time()\n... s.enter(5, 1, print_time, ())\n... s.enter(10, 1, print_time, ())\n... s.run()\n... print time.time()\n...\n>>> print_some_times()\n930343690.257\nFrom print_time 930343695.274\nFrom print_time 930343700.273\n930343700.276\n```", "python_version": "2.2", "length": 671, "url": "https://docs.python.org/2.2/lib/module-sched.html"} {"title": "16.3 ScrolledText -- Scrolled Text Widget", "text": "node527.html | tkinter.html | module-turtle.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 16.3 ScrolledText --\nScrolled Text Widget\nAvailability: Tk.\nThe ScrolledText module provides a class of the same name\nwhich implements a basic text widget which has a vertical scroll bar\nconfigured to do the ``right thing.'' Using the ScrolledText\nclass is a lot easier than setting up a text widget and scroll bar\ndirectly. The constructor is the same as that of the\nTkinter.Text class.\nThe text widget and scrollbar are packed together in a Frame,\nand the methods of the Grid and Pack geometry managers\nare acquired from the Frame object. This allows the\nScrolledText widget to be used directly to achieve most normal\ngeometry management behavior.\nShould more specific control be necessary, the following attributes\nare available:", "python_version": "2.2", "length": 862, "url": "https://docs.python.org/2.2/lib/module-ScrolledText.html"} {"title": "7.3 select -- Waiting for I/O completion", "text": "socket-example.html | someos.html | poll-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.3 select --\nWaiting for I/O completion\nThis module provides access to the select()\nand poll() functions\navailable in most operating systems. Note that on Windows, it only\nworks for sockets; on other operating systems, it also works for other\nfile types (in particular, on Unix, it works on pipes). It cannot\nbe used on regular files to determine whether a file has grown since\nit was last read.\nThe module defines the following:", "python_version": "2.2", "length": 565, "url": "https://docs.python.org/2.2/lib/module-select.html"} {"title": "13.2 sgmllib -- Simple SGML parser", "text": "htmlparser-example.html | markup.html | module-htmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.2 sgmllib --\nSimple SGML parser\nThis module defines a class SGMLParser which serves as the\nbasis for parsing text files formatted in SGML (Standard Generalized\nMark-up Language). In fact, it does not provide a full SGML parser\n-- it only parses SGML insofar as it is used by HTML, and the module\nonly exists as a base for the htmllib (module-htmllib.html) module. Another\nHTML parser which supports XHTML and offers a somewhat different\ninterface is available in the HTMLParser (module-HTMLParser.html) module.\nSGMLParser instances have the following interface methods:\nApart from overriding or extending the methods listed above, derived\nclasses may also define methods of the following form to define\nprocessing of specific tags. Tag names in the input stream are case\nindependent; the tag occurring in method names must be in lower\ncase:", "python_version": "2.2", "length": 984, "url": "https://docs.python.org/2.2/lib/module-sgmllib.html"} {"title": "15.3 sha -- SHA message digest algorithm", "text": "module-md5.html | crypto.html | module-mpz.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 15.3 sha --\nSHA message digest algorithm\nThis module implements the interface to NIST'ssecure hash\nalgorithm,known as SHA. It is used in\nthe same way as the md5 (module-md5.html) module: use new()\nto create an sha object, then feed this object with arbitrary strings\nusing the update() method, and at any point you can ask it\nfor the digest of the concatenation of the strings fed to it\nso far. SHA digests are 160 bits instead of\nMD5's 128 bits.\nThe following values are provided as constants in the module and as\nattributes of the sha objects returned by new():\nAn sha object has the same methods as md5 objects:", "python_version": "2.2", "length": 743, "url": "https://docs.python.org/2.2/lib/module-sha.html"} {"title": "3.17 shelve -- Python object persistence", "text": "module-copyreg.html | python.html | module-copy.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.17 shelve --\nPython object persistence\nA ``shelf'' is a persistent, dictionary-like object. The difference\nwith ``dbm'' databases is that the values (not the keys!) in a shelf\ncan be essentially arbitrary Python objects -- anything that the\npickle (module-pickle.html) module can handle. This includes most class\ninstances, recursive data types, and objects containing lots of shared\nsub-objects. The keys are ordinary strings.\nTo summarize the interface (`key` is a string, `data` is an\narbitrary object):\n```text\n\nimport shelve\n\nd = shelve.open(filename) # open, with (g)dbm filename -- no suffix\n\nd[key] = data # store data at key (overwrites old data if\n# using an existing key)\ndata = d[key] # retrieve data at key (raise KeyError if no\n# such key)\ndel d[key] # delete data stored at key (raises KeyError\n# if no such key)\nflag = d.has_key(key) # true if the key exists\nlist = d.keys() # a list of all existing keys (slow!)\n\nd.close() # close it\n```\nRestrictions:\n- The choice of which database package will be used\n(e.g. dbm (module-dbm.html) or gdbm (module-gdbm.html)) depends on which interface\nis available. Therefore it is not safe to open the database directly\nusing dbm (module-dbm.html). The database is also (unfortunately) subject\nto the limitations of dbm (module-dbm.html), if it is used -- this means\nthat (the pickled representation of) the objects stored in the\ndatabase should be fairly small, and in rare cases key collisions may\ncause the database to refuse updates.\n- Dependent on the implementation, closing a persistent dictionary may\nor may not be necessary to flush changes to disk.\n- The shelve module does not support concurrent read/write\naccess to shelved objects. (Multiple simultaneous read accesses are\nsafe.) When a program has a shelf open for writing, no other program\nshould have it open for reading or writing. Unix file locking can\nbe used to solve this, but this differs across Unix versions and\nrequires knowledge about the database implementation used.", "python_version": "2.2", "length": 2133, "url": "https://docs.python.org/2.2/lib/module-shelve.html"} {"title": "5.15 shlex -- Simple lexical analysis", "text": "Cmd-objects.html | misc.html | shlex-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.15 shlex --\nSimple lexical analysis\nNew in version 1.5.2.\nThe shlex class makes it easy to write lexical analyzers for\nsimple syntaxes resembling that of the Unix shell. This will often\nbe useful for writing minilanguages, e.g. in run control files for\nPython applications.\nSee Also:", "python_version": "2.2", "length": 416, "url": "https://docs.python.org/2.2/lib/module-shlex.html"} {"title": "6.23 shutil -- High-level file operations", "text": "module-fnmatch.html | allos.html | shutil-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.23 shutil --\nHigh-level file operations\nThe shutil module offers a number of high-level operations on\nfiles and collections of files. In particular, functions are provided\nwhich support file copying and removal.\nCaveat: On MacOS, the resource fork and other metadata are\nnot used. For file copies, this means that resources will be lost and\nfile type and creator codes will not be correct.", "python_version": "2.2", "length": 527, "url": "https://docs.python.org/2.2/lib/module-shutil.html"} {"title": "7.1 signal -- Set handlers for asynchronous events", "text": "someos.html | someos.html | node214.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.1 signal --\nSet handlers for asynchronous events\nThis module provides mechanisms to use signal handlers in Python.\nSome general rules for working with signals and their handlers:\n- A handler for a particular signal, once set, remains installed until\nit is explicitly reset (Python emulates the BSD style interface\nregardless of the underlying implementation), with the exception of\nthe handler for SIGCHLD, which follows the underlying\nimplementation.\n- There is no way to ``block'' signals temporarily from critical\nsections (since this is not supported by all Unix flavors).\n- Although Python signal handlers are called asynchronously as far as\nthe Python user is concerned, they can only occur between the\n``atomic'' instructions of the Python interpreter. This means that\nsignals arriving during long calculations implemented purely in C\n(such as regular expression matches on large bodies of text) may be\ndelayed for an arbitrary amount of time.\n- When a signal arrives during an I/O operation, it is possible that the\nI/O operation raises an exception after the signal handler returns.\nThis is dependent on the underlying Unix system's semantics regarding\ninterrupted system calls.\n- Because the C signal handler always returns, it makes little sense to\ncatch synchronous errors like SIGFPE or SIGSEGV.\n- Python installs a small number of signal handlers by default:\nSIGPIPE is ignored (so write errors on pipes and sockets can be\nreported as ordinary Python exceptions) and SIGINT is translated\ninto a KeyboardInterrupt exception. All of these can be\noverridden.\n- Some care must be taken if both signals and threads are used in the\nsame program. The fundamental thing to remember in using signals and\nthreads simultaneously is: always perform signal() operations\nin the main thread of execution. Any thread can perform an\nalarm(), getsignal(), or pause();\nonly the main thread can set a new signal handler, and the main thread\nwill be the only one to receive signals (this is enforced by the\nPython signal module, even if the underlying thread\nimplementation supports sending signals to individual threads). This\nmeans that signals can't be used as a means of inter-thread\ncommunication. Use locks instead.\nThe variables defined in the signal module are:\nThe signal module defines the following functions:", "python_version": "2.2", "length": 2437, "url": "https://docs.python.org/2.2/lib/module-signal.html"} {"title": "11.17 SimpleHTTPServer -- Simple HTTP request handler", "text": "module-BaseHTTPServer.html | internet.html | module-CGIHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.17 SimpleHTTPServer --\nSimple HTTP request handler\nThe SimpleHTTPServer module defines a request-handler class,\ninterface compatible with BaseHTTPServer.BaseHTTPRequestHandler\nwhich serves files only from a base directory.\nThe SimpleHTTPServer module defines the following class:\nThe SimpleHTTPRequestHandler defines the following member\nvariables:\nThe SimpleHTTPRequestHandler defines the following methods:", "python_version": "2.2", "length": 563, "url": "https://docs.python.org/2.2/lib/module-SimpleHTTPServer.html"} {"title": "11.21 SimpleXMLRPCServer -- Basic XML-RPC server", "text": "xmlrpc-client-example.html | internet.html | simple-xmlrpc-servers.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.21 SimpleXMLRPCServer --\nBasic XML-RPC server\nThe SimpleXMLRPCServer module provides a basic server\nframework for XML-RPC servers written in Python. The server object is\nbased on the SocketServer (module-SocketServer.html).TCPServer class,\nand the request handler is based on the\nBaseHTTPServer (module-BaseHTTPServer.html).BaseHTTPRequestHandler class.", "python_version": "2.2", "length": 509, "url": "https://docs.python.org/2.2/lib/module-SimpleXMLRPCServer.html"} {"title": "3.27 site -- Site-specific configuration hook", "text": "module-new.html | python.html | module-user.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.27 site --\nSite-specific configuration hook\nThis module is automatically imported during initialization.\nIn earlier versions of Python (up to and including 1.5a3), scripts or\nmodules that needed to use site-specific modules would place\n\"import site\" somewhere near the top of their code. This is no\nlonger necessary.\nThis will append site-specific paths to the module search path.\nIt starts by constructing up to four directories from a head and a\ntail part. For the head part, it uses `sys.prefix` and\n`sys.exec_prefix`; empty heads are skipped. For\nthe tail part, it uses the empty string (on Macintosh or Windows) or\nit uses first lib/python2.2/site-packages and then\nlib/site-python (on Unix). For each of the distinct\nhead-tail combinations, it sees if it refers to an existing directory,\nand if so, adds to `sys.path`, and also inspects the path for\nconfiguration files.\nA path configuration file is a file whose name has the form\npackage.pth; its contents are additional items (one\nper line) to be added to `sys.path`. Non-existing items are\nnever added to `sys.path`, but no check is made that the item\nrefers to a directory (rather than a file). No item is added to\n`sys.path` more than once. Blank lines and lines beginning with\n`#` are skipped. Lines starting with `import` are executed.\nFor example, suppose `sys.prefix` and `sys.exec_prefix` are\nset to /usr/local. The Python 2.2 library is then\ninstalled in /usr/local/lib/python2.2 (where only the\nfirst three characters of `sys.version` are used to form the\ninstallation path name). Suppose this has a subdirectory\n/usr/local/lib/python2.2/site-packages with three\nsubsubdirectories, foo, bar and spam, and two\npath configuration files, foo.pth and bar.pth. Assume\nfoo.pth contains the following:\n```text\n\n# foo package configuration\n\nfoo\nbar\nbletch\n```\nand bar.pth contains:\n```text\n\n# bar package configuration\n\nbar\n```\nThen the following directories are added to `sys.path`, in this\norder:\n```text\n\n/usr/local/lib/python1.5/site-packages/bar\n/usr/local/lib/python1.5/site-packages/foo\n```\nNote that bletch is omitted because it doesn't exist; the\nbar directory precedes the foo directory because\nbar.pth comes alphabetically before foo.pth; and\nspam is omitted because it is not mentioned in either path\nconfiguration file.\nAfter these path manipulations, an attempt is made to import a module\nnamed sitecustomize, which can\nperform arbitrary site-specific customizations. If this import fails\nwith an ImportError exception, it is silently ignored.", "python_version": "2.2", "length": 2649, "url": "https://docs.python.org/2.2/lib/module-site.html"} {"title": "11.12 smtplib -- SMTP protocol client", "text": "nntp-objects.html | internet.html | SMTP-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.12 smtplib --\nSMTP protocol client\nThe smtplib module defines an SMTP client session object that\ncan be used to send mail to any Internet machine with an SMTP or ESMTP\nlistener daemon. For details of SMTP and ESMTP operation, consult\nRFC 821 (http://www.faqs.org/rfcs/rfc821.html) (Simple Mail Transfer Protocol) and RFC 1869 (http://www.faqs.org/rfcs/rfc1869.html)\n(SMTP Service Extensions).\nA nice selection of exceptions is defined as well:\nSee Also:", "python_version": "2.2", "length": 591, "url": "https://docs.python.org/2.2/lib/module-smtplib.html"} {"title": "14.10 sndhdr -- Determine type of sound file", "text": "module-imghdr.html | mmedia.html | crypto.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.10 sndhdr --\nDetermine type of sound file\nThe sndhdr provides utility functions which attempt to\ndetermine the type of sound data which is in a file. When these\nfunctions are able to determine what type of sound data is stored in a\nfile, they return a tuple `( type , sampling_rate , channels , frames , bits_per_sample )`. The value for\ntype indicates the data type and will be one of the strings\n`'aifc'`, `'aiff'`, `'au'`, `'hcom'`,\n`'sndr'`, `'sndt'`, `'voc'`, `'wav'`,\n`'8svx'`, `'sb'`, `'ub'`, or `'ul'`. The\nsampling_rate will be either the actual value or `0` if\nunknown or difficult to decode. Similarly, channels will be\neither the number of channels or `0` if it cannot be determined\nor if the value is difficult to decode. The value for frames\nwill be either the number of frames or `-1`. The last item in\nthe tuple, bits_per_sample, will either be the sample size in\nbits or `'A'` for A-LAWor `'U'` for\nu-LAW.", "python_version": "2.2", "length": 1053, "url": "https://docs.python.org/2.2/lib/module-sndhdr.html"} {"title": "7.2 socket -- Low-level networking interface", "text": "node214.html | someos.html | socket-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.2 socket --\nLow-level networking interface\nThis module provides access to the BSD socket interface.\nIt is available on all modern Unix systems, Windows, MacOS, BeOS,\nOS/2, and probably additional platforms.\nFor an introduction to socket programming (in C), see the following\npapers: An Introductory 4.3BSD Interprocess Communication\nTutorial, by Stuart Sechrest and An Advanced 4.3BSD\nInterprocess Communication Tutorial, by Samuel J. Leffler et al,\nboth in the Unix Programmer's Manual, Supplementary Documents 1\n(sections PS1:7 and PS1:8). The platform-specific reference material\nfor the various socket-related system calls are also a valuable source\nof information on the details of socket semantics. For Unix, refer\nto the manual pages; for Windows, see the WinSock (or Winsock 2)\nspecification.\nFor IPv6-ready APIs, readers may want to refer to RFC 2553 (http://www.faqs.org/rfcs/rfc2553.html) titled\nBasic Socket Interface Extensions for IPv6.\nThe Python interface is a straightforward transliteration of the\nUnix system call and library interface for sockets to Python's\nobject-oriented style: the socket() function returns a\nsocket objectwhose methods implement the\nvarious socket system calls. Parameter types are somewhat\nhigher-level than in the C interface: as with read() and\nwrite() operations on Python files, buffer allocation on\nreceive operations is automatic, and buffer length is implicit on send\noperations.\nSocket addresses are represented as follows:\nA single string is used for the AF_UNIX address family.\nA pair `( host , port )` is used for the\nAF_INET address family, where host is a string\nrepresenting either a hostname in Internet domain notation like\n`'daring.cwi.nl'` or an IPv4 address like `'100.50.200.5'`,\nand port is an integral port number.\nFor AF_INET6 address family, a four-tuple\n`( host , port , flowinfo , scopeid )` is\nused, where flowinfo and scopeid represents\n`sin6_flowinfo` and `sin6_scope_id` member in\nstruct sockaddr_in6 in C.\nFor socket module methods, flowinfo and scopeid\ncan be omitted just for backward compatibility. Note, however,\nomission of scopeid can cause problems in manipulating scoped\nIPv6 addresses. Other address families are currently not supported.\nThe address format required by a particular socket object is\nautomatically selected based on the address family specified when the\nsocket object was created.\nFor IPv4 addresses, two special forms are accepted instead of a host\naddress: the empty string represents INADDR_ANY, and the string\n`''` represents INADDR_BROADCAST.\nThe behavior is not available for IPv6 for backward compatibility,\ntherefore, you may want to avoid these if you intend to support IPv6 with\nyour Python programs.\nIf you use a hostname in the host portion of IPv4/v6 socket\naddress, the program may show a nondeterministic behavior, as Python\nuses the first address returned from the DNS resolution. The socket\naddress will be resolved differently into an actual IPv4/v6 address,\ndepending on the results from DNS resolution and/or the host\nconfiguration. For deterministic behavior use a numeric address in\nhost portion.\nAll errors raise exceptions. The normal exceptions for invalid\nargument types and out-of-memory conditions can be raised; errors\nrelated to socket or address semantics raise the error\nsocket.error.\nNon-blocking mode is supported through the\nsetblocking() method.\nThe module socket exports the following constants and functions:\nSee Also:", "python_version": "2.2", "length": 3597, "url": "https://docs.python.org/2.2/lib/module-socket.html"} {"title": "11.15 SocketServer -- A framework for network servers", "text": "module-urlparse.html | internet.html | module-BaseHTTPServer.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.15 SocketServer --\nA framework for network servers\nThe SocketServer module simplifies the task of writing network\nservers.\nThere are four basic server classes: TCPServer uses the\nInternet TCP protocol, which provides for continuous streams of data\nbetween the client and server. UDPServer uses datagrams, which\nare discrete packets of information that may arrive out of order or be\nlost while in transit. The more infrequently used\nUnixStreamServer and UnixDatagramServer classes are\nsimilar, but use Unix domain sockets; they're not available on\nnon-Unix platforms. For more details on network programming, consult\na book such as W. Richard Steven's UNIX Network Programming\nor Ralph Davis's Win32 Network Programming.\nThese four classes process requests synchronously; each request\nmust be completed before the next request can be started. This isn't\nsuitable if each request takes a long time to complete, because it\nrequires a lot of computation, or because it returns a lot of data\nwhich the client is slow to process. The solution is to create a\nseparate process or thread to handle each request; the\nForkingMixIn and ThreadingMixIn mix-in classes can be\nused to support asynchronous behaviour.\nCreating a server requires several steps. First, you must create a\nrequest handler class by subclassing the BaseRequestHandler\nclass and overriding its handle() method; this method will\nprocess incoming requests. Second, you must instantiate one of the\nserver classes, passing it the server's address and the request\nhandler class. Finally, call the handle_request() or\nserve_forever() method of the server object to process one or\nmany requests.\nServer classes have the same external methods and attributes, no\nmatter what network protocol they use:\nThe server classes support the following class variables:\nThere are various server methods that can be overridden by subclasses\nof base server classes like TCPServer; these methods aren't\nuseful to external users of the server object.\nThe request handler class must define a new handle() method,\nand can override any of the following methods. A new instance is\ncreated for each request.", "python_version": "2.2", "length": 2288, "url": "https://docs.python.org/2.2/lib/module-SocketServer.html"} {"title": "6.4 stat -- Interpreting stat() results", "text": "module-dircache.html | allos.html | module-statcache.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.4 stat --\nInterpreting stat() results\nThe stat module defines constants and functions for\ninterpreting the results of os.stat(),\nos.fstat() and os.lstat() (if they exist). For\ncomplete details about the stat(), fstat() and\nlstat() calls, consult the documentation for your system.\nThe stat module defines the following functions to test for\nspecific file types:\nTwo additional functions are defined for more general manipulation of\nthe file's mode:\nNormally, you would use the os.path.is*() functions for\ntesting the type of a file; the functions here are useful when you are\ndoing multiple tests of the same file and wish to avoid the overhead of\nthe stat() system call for each test. These are also\nuseful when checking for information about a file that isn't handled\nby os.path (module-os.path.html), like the tests for block and character\ndevices.\nAll the variables below are simply symbolic indexes into the 10-tuple\nreturned by os.stat(), os.fstat() or\nos.lstat().\nThe interpretation of ``file size'' changes according to the file\ntype. For plain files this is the size of the file in bytes. For\nFIFOs and sockets under most flavors of Unix (including Linux in\nparticular), the ``size'' is the number of bytes waiting to be read at\nthe time of the call to os.stat(), os.fstat(),\nor os.lstat(); this can sometimes be useful, especially for\npolling one of these special files after a non-blocking open. The\nmeaning of the size field for other character and block devices varies\nmore, depending on the implementation of the underlying system call.\nExample:", "python_version": "2.2", "length": 1700, "url": "https://docs.python.org/2.2/lib/module-stat.html"} {"title": "6.5 statcache -- An optimization of os.stat()", "text": "module-stat.html | allos.html | module-statvfs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.5 statcache --\nAn optimization of os.stat()\nDeprecated since release 2.2.\nUse os (module-os.html).stat() directly instead\nof using the cache; the cache introduces a very high level of\nfragility in applications using it and complicates application code\nwith the addition of cache management support.\nThe statcache module provides a simple optimization to\nos.stat(): remembering the values of previous invocations.\nThe statcache module defines the following functions:\nThe rest of the functions are used to clear the cache, or parts of\nit.\nExample:", "python_version": "2.2", "length": 681, "url": "https://docs.python.org/2.2/lib/module-statcache.html"} {"title": "6.6 statvfs -- Constants used with os.statvfs()", "text": "module-statcache.html | allos.html | module-filecmp.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.6 statvfs --\nConstants used with os.statvfs()\nThe statvfs module defines constants so interpreting the result\nif os.statvfs(), which returns a tuple, can be made without\nremembering ``magic numbers.'' Each of the constants defined in this\nmodule is the index of the entry in the tuple returned by\nos.statvfs() that contains the specified information.", "python_version": "2.2", "length": 490, "url": "https://docs.python.org/2.2/lib/module-statvfs.html"} {"title": "4.1 string -- Common string operations", "text": "strings.html | strings.html | module-re.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.1 string --\nCommon string operations\nThis module defines some constants useful for checking character\nclasses and some useful string functions. See the module\nre (module-re.html)for string functions based on regular\nexpressions.\nThe constants defined in this module are:\nMany of the functions provided by this module are also defined as\nmethods of string and Unicode objects; see ``String Methods'' (section\n2.2.6 (string-methods.html#string-methods)) for more information on those.\nThe functions defined in this module are:", "python_version": "2.2", "length": 652, "url": "https://docs.python.org/2.2/lib/module-string.html"} {"title": "4.6 StringIO -- Read and write strings as files", "text": "module-fpformat.html | strings.html | module-cStringIO.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.6 StringIO --\nRead and write strings as files\nThis module implements a file-like class, StringIO,\nthat reads and writes a string buffer (also known as memory\nfiles). See the description of file objects for operations (section\n2.2.8 (bltin-file-objects.html#bltin-file-objects)).\nThe following methods of StringIO objects require special\nmention:", "python_version": "2.2", "length": 488, "url": "https://docs.python.org/2.2/lib/module-StringIO.html"} {"title": "4.3 struct -- Interpret strings as packed binary data", "text": "node102.html | strings.html | module-difflib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.3 struct --\nInterpret strings as packed binary data\nThis module performs conversions between Python values and C\nstructs represented as Python strings. It uses format strings\n(explained below) as compact descriptions of the lay-out of the C\nstructs and the intended conversion to/from Python values. This can\nbe used in handling binary data stored in files or from network\nconnections, among other sources.\nThe module defines the following exception and functions:\nFormat characters have the following meaning; the conversion between\nC and Python values should be obvious given their types:\nNotes:\n(1): The \"q\" and \"Q\" conversion codes are available in\nnative mode only if the platform C compiler supports C long long,\nor, on Windows, __int64. They are always available in standard\nmodes.\nNew in version 2.2.\nA format character may be preceded by an integral repeat count. For\nexample, the format string `'4h'` means exactly the same as\n`'hhhh'`.\nWhitespace characters between formats are ignored; a count and its\nformat must not contain whitespace though.\nFor the \"s\" format character, the count is interpreted as the\nsize of the string, not a repeat count like for the other format\ncharacters; for example, `'10s'` means a single 10-byte string, while\n`'10c'` means 10 characters. For packing, the string is\ntruncated or padded with null bytes as appropriate to make it fit.\nFor unpacking, the resulting string always has exactly the specified\nnumber of bytes. As a special case, `'0s'` means a single, empty\nstring (while `'0c'` means 0 characters).\nThe \"p\" format character encodes a \"Pascal string\", meaning\na short variable-length string stored in a fixed number of bytes.\nThe count is the total number of bytes stored. The first byte stored is\nthe length of the string, or 255, whichever is smaller. The bytes\nof the string follow. If the string passed in to pack() is too\nlong (longer than the count minus 1), only the leading count-1 bytes of the\nstring are stored. If the string is shorter than count-1, it is padded\nwith null bytes so that exactly count bytes in all are used. Note that\nfor unpack(), the \"p\" format character consumes count\nbytes, but that the string returned can never contain more than 255\ncharacters.\nFor the \"I\", \"L\", \"q\" and \"Q\"\nformat characters, the return value is a Python long integer.\nFor the \"P\" format character, the return value is a Python\ninteger or long integer, depending on the size needed to hold a\npointer when it has been cast to an integer type. A NULL pointer will\nalways be returned as the Python integer `0`. When packing pointer-sized\nvalues, Python integer or long integer objects may be used. For\nexample, the Alpha and Merced processors use 64-bit pointer values,\nmeaning a Python long integer will be used to hold the pointer; other\nplatforms use 32-bit pointers and will use a Python integer.\nBy default, C numbers are represented in the machine's native format\nand byte order, and properly aligned by skipping pad bytes if\nnecessary (according to the rules used by the C compiler).\nAlternatively, the first character of the format string can be used to\nindicate the byte order, size and alignment of the packed data,\naccording to the following table:\nIf the first character is not one of these, \"@\" is assumed.\nNative byte order is big-endian or little-endian, depending on the\nhost system. For example, Motorola and Sun processors are big-endian;\nIntel and DEC processors are little-endian.\nNative size and alignment are determined using the C compiler's\nsizeof expression. This is always combined with native byte\norder.\nStandard size and alignment are as follows: no alignment is required\nfor any type (so you have to use pad bytes);\nshort is 2 bytes;\nint and long are 4 bytes;\nlong long (__int64 on Windows) is 8 bytes;\nfloat and double are 32-bit and 64-bit\nIEEE floating point numbers, respectively.\nNote the difference between \"@\" and \"=\": both use\nnative byte order, but the size and alignment of the latter is\nstandardized.\nThe form \"!\" is available for those poor souls who claim they\ncan't remember whether network byte order is big-endian or\nlittle-endian.\nThere is no way to indicate non-native byte order (force\nbyte-swapping); use the appropriate choice of \"<\" or\n\">\".\nThe \"P\" format character is only available for the native\nbyte ordering (selected as the default or with the \"@\" byte\norder character). The byte order character \"=\" chooses to\nuse little- or big-endian ordering based on the host system. The\nstruct module does not interpret this as native ordering, so the\n\"P\" format is not available.\nExamples (all using native byte order, size and alignment, on a\nbig-endian machine):\n```text\n\n>>> from struct import *\n>>> pack('hhl', 1, 2, 3)\n'\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03'\n>>> unpack('hhl', '\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03')\n(1, 2, 3)\n>>> calcsize('hhl')\n8\n```\nHint: to align the end of a structure to the alignment requirement of\na particular type, end the format with the code for that type with a\nrepeat count of zero. For example, the format `'llh0l'`\nspecifies two pad bytes at the end, assuming longs are aligned on\n4-byte boundaries. This only works when native size and alignment are\nin effect; standard size and alignment does not enforce any alignment.", "python_version": "2.2", "length": 5383, "url": "https://docs.python.org/2.2/lib/module-struct.html"} {"title": "14.4 sunau -- Read and write Sun AU files", "text": "module-aifc.html | mmedia.html | au-read-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.4 sunau --\nRead and write Sun AU files\nThe sunau module provides a convenient interface to the Sun\nAU sound format. Note that this module is interface-compatible with\nthe modules aifc (module-aifc.html) and wave (module-wave.html).\nAn audio file consists of a header followed by the data. The fields\nof the header are:\nApart from the info field, all header fields are 4 bytes in size.\nThey are all 32-bit unsigned integers encoded in big-endian byte\norder.\nThe sunau module defines the following functions:\nThe sunau module defines the following exception:\nThe sunau module defines the following data items:", "python_version": "2.2", "length": 745, "url": "https://docs.python.org/2.2/lib/module-sunau.html"} {"title": "21.2 SUNAUDIODEV -- Constants used with sunaudiodev", "text": "audio-device-objects.html | sunos.html | node604.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 21.2 SUNAUDIODEV --\nConstants used with sunaudiodev\nAvailability: SunOS.\nThis is a companion module to\nsunaudiodev (module-sunaudiodev.html)which defines\nuseful symbolic constants like MIN_GAIN,\nMAX_GAIN, SPEAKER, etc. The names of the\nconstants are the same names as used in the C include file\n``, with the leading string \"AUDIO_\"stripped.", "python_version": "2.2", "length": 490, "url": "https://docs.python.org/2.2/lib/module-sunaudiodev-constants.html"} {"title": "21.1 sunaudiodev -- Access to Sun audio hardware", "text": "sunos.html | sunos.html | audio-device-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 21.1 sunaudiodev --\nAccess to Sun audio hardware\nAvailability: SunOS.\nThis module allows you to access the Sun audio interface. The Sun\naudio hardware is capable of recording and playing back audio data\nin u-LAWformat with a sample rate of 8K per second. A\nfull description can be found in the audio(7I) manual page.\nThe module\nSUNAUDIODEV (module-sunaudiodev-constants.html)\ndefines constants which may be used with this module.\nThis module defines the following variables and functions:", "python_version": "2.2", "length": 621, "url": "https://docs.python.org/2.2/lib/module-sunaudiodev.html"} {"title": "18.2 symbol -- Constants used with Python parse trees", "text": "node558.html | language.html | module-token.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.2 symbol --\nConstants used with Python parse trees\nThis module provides constants which represent the numeric values of\ninternal nodes of the parse tree. Unlike most Python constants, these\nuse lower-case names. Refer to the file Grammar/Grammar in the\nPython distribution for the definitions of the names in the context of\nthe language grammar. The specific numeric values which the names map\nto may change between Python versions.\nThis module also provides one additional data object:", "python_version": "2.2", "length": 619, "url": "https://docs.python.org/2.2/lib/module-symbol.html"} {"title": "3.1 sys -- System-specific parameters and functions", "text": "python.html | python.html | module-gc.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.1 sys --\nSystem-specific parameters and functions\nThis module provides access to some variables used or maintained by the\ninterpreter and to functions that interact strongly with the interpreter.\nIt is always available.", "python_version": "2.2", "length": 345, "url": "https://docs.python.org/2.2/lib/module-sys.html"} {"title": "8.17 syslog -- Unix syslog library routines", "text": "module-nis.html | unix.html | module-commands.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.17 syslog --\nUnix syslog library routines\nAvailability: Unix.\nThis module provides an interface to the Unix `syslog` library\nroutines. Refer to the Unix manual pages for a detailed description\nof the `syslog` facility.\nThe module defines the following functions:\nThe module defines the following constants:", "python_version": "2.2", "length": 440, "url": "https://docs.python.org/2.2/lib/module-syslog.html"} {"title": "18.6 tabnanny -- Detection of ambiguous indentation", "text": "module-tokenize.html | language.html | module-pyclbr.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.6 tabnanny --\nDetection of ambiguous indentation\nFor the time being this module is intended to be called as a script.\nHowever it is possible to import it into an IDE and use the function\ncheck() described below.\nWarning:\nThe API provided by this module is likely to change\nin future releases; such changes may not be backward compatible.", "python_version": "2.2", "length": 479, "url": "https://docs.python.org/2.2/lib/module-tabnanny.html"} {"title": "11.13 telnetlib -- Telnet client", "text": "SMTP-example.html | internet.html | telnet-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.13 telnetlib --\nTelnet client\nThe telnetlib module provides a Telnet class that\nimplements the Telnet protocol. See RFC 854 (http://www.faqs.org/rfcs/rfc854.html) for details about the\nprotocol. In addition, it provides symbolic constants for the protocol\ncharacters (IAC/DONT/DO/WONT/WILL), and for the telnet options. The\nsymbolic names of the telnet options follow the definitions in\n`arpa/telnet.h`, with the leading `TELOPT_` removed. For\nsymbolic names of options which are traditionally not included in\n`arpa/telnet.h`, see the module source itself.\nSee Also:", "python_version": "2.2", "length": 706, "url": "https://docs.python.org/2.2/lib/module-telnetlib.html"} {"title": "6.19 tempfile -- Generate temporary file names", "text": "module-getopt.html | allos.html | module-errno.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.19 tempfile --\nGenerate temporary file names\nThis module generates temporary file names. It is not Unix specific,\nbut it may require some help on non-Unix systems.\nThe module defines the following user-callable functions:\nThe module uses two global variables that tell it how to construct a\ntemporary name. The caller may assign values to them; by default they\nare initialized at the first call to mktemp().", "python_version": "2.2", "length": 542, "url": "https://docs.python.org/2.2/lib/module-tempfile.html"} {"title": "8.8 termios -- POSIX style tty control", "text": "module-gdbm.html | unix.html | node263.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.8 termios --\nPOSIX style tty control\nAvailability: Unix.\nThis module provides an interface to the POSIX calls for tty I/O\ncontrol. For a complete description of these calls, see the POSIX or\nUnix manual pages. It is only available for those Unix versions\nthat support POSIX termios style tty I/O control (and then\nonly if configured at installation time).\nAll functions in this module take a file descriptor fd as their\nfirst argument. This can be an integer file descriptor, such as\nreturned by `sys.stdin.fileno()`, or a file object, such as\n`sys.stdin` itself.\nThis module also defines all the constants needed to work with the\nfunctions provided here; these have the same name as their\ncounterparts in C. Please refer to your system documentation for more\ninformation on using these terminal control interfaces.\nThe module defines the following functions:\nSee Also:", "python_version": "2.2", "length": 996, "url": "https://docs.python.org/2.2/lib/module-termios.html"} {"title": "8.9 TERMIOS -- Constants used with the termios module", "text": "node263.html | unix.html | module-tty.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.9 TERMIOS --\nConstants used with the termios module\nAvailability: Unix.\nDeprecated since release 2.1.\nImport needed constants from termios (module-termios.html)\ninstead.", "python_version": "2.2", "length": 295, "url": "https://docs.python.org/2.2/lib/module-TERMIOSuppercase.html"} {"title": "7.4 thread -- Multiple threads of control", "text": "poll-objects.html | someos.html | module-threading.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.4 thread --\nMultiple threads of control\nThis module provides low-level primitives for working with multiple\nthreads (a.k.a. light-weight processes or tasks) -- multiple\nthreads of control sharing their global data space. For\nsynchronization, simple locks (a.k.a. mutexes or binary\nsemaphores) are provided.\nThe module is optional. It is supported on Windows NT and '95, SGI\nIRIX, Solaris 2.x, as well as on systems that have a POSIX thread\n(a.k.a. ``pthread'') implementation.\nIt defines the following constant and functions:\nLock objects have the following methods:\nCaveats:", "python_version": "2.2", "length": 714, "url": "https://docs.python.org/2.2/lib/module-thread.html"} {"title": "7.5 threading -- Higher-level threading interface", "text": "module-thread.html | someos.html | lock-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.5 threading --\nHigher-level threading interface\nThis module constructs higher-level threading interfaces on top of the\nlower level thread (module-thread.html) module.\nThis module is safe for use with \"from threading import *\". It\ndefines the following functions and objects:\nDetailed interfaces for the objects are documented below.\nThe design of this module is loosely based on Java's threading model.\nHowever, where Java makes locks and condition variables basic behavior\nof every object, they are separate objects in Python. Python's Thread\nclass supports a subset of the behavior of Java's Thread class;\ncurrently, there are no priorities, no thread groups, and threads\ncannot be destroyed, stopped, suspended, resumed, or interrupted. The\nstatic methods of Java's Thread class, when implemented, are mapped to\nmodule-level functions.\nAll of the methods described below are executed atomically.", "python_version": "2.2", "length": 1034, "url": "https://docs.python.org/2.2/lib/module-threading.html"} {"title": "6.9 time -- Time access and conversions", "text": "popen3-objects.html | allos.html | module-sched.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 6.9 time --\nTime access and conversions\nThis module provides various time-related functions.\nIt is always available, but not all functions are available\non all platforms.\nAn explanation of some terminology and conventions is in order.\n- The epochis the point where the time starts. On\nJanuary 1st of that year, at 0 hours, the ``time since the epoch'' is\nzero. For Unix, the epoch is 1970. To find out what the epoch is,\nlook at `gmtime(0)`.\n- The functions in this module do not handle dates and times before the\nepoch or far in the future. The cut-off point in the future is\ndetermined by the C library; for Unix, it is typically in\n2038.\n- Year 2000 (Y2K) issues: Python\ndepends on the platform's C library, which generally doesn't have year\n2000 issues, since all dates and times are represented internally as\nseconds since the epoch. Functions accepting a time tuple (see below)\ngenerally require a 4-digit year. For backward compatibility, 2-digit\nyears are supported if the module variable `accept2dyear` is a\nnon-zero integer; this variable is initialized to `1` unless the\nenvironment variable PYTHONY2K is set to a non-empty string,\nin which case it is initialized to `0`. Thus, you can set\nPYTHONY2K to a non-empty string in the environment to require 4-digit\nyears for all year input. When 2-digit years are accepted, they are\nconverted according to the POSIX or X/Open standard: values 69-99\nare mapped to 1969-1999, and values 0-68 are mapped to 2000-2068.\nValues 100-1899 are always illegal. Note that this is new as of\nPython 1.5.2(a2); earlier versions, up to Python 1.5.1 and 1.5.2a1,\nwould add 1900 to year values below 1900.\n- UTCis Coordinated Universal Time(formerly known as Greenwich Mean\nTime,or GMT). The acronym UTC is not a\nmistake but a compromise between English and French.\n- DST is Daylight Saving Time,an adjustment\nof the timezone by (usually) one hour during part of the year. DST\nrules are magic (determined by local law) and can change from year to\nyear. The C library has a table containing the local rules (often it\nis read from a system file for flexibility) and is the only source of\nTrue Wisdom in this respect.\n- The precision of the various real-time functions may be less than\nsuggested by the units in which their value or argument is expressed.\nE.g. on most Unix systems, the clock ``ticks'' only 50 or 100 times a\nsecond, and on the Mac, times are only accurate to whole seconds.\n- On the other hand, the precision of time() and\nsleep() is better than their Unix equivalents: times are\nexpressed as floating point numbers, time() returns the\nmost accurate time available (using Unix gettimeofday()\nwhere available), and sleep() will accept a time with a\nnonzero fraction (Unix select() is used to implement\nthis, where available).\n- The time tuple as returned by gmtime(),\nlocaltime(), and strptime(), and accepted by\nasctime(), mktime() and strftime(),\nis a tuple of 9 integers:\nNote that unlike the C structure, the month value is a\nrange of 1-12, not 0-11. A year value will be handled as described\nunder ``Year 2000 (Y2K) issues'' above. A `-1` argument as\ndaylight savings flag, passed to mktime() will usually\nresult in the correct daylight savings state to be filled in.\nWhen a tuple with an incorrect length is passed to a function\nexpecting a time tuple, or having elements of the wrong type, a\nTypeError is raised.\nThe module defines the following functions and data items:", "python_version": "2.2", "length": 3565, "url": "https://docs.python.org/2.2/lib/module-time.html"} {"title": "16.2 Tix -- Extension widgets for Tk", "text": "node515.html | tkinter.html | node517.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 16.2 Tix --\nExtension widgets for Tk\nThe Tix (Tk Interface Extension) module provides an\nadditional rich set of widgets. Although the standard Tk library has\nmany useful widgets, they are far from complete. The Tix\nlibrary provides most of the commonly needed widgets that are missing\nfrom standard Tk: HList, ComboBox, Control\n(a.k.a. SpinBox) and an assortment of scrollable widgets. Tix\nalso includes many more widgets that are generally useful in a wide\nrange of applications: NoteBook, FileEntry,\nPanedWindow, etc; there are more than 40 of them.\nWith all these new widgets, you can introduce new interaction\ntechniques into applications, creating more useful and more intuitive\nuser interfaces. You can design your application by choosing the most\nappropriate widgets to match the special needs of your application and\nusers.\nSee Also:", "python_version": "2.2", "length": 965, "url": "https://docs.python.org/2.2/lib/module-Tix.html"} {"title": "16.1 Tkinter -- Python interface to Tcl/Tk", "text": "tkinter.html | tkinter.html | node500.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 16.1 Tkinter --\nPython interface to Tcl/Tk\nThe Tkinter module (``Tk interface'') is the standard Python\ninterface to the Tk GUI toolkit, now maintained at ActiveState. Both\nTk and Tkinter are available on most Unix platforms, as well\nas on Windows and Macintosh systems.\nSee Also:", "python_version": "2.2", "length": 404, "url": "https://docs.python.org/2.2/lib/module-Tkinter.html"} {"title": "18.3 token -- Constants used with Python parse trees", "text": "module-symbol.html | language.html | module-keyword.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.3 token --\nConstants used with Python parse trees\nThis module provides constants which represent the numeric values of\nleaf nodes of the parse tree (terminal tokens). Refer to the file\nGrammar/Grammar in the Python distribution for the definitions\nof the names in the context of the language grammar. The specific\nnumeric values which the names map to may change between Python\nversions.\nThis module also provides one data object and some functions. The\nfunctions mirror definitions in the Python C header files.", "python_version": "2.2", "length": 653, "url": "https://docs.python.org/2.2/lib/module-token.html"} {"title": "18.5 tokenize -- Tokenizer for Python source", "text": "module-keyword.html | language.html | module-tabnanny.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 18.5 tokenize --\nTokenizer for Python source\nThe tokenize module provides a lexical scanner for Python\nsource code, implemented in Python. The scanner in this module\nreturns comments as tokens as well, making it useful for implementing\n``pretty-printers,'' including colorizers for on-screen displays.\nThe primary entry point is a generator:\nAn older entry point is retained for backward compatibility:\nAll constants from the token (module-token.html) module are also exported from\ntokenize, as are two additional token type values that might be\npassed to the tokeneater function by tokenize():", "python_version": "2.2", "length": 734, "url": "https://docs.python.org/2.2/lib/module-tokenize.html"} {"title": "3.12 traceback -- Print or retrieve a stack traceback", "text": "inspect-stack.html | python.html | traceback-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.12 traceback --\nPrint or retrieve a stack traceback\nThis module provides a standard interface to extract, format and print\nstack traces of Python programs. It exactly mimics the behavior of\nthe Python interpreter when it prints a stack trace. This is useful\nwhen you want to print stack traces under program control, e.g. in a\n``wrapper'' around the interpreter.\nThe module uses traceback objects -- this is the object type\nthat is stored in the variables `sys.exc_traceback` and\n`sys.last_traceback` and returned as the third item from\nsys.exc_info().\nThe module defines the following functions:", "python_version": "2.2", "length": 737, "url": "https://docs.python.org/2.2/lib/module-traceback.html"} {"title": "8.10 tty -- Terminal control functions", "text": "module-TERMIOSuppercase.html | unix.html | module-pty.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8.10 tty --\nTerminal control functions\nAvailability: Unix.\nThe tty module defines functions for putting the tty into\ncbreak and raw modes.\nBecause it requires the termios (module-termios.html) module, it will work\nonly on Unix.\nThe tty module defines the following functions:", "python_version": "2.2", "length": 415, "url": "https://docs.python.org/2.2/lib/module-tty.html"} {"title": "16.4 turtle -- Turtle graphics for Tk", "text": "module-ScrolledText.html | tkinter.html | pen-rawpen-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 16.4 turtle --\nTurtle graphics for Tk\nAvailability: Tk.\nThe turtle module provides turtle graphics primitives, in both an\nobject-oriented and procedure-oriented ways. Because it uses Tkinter\nfor the underlying graphics, it needs a version of python installed with\nTk support.\nThe procedural interface uses a pen and a canvas which are automagically\ncreated when any of the functions are called.\nThe turtle module defines the following functions:\nThis module also does `from math import *`, so see the\ndocumentation for the math (module-math.html) module for additional constants\nand functions useful for turtle graphics.\nFor examples, see the code of the demo() function.\nThis module defines the following classes:", "python_version": "2.2", "length": 861, "url": "https://docs.python.org/2.2/lib/module-turtle.html"} {"title": "3.6 types -- Names for all built-in types", "text": "atexit-example.html | python.html | module-UserDict.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.6 types --\nNames for all built-in types\nThis module defines names for all object types that are used by the\nstandard Python interpreter, but not for the types defined by various\nextension modules. It is safe to use \"from types import *\" --\nthe module does not export any names besides the ones listed here.\nNew names exported by future versions of this module will all end in\n\"Type\".\nTypical use is for functions that do different things depending on\ntheir argument types, like the following:\n```text\n\nfrom types import *\ndef delete(list, item):\nif type(item) is IntType:\ndel list[item]\nelse:\nlist.remove(item)\n```\nThe module defines the following names:", "python_version": "2.2", "length": 794, "url": "https://docs.python.org/2.2/lib/module-types.html"} {"title": "4.9 unicodedata -- Unicode Database", "text": "stream-recoder-objects.html | strings.html | misc.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4.9 unicodedata --\nUnicode Database\nThis module provides access to the Unicode Character Database which\ndefines character properties for all Unicode characters. The data in\nthis database is based on the UnicodeData.txt file version\n3.0.0 which is publically available from ftp://ftp.unicode.org/.\nThe module uses the same names and symbols as defined by the\nUnicodeData File Format 3.0.0 (see\nhttp://www.unicode.org/Public/UNIDATA/UnicodeData.html). It\ndefines the following functions:", "python_version": "2.2", "length": 621, "url": "https://docs.python.org/2.2/lib/module-unicodedata.html"} {"title": "5.3 unittest -- Unit testing framework", "text": "node130.html | misc.html | organizing-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.3 unittest --\nUnit testing framework\nThe Python unit testing framework, often referred to as ``PyUnit,'' is\na Python language version of JUnit, by Kent Beck and Erich Gamma.\nJUnit is, in turn, a Java version of Kent's Smalltalk testing\nframework. Each is the de facto standard unit testing framework for\nits respective language.\nPyUnit supports test automation, sharing of setup and shutdown code\nfor tests, aggregation of tests into collections, and independence of\nthe tests from the reporting framework. The unittest module\nprovides classes that make it easy to support these qualities for a\nset of tests.\nTo achieve this, PyUnit supports some important concepts:\nThe test case and test fixture concepts are supported through the\nTestCase and FunctionTestCase classes; the former\nshould be used when creating new tests, and the later can be used when\nintegrating existing test code with a PyUnit-driven framework. When\nbuilding test fixtures using TestCase, the setUp()\nand tearDown() methods can be overridden to provide\ninitialization and cleanup for the fixture. With\nFunctionTestCase, existing functions can be passed to the\nconstructor for these purposes. When the test is run, the\nfixture initialization is run first; if it succeeds, the cleanup\nmethod is run after the test has been executed, regardless of the\noutcome of the test. Each instance of the TestCase will only\nbe used to run a single test method, so a new fixture is created for\neach test.\nTest suites are implemented by the TestSuite class. This\nclass allows individual tests and test suites to be aggregated; when\nthe suite is executed, all tests added directly to the suite and in\n``child'' test suites are run.\nA test runner is an object that provides a single method,\nrun(), which accepts a TestCase or TestSuite\nobject as a parameter, and returns a result object. The class\nTestResult is provided for use as the result object. PyUnit\nprovide the TextTestRunner as an example test runner which\nreports test results on the standard error stream by default.\nAlternate runners can be implemented for other environments (such as\ngraphical environments) without any need to derive from a specific\nclass.\nSee Also:", "python_version": "2.2", "length": 2317, "url": "https://docs.python.org/2.2/lib/module-unittest.html"} {"title": "11.4 urllib -- Open arbitrary resources by URL", "text": "module-cgitb.html | internet.html | urlopener-objs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.4 urllib --\nOpen arbitrary resources by URL\nThis module provides a high-level interface for fetching data across\nthe World Wide Web. In particular, the urlopen() function\nis similar to the built-in function open(), but accepts\nUniversal Resource Locators (URLs) instead of filenames. Some\nrestrictions apply -- it can only open URLs for reading, and no seek\noperations are available.\nIt defines the following public functions:\nThe public functions urlopen() and\nurlretrieve() create an instance of the\nFancyURLopener class and use it to perform their requested\nactions. To override this functionality, programmers can create a\nsubclass of URLopener or FancyURLopener, then assign\nthat an instance of that class to the\n`urllib._urlopener` variable before calling the desired function.\nFor example, applications may want to specify a different\nUser-Agent: header than URLopener defines. This\ncan be accomplished with the following code:\n```text\n\nclass AppURLopener(urllib.FancyURLopener):\ndef __init__(self, *args):\nself.version = \"App/1.7\"\nurllib.FancyURLopener.__init__(self, *args)\n\nurllib._urlopener = AppURLopener()\n```\nRestrictions:\n- Currently, only the following protocols are supported: HTTP, (versions\n0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.\n- The caching feature of urlretrieve() has been disabled\nuntil I find the time to hack proper processing of Expiration time\nheaders.\n- There should be a function to query whether a particular URL is in\nthe cache.\n- For backward compatibility, if a URL appears to point to a local file\nbut the file can't be opened, the URL is re-interpreted using the FTP\nprotocol. This can sometimes cause confusing error messages.\n- The urlopen() and urlretrieve() functions can\ncause arbitrarily long delays while waiting for a network connection\nto be set up. This means that it is difficult to build an interactive\nWeb client using these functions without using threads.\n- The data returned by urlopen() or urlretrieve()\nis the raw data returned by the server. This may be binary data\n(e.g. an image), plain text or (for example) HTML. The\nHTTPprotocol provides type information in the\nreply header, which can be inspected by looking at the\nContent-Type: header. For the\nGopherprotocol, type information is encoded\nin the URL; there is currently no easy way to extract it. If the\nreturned data is HTML, you can use the module\nhtmllib (module-htmllib.html)to parse it.\n- This module does not support the use of proxies which require\nauthentication. This may be implemented in the future.\n- Although the urllib module contains (undocumented) routines\nto parse and unparse URL strings, the recommended interface for URL\nmanipulation is in module urlparse (module-urlparse.html).", "python_version": "2.2", "length": 2876, "url": "https://docs.python.org/2.2/lib/module-urllib.html"} {"title": "11.5 urllib2 -- extensible library for opening URLs", "text": "node307.html | internet.html | request-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.5 urllib2 --\nextensible library for opening URLs\nThe urllib2 module defines functions and classes which help\nin opening URLs (mostly HTTP) in a complex world -- basic and digest\nauthentication, redirections and more.\nThe urllib2 module defines the following functions:\nThe following exceptions are raised as appropriate:\nThe following classes are provided:", "python_version": "2.2", "length": 492, "url": "https://docs.python.org/2.2/lib/module-urllib2.html"} {"title": "11.14 urlparse -- Parse URLs into components", "text": "telnet-example.html | internet.html | module-SocketServer.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.14 urlparse --\nParse URLs into components\nThis module defines a standard interface to break Uniform Resource\nLocator (URL) strings up in components (addressing scheme, network\nlocation, path etc.), to combine the components back into a URL\nstring, and to convert a ``relative URL'' to an absolute URL given a\n``base URL.''\nThe module has been designed to match the Internet RFC on Relative\nUniform Resource Locators (and discovered a bug in an earlier\ndraft!).\nIt defines the following functions:", "python_version": "2.2", "length": 643, "url": "https://docs.python.org/2.2/lib/module-urlparse.html"} {"title": "3.28 user -- User-specific configuration hook", "text": "module-site.html | python.html | module-builtin.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.28 user --\nUser-specific configuration hook\nAs a policy, Python doesn't run user-specified code on startup of\nPython programs. (Only interactive sessions execute the script\nspecified in the PYTHONSTARTUP environment variable if it\nexists).\nHowever, some programs or sites may find it convenient to allow users\nto have a standard customization file, which gets run when a program\nrequests it. This module implements such a mechanism. A program\nthat wishes to use the mechanism must execute the statement\n```text\n\nimport user\n```\nThe user module looks for a file .pythonrc.py in the user's\nhome directory and if it can be opened, executes it (using\nexecfile()) in its own (the\nmodule user's) global namespace. Errors during this phase\nare not caught; that's up to the program that imports the\nuser module, if it wishes. The home directory is assumed to\nbe named by the HOME environment variable; if this is not set,\nthe current directory is used.\nThe user's .pythonrc.py could conceivably test for\n`sys.version` if it wishes to do different things depending on\nthe Python version.\nA warning to users: be very conservative in what you place in your\n.pythonrc.py file. Since you don't know which programs will\nuse it, changing the behavior of standard modules or functions is\ngenerally not a good idea.\nA suggestion for programmers who wish to use this mechanism: a simple\nway to let users specify options for your package is to have them\ndefine variables in their .pythonrc.py file that you test in\nyour module. For example, a module spam that has a verbosity\nlevel can look for a variable `user.spam_verbose`, as follows:\n```text\n\nimport user\ntry:\nverbose = user.spam_verbose # user's verbosity preference\nexcept AttributeError:\nverbose = 0 # default verbosity\n```\nPrograms with extensive customization needs are better off reading a\nprogram-specific customization file.\nPrograms with security or privacy concerns should not import\nthis module; a user can easily break into a program by placing\narbitrary code in the .pythonrc.py file.\nModules for general use should not import this module; it may\ninterfere with the operation of the importing program.", "python_version": "2.2", "length": 2286, "url": "https://docs.python.org/2.2/lib/module-user.html"} {"title": "3.7 UserDict -- Class wrapper for dictionary objects", "text": "module-types.html | python.html | module-UserList.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.7 UserDict --\nClass wrapper for dictionary objects\nNote:\nThis module is available for backward compatibility only. If\nyou are writing code that does not need to work with versions of\nPython earlier than Python 2.2, please consider subclassing directly\nfrom the built-in dictionary type.\nThis module defines a class that acts as a wrapper around\ndictionary objects. It is a useful base class for\nyour own dictionary-like classes, which can inherit from\nthem and override existing methods or add new ones. In this way one\ncan add new behaviors to dictionaries.\nThe UserDict module defines the UserDict class:\nIn addition to supporting the methods and operations of mappings (see\nsection 2.2.7 (typesmapping.html#typesmapping)), UserDict instances provide the\nfollowing attribute:", "python_version": "2.2", "length": 915, "url": "https://docs.python.org/2.2/lib/module-UserDict.html"} {"title": "3.8 UserList -- Class wrapper for list objects", "text": "module-UserDict.html | python.html | module-UserString.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.8 UserList --\nClass wrapper for list objects\nNote:\nThis module is available for backward compatibility only. If\nyou are writing code that does not need to work with versions of\nPython earlier than Python 2.2, please consider subclassing directly\nfrom the built-in list type.\nThis module defines a class that acts as a wrapper around\nlist objects. It is a useful base class for\nyour own list-like classes, which can inherit from\nthem and override existing methods or add new ones. In this way one\ncan add new behaviors to lists.\nThe UserList module defines the UserList class:\nIn addition to supporting the methods and operations of mutable\nsequences (see section 2.2.6 (typesseq.html#typesseq)), UserList instances\nprovide the following attribute:\nSubclassing requirements:\nSubclasses of UserList are expect to offer a constructor which\ncan be called with either no arguments or one argument. List\noperations which return a new sequence attempt to create an instance\nof the actual implementation class. To do so, it assumes that the\nconstructor can be called with a single parameter, which is a sequence\nobject used as a data source.\nIf a derived class does not wish to comply with this requirement, all\nof the special methods supported by this class will need to be\noverridden; please consult the sources for information about the\nmethods which need to be provided in that case.\nChanged in version 2.0:\nPython versions 1.5.2 and 1.6 also required that the\nconstructor be callable with no parameters, and offer\na mutable data attribute. Earlier versions\nof Python did not attempt to create instances of the\nderived class.", "python_version": "2.2", "length": 1764, "url": "https://docs.python.org/2.2/lib/module-UserList.html"} {"title": "3.9 UserString -- Class wrapper for string objects", "text": "module-UserList.html | python.html | module-operator.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.9 UserString --\nClass wrapper for string objects\nNote:\nThis UserString class from this module is available for\nbackward compatibility only. If you are writing code that does not\nneed to work with versions of Python earlier than Python 2.2, please\nconsider subclassing directly from the built-in str type\ninstead of using UserString (there is no built-in equivalent\nto MutableString).\nThis module defines a class that acts as a wrapper around string\nobjects. It is a useful base class for your own string-like classes,\nwhich can inherit from them and override existing methods or add new\nones. In this way one can add new behaviors to strings.\nIt should be noted that these classes are highly inefficient compared\nto real string or Unicode objects; this is especially the case for\nMutableString.\nThe UserString module defines the following classes:\nIn addition to supporting the methods and operations of string and\nUnicode objects (see section 2.2.6 (string-methods.html#string-methods), ``String\nMethods''), UserString instances provide the following\nattribute:", "python_version": "2.2", "length": 1203, "url": "https://docs.python.org/2.2/lib/module-UserString.html"} {"title": "12.16 uu -- Encode and decode uuencode files", "text": "module-quopri.html | netdata.html | module-xdrlib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.16 uu --\nEncode and decode uuencode files\nThis module encodes and decodes files in uuencode format, allowing\narbitrary binary data to be transferred over ASCII-only connections.\nWherever a file argument is expected, the methods accept a file-like\nobject. For backwards compatibility, a string containing a pathname\nis also accepted, and the corresponding file will be opened for\nreading and writing; the pathname `'-'` is understood to mean the\nstandard input or output. However, this interface is deprecated; it's\nbetter for the caller to open the file itself, and be sure that, when\nrequired, the mode is `'rb'` or `'wb'` on Windows or DOS.\nThis code was contributed by Lance Ellinghouse, and modified by Jack\nJansen.\nThe uu module defines the following functions:", "python_version": "2.2", "length": 905, "url": "https://docs.python.org/2.2/lib/module-uu.html"} {"title": "3.20 warnings -- Warning control", "text": "module-marshal.html | python.html | warning-categories.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.20 warnings --\nWarning control\nNew in version 2.1.\nWarning messages are typically issued in situations where it is useful\nto alert the user of some condition in a program, where that condition\n(normally) doesn't warrant raising an exception and terminating the\nprogram. For example, one might want to issue a warning when a\nprogram uses an obsolete module.\nPython programmers issue warnings by calling the warn()\nfunction defined in this module. (C programmers use\nPyErr_Warn(); see the\nPython/C API Reference\nManual (../api/exceptionHandling.html) for details).\nWarning messages are normally written to `sys.stderr`, but their\ndisposition can be changed flexibly, from ignoring all warnings to\nturning them into exceptions. The disposition of warnings can vary\nbased on the warning category (see below), the text of the warning\nmessage, and the source location where it is issued. Repetitions of a\nparticular warning for the same source location are typically\nsuppressed.\nThere are two stages in warning control: first, each time a warning is\nissued, a determination is made whether a message should be issued or\nnot; next, if a message is to be issued, it is formatted and printed\nusing a user-settable hook.\nThe determination whether to issue a warning message is controlled by\nthe warning filter, which is a sequence of matching rules and actions.\nRules can be added to the filter by calling\nfilterwarnings() and reset to its default state by calling\nresetwarnings().\nThe printing of warning messages is done by calling\nshowwarning(), which may be overidden; the default\nimplementation of this function formats the message by calling\nformatwarning(), which is also available for use by custom\nimplementations.", "python_version": "2.2", "length": 1856, "url": "https://docs.python.org/2.2/lib/module-warnings.html"} {"title": "14.5 wave -- Read and write WAV files", "text": "au-write-objects.html | mmedia.html | Wave-read-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 14.5 wave --\nRead and write WAV files\nThe wave module provides a convenient interface to the WAV sound\nformat. It does not support compression/decompression, but it does support\nmono/stereo.\nThe wave module defines the following function and exception:", "python_version": "2.2", "length": 394, "url": "https://docs.python.org/2.2/lib/module-wave.html"} {"title": "3.3 weakref -- Weak references", "text": "module-gc.html | python.html | weakref-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3.3 weakref --\nWeak references\nNew in version 2.1.\nThe weakref module allows the Python programmer to create\nweak references to objects.\nIn the discussion which follows, the term referent means the\nobject which is referred to by a weak reference.\nXXX -- need to say more here!\nNot all objects can be weakly referenced; those objects which do\ninclude class instances, functions written in Python (but not in C),\nand methods (both bound and unbound). Extension types can easily\nbe made to support weak references; see section 3.3.3 (weakref-extension.html#weakref-extension),\n``Weak References in Extension Types,'' for more information.\nSee Also:", "python_version": "2.2", "length": 778, "url": "https://docs.python.org/2.2/lib/module-weakref.html"} {"title": "11.1 webbrowser -- Convenient Web-browser controller", "text": "internet.html | internet.html | browser-controllers.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.1 webbrowser --\nConvenient Web-browser controller\nThe webbrowser module provides a very high-level interface to\nallow displaying Web-based documents to users. The controller objects\nare easy to use and are platform-independent. Under most\ncircumstances, simply calling the open() function from this\nmodule will do the right thing.\nUnder Unix, graphical browsers are preferred under X11, but text-mode\nbrowsers will be used if graphical browsers are not available or an X11\ndisplay isn't available. If text-mode browsers are used, the calling\nprocess will block until the user exits the browser.\nUnder Unix, if the environment variable BROWSER exists, it\nis interpreted to override the platform default list of browsers, as a\ncolon-separated list of browsers to try in order. When the value of\na list part contains the string `%s`, then it is interpreted as\na literal browser command line to be used with the argument URL\nsubstituted for the `%s`; if the part does not contain\n`%s`, it is simply interpreted as the name of the browser to\nlaunch.\nFor non-Unix platforms, or when X11 browsers are available on\nUnix, the controlling process will not wait for the user to finish\nwith the browser, but allow the browser to maintain its own window on\nthe display.\nThe following exception is defined:\nThe following functions are defined:\nA number of browser types are predefined. This table gives the type\nnames that may be passed to the get() function and the\ncorresponding instantiations for the controller classes, all defined\nin this module.\nNotes:\n(1): ``Konqueror'' is the file manager for the KDE desktop environment for\nUNIX, and only makes sense to use if KDE is running. Some way of\nreliably detecting KDE would be nice; the KDEDIR variable is\nnot sufficient. Note also that the name ``kfm'' is used even when\nusing the konqueror command with KDE 2 -- the\nimplementation selects the best strategy for running Konqueror.\n(2): Only on Windows platforms; requires the common\nextension modules win32api and win32con.\n(3): Only on MacOS platforms; requires the standard MacPython ic\nmodule, described in the Macintosh\nLibrary Modules (../mac/module-ic.html) manual.", "python_version": "2.2", "length": 2303, "url": "https://docs.python.org/2.2/lib/module-webbrowser.html"} {"title": "7.11 whichdb -- Guess which DBM module created a database", "text": "dbhash-objects.html | someos.html | module-bsddb.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.11 whichdb --\nGuess which DBM module created a database\nThe single function in this module attempts to guess which of the\nseveral simple database modules available-dbm (module-dbm.html),\ngdbm (module-gdbm.html), or dbhash (module-dbhash.html)-should be used to open a\ngiven file.", "python_version": "2.2", "length": 416, "url": "https://docs.python.org/2.2/lib/module-whichdb.html"} {"title": "5.7 whrandom -- Pseudo-random number generator", "text": "module-random.html | misc.html | module-bisect.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.7 whrandom --\nPseudo-random number generator\nDeprecated since release 2.1.\nUse random (module-random.html) instead.\nNote:\nThis module was an implementation detail of the\nrandom (module-random.html) module in releases of Python prior to 2.1. It is\nno longer used. Please do not use this module directly; use\nrandom (module-random.html) instead.\nThis module implements a Wichmann-Hill pseudo-random number generator\nclass that is also named whrandom. Instances of the\nwhrandom class conform to the Random Number Generator\ninterface described in section #rng-objects. They also offer the\nfollowing method, specific to the Wichmann-Hill algorithm:\nWhen imported, the whrandom module also creates an instance of\nthe whrandom class, and makes the methods of that instance\navailable at the module level. Therefore one can write either\n`N = whrandom.random()` or:\n```text\n\ngenerator = whrandom.whrandom()\nN = generator.random()\n```\nNote that using separate instances of the generator leads to\nindependent sequences of pseudo-random numbers.", "python_version": "2.2", "length": 1167, "url": "https://docs.python.org/2.2/lib/module-whrandom.html"} {"title": "22.3 winsound -- Sound-playing interface for Windows", "text": "handle-object.html | node604.html | undoc.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 22.3 winsound --\nSound-playing interface for Windows\nAvailability: Windows.\nNew in version 1.5.2.\nThe winsound module provides access to the basic\nsound-playing machinery provided by Windows platforms. It includes\ntwo functions and several constants.", "python_version": "2.2", "length": 378, "url": "https://docs.python.org/2.2/lib/module-winsound.html"} {"title": "12.17 xdrlib -- Encode and decode XDR data", "text": "module-uu.html | netdata.html | xdr-packer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12.17 xdrlib --\nEncode and decode XDR data\nThe xdrlib module supports the External Data Representation\nStandard as described in RFC 1014 (http://www.faqs.org/rfcs/rfc1014.html), written by Sun Microsystems,\nInc. June 1987. It supports most of the data types described in the\nRFC.\nThe xdrlib module defines two classes, one for packing\nvariables into XDR representation, and another for unpacking from XDR\nrepresentation. There are also two exception classes.\nSee Also:", "python_version": "2.2", "length": 605, "url": "https://docs.python.org/2.2/lib/module-xdrlib.html"} {"title": "13.6 xml.dom -- The Document Object Model API", "text": "expat-errors.html | markup.html | node437.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.6 xml.dom --\nThe Document Object Model API\nNew in version 2.0.\nThe Document Object Model, or ``DOM,'' is a cross-language API from\nthe World Wide Web Consortium (W3C) for accessing and modifying XML\ndocuments. A DOM implementation presents an XML document as a tree\nstructure, or allows client code to build such a structure from\nscratch. It then gives access to the structure through a set of\nobjects which provided well-known interfaces.\nThe DOM is extremely useful for random-access applications. SAX only\nallows you a view of one bit of the document at a time. If you are\nlooking at one SAX element, you have no access to another. If you are\nlooking at a text node, you have no access to a containing element.\nWhen you write a SAX application, you need to keep track of your\nprogram's position in the document somewhere in your own code. SAX\ndoes not do it for you. Also, if you need to look ahead in the XML\ndocument, you are just out of luck.\nSome applications are simply impossible in an event driven model with\nno access to a tree. Of course you could build some sort of tree\nyourself in SAX events, but the DOM allows you to avoid writing that\ncode. The DOM is a standard tree representation for XML data.\nThe Document Object Model is being defined by the W3C in stages, or\n``levels'' in their terminology. The Python mapping of the API is\nsubstantially based on the DOM Level 2 recommendation. Some aspects\nof the API will only become available in Python 2.1, or may only be\navailable in particular DOM implementations.\nDOM applications typically start by parsing some XML into a DOM. How\nthis is accomplished is not covered at all by DOM Level 1, and Level 2\nprovides only limited improvements. There is a\nDOMImplementation object class which provides access to\nDocument creation methods, but these methods were only added\nin DOM Level 2 and were not implemented in time for Python 2.0. There\nis also no well-defined way to access these methods without an\nexisting Document object. For Python 2.0, consult the\ndocumentation for each particular DOM implementation to determine the\nbootstrap procedure needed to create and initialize Document\nand DocumentType instances.\nOnce you have a DOM document object, you can access the parts of your\nXML document through its properties and methods. These properties are\ndefined in the DOM specification; this portion of the reference manual\ndescribes the interpretation of the specification in Python.\nThe specification provided by the W3C defines the DOM API for Java,\nECMAScript, and OMG IDL. The Python mapping defined here is based in\nlarge part on the IDL version of the specification, but strict\ncompliance is not required (though implementations are free to support\nthe strict mapping from IDL). See section 13.6.3 (dom-conformance.html#dom-conformance),\n``Conformance,'' for a detailed discussion of mapping requirements.\nSee Also:", "python_version": "2.2", "length": 3020, "url": "https://docs.python.org/2.2/lib/module-xml.dom.html"} {"title": "13.7 xml.dom.minidom -- Lightweight DOM implementation", "text": "dom-accessor-methods.html | markup.html | dom-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.7 xml.dom.minidom --\nLightweight DOM implementation\nNew in version 2.0.\nxml.dom.minidom is a light-weight implementation of the\nDocument Object Model interface. It is intended to be\nsimpler than the full DOM and also significantly smaller.\nDOM applications typically start by parsing some XML into a DOM. With\nxml.dom.minidom, this is done through the parse functions:\n```text\n\nfrom xml.dom.minidom import parse, parseString\n\ndom1 = parse('c:\\\\temp\\\\mydata.xml') # parse an XML file by name\n\ndatasource = open('c:\\\\temp\\\\mydata.xml')\ndom2 = parse(datasource) # parse an open file\n\ndom3 = parseString('Some data some more data')\n```\nThe parse function can take either a filename or an open file object.\nIf you have XML in a string, you can use the\nparseString() function instead:\nBoth functions return a Document object representing the\ncontent of the document.\nYou can also create a Document node merely by instantiating a\ndocument object. Then you could add child nodes to it to populate\nthe DOM:\n```text\n\nfrom xml.dom.minidom import Document\n\nnewdoc = Document()\nnewel = newdoc.createElement(\"some_tag\")\nnewdoc.appendChild(newel)\n```\nOnce you have a DOM document object, you can access the parts of your\nXML document through its properties and methods. These properties are\ndefined in the DOM specification. The main property of the document\nobject is the documentElement property. It gives you the\nmain element in the XML document: the one that holds all others. Here\nis an example program:\n```text\n\ndom3 = parseString(\"Some data\")\nassert dom3.documentElement.tagName == \"myxml\"\n```\nWhen you are finished with a DOM, you should clean it up. This is\nnecessary because some versions of Python do not support garbage\ncollection of objects that refer to each other in a cycle. Until this\nrestriction is removed from all versions of Python, it is safest to\nwrite your code as if cycles would not be cleaned up.\nThe way to clean up a DOM is to call its unlink() method:\n```text\n\ndom1.unlink()\ndom2.unlink()\ndom3.unlink()\n```\nunlink() is a xml.dom.minidom-specific extension to\nthe DOM API. After calling unlink() on a node, the node and\nits descendents are essentially useless.\nSee Also:", "python_version": "2.2", "length": 2365, "url": "https://docs.python.org/2.2/lib/module-xml.dom.minidom.html"} {"title": "13.8 xml.dom.pulldom -- Support for building partial DOM trees", "text": "minidom-and-dom.html | markup.html | domeventstream-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.8 xml.dom.pulldom --\nSupport for building partial DOM trees\nNew in version 2.0.\nxml.dom.pulldom allows building only selected portions of a\nDocument Object Model representation of a document from SAX events.", "python_version": "2.2", "length": 356, "url": "https://docs.python.org/2.2/lib/module-xml.dom.pulldom.html"} {"title": "13.5 xml.parsers.expat -- Fast XML parsing using Expat", "text": "module-htmlentitydefs.html | markup.html | xmlparser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.5 xml.parsers.expat --\nFast XML parsing using Expat\nNew in version 2.0.\nThe xml.parsers.expat module is a Python interface to the\nExpatnon-validating XML parser.\nThe module provides a single extension type, xmlparser, that\nrepresents the current state of an XML parser. After an\nxmlparser object has been created, various attributes of the object\ncan be set to handler functions. When an XML document is then fed to\nthe parser, the handler functions are called for the character data\nand markup in the XML document.\nThis module uses the pyexpatmodule to\nprovide access to the Expat parser. Direct use of the\npyexpat module is deprecated.\nThis module provides one exception and one type object:\nThe xml.parsers.expat module contains two functions:", "python_version": "2.2", "length": 896, "url": "https://docs.python.org/2.2/lib/module-xml.parsers.expat.html"} {"title": "13.10 xml.sax.handler -- Base classes for SAX handlers", "text": "sax-exception-objects.html | markup.html | content-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.10 xml.sax.handler --\nBase classes for SAX handlers\nNew in version 2.0.\nThe SAX API defines four kinds of handlers: content handlers, DTD\nhandlers, error handlers, and entity resolvers. Applications normally\nonly need to implement those interfaces whose events they are\ninterested in; they can implement the interfaces in a single object or\nin multiple objects. Handler implementations should inherit from the\nbase classes provided in the module xml.sax, so that all\nmethods get default implementations.\nIn addition to these classes, xml.sax.handler provides\nsymbolic constants for the feature and property names.", "python_version": "2.2", "length": 769, "url": "https://docs.python.org/2.2/lib/module-xml.sax.handler.html"} {"title": "13.9 xml.sax -- Support for SAX2 parsers", "text": "domeventstream-objects.html | markup.html | sax-exception-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.9 xml.sax --\nSupport for SAX2 parsers\nNew in version 2.0.\nThe xml.sax package provides a number of modules which\nimplement the Simple API for XML (SAX) interface for Python. The\npackage itself provides the SAX exceptions and the convenience\nfunctions which will be most used by users of the SAX API.\nThe convenience functions are:\nA typical SAX application uses three kinds of objects: readers,\nhandlers and input sources. ``Reader'' in this context is another\nterm for parser, i.e. some piece of code that reads the bytes or\ncharacters from the input source, and produces a sequence of events.\nThe events then get distributed to the handler objects, i.e. the\nreader invokes a method on the handler. A SAX application must\ntherefore obtain a reader object, create or open the input sources,\ncreate the handlers, and connect these objects all together. As the\nfinal step of preparation, the reader is called to parse the input.\nDuring parsing, methods on the handler objects are called based on\nstructural and syntactic events from the input data.\nFor these objects, only the interfaces are relevant; they are normally\nnot instantiated by the application itself. Since Python does not have\nan explicit notion of interface, they are formally introduced as\nclasses, but applications may use implementations which do not inherit\nfrom the provided classes. The InputSource, Locator,\nAttributesImpl, AttributesNSImpl, and\nXMLReader interfaces are defined in the module\nxml.sax.xmlreader (module-xml.sax.xmlreader.html). The handler interfaces are defined in\nxml.sax.handler (module-xml.sax.handler.html). For convenience, InputSource\n(which is often instantiated directly) and the handler classes are\nalso available from xml.sax. These interfaces are described\nbelow.\nIn addition to these classes, xml.sax provides the following\nexception classes.\nSee Also:", "python_version": "2.2", "length": 2006, "url": "https://docs.python.org/2.2/lib/module-xml.sax.html"} {"title": "13.11 xml.sax.saxutils -- SAX Utilities", "text": "sax-error-handler.html | markup.html | module-xml.sax.xmlreader.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.11 xml.sax.saxutils --\nSAX Utilities\nNew in version 2.0.\nThe module xml.sax.saxutils contains a number of classes and\nfunctions that are commonly useful when creating SAX applications,\neither in direct use, or as base classes.", "python_version": "2.2", "length": 379, "url": "https://docs.python.org/2.2/lib/module-xml.sax.saxutils.html"} {"title": "13.12 xml.sax.xmlreader -- Interface for XML parsers", "text": "module-xml.sax.saxutils.html | markup.html | xmlreader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.12 xml.sax.xmlreader --\nInterface for XML parsers\nNew in version 2.0.\nSAX parsers implement the XMLReader interface. They are\nimplemented in a Python module, which must provide a function\ncreate_parser(). This function is invoked by\nxml.sax.make_parser() with no arguments to create a new\nparser object.", "python_version": "2.2", "length": 455, "url": "https://docs.python.org/2.2/lib/module-xml.sax.xmlreader.html"} {"title": "13.13 xmllib -- A parser for XML documents", "text": "attributes-ns-impl-objects.html | markup.html | xml-namespace.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 13.13 xmllib --\nA parser for XML documents\nDeprecated since release 2.0.\nUse xml.sax (module-xml.sax.html) instead. The newer XML\npackage includes full support for XML 1.0.\nChanged in version 1.5.2:\nAdded namespace support.\nThis module defines a class XMLParser which serves as the basis\nfor parsing text files formatted in XML (Extensible Markup Language).\nThis class provides the following interface methods and instance variables:\nSee Also:\n---\n#### Footnotes", "python_version": "2.2", "length": 610, "url": "https://docs.python.org/2.2/lib/module-xmllib.html"} {"title": "11.20 xmlrpclib -- XML-RPC client access", "text": "cookie-example.html | internet.html | server-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 11.20 xmlrpclib -- XML-RPC client access\nNew in version 2.2.\nXML-RPC is a Remote Procedure Call method that uses XML passed via\nHTTP as a transport. With it, a client can call methods with\nparameters on a remote server (the server is named by a URI) and get back\nstructured data. This module supports writing XML-RPC client code; it\nhandles all the details of translating between conformable Python\nobjects and XML on the wire.\nSee Also:", "python_version": "2.2", "length": 576, "url": "https://docs.python.org/2.2/lib/module-xmlrpclib.html"} {"title": "5.12 xreadlines -- Efficient iteration over a file", "text": "module-fileinput.html | misc.html | module-calendar.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 5.12 xreadlines --\nEfficient iteration over a file\nNew in version 2.1.\nThis module defines a new object type which can efficiently iterate\nover the lines of a file. An xreadlines object is a sequence type\nwhich implements simple in-order indexing beginning at `0`, as\nrequired by for statement or the\nfilter() function.\nThus, the code\n```text\n\nimport xreadlines, sys\n\nfor line in xreadlines.xreadlines(sys.stdin):\npass\n```\nhas approximately the same speed and memory consumption as\n```text\n\nwhile 1:\nlines = sys.stdin.readlines(8*1024)\nif not lines: break\nfor line in lines:\npass\n```\nexcept the clarity of the for statement is retained in the\nformer case.\nAn xreadlines object s supports the following sequence\noperation:\nIf successive values of i are not sequential starting from\n`0`, this code will raise RuntimeError.", "python_version": "2.2", "length": 958, "url": "https://docs.python.org/2.2/lib/module-xreadlines.html"} {"title": "7.15 zipfile -- Work with ZIP archives", "text": "module-gzip.html | someos.html | zipfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.15 zipfile --\nWork with ZIP archives\nNew in version 1.6.\nThe ZIP file format is a common archive and compression standard.\nThis module provides tools to create, read, write, append, and list a\nZIP file. Any advanced use of this module will require an\nunderstanding of the format, as defined in\nPKZIP Application\nNote (http://www.pkware.com/appnote.html).\nThis module does not currently handle ZIP files which have appended\ncomments, or multi-disk ZIP files.\nThe available attributes of this module are:\nSee Also:", "python_version": "2.2", "length": 649, "url": "https://docs.python.org/2.2/lib/module-zipfile.html"} {"title": "7.13 zlib -- Compression compatible with gzip", "text": "bsddb-objects.html | someos.html | module-gzip.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7.13 zlib --\nCompression compatible with gzip\nFor applications that require data compression, the functions in this\nmodule allow compression and decompression, using the zlib library.\nThe zlib library has its own home page at\nhttp://www.gzip.org/zlib/. Version 1.1.3 is the\nmost recent version as of September 2000; use a later version if one\nis available. There are known incompatibilities between the Python\nmodule and earlier versions of the zlib library.\nThe available exception and functions in this module are:\nCompression objects support the following methods:\nDecompression objects support the following methods, and two attributes:", "python_version": "2.2", "length": 773, "url": "https://docs.python.org/2.2/lib/module-zlib.html"} {"title": "11.19.2 Morsel Objects", "text": "cookie-objects.html | module-Cookie.html | cookie-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.19.2 Morsel Objects", "python_version": "2.2", "length": 167, "url": "https://docs.python.org/2.2/lib/morsel-objects.html"} {"title": "22.1.2 Console I/O", "text": "msvcrt-files.html | module-msvcrt.html | msvcrt-other.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 22.1.2 Console I/O", "python_version": "2.2", "length": 159, "url": "https://docs.python.org/2.2/lib/msvcrt-console.html"} {"title": "22.1.1 File Operations", "text": "module-msvcrt.html | module-msvcrt.html | msvcrt-console.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 22.1.1 File Operations", "python_version": "2.2", "length": 166, "url": "https://docs.python.org/2.2/lib/msvcrt-files.html"} {"title": "22.1.3 Other Functions", "text": "msvcrt-console.html | module-msvcrt.html | module--winreg.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 22.1.3 Other Functions", "python_version": "2.2", "length": 167, "url": "https://docs.python.org/2.2/lib/msvcrt-other.html"} {"title": "12.10.2 MultiFile Example", "text": "MultiFile-objects.html | module-multifile.html | module-rfc822.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.10.2 MultiFile Example", "python_version": "2.2", "length": 175, "url": "https://docs.python.org/2.2/lib/multifile-example.html"} {"title": "12.10.1 MultiFile Objects", "text": "module-multifile.html | module-multifile.html | multifile-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.10.1 MultiFile Objects\nA MultiFile instance has the following methods:\nFinally, MultiFile instances have two public instance variables:", "python_version": "2.2", "length": 291, "url": "https://docs.python.org/2.2/lib/MultiFile-objects.html"} {"title": "6.11.1 Mutex Objects", "text": "module-mutex.html | module-mutex.html | module-getpass.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.11.1 Mutex Objects\nmutex objects have following methods:", "python_version": "2.2", "length": 200, "url": "https://docs.python.org/2.2/lib/mutex-objects.html"} {"title": "12. Internet Data Handling", "text": "asyncore-example.html | lib.html | module-formatter.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 12. Internet Data Handling\nThis chapter describes modules which support handling data formats\ncommonly used on the Internet.", "python_version": "2.2", "length": 262, "url": "https://docs.python.org/2.2/lib/netdata.html"} {"title": "12.18.1 netrc Objects", "text": "module-netrc.html | module-netrc.html | module-robotparser.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.18.1 netrc Objects\nA netrc instance has the following methods:\nInstances of netrc have public instance variables:", "python_version": "2.2", "length": 262, "url": "https://docs.python.org/2.2/lib/netrc-objects.html"} {"title": "11.11.1 NNTP Objects", "text": "module-nntplib.html | module-nntplib.html | module-smtplib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.11.1 NNTP Objects\nNNTP instances have the following methods. The response that is\nreturned as the first item in the return tuple of almost all methods\nis the server's response: a string beginning with a three-digit code.\nIf the server's response indicates an error, the method raises one of\nthe above exceptions.", "python_version": "2.2", "length": 461, "url": "https://docs.python.org/2.2/lib/nntp-objects.html"} {"title": "4.8.1 Codec Base Classes", "text": "module-codecs.html | module-codecs.html | codec-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.8.1 Codec Base Classes\nThe codecs defines a set of base classes which define the\ninterface and can also be used to easily write you own codecs for use\nin Python.\nEach codec has to define four interfaces to make it usable as codec in\nPython: stateless encoder, stateless decoder, stream reader and stream\nwriter. The stream reader and writers typically reuse the stateless\nencoder/decoder to implement the file protocols.\nThe Codec class defines the interface for stateless\nencoders/decoders.\nTo simplify and standardize error handling, the encode() and\ndecode() methods may implement different error handling\nschemes by providing the errors string argument. The following\nstring values are defined and implemented by all standard Python\ncodecs:", "python_version": "2.2", "length": 889, "url": "https://docs.python.org/2.2/lib/node100.html"} {"title": "4.2.6 Examples", "text": "match-objects.html | module-re.html | module-struct.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.2.6 Examples\nSimulating scanf()\nPython does not currently have an equivalent to scanf().\nRegular expressions are generally more powerful, though also more\nverbose, than scanf() format strings. The table below\noffers some more-or-less equivalent mappings between\nscanf() format tokens and regular expressions.\nTo extract the filename and numbers from a string like\n```text\n\n/usr/sbin/sendmail - 0 errors, 4 warnings\n```\nyou would use a scanf() format like\n```text\n\n%s - %d errors, %d warnings\n```\nThe equivalent regular expression would be\n```text\n\n([^\\s]+) - (\\d+) errors, (\\d+) warnings\n```", "python_version": "2.2", "length": 732, "url": "https://docs.python.org/2.2/lib/node102.html"} {"title": "5.1.1 Normal Usage", "text": "module-doctest.html | module-doctest.html | node110.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.1.1 Normal Usage\nIn normal use, end each module M with:\n```text\n\ndef _test():\nimport doctest, M # replace M with your module's name\nreturn doctest.testmod(M) # ditto\n\nif __name__ == \"__main__\":\n_test()\n```\nThen running the module as a script causes the examples in the docstrings\nto get executed and verified:\n```text\n\npython M.py\n```\nThis won't display anything unless an example fails, in which case the\nfailing example(s) and the cause(s) of the failure(s) are printed to stdout,\nand the final line of output is `'Test failed.'`.\nRun it with the -v switch instead:\n```text\n\npython M.py -v\n```\nand a detailed report of all examples tried is printed to `stdout`,\nalong with assorted summaries at the end.\nYou can force verbose mode by passing `verbose=1` to testmod, or\nprohibit it by passing `verbose=0`. In either of those cases,\n`sys.argv` is not examined by testmod.\nIn any case, testmod returns a 2-tuple of ints `( f , t )`, where f is the number of docstring examples that\nfailed and t is the total number of docstring examples\nattempted.", "python_version": "2.2", "length": 1187, "url": "https://docs.python.org/2.2/lib/node109.html"} {"title": "5.1.2 Which Docstrings Are Examined?", "text": "node109.html | module-doctest.html | node111.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.1.2 Which Docstrings Are Examined?\nSee docstring.py for all the details. They're unsurprising: the\nmodule docstring, and all function, class and method docstrings are\nsearched, with the exception of docstrings attached to objects with private\nnames.\nIn addition, if `M.__test__` exists and \"is true\", it must be a\ndict, and each entry maps a (string) name to a function object, class\nobject, or string. Function and class object docstrings found from\n`M.__test__` are searched even if the name is private, and\nstrings are searched directly as if they were docstrings. In output,\na key `K` in `M.__test__` appears with name\n```text\n\n.__test__.K\n```\nAny classes found are recursively searched similarly, to test docstrings in\ntheir contained methods and nested classes. While private names reached\nfrom M's globals are skipped, all names reached from\n`M.__test__` are searched.", "python_version": "2.2", "length": 1020, "url": "https://docs.python.org/2.2/lib/node110.html"} {"title": "5.1.3 What's the Execution Context?", "text": "node110.html | module-doctest.html | node112.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.1.3 What's the Execution Context?\nBy default, each time testmod finds a docstring to test, it uses a\ncopy of M's globals, so that running tests on a module\ndoesn't change the module's real globals, and so that one test in\nM can't leave behind crumbs that accidentally allow another test\nto work. This means examples can freely use any names defined at top-level\nin M, and names defined earlier in the docstring being run. It\nalso means that sloppy imports (see below) can cause examples in external\ndocstrings to use globals inappropriate for them.\nYou can force use of your own dict as the execution context by passing\n`globs=your_dict` to testmod() instead. Presumably this\nwould be a copy of `M.__dict__` merged with the globals from other\nimported modules.", "python_version": "2.2", "length": 894, "url": "https://docs.python.org/2.2/lib/node111.html"} {"title": "5.1.4 What About Exceptions?", "text": "node111.html | module-doctest.html | node113.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.1.4 What About Exceptions?\nNo problem, as long as the only output generated by the example is the\ntraceback itself. For example:\n```text\n\n>>> [1, 2, 3].remove(42)\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nValueError: list.remove(x): x not in list\n>>>\n```\nNote that only the exception type and value are compared (specifically,\nonly the last line in the traceback). The various ``File'' lines in\nbetween can be left out (unless they add significantly to the documentation\nvalue of the example).", "python_version": "2.2", "length": 649, "url": "https://docs.python.org/2.2/lib/node112.html"} {"title": "4.8.1 Codec Base Classes", "text": "module-codecs.html | module-codecs.html | codec-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.8.1 Codec Base Classes\nThe codecs defines a set of base classes which define the\ninterface and can also be used to easily write you own codecs for use\nin Python.\nEach codec has to define four interfaces to make it usable as codec in\nPython: stateless encoder, stateless decoder, stream reader and stream\nwriter. The stream reader and writers typically reuse the stateless\nencoder/decoder to implement the file protocols.\nThe Codec class defines the interface for stateless\nencoders/decoders.\nTo simplify and standardize error handling, the encode() and\ndecode() methods may implement different error handling\nschemes by providing the errors string argument. The following\nstring values are defined and implemented by all standard Python\ncodecs:", "python_version": "2.2", "length": 889, "url": "https://docs.python.org/2.2/lib/node113.html"} {"title": "5.1.6 How are Docstring Examples Recognized?", "text": "node113.html | module-doctest.html | node115.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.1.6 How are Docstring Examples Recognized?\nIn most cases a copy-and-paste of an interactive console session works fine\n-- just make sure the leading whitespace is rigidly consistent (you can mix\ntabs and spaces if you're too lazy to do it right, but doctest is not in\nthe business of guessing what you think a tab means).\n```text\n\n>>> # comments are ignored\n>>> x = 12\n>>> x\n12\n>>> if x == 13:\n... print \"yes\"\n... else:\n... print \"no\"\n... print \"NO\"\n... print \"NO!!!\"\n...\nno\nNO\nNO!!!\n>>>\n```\nAny expected output must immediately follow the final\n`'> > > '` or `'... '` line containing the code, and\nthe expected output (if any) extends to the next `'> > > '`\nor all-whitespace line.\nThe fine print:\n- Expected output cannot contain an all-whitespace line, since such a\nline is taken to signal the end of expected output.\n- Output to stdout is captured, but not output to stderr (exception\ntracebacks are captured via a different means).\n- If you continue a line via backslashing in an interactive session, or\nfor any other reason use a backslash, you need to double the backslash in\nthe docstring version. This is simply because you're in a string, and so\nthe backslash must be escaped for it to survive intact. Like:\n```text\n\n>>> if \"yes\" == \\\\\n... \"y\" + \\\\\n... \"es\":\n... print 'yes'\nyes\n```\n- The starting column doesn't matter:\n```text\n\n>>> assert \"Easy!\"\n>>> import math\n>>> math.floor(1.9)\n1.0\n```\nand as many leading whitespace characters are stripped from the\nexpected output as appeared in the initial `'> > > '` line\nthat triggered it.", "python_version": "2.2", "length": 1678, "url": "https://docs.python.org/2.2/lib/node114.html"} {"title": "5.1.7 Warnings", "text": "node114.html | module-doctest.html | node116.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.1.7 Warnings\n1. Sloppy imports can cause trouble; e.g., if you do\n```text\n\nfrom XYZ import XYZclass\n```\nthen XYZclass is a name in `M.__dict__` too, and doctest\nhas no way to know that XYZclass wasn't defined in\nM. So it may try to execute the examples in\nXYZclass's docstring, and those in turn may require a\ndifferent set of globals to work correctly. I prefer to do\n```import *`''-friendly imports, a la\n\n```text\nfrom XYZ import XYZclass as _XYZclass\n```\n\nand then the leading underscore makes _XYZclass a private name so\ntestmod skips it by default. Other approaches are described in\ndoctest.py.\n2. doctest is serious about requiring exact matches in expected\noutput. If even a single character doesn't match, the test fails. This\nwill probably surprise you a few times, as you learn exactly what Python\ndoes and doesn't guarantee about output. For example, when printing a\ndict, Python doesn't guarantee that the key-value pairs will be printed\nin any particular order, so a test like\n\n```text\n>>> foo()\n{\"Hermione\": \"hippogryph\", \"Harry\": \"broomstick\"}\n>>>\n```\n\nis vulnerable! One workaround is to do\n\n```text\n>>> foo() == {\"Hermione\": \"hippogryph\", \"Harry\": \"broomstick\"}\n1\n>>>\n```\n\ninstead. Another is to do\n\n```text\n>>> d = foo().items()\n>>> d.sort()\n>>> d\n[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]\n```\n\nThere are others, but you get the idea.\n\nAnother bad idea is to print things that embed an object address, like\n\n```text\n>>> id(1.0) # certain to fail some of the time\n7948648\n>>>\n```\n\nFloating-point numbers are also subject to small output variations across\nplatforms, because Python defers to the platform C library for float\nformatting, and C libraries vary widely in quality here.\n\n```text\n>>> 1./7 # risky\n0.14285714285714285\n>>> print 1./7 # safer\n0.142857142857\n>>> print round(1./7, 6) # much safer\n0.142857\n```\n\nNumbers of the form `I/2.**J` are safe across all platforms, and I\noften contrive doctest examples to produce numbers of that form:\n\n```text\n>>> 3./4 # utterly safe\n0.75\n```\n\nSimple fractions are also easier for people to understand, and that makes\nfor better documentation.", "python_version": "2.2", "length": 2254, "url": "https://docs.python.org/2.2/lib/node115.html"} {"title": "5.1.8 Soapbox", "text": "node115.html | module-doctest.html | module-unittest.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.1.8 Soapbox\nThe first word in doctest is \"doc\", and that's why the author wrote\ndoctest: to keep documentation up to date. It so happens that doctest\nmakes a pleasant unit testing environment, but that's not its primary\npurpose.\nChoose docstring examples with care. There's an art to this that needs to\nbe learned -- it may not be natural at first. Examples should add genuine\nvalue to the documentation. A good example can often be worth many words.\nIf possible, show just a few normal cases, show endcases, show interesting\nsubtle cases, and show an example of each kind of exception that can be\nraised. You're probably testing for endcases and subtle cases anyway in an\ninteractive shell: doctest wants to make it as easy as possible to capture\nthose sessions, and will verify they continue to work as designed forever\nafter.\nIf done with care, the examples will be invaluable for your users, and will\npay back the time it takes to collect them many times over as the years go\nby and \"things change\". I'm still amazed at how often one of my doctest\nexamples stops working after a \"harmless\" change.", "python_version": "2.2", "length": 1243, "url": "https://docs.python.org/2.2/lib/node116.html"} {"title": "5.2.1 Normal Usage", "text": "module-doctest.html | module-doctest.html | node124.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.1 Normal Usage\nIn normal use, end each module M with:\n```text\n\ndef _test():\nimport doctest, M # replace M with your module's name\nreturn doctest.testmod(M) # ditto\n\nif __name__ == \"__main__\":\n_test()\n```\nThen running the module as a script causes the examples in the docstrings\nto get executed and verified:\n```text\n\npython M.py\n```\nThis won't display anything unless an example fails, in which case the\nfailing example(s) and the cause(s) of the failure(s) are printed to stdout,\nand the final line of output is `'Test failed.'`.\nRun it with the -v switch instead:\n```text\n\npython M.py -v\n```\nand a detailed report of all examples tried is printed to `stdout`,\nalong with assorted summaries at the end.\nYou can force verbose mode by passing `verbose=1` to testmod, or\nprohibit it by passing `verbose=0`. In either of those cases,\n`sys.argv` is not examined by testmod.\nIn any case, testmod returns a 2-tuple of ints `( f , t )`, where f is the number of docstring examples that\nfailed and t is the total number of docstring examples\nattempted.", "python_version": "2.2", "length": 1187, "url": "https://docs.python.org/2.2/lib/node123.html"} {"title": "5.2.2 Which Docstrings Are Examined?", "text": "node123.html | module-doctest.html | node125.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.2 Which Docstrings Are Examined?\nSee docstring.py for all the details. They're unsurprising: the\nmodule docstring, and all function, class and method docstrings are\nsearched, with the exception of docstrings attached to objects with private\nnames. Objects imported into the module are not searched.\nIn addition, if `M.__test__` exists and \"is true\", it must be a\ndict, and each entry maps a (string) name to a function object, class\nobject, or string. Function and class object docstrings found from\n`M.__test__` are searched even if the name is private, and\nstrings are searched directly as if they were docstrings. In output,\na key `K` in `M.__test__` appears with name\n```text\n\n.__test__.K\n```\nAny classes found are recursively searched similarly, to test docstrings in\ntheir contained methods and nested classes. While private names reached\nfrom M's globals are skipped, all names reached from\n`M.__test__` are searched.", "python_version": "2.2", "length": 1071, "url": "https://docs.python.org/2.2/lib/node124.html"} {"title": "5.2.3 What's the Execution Context?", "text": "node124.html | module-doctest.html | node126.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.3 What's the Execution Context?\nBy default, each time testmod finds a docstring to test, it uses a\ncopy of M's globals, so that running tests on a module\ndoesn't change the module's real globals, and so that one test in\nM can't leave behind crumbs that accidentally allow another test\nto work. This means examples can freely use any names defined at top-level\nin M, and names defined earlier in the docstring being run.\nYou can force use of your own dict as the execution context by passing\n`globs=your_dict` to testmod() instead. Presumably this\nwould be a copy of `M.__dict__` merged with the globals from other\nimported modules.", "python_version": "2.2", "length": 767, "url": "https://docs.python.org/2.2/lib/node125.html"} {"title": "5.2.4 What About Exceptions?", "text": "node125.html | module-doctest.html | node127.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.4 What About Exceptions?\nNo problem, as long as the only output generated by the example is the\ntraceback itself. For example:\n```text\n\n>>> [1, 2, 3].remove(42)\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nValueError: list.remove(x): x not in list\n>>>\n```\nNote that only the exception type and value are compared (specifically,\nonly the last line in the traceback). The various ``File'' lines in\nbetween can be left out (unless they add significantly to the documentation\nvalue of the example).", "python_version": "2.2", "length": 649, "url": "https://docs.python.org/2.2/lib/node126.html"} {"title": "5.2.5 Advanced Usage", "text": "node126.html | module-doctest.html | node128.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.5 Advanced Usage\ntestmod() actually creates a local instance of class\nTester, runs appropriate methods of that class, and merges\nthe results into global Tester instance `master`.\nYou can create your own instances of Tester, and so build your\nown policies, or even run methods of `master` directly. See\n`Tester.__doc__` for details.", "python_version": "2.2", "length": 467, "url": "https://docs.python.org/2.2/lib/node127.html"} {"title": "5.2.6 How are Docstring Examples Recognized?", "text": "node127.html | module-doctest.html | node129.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.6 How are Docstring Examples Recognized?\nIn most cases a copy-and-paste of an interactive console session works fine\n-- just make sure the leading whitespace is rigidly consistent (you can mix\ntabs and spaces if you're too lazy to do it right, but doctest is not in\nthe business of guessing what you think a tab means).\n```text\n\n>>> # comments are ignored\n>>> x = 12\n>>> x\n12\n>>> if x == 13:\n... print \"yes\"\n... else:\n... print \"no\"\n... print \"NO\"\n... print \"NO!!!\"\n...\nno\nNO\nNO!!!\n>>>\n```\nAny expected output must immediately follow the final\n`'> > > '` or `'... '` line containing the code, and\nthe expected output (if any) extends to the next `'> > > '`\nor all-whitespace line.\nThe fine print:\n- Expected output cannot contain an all-whitespace line, since such a\nline is taken to signal the end of expected output.\n- Output to stdout is captured, but not output to stderr (exception\ntracebacks are captured via a different means).\n- If you continue a line via backslashing in an interactive session, or\nfor any other reason use a backslash, you need to double the backslash in\nthe docstring version. This is simply because you're in a string, and so\nthe backslash must be escaped for it to survive intact. Like:\n```text\n\n>>> if \"yes\" == \\\\\n... \"y\" + \\\\\n... \"es\":\n... print 'yes'\nyes\n```\n- The starting column doesn't matter:\n```text\n\n>>> assert \"Easy!\"\n>>> import math\n>>> math.floor(1.9)\n1.0\n```\nand as many leading whitespace characters are stripped from the\nexpected output as appeared in the initial `'> > > '` line\nthat triggered it.", "python_version": "2.2", "length": 1678, "url": "https://docs.python.org/2.2/lib/node128.html"} {"title": "5.2.7 Warnings", "text": "node128.html | module-doctest.html | node130.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.7 Warnings\n1. doctest is serious about requiring exact matches in expected\noutput. If even a single character doesn't match, the test fails. This\nwill probably surprise you a few times, as you learn exactly what Python\ndoes and doesn't guarantee about output. For example, when printing a\ndict, Python doesn't guarantee that the key-value pairs will be printed\nin any particular order, so a test like\n```text\n\n>>> foo()\n{\"Hermione\": \"hippogryph\", \"Harry\": \"broomstick\"}\n>>>\n```\nis vulnerable! One workaround is to do\n```text\n\n>>> foo() == {\"Hermione\": \"hippogryph\", \"Harry\": \"broomstick\"}\n1\n>>>\n```\ninstead. Another is to do\n```text\n\n>>> d = foo().items()\n>>> d.sort()\n>>> d\n[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]\n```\nThere are others, but you get the idea.\nAnother bad idea is to print things that embed an object address, like\n```text\n\n>>> id(1.0) # certain to fail some of the time\n7948648\n>>>\n```\nFloating-point numbers are also subject to small output variations across\nplatforms, because Python defers to the platform C library for float\nformatting, and C libraries vary widely in quality here.\n```text\n\n>>> 1./7 # risky\n0.14285714285714285\n>>> print 1./7 # safer\n0.142857142857\n>>> print round(1./7, 6) # much safer\n0.142857\n```\nNumbers of the form `I/2.**J` are safe across all platforms, and I\noften contrive doctest examples to produce numbers of that form:\n```text\n\n>>> 3./4 # utterly safe\n0.75\n```\nSimple fractions are also easier for people to understand, and that makes\nfor better documentation.\n2. Be careful if you have code that must only execute once.\nIf you have module-level code that must only execute once, a more foolproof\ndefinition of _test() is\n```text\n\ndef _test():\nimport doctest, sys\ndoctest.testmod(sys.modules[\"__main__\"])\n```", "python_version": "2.2", "length": 1908, "url": "https://docs.python.org/2.2/lib/node129.html"} {"title": "5.2.8 Soapbox", "text": "node129.html | module-doctest.html | module-unittest.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.8 Soapbox\nThe first word in doctest is \"doc\", and that's why the author wrote\ndoctest: to keep documentation up to date. It so happens that doctest\nmakes a pleasant unit testing environment, but that's not its primary\npurpose.\nChoose docstring examples with care. There's an art to this that needs to\nbe learned -- it may not be natural at first. Examples should add genuine\nvalue to the documentation. A good example can often be worth many words.\nIf possible, show just a few normal cases, show endcases, show interesting\nsubtle cases, and show an example of each kind of exception that can be\nraised. You're probably testing for endcases and subtle cases anyway in an\ninteractive shell: doctest wants to make it as easy as possible to capture\nthose sessions, and will verify they continue to work as designed forever\nafter.\nIf done with care, the examples will be invaluable for your users, and will\npay back the time it takes to collect them many times over as the years go\nby and \"things change\". I'm still amazed at how often one of my doctest\nexamples stops working after a \"harmless\" change.", "python_version": "2.2", "length": 1243, "url": "https://docs.python.org/2.2/lib/node130.html"} {"title": "6.13.3 Constants", "text": "curses-window-objects.html | module-curses.html | module-curses.textpad.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.13.3 Constants\nThe curses module defines the following data members:\nSeveral constants are available to specify character cell attributes:\nKeys are referred to by integer constants with names starting with\n\"KEY_\". The exact keycaps available are system dependent.\nOn VT100s and their software emulations, such as X terminal emulators,\nthere are normally at least four function keys (KEY_F1,\nKEY_F2, KEY_F3, KEY_F4) available,\nand the arrow keys mapped to KEY_UP, KEY_DOWN,\nKEY_LEFT and KEY_RIGHT in the obvious way. If\nyour machine has a PC keybboard, it is safe to expect arrow keys and\ntwelve function keys (older PC keyboards may have only ten function\nkeys); also, the following keypad mappings are standard:\nThe following table lists characters from the alternate character set.\nThese are inherited from the VT100 terminal, and will generally be\navailable on software emulations such as X terminals. When there\nis no graphic available, curses falls back on a crude printable ASCII\napproximation.\nNote: These are available only after initscr() has\nbeen called.\nThe following table lists the predefined colors:", "python_version": "2.2", "length": 1274, "url": "https://docs.python.org/2.2/lib/node167.html"} {"title": "6.13.3 Constants", "text": "curses-window-objects.html | module-curses.html | module-curses.textpad.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.13.3 Constants\nThe curses module defines the following data members:\nSeveral constants are available to specify character cell attributes:\nKeys are referred to by integer constants with names starting with\n\"KEY_\". The exact keycaps available are system dependent.\nOn VT100s and their software emulations, such as X terminal emulators,\nthere are normally at least four function keys (KEY_F1,\nKEY_F2, KEY_F3, KEY_F4) available,\nand the arrow keys mapped to KEY_UP, KEY_DOWN,\nKEY_LEFT and KEY_RIGHT in the obvious way. If\nyour machine has a PC keybboard, it is safe to expect arrow keys and\ntwelve function keys (older PC keyboards may have only ten function\nkeys); also, the following keypad mappings are standard:\nThe following table lists characters from the alternate character set.\nThese are inherited from the VT100 terminal, and will generally be\navailable on software emulations such as X terminals. When there\nis no graphic available, curses falls back on a crude printable ASCII\napproximation.\nNote:\nThese are available only after initscr() has\nbeen called.\nThe following table lists the predefined colors:", "python_version": "2.2", "length": 1274, "url": "https://docs.python.org/2.2/lib/node181.html"} {"title": "6.24.1 Background, details, hints, tips and caveats", "text": "module-locale.html | module-locale.html | embedding-locale.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.24.1 Background, details, hints, tips and caveats\nThe C standard defines the locale as a program-wide property that may\nbe relatively expensive to change. On top of that, some\nimplementation are broken in such a way that frequent locale changes\nmay cause core dumps. This makes the locale somewhat painful to use\ncorrectly.\nInitially, when a program is started, the locale is the \"C\" locale, no\nmatter what the user's preferred locale is. The program must\nexplicitly say that it wants the user's preferred locale settings by\ncalling `setlocale(LC_ALL, '')`.\nIt is generally a bad idea to call setlocale() in some library\nroutine, since as a side effect it affects the entire program. Saving\nand restoring it is almost as bad: it is expensive and affects other\nthreads that happen to run before the settings have been restored.\nIf, when coding a module for general use, you need a locale\nindependent version of an operation that is affected by the locale\n(e.g. string.lower(), or certain formats used with\ntime.strftime())), you will have to find a way to do it\nwithout using the standard library routine. Even better is convincing\nyourself that using locale settings is okay. Only as a last resort\nshould you document that your module is not compatible with\nnon-\"C\" locale settings.\nThe case conversion functions in the\nstring (module-string.html)and\nstropmodules are affected by the locale\nsettings. When a call to the setlocale() function changes\nthe LC_CTYPE settings, the variables\n`string.lowercase`, `string.uppercase` and\n`string.letters` (and their counterparts in strop) are\nrecalculated. Note that this code that uses these variable through\n`from ... import ...', e.g. `from string\nimport letters`, is not affected by subsequent setlocale()\ncalls.\nThe only way to perform numeric operations according to the locale\nis to use the special functions defined by this module:\natof(), atoi(), format(),\nstr().", "python_version": "2.2", "length": 2061, "url": "https://docs.python.org/2.2/lib/node183.html"} {"title": "6.25.1 GNU gettext API", "text": "module-gettext.html | module-gettext.html | node187.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.25.1 GNU gettext API\nThe gettext module defines the following API, which is very\nsimilar to the GNU gettext API. If you use this API you\nwill affect the translation of your entire application globally. Often\nthis is what you want if your application is monolingual, with the choice\nof language dependent on the locale of your user. If you are\nlocalizing a Python module, or if your application needs to switch\nlanguages on the fly, you probably want to use the class-based API\ninstead.\nNote that GNU gettext also defines a dcgettext()\nmethod, but this was deemed not useful and so it is currently\nunimplemented.\nHere's an example of typical usage for this API:\n```text\n\nimport gettext\ngettext.bindtextdomain('myapplication', '/path/to/my/language/directory')\ngettext.textdomain('myapplication')\n_ = gettext.gettext\n# ...\nprint _('This is a translatable string.')\n```", "python_version": "2.2", "length": 1007, "url": "https://docs.python.org/2.2/lib/node186.html"} {"title": "6.25.2 Class-based API", "text": "node186.html | module-gettext.html | node188.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.25.2 Class-based API\nThe class-based API of the gettext module gives you more\nflexibility and greater convenience than the GNU gettext\nAPI. It is the recommended way of localizing your Python applications and\nmodules. gettext defines a ``translations'' class which\nimplements the parsing of GNU .mo format files, and has methods\nfor returning either standard 8-bit strings or Unicode strings.\nTranslations instances can also install themselves in the built-in\nnamespace as the function _().\n---\n#### Footnotes", "python_version": "2.2", "length": 643, "url": "https://docs.python.org/2.2/lib/node187.html"} {"title": "6.25.2.1 The NullTranslations class", "text": "node187.html | node187.html | node189.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.1 The NullTranslations class\nTranslation classes are what actually implement the translation of\noriginal source file message strings to translated message strings.\nThe base class used by all translation classes is\nNullTranslations; this provides the basic interface you can use\nto write your own specialized translation classes. Here are the\nmethods of NullTranslations:", "python_version": "2.2", "length": 504, "url": "https://docs.python.org/2.2/lib/node188.html"} {"title": "6.25.2.2 The GNUTranslations class", "text": "node188.html | node187.html | node190.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.2 The GNUTranslations class\nThe gettext module provides one additional class derived from\nNullTranslations: GNUTranslations. This class\noverrides _parse() to enable reading GNU gettext\nformat .mo files in both big-endian and little-endian format.\nIt also parses optional meta-data out of the translation catalog. It\nis convention with GNU gettext to include meta-data as the\ntranslation for the empty string. This meta-data is in RFC 822 (http://www.ietf.org/rfc/rfc0822.txt)-style\n`key: value` pairs. If the key `Content-Type` is found,\nthen the `charset` property is used to initialize the\n``protected'' _charset instance variable. The entire set of\nkey/value pairs are placed into a dictionary and set as the\n``protected'' _info instance variable.\nIf the .mo file's magic number is invalid, or if other problems\noccur while reading the file, instantiating a GNUTranslations class\ncan raise IOError.\nThe other usefully overridden method is ugettext(), which\nreturns a Unicode string by passing both the translated message string\nand the value of the ``protected'' _charset variable to the\nbuiltin unicode() function.", "python_version": "2.2", "length": 1251, "url": "https://docs.python.org/2.2/lib/node189.html"} {"title": "6.25.2.3 Solaris message catalog support", "text": "node189.html | node187.html | node191.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.3 Solaris message catalog support\nThe Solaris operating system defines its own binary\n.mo file format, but since no documentation can be found on\nthis format, it is not supported at this time.", "python_version": "2.2", "length": 325, "url": "https://docs.python.org/2.2/lib/node190.html"} {"title": "6.25.2.4 The Catalog constructor", "text": "node190.html | node187.html | node192.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.4 The Catalog constructor\nGNOMEuses a version of the gettext module by\nJames Henstridge, but this version has a slightly different API. Its\ndocumented usage was:\n```text\n\nimport gettext\ncat = gettext.Catalog(domain, localedir)\n_ = cat.gettext\nprint _('hello world')\n```\nFor compatibility with this older module, the function\nCatalog() is an alias for the the translation()\nfunction described above.\nOne difference between this module and Henstridge's: his catalog\nobjects supported access through a mapping API, but this appears to be\nunused and so is not currently supported.", "python_version": "2.2", "length": 709, "url": "https://docs.python.org/2.2/lib/node191.html"} {"title": "6.25.3 Internationalizing your programs and modules", "text": "node191.html | module-gettext.html | node193.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.25.3 Internationalizing your programs and modules\nInternationalization (I18N) refers to the operation by which a program\nis made aware of multiple languages. Localization (L10N) refers to\nthe adaptation of your program, once internationalized, to the local\nlanguage and cultural habits. In order to provide multilingual\nmessages for your Python programs, you need to take the following\nsteps:\n1. prepare your program or module by specially marking\ntranslatable strings\n2. run a suite of tools over your marked files to generate raw\nmessages catalogs\n3. create language specific translations of the message catalogs\n4. use the gettext module so that message strings are\nproperly translated\nIn order to prepare your code for I18N, you need to look at all the\nstrings in your files. Any string that needs to be translated\nshould be marked by wrapping it in `_('...')` - i.e. a call to\nthe function _(). For example:\n```text\n\nfilename = 'mylog.txt'\nmessage = _('writing a log message')\nfp = open(filename, 'w')\nfp.write(message)\nfp.close()\n```\nIn this example, the string `'writing a log message'` is marked as\na candidate for translation, while the strings `'mylog.txt'` and\n`'w'` are not.\nThe Python distribution comes with two tools which help you generate\nthe message catalogs once you've prepared your source code. These may\nor may not be available from a binary distribution, but they can be\nfound in a source distribution, in the Tools/i18n directory.\nThe pygettext6.4 (#foot20994) program\nscans all your Python source code looking for the strings you\npreviously marked as translatable. It is similar to the GNU\ngettext program except that it understands all the\nintricacies of Python source code, but knows nothing about C or C++\nsource code. You don't need GNU `gettext` unless you're also\ngoing to be translating C code (e.g. C extension modules).\npygettext generates textual Uniforum-style human readable\nmessage catalog .pot files, essentially structured human\nreadable files which contain every marked string in the source code,\nalong with a placeholder for the translation strings.\npygettext is a command line script that supports a similar\ncommand line interface as xgettext; for details on its use,\nrun:\n```text\n\npygettext.py --help\n```\nCopies of these .pot files are then handed over to the\nindividual human translators who write language-specific versions for\nevery supported natural language. They send you back the filled in\nlanguage-specific versions as a .po file. Using the\nmsgfmt.py6.5 (#foot20995) program (in the Tools/i18n directory), you take the\n.po files from your translators and generate the\nmachine-readable .mo binary catalog files. The .mo\nfiles are what the gettext module uses for the actual\ntranslation processing during run-time.\nHow you use the gettext module in your code depends on\nwhether you are internationalizing your entire application or a single\nmodule.\n---\n#### Footnotes", "python_version": "2.2", "length": 3053, "url": "https://docs.python.org/2.2/lib/node192.html"} {"title": "6.25.3.1 Localizing your module", "text": "node192.html | node192.html | node194.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.1 Localizing your module\nIf you are localizing your module, you must take care not to make\nglobal changes, e.g. to the built-in namespace. You should not use\nthe GNU `gettext` API but instead the class-based API.\nLet's say your module is called ``spam'' and the module's various\nnatural language translation .mo files reside in\n/usr/share/locale in GNU gettext format. Here's what\nyou would put at the top of your module:\n```text\n\nimport gettext\nt = gettext.translation('spam', '/usr/share/locale')\n_ = t.gettext\n```\nIf your translators were providing you with Unicode strings in their\n.po files, you'd instead do:\n```text\n\nimport gettext\nt = gettext.translation('spam', '/usr/share/locale')\n_ = t.ugettext\n```", "python_version": "2.2", "length": 843, "url": "https://docs.python.org/2.2/lib/node193.html"} {"title": "6.25.3.2 Localizing your application", "text": "node193.html | node192.html | node195.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.2 Localizing your application\nIf you are localizing your application, you can install the _()\nfunction globally into the built-in namespace, usually in the main driver file\nof your application. This will let all your application-specific\nfiles just use `_('...')` without having to explicitly install it in\neach file.\nIn the simple case then, you need only add the following bit of code\nto the main driver file of your application:\n```text\n\nimport gettext\ngettext.install('myapplication')\n```\nIf you need to set the locale directory or the unicode flag,\nyou can pass these into the install() function:\n```text\n\nimport gettext\ngettext.install('myapplication', '/usr/share/locale', unicode=1)\n```", "python_version": "2.2", "length": 827, "url": "https://docs.python.org/2.2/lib/node194.html"} {"title": "6.25.3.3 Changing languages on the fly", "text": "node194.html | node192.html | node196.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.3 Changing languages on the fly\nIf your program needs to support many languages at the same time, you\nmay want to create multiple translation instances and then switch\nbetween them explicitly, like so:\n```text\n\nimport gettext\n\nlang1 = gettext.translation(languages=['en'])\nlang2 = gettext.translation(languages=['fr'])\nlang3 = gettext.translation(languages=['de'])\n\n# start by using language1\nlang1.install()\n\n# ... time goes by, user selects language 2\nlang2.install()\n\n# ... more time goes by, user selects language 3\nlang3.install()\n```", "python_version": "2.2", "length": 672, "url": "https://docs.python.org/2.2/lib/node195.html"} {"title": "6.25.3.4 Deferred translations", "text": "node195.html | node192.html | node197.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.4 Deferred translations\nIn most coding situations, strings are translated were they are coded.\nOccasionally however, you need to mark strings for translation, but\ndefer actual translation until later. A classic example is:\n```text\n\nanimals = ['mollusk',\n'albatross',\n'rat',\n'penguin',\n'python',\n]\n# ...\nfor a in animals:\nprint a\n```\nHere, you want to mark the strings in the `animals` list as being\ntranslatable, but you don't actually want to translate them until they\nare printed.\nHere is one way you can handle this situation:\n```text\n\ndef _(message): return message\n\nanimals = [_('mollusk'),\n_('albatross'),\n_('rat'),\n_('penguin'),\n_('python'),\n]\n\ndel _\n\n# ...\nfor a in animals:\nprint _(a)\n```\nThis works because the dummy definition of _() simply returns\nthe string unchanged. And this dummy definition will temporarily\noverride any definition of _() in the built-in namespace\n(until the del command).\nTake care, though if you have a previous definition of _ in\nthe local namespace.\nNote that the second use of _() will not identify ``a'' as\nbeing translatable to the pygettext program, since it is not\na string.\nAnother way to handle this is with the following example:\n```text\n\ndef N_(message): return message\n\nanimals = [N_('mollusk'),\nN_('albatross'),\nN_('rat'),\nN_('penguin'),\nN_('python'),\n]\n\n# ...\nfor a in animals:\nprint _(a)\n```\nIn this case, you are marking translatable strings with the function\nN_(),6.6 (#foot20996) which won't conflict with any definition of\n_(). However, you will need to teach your message extraction\nprogram to look for translatable strings marked with N_().\npygettext and xpot both support this through the\nuse of command line switches.", "python_version": "2.2", "length": 1809, "url": "https://docs.python.org/2.2/lib/node196.html"} {"title": "6.24.1 Background, details, hints, tips and caveats", "text": "module-locale.html | module-locale.html | embedding-locale.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.24.1 Background, details, hints, tips and caveats\nThe C standard defines the locale as a program-wide property that may\nbe relatively expensive to change. On top of that, some\nimplementation are broken in such a way that frequent locale changes\nmay cause core dumps. This makes the locale somewhat painful to use\ncorrectly.\nInitially, when a program is started, the locale is the \"C\" locale, no\nmatter what the user's preferred locale is. The program must\nexplicitly say that it wants the user's preferred locale settings by\ncalling `setlocale(LC_ALL, '')`.\nIt is generally a bad idea to call setlocale() in some library\nroutine, since as a side effect it affects the entire program. Saving\nand restoring it is almost as bad: it is expensive and affects other\nthreads that happen to run before the settings have been restored.\nIf, when coding a module for general use, you need a locale\nindependent version of an operation that is affected by the locale\n(e.g. string.lower(), or certain formats used with\ntime.strftime())), you will have to find a way to do it\nwithout using the standard library routine. Even better is convincing\nyourself that using locale settings is okay. Only as a last resort\nshould you document that your module is not compatible with\nnon-\"C\" locale settings.\nThe case conversion functions in the\nstring (module-string.html)module are affected by the\nlocale settings. When a call to the setlocale() function\nchanges the LC_CTYPE settings, the variables\n`string.lowercase`, `string.uppercase` and\n`string.letters` are recalculated. Note that this code that uses\nthese variable through `from ... import ...',\ne.g. `from string import letters`, is not affected by subsequent\nsetlocale() calls.\nThe only way to perform numeric operations according to the locale\nis to use the special functions defined by this module:\natof(), atoi(), format(),\nstr().", "python_version": "2.2", "length": 2017, "url": "https://docs.python.org/2.2/lib/node197.html"} {"title": "6.25.1 GNU gettext API", "text": "module-gettext.html | module-gettext.html | node201.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.25.1 GNU gettext API\nThe gettext module defines the following API, which is very\nsimilar to the GNU gettext API. If you use this API you\nwill affect the translation of your entire application globally. Often\nthis is what you want if your application is monolingual, with the choice\nof language dependent on the locale of your user. If you are\nlocalizing a Python module, or if your application needs to switch\nlanguages on the fly, you probably want to use the class-based API\ninstead.\nNote that GNU gettext also defines a dcgettext()\nmethod, but this was deemed not useful and so it is currently\nunimplemented.\nHere's an example of typical usage for this API:\n```text\n\nimport gettext\ngettext.bindtextdomain('myapplication', '/path/to/my/language/directory')\ngettext.textdomain('myapplication')\n_ = gettext.gettext\n# ...\nprint _('This is a translatable string.')\n```", "python_version": "2.2", "length": 1007, "url": "https://docs.python.org/2.2/lib/node200.html"} {"title": "6.25.2 Class-based API", "text": "node200.html | module-gettext.html | node202.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.25.2 Class-based API\nThe class-based API of the gettext module gives you more\nflexibility and greater convenience than the GNU gettext\nAPI. It is the recommended way of localizing your Python applications and\nmodules. gettext defines a ``translations'' class which\nimplements the parsing of GNU .mo format files, and has methods\nfor returning either standard 8-bit strings or Unicode strings.\nTranslations instances can also install themselves in the built-in\nnamespace as the function _().\n---\n#### Footnotes", "python_version": "2.2", "length": 643, "url": "https://docs.python.org/2.2/lib/node201.html"} {"title": "6.25.2.1 The NullTranslations class", "text": "node201.html | node201.html | node203.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.1 The NullTranslations class\nTranslation classes are what actually implement the translation of\noriginal source file message strings to translated message strings.\nThe base class used by all translation classes is\nNullTranslations; this provides the basic interface you can use\nto write your own specialized translation classes. Here are the\nmethods of NullTranslations:", "python_version": "2.2", "length": 504, "url": "https://docs.python.org/2.2/lib/node202.html"} {"title": "6.25.2.2 The GNUTranslations class", "text": "node202.html | node201.html | node204.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.2 The GNUTranslations class\nThe gettext module provides one additional class derived from\nNullTranslations: GNUTranslations. This class\noverrides _parse() to enable reading GNU gettext\nformat .mo files in both big-endian and little-endian format.\nIt also parses optional meta-data out of the translation catalog. It\nis convention with GNU gettext to include meta-data as the\ntranslation for the empty string. This meta-data is in RFC 822 (http://www.faqs.org/rfcs/rfc822.html)-style\n`key: value` pairs. If the key `Content-Type` is found,\nthen the `charset` property is used to initialize the\n``protected'' _charset instance variable. The entire set of\nkey/value pairs are placed into a dictionary and set as the\n``protected'' _info instance variable.\nIf the .mo file's magic number is invalid, or if other problems\noccur while reading the file, instantiating a GNUTranslations class\ncan raise IOError.\nThe other usefully overridden method is ugettext(), which\nreturns a Unicode string by passing both the translated message string\nand the value of the ``protected'' _charset variable to the\nbuiltin unicode() function.", "python_version": "2.2", "length": 1252, "url": "https://docs.python.org/2.2/lib/node203.html"} {"title": "6.25.2.3 Solaris message catalog support", "text": "node203.html | node201.html | node205.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.3 Solaris message catalog support\nThe Solaris operating system defines its own binary\n.mo file format, but since no documentation can be found on\nthis format, it is not supported at this time.", "python_version": "2.2", "length": 325, "url": "https://docs.python.org/2.2/lib/node204.html"} {"title": "6.25.2.4 The Catalog constructor", "text": "node204.html | node201.html | node206.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.2.4 The Catalog constructor\nGNOMEuses a version of the gettext module by\nJames Henstridge, but this version has a slightly different API. Its\ndocumented usage was:\n```text\n\nimport gettext\ncat = gettext.Catalog(domain, localedir)\n_ = cat.gettext\nprint _('hello world')\n```\nFor compatibility with this older module, the function\nCatalog() is an alias for the the translation()\nfunction described above.\nOne difference between this module and Henstridge's: his catalog\nobjects supported access through a mapping API, but this appears to be\nunused and so is not currently supported.", "python_version": "2.2", "length": 709, "url": "https://docs.python.org/2.2/lib/node205.html"} {"title": "6.25.3 Internationalizing your programs and modules", "text": "node205.html | module-gettext.html | node207.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.25.3 Internationalizing your programs and modules\nInternationalization (I18N) refers to the operation by which a program\nis made aware of multiple languages. Localization (L10N) refers to\nthe adaptation of your program, once internationalized, to the local\nlanguage and cultural habits. In order to provide multilingual\nmessages for your Python programs, you need to take the following\nsteps:\n1. prepare your program or module by specially marking\ntranslatable strings\n2. run a suite of tools over your marked files to generate raw\nmessages catalogs\n3. create language specific translations of the message catalogs\n4. use the gettext module so that message strings are\nproperly translated\nIn order to prepare your code for I18N, you need to look at all the\nstrings in your files. Any string that needs to be translated\nshould be marked by wrapping it in `_('...')` -- that is, a call\nto the function _(). For example:\n```text\n\nfilename = 'mylog.txt'\nmessage = _('writing a log message')\nfp = open(filename, 'w')\nfp.write(message)\nfp.close()\n```\nIn this example, the string `'writing a log message'` is marked as\na candidate for translation, while the strings `'mylog.txt'` and\n`'w'` are not.\nThe Python distribution comes with two tools which help you generate\nthe message catalogs once you've prepared your source code. These may\nor may not be available from a binary distribution, but they can be\nfound in a source distribution, in the Tools/i18n directory.\nThe pygettext6.4 (#foot22675) program\nscans all your Python source code looking for the strings you\npreviously marked as translatable. It is similar to the GNU\ngettext program except that it understands all the\nintricacies of Python source code, but knows nothing about C or C++\nsource code. You don't need GNU `gettext` unless you're also\ngoing to be translating C code (such as C extension modules).\npygettext generates textual Uniforum-style human readable\nmessage catalog .pot files, essentially structured human\nreadable files which contain every marked string in the source code,\nalong with a placeholder for the translation strings.\npygettext is a command line script that supports a similar\ncommand line interface as xgettext; for details on its use,\nrun:\n```text\n\npygettext.py --help\n```\nCopies of these .pot files are then handed over to the\nindividual human translators who write language-specific versions for\nevery supported natural language. They send you back the filled in\nlanguage-specific versions as a .po file. Using the\nmsgfmt.py6.5 (#foot22676) program (in the Tools/i18n directory), you take the\n.po files from your translators and generate the\nmachine-readable .mo binary catalog files. The .mo\nfiles are what the gettext module uses for the actual\ntranslation processing during run-time.\nHow you use the gettext module in your code depends on\nwhether you are internationalizing your entire application or a single\nmodule.\n---\n#### Footnotes", "python_version": "2.2", "length": 3061, "url": "https://docs.python.org/2.2/lib/node206.html"} {"title": "6.25.3.1 Localizing your module", "text": "node206.html | node206.html | node208.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.1 Localizing your module\nIf you are localizing your module, you must take care not to make\nglobal changes, e.g. to the built-in namespace. You should not use\nthe GNU `gettext` API but instead the class-based API.\nLet's say your module is called ``spam'' and the module's various\nnatural language translation .mo files reside in\n/usr/share/locale in GNU gettext format. Here's what\nyou would put at the top of your module:\n```text\n\nimport gettext\nt = gettext.translation('spam', '/usr/share/locale')\n_ = t.gettext\n```\nIf your translators were providing you with Unicode strings in their\n.po files, you'd instead do:\n```text\n\nimport gettext\nt = gettext.translation('spam', '/usr/share/locale')\n_ = t.ugettext\n```", "python_version": "2.2", "length": 843, "url": "https://docs.python.org/2.2/lib/node207.html"} {"title": "6.25.3.2 Localizing your application", "text": "node207.html | node206.html | node209.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.2 Localizing your application\nIf you are localizing your application, you can install the _()\nfunction globally into the built-in namespace, usually in the main driver file\nof your application. This will let all your application-specific\nfiles just use `_('...')` without having to explicitly install it in\neach file.\nIn the simple case then, you need only add the following bit of code\nto the main driver file of your application:\n```text\n\nimport gettext\ngettext.install('myapplication')\n```\nIf you need to set the locale directory or the unicode flag,\nyou can pass these into the install() function:\n```text\n\nimport gettext\ngettext.install('myapplication', '/usr/share/locale', unicode=1)\n```", "python_version": "2.2", "length": 827, "url": "https://docs.python.org/2.2/lib/node208.html"} {"title": "6.25.3.3 Changing languages on the fly", "text": "node208.html | node206.html | node210.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.3 Changing languages on the fly\nIf your program needs to support many languages at the same time, you\nmay want to create multiple translation instances and then switch\nbetween them explicitly, like so:\n```text\n\nimport gettext\n\nlang1 = gettext.translation(languages=['en'])\nlang2 = gettext.translation(languages=['fr'])\nlang3 = gettext.translation(languages=['de'])\n\n# start by using language1\nlang1.install()\n\n# ... time goes by, user selects language 2\nlang2.install()\n\n# ... more time goes by, user selects language 3\nlang3.install()\n```", "python_version": "2.2", "length": 672, "url": "https://docs.python.org/2.2/lib/node209.html"} {"title": "6.25.3.4 Deferred translations", "text": "node209.html | node206.html | node211.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 6.25.3.4 Deferred translations\nIn most coding situations, strings are translated were they are coded.\nOccasionally however, you need to mark strings for translation, but\ndefer actual translation until later. A classic example is:\n```text\n\nanimals = ['mollusk',\n'albatross',\n'rat',\n'penguin',\n'python',\n]\n# ...\nfor a in animals:\nprint a\n```\nHere, you want to mark the strings in the `animals` list as being\ntranslatable, but you don't actually want to translate them until they\nare printed.\nHere is one way you can handle this situation:\n```text\n\ndef _(message): return message\n\nanimals = [_('mollusk'),\n_('albatross'),\n_('rat'),\n_('penguin'),\n_('python'),\n]\n\ndel _\n\n# ...\nfor a in animals:\nprint _(a)\n```\nThis works because the dummy definition of _() simply returns\nthe string unchanged. And this dummy definition will temporarily\noverride any definition of _() in the built-in namespace\n(until the del command).\nTake care, though if you have a previous definition of _ in\nthe local namespace.\nNote that the second use of _() will not identify ``a'' as\nbeing translatable to the pygettext program, since it is not\na string.\nAnother way to handle this is with the following example:\n```text\n\ndef N_(message): return message\n\nanimals = [N_('mollusk'),\nN_('albatross'),\nN_('rat'),\nN_('penguin'),\nN_('python'),\n]\n\n# ...\nfor a in animals:\nprint _(a)\n```\nIn this case, you are marking translatable strings with the function\nN_(),6.6 (#foot22677) which won't conflict with any definition of\n_(). However, you will need to teach your message extraction\nprogram to look for translatable strings marked with N_().\npygettext and xpot both support this through the\nuse of command line switches.", "python_version": "2.2", "length": 1809, "url": "https://docs.python.org/2.2/lib/node210.html"} {"title": "6.25.4 Acknowledgements", "text": "node210.html | module-gettext.html | someos.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.25.4 Acknowledgements\nThe following people contributed code, feedback, design suggestions,\nprevious implementations, and valuable experience to the creation of\nthis module:\n- Peter Funk\n- James Henstridge\n- Marc-André Lemburg\n- Martin von Löwis\n- François Pinard\n- Barry Warsaw", "python_version": "2.2", "length": 410, "url": "https://docs.python.org/2.2/lib/node211.html"} {"title": "7.1.1 Example", "text": "module-signal.html | module-signal.html | module-socket.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.1.1 Example\nHere is a minimal example program. It uses the alarm()\nfunction to limit the time spent waiting to open a file; this is\nuseful if the file is for a serial device that may not be turned on,\nwhich would normally cause the os.open() to hang\nindefinitely. The solution is to set a 5-second alarm before opening\nthe file; if the operation takes too long, the alarm signal will be\nsent, and the handler raises an exception.", "python_version": "2.2", "length": 574, "url": "https://docs.python.org/2.2/lib/node214.html"} {"title": "8.15.1 Resource Limits", "text": "module-resource.html | module-resource.html | node256.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.15.1 Resource Limits\nResources usage can be limited using the setrlimit() function\ndescribed below. Each resource is controlled by a pair of limits: a\nsoft limit and a hard limit. The soft limit is the current limit, and\nmay be lowered or raised by a process over time. The soft limit can\nnever exceed the hard limit. The hard limit can be lowered to any\nvalue greater than the soft limit, but not raised. (Only processes with\nthe effective UID of the super-user can raise a hard limit.)\nThe specific resources that can be limited are system dependent. They\nare described in the getrlimit(2) man page. The resources\nlisted below are supported when the underlying operating system\nsupports them; resources which cannot be checked or controlled by the\noperating system are not defined in this module for those platforms.\nThese symbols define resources whose consumption can be controlled\nusing the setrlimit() and getrlimit() functions\ndescribed below. The values of these symbols are exactly the constants\nused by C programs.\nThe Unix man page for getrlimit(2) lists the available\nresources. Note that not all systems use the same symbol or same\nvalue to denote the same resource.", "python_version": "2.2", "length": 1322, "url": "https://docs.python.org/2.2/lib/node255.html"} {"title": "8.15.2 Resource Usage", "text": "node255.html | module-resource.html | module-nis.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.15.2 Resource Usage\nThese functiona are used to retrieve resource usage information:\nThe following RUSAGE_* symbols are passed to the\ngetrusage() function to specify which processes information\nshould be provided for.", "python_version": "2.2", "length": 355, "url": "https://docs.python.org/2.2/lib/node256.html"} {"title": "9.2 How It Works", "text": "debugger-commands.html | module-pdb.html | profile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 9.2 How It Works\nSome changes were made to the interpreter:\n- `sys.settrace( func )` sets the global trace function\n- there can also a local trace function (see later)\nTrace functions have three arguments: frame, event, and\narg. frame is the current stack frame. event is a\nstring: `'call'`, `'line'`, `'return'` or\n`'exception'`. arg depends on the event type.\nThe global trace function is invoked (with event set to\n`'call'`) whenever a new local scope is entered; it should return\na reference to the local trace function to be used that scope, or\n`None` if the scope shouldn't be traced.\nThe local trace function should return a reference to itself (or to\nanother function for further tracing in that scope), or `None` to\nturn off tracing in that scope.\nInstance methods are accepted (and very useful!) as trace functions.\nThe events have the following meaning:\n`'call'`: A function is called (or some other code block entered). The global\ntrace function is called; arg is the argument list to the function;\nthe return value specifies the local trace function.\n`'line'`: The interpreter is about to execute a new line of code (sometimes\nmultiple line events on one line exist). The local trace function is\ncalled; arg in None; the return value specifies the new local trace\nfunction.\n`'return'`: A function (or other code block) is about to return. The local trace\nfunction is called; arg is the value that will be returned. The trace\nfunction's return value is ignored.\n`'exception'`: An exception has occurred. The local trace function is called; arg is\na triple (exception, value, traceback); the return value specifies the\nnew local trace function\nNote that as an exception is propagated down the chain of callers, an\n`'exception'` event is generated at each level.\nFor more information on code and frame objects, refer to the\nPython Reference Manual (../ref/ref.html).", "python_version": "2.2", "length": 2013, "url": "https://docs.python.org/2.2/lib/node262.html"} {"title": "8.8.1 Example", "text": "module-termios.html | module-termios.html | module-TERMIOSuppercase.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.8.1 Example\nHere's a function that prompts for a password with echoing turned\noff. Note the technique using a separate tcgetattr() call\nand a try ... finally statement to ensure that the\nold tty attributes are restored exactly no matter what happens:\n```text\n\ndef getpass(prompt = \"Password: \"):\nimport termios, sys\nfd = sys.stdin.fileno()\nold = termios.tcgetattr(fd)\nnew = termios.tcgetattr(fd)\nnew[3] = new[3] & ~termios.ECHO # lflags\ntry:\ntermios.tcsetattr(fd, termios.TCSADRAIN, new)\npasswd = raw_input(prompt)\nfinally:\ntermios.tcsetattr(fd, termios.TCSADRAIN, old)\nreturn passwd\n```", "python_version": "2.2", "length": 744, "url": "https://docs.python.org/2.2/lib/node263.html"} {"title": "8.15.1 Resource Limits", "text": "module-resource.html | module-resource.html | node273.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.15.1 Resource Limits\nResources usage can be limited using the setrlimit() function\ndescribed below. Each resource is controlled by a pair of limits: a\nsoft limit and a hard limit. The soft limit is the current limit, and\nmay be lowered or raised by a process over time. The soft limit can\nnever exceed the hard limit. The hard limit can be lowered to any\nvalue greater than the soft limit, but not raised. (Only processes with\nthe effective UID of the super-user can raise a hard limit.)\nThe specific resources that can be limited are system dependent. They\nare described in the getrlimit(2) man page. The resources\nlisted below are supported when the underlying operating system\nsupports them; resources which cannot be checked or controlled by the\noperating system are not defined in this module for those platforms.\nThese symbols define resources whose consumption can be controlled\nusing the setrlimit() and getrlimit() functions\ndescribed below. The values of these symbols are exactly the constants\nused by C programs.\nThe Unix man page for getrlimit(2) lists the available\nresources. Note that not all systems use the same symbol or same\nvalue to denote the same resource. This module does not attempt to\nmask platform differences -- symbols not defined for a platform will\nnot be available from this module on that platform.", "python_version": "2.2", "length": 1475, "url": "https://docs.python.org/2.2/lib/node272.html"} {"title": "8.15.2 Resource Usage", "text": "node272.html | module-resource.html | module-nis.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.15.2 Resource Usage\nThese functiona are used to retrieve resource usage information:\nThe following RUSAGE_* symbols are passed to the\ngetrusage() function to specify which processes information\nshould be provided for.", "python_version": "2.2", "length": 355, "url": "https://docs.python.org/2.2/lib/node273.html"} {"title": "10.1 Introduction to the profiler", "text": "profile.html | profile.html | node282.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.1 Introduction to the profiler\nA profiler is a program that describes the run time performance\nof a program, providing a variety of statistics. This documentation\ndescribes the profiler functionality provided in the modules\nprofile and pstats. This profiler provides\ndeterministic profiling of any Python programs. It also\nprovides a series of report generation tools to allow users to rapidly\nexamine the results of a profile operation.", "python_version": "2.2", "length": 564, "url": "https://docs.python.org/2.2/lib/node281.html"} {"title": "10.2 How Is This Profiler Different From The Old Profiler?", "text": "node281.html | profile.html | profile-instant.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.2 How Is This Profiler Different From The Old Profiler?\n(This section is of historical importance only; the old profiler\ndiscussed here was last seen in Python 1.1.)\nThe big changes from old profiling module are that you get more\ninformation, and you pay less CPU time. It's not a trade-off, it's a\ntrade-up.\nTo be specific:\nBugs removed:: Local stack frame is no longer molested, execution time is now charged\nto correct functions.\nAccuracy increased:: Profiler execution time is no longer charged to user's code,\ncalibration for platform is supported, file reads are not done by\nprofiler during profiling (and charged to user's code!).\nSpeed increased:: Overhead CPU cost was reduced by more than a factor of two (perhaps a\nfactor of five), lightweight profiler module is all that must be\nloaded, and the report generating module (pstats) is not needed\nduring profiling.\nRecursive functions support:: Cumulative times in recursive functions are correctly calculated;\nrecursive entries are counted.\nLarge growth in report generating UI:: Distinct profiles runs can be added together forming a comprehensive\nreport; functions that import statistics take arbitrary lists of\nfiles; sorting criteria is now based on keywords (instead of 4 integer\noptions); reports shows what functions were profiled as well as what\nprofile file was referenced; output format has been improved.", "python_version": "2.2", "length": 1509, "url": "https://docs.python.org/2.2/lib/node282.html"} {"title": "11.2.5 Caring about security", "text": "Functions_in_cgi_module.html | module-cgi.html | node284.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.5 Caring about security\nThere's one important rule: if you invoke an external program (e.g.\nvia the os.system() or os.popen() functions),\nmake very sure you don't pass arbitrary strings received from the\nclient to the shell. This is a well-known security hole whereby\nclever hackers anywhere on the web can exploit a gullible CGI script\nto invoke arbitrary shell commands. Even parts of the URL or field\nnames cannot be trusted, since the request doesn't have to come from\nyour form!\nTo be on the safe side, if you must pass a string gotten from a form\nto a shell command, you should make sure the string contains only\nalphanumeric characters, dashes, underscores, and periods.", "python_version": "2.2", "length": 826, "url": "https://docs.python.org/2.2/lib/node283.html"} {"title": "10.4 What Is Deterministic Profiling?", "text": "profile-instant.html | profile.html | module-profile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.4 What Is Deterministic Profiling?\nDeterministic profiling is meant to reflect the fact that all\nfunction call, function return, and exception events\nare monitored, and precise timings are made for the intervals between\nthese events (during which time the user's code is executing). In\ncontrast, statistical profiling (which is not done by this\nmodule) randomly samples the effective instruction pointer, and\ndeduces where time is being spent. The latter technique traditionally\ninvolves less overhead (as the code does not need to be instrumented),\nbut provides only relative indications of where time is being spent.\nIn Python, since there is an interpreter active during execution, the\npresence of instrumented code is not required to do deterministic\nprofiling. Python automatically provides a hook (optional\ncallback) for each event. In addition, the interpreted nature of\nPython tends to add so much overhead to execution, that deterministic\nprofiling tends to only add small processing overhead in typical\napplications. The result is that deterministic profiling is not that\nexpensive, yet provides extensive run time statistics about the\nexecution of a Python program.\nCall count statistics can be used to identify bugs in code (surprising\ncounts), and to identify possible inline-expansion points (high call\ncounts). Internal time statistics can be used to identify ``hot\nloops'' that should be carefully optimized. Cumulative time\nstatistics should be used to identify high level errors in the\nselection of algorithms. Note that the unusual handling of cumulative\ntimes in this profiler allows statistics for recursive implementations\nof algorithms to be directly compared to iterative implementations.", "python_version": "2.2", "length": 1854, "url": "https://docs.python.org/2.2/lib/node284.html"} {"title": "11.2.7 Testing your CGI script", "text": "node284.html | module-cgi.html | node286.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.7 Testing your CGI script\nUnfortunately, a CGI script will generally not run when you try it\nfrom the command line, and a script that works perfectly from the\ncommand line may fail mysteriously when run from the server. There's\none reason why you should still test your script from the command\nline: if it contains a syntax error, the Python interpreter won't\nexecute it at all, and the HTTP server will most likely send a cryptic\nerror to the client.\nAssuming your script has no syntax errors, yet it does not work, you\nhave no choice but to read the next section.", "python_version": "2.2", "length": 698, "url": "https://docs.python.org/2.2/lib/node285.html"} {"title": "11.2.8 Debugging CGI scripts", "text": "node285.html | module-cgi.html | node287.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.8 Debugging CGI scripts\nFirst of all, check for trivial installation errors -- reading the\nsection above on installing your CGI script carefully can save you a\nlot of time. If you wonder whether you have understood the\ninstallation procedure correctly, try installing a copy of this module\nfile (cgi.py) as a CGI script. When invoked as a script, the file\nwill dump its environment and the contents of the form in HTML form.\nGive it the right mode etc, and send it a request. If it's installed\nin the standard cgi-bin directory, it should be possible to send it a\nrequest by entering a URL into your browser of the form:\n```text\n\nhttp://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home\n```\nIf this gives an error of type 404, the server cannot find the script\n- perhaps you need to install it in a different directory. If it\ngives another error (e.g. 500), there's an installation problem that\nyou should fix before trying to go any further. If you get a nicely\nformatted listing of the environment and form content (in this\nexample, the fields should be listed as ``addr'' with value ``At Home''\nand ``name'' with value ``Joe Blow''), the cgi.py script has been\ninstalled correctly. If you follow the same procedure for your own\nscript, you should now be able to debug it.\nThe next step could be to call the cgi module's\ntest() function from your script: replace its main code\nwith the single statement\n```text\n\ncgi.test()\n```\nThis should produce the same results as those gotten from installing\nthe cgi.py file itself.\nWhen an ordinary Python script raises an unhandled exception\n(e.g. because of a typo in a module name, a file that can't be opened,\netc.), the Python interpreter prints a nice traceback and exits.\nWhile the Python interpreter will still do this when your CGI script\nraises an exception, most likely the traceback will end up in one of\nthe HTTP server's log file, or be discarded altogether.\nFortunately, once you have managed to get your script to execute\nsome code, it is easy to catch exceptions and cause a traceback\nto be printed. The test() function below in this module is\nan example. Here are the rules:\n1. Import the traceback module before entering the try\n... except statement\n2. Assign `sys.stderr` to be `sys.stdout`\n3. Make sure you finish printing the headers and the blank line\nearly\n4. Wrap all remaining code in a try ... except\nstatement\n5. In the except clause, call traceback.print_exc()\nFor example:\n```text\n\nimport sys\nimport traceback\nprint \"Content-Type: text/html\"\nprint\nsys.stderr = sys.stdout\ntry:\n...your code here...\nexcept:\nprint \"\\n\\n

    \"\ntraceback.print_exc()\n```\nNotes: The assignment to `sys.stderr` is needed because the\ntraceback prints to `sys.stderr`.\nThe `print \"\\n\\n
    \"` statement is necessary to\ndisable the word wrapping in HTML.\nIf you suspect that there may be a problem in importing the traceback\nmodule, you can use an even more robust approach (which only uses\nbuilt-in modules):\n```text\n\nimport sys\nsys.stderr = sys.stdout\nprint \"Content-Type: text/plain\"\nprint\n...your code here...\n```\nThis relies on the Python interpreter to print the traceback. The\ncontent type of the output is set to plain text, which disables all\nHTML processing. If your script works, the raw HTML will be displayed\nby your client. If it raises an exception, most likely after the\nfirst two lines have been printed, a traceback will be displayed.\nBecause no HTML interpretation is going on, the traceback will\nreadable.", "python_version": "2.2", "length": 3607, "url": "https://docs.python.org/2.2/lib/node286.html"}
    {"title": "11.2.9 Common problems and solutions", "text": "node286.html | module-cgi.html | module-urllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.9 Common problems and solutions", "python_version": "2.2", "length": 170, "url": "https://docs.python.org/2.2/lib/node287.html"}
    {"title": "10.8 Extensions -- Deriving Better Profilers", "text": "profile-calibration.html | profile.html | internet.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.8 Extensions -- Deriving Better Profilers\nThe Profile class of module profile was written so that\nderived classes could be developed to extend the profiler. The details\nare not described here, as doing this successfully requires an expert\nunderstanding of how the Profile class works internally. Study\nthe source code of module profile carefully if you want to\npursue this.\nIf all you want to do is change how current time is determined (for\nexample, to force use of wall-clock time or elapsed process time),\npass the timing function you want to the Profile class\nconstructor:\n```text\n\npr = profile.Profile(your_time_func)\n```\nThe resulting profiler will then call `your_time_func()`.\nThe function should return a single number, or a list of\nnumbers whose sum is the current time (like what os.times()\nreturns). If the function returns a single time number, or the list of\nreturned numbers has length 2, then you will get an especially fast\nversion of the dispatch routine.\nBe warned that you should calibrate the profiler class for the\ntimer function that you choose. For most machines, a timer that\nreturns a lone integer value will provide the best results in terms of\nlow overhead during profiling. (os.times() is\npretty bad, as it returns a tuple of floating point values). If\nyou want to substitute a better timer in the cleanest fashion,\nderive a class and hardwire a replacement dispatch method that best\nhandles your timer call, along with the appropriate calibration\nconstant.", "python_version": "2.2", "length": 1626, "url": "https://docs.python.org/2.2/lib/node289.html"}
    {"title": "11.2.2 Using the cgi module", "text": "cgi-intro.html | module-cgi.html | node296.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.2 Using the cgi module\nBegin by writing \"import cgi\". Do not use \"from cgi import\n*\" -- the module defines all sorts of names for its own use or for\nbackward compatibility that you don't want in your namespace.\nWhen you write a new script, consider adding the line:\n```text\n\nimport cgitb; cgitb.enable()\n```\nThis activates a special exception handler that will display detailed\nreports in the Web browser if any errors occur. If you'd rather not\nshow the guts of your program to users of your script, you can have\nthe reports saved to files instead, with a line like this:\n```text\n\nimport cgitb; cgitb.enable(display=0, logdir=\"/tmp\")\n```\nIt's very helpful to use this feature during script development.\nThe reports produced by cgitb (module-cgitb.html) provide information that\ncan save you a lot of time in tracking down bugs. You can always\nremove the `cgitb` line later when you have tested your script\nand are confident that it works correctly.\nTo get at submitted form data,\nit's best to use the FieldStorage class. The other classes\ndefined in this module are provided mostly for backward compatibility.\nInstantiate it exactly once, without arguments. This reads the form\ncontents from standard input or the environment (depending on the\nvalue of various environment variables set according to the CGI\nstandard). Since it may consume standard input, it should be\ninstantiated only once.\nThe FieldStorage instance can be indexed like a Python\ndictionary, and also supports the standard dictionary methods\nhas_key() and keys(). The built-in len()\nis also supported. Form fields containing empty strings are ignored\nand do not appear in the dictionary; to keep such values, provide\na true value for the the optional keep_blank_values keyword\nparameter when creating the FieldStorage instance.\nFor instance, the following code (which assumes that the\nContent-Type: header and blank line have already been\nprinted) checks that the fields `name` and `addr` are both\nset to a non-empty string:\n```text\n\nform = cgi.FieldStorage()\nif not (form.has_key(\"name\") and form.has_key(\"addr\")):\nprint \"

    Error

    \"\nprint \"Please fill in the name and addr fields.\"\nreturn\nprint \"

    name:\", form[\"name\"].value\nprint \"

    addr:\", form[\"addr\"].value\n...further form processing here...\n```\nHere the fields, accessed through \"form[key]\", are\nthemselves instances of FieldStorage (or\nMiniFieldStorage, depending on the form encoding).\nThe value attribute of the instance yields the string value\nof the field. The getvalue() method returns this string value\ndirectly; it also accepts an optional second argument as a default to\nreturn if the requested key is not present.\nIf the submitted form data contains more than one field with the same\nname, the object retrieved by \"form[key]\" is not a\nFieldStorage or MiniFieldStorage\ninstance but a list of such instances. Similarly, in this situation,\n\"form.getvalue(key)\" would return a list of strings.\nIf you expect this possibility\n(when your HTML form contains multiple fields with the same name), use\nthe type() built-in function to determine whether you\nhave a single instance or a list of instances. For example, this\ncode concatenates any number of username fields, separated by\ncommas:\n```text\n\nfrom types import ListType\n\nvalue = form.getvalue(\"username\", \"\")\nif isinstance(value, ListType):\n# Multiple username fields specified\nusernames = \",\".join(value)\nelse:\n# Single or no username field specified\nusernames = value\n```\nIf a field represents an uploaded file, accessing the value via the\nvalue attribute or the getvalue() method reads the\nentire file in memory as a string. This may not be what you want.\nYou can test for an uploaded file by testing either the filename\nattribute or the file attribute. You can then read the data at\nleisure from the file attribute:\n```text\n\nfileitem = form[\"userfile\"]\nif fileitem.file:\n# It's an uploaded file; count lines\nlinecount = 0\nwhile 1:\nline = fileitem.file.readline()\nif not line: break\nlinecount = linecount + 1\n```\nThe file upload draft standard entertains the possibility of uploading\nmultiple files from one field (using a recursive\nmultipart/* encoding). When this occurs, the item will be\na dictionary-like FieldStorage item. This can be determined\nby testing its type attribute, which should be\nmultipart/form-data (or perhaps another MIME type matching\nmultipart/*). In this case, it can be iterated over\nrecursively just like the top-level form object.\nWhen a form is submitted in the ``old'' format (as the query string or\nas a single data part of type\napplication/x-www-form-urlencoded), the items will actually\nbe instances of the class MiniFieldStorage. In this case, the\nlist, file, and filename attributes are\nalways `None`.", "python_version": "2.2", "length": 4862, "url": "https://docs.python.org/2.2/lib/node295.html"} {"title": "11.2.3 Higher Level Interface", "text": "node295.html | module-cgi.html | node297.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.3 Higher Level Interface\nNew in version 2.2.\nThe previous section explains how to read CGI form data using the\nFieldStorage class. This section describes a higher level\ninterface which was added to this class to allow one to do it in a\nmore readable and intuitive way. The interface doesn't make the\ntechniques described in previous sections obsolete -- they are still\nuseful to process file uploads efficiently, for example.\nThe interface consists of two simple methods. Using the methods\nyou can process form data in a generic way, without the need to worry\nwhether only one or more values were posted under one name.\nIn the previous section, you learned to write following code anytime\nyou expected a user to post more than one value under one name:\n```text\n\nfrom types import ListType\n\nitem = form.getvalue(\"item\")\nif isinstance(item, ListType):\n# The user is requesting more than one item.\nelse:\n# The user is requesting only one item.\n```\nThis situation is common for example when a form contains a group of\nmultiple checkboxes with the same name:\n```text\n\n\n\n```\nIn most situations, however, there's only one form control with a\nparticular name in a form and then you expect and need only one value\nassociated with this name. So you write a script containing for\nexample this code:\n```text\n\nuser = form.getvalue(\"user\").toupper()\n```\nThe problem with the code is that you should never expect that a\nclient will provide valid input to your scripts. For example, if a\ncurious user appends another \"user=foo\" pair to the query string,\nthen the script would crash, because in this situation the\n`getvalue(\"user\")` method call returns a list instead of a\nstring. Calling the toupper() method on a list is not valid\n(since lists do not have a method of this name) and results in an\nAttributeError exception.\nTherefore, the appropriate way to read form data values was to always\nuse the code which checks whether the obtained value is a single value\nor a list of values. That's annoying and leads to less readable\nscripts.\nA more convenient approach is to use the methods getfirst()\nand getlist() provided by this higher level interface.\nUsing these methods you can write nice compact code:\n```text\n\nimport cgi\nform = cgi.FieldStorage()\nuser = form.getfirst(\"user\").toupper() # This way it's safe.\nfor item in form.getlist(\"item\"):\ndo_something(item)\n```", "python_version": "2.2", "length": 2580, "url": "https://docs.python.org/2.2/lib/node296.html"} {"title": "11.2.4 Old classes", "text": "node296.html | module-cgi.html | node298.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.4 Old classes\nThese classes, present in earlier versions of the cgi module,\nare still supported for backward compatibility. New applications\nshould use the FieldStorage class.\nSvFormContentDict stores single value form content as\ndictionary; it assumes each field name occurs in the form only once.\nFormContentDict stores multiple value form content as a\ndictionary (the form items are lists of values). Useful if your form\ncontains multiple fields with the same name.\nOther classes (FormContent, InterpFormContentDict) are\npresent for backwards compatibility with really old applications only.\nIf you still use these and would be inconvenienced when they\ndisappeared from a next version of this module, drop me a note.", "python_version": "2.2", "length": 852, "url": "https://docs.python.org/2.2/lib/node297.html"} {"title": "11.2.5 Functions", "text": "node297.html | module-cgi.html | cgi-security.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.5 Functions\nThese are useful if you want more control, or if you want to employ\nsome of the algorithms implemented in this module in other\ncircumstances.", "python_version": "2.2", "length": 291, "url": "https://docs.python.org/2.2/lib/node298.html"} {"title": "11.2.7 Installing your CGI script on a Unix system", "text": "cgi-security.html | module-cgi.html | node301.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.7 Installing your CGI script on a Unix system\nRead the documentation for your HTTP server and check with your local\nsystem administrator to find the directory where CGI scripts should be\ninstalled; usually this is in a directory cgi-bin in the server tree.\nMake sure that your script is readable and executable by ``others''; the\nUnix file mode should be `0755` octal (use \"chmod 0755\nfilename\"). Make sure that the first line of the script contains\n`#!` starting in column 1 followed by the pathname of the Python\ninterpreter, for instance:\n```text\n\n#!/usr/local/bin/python\n```\nMake sure the Python interpreter exists and is executable by ``others''.\nMake sure that any files your script needs to read or write are\nreadable or writable, respectively, by ``others'' -- their mode\nshould be `0644` for readable and `0666` for writable. This\nis because, for security reasons, the HTTP server executes your script\nas user ``nobody'', without any special privileges. It can only read\n(write, execute) files that everybody can read (write, execute). The\ncurrent directory at execution time is also different (it is usually\nthe server's cgi-bin directory) and the set of environment variables\nis also different from what you get when you log in. In particular, don't\ncount on the shell's search path for executables (PATH) or\nthe Python module search path (PYTHONPATH) to be set to\nanything interesting.\nIf you need to load modules from a directory which is not on Python's\ndefault module search path, you can change the path in your script,\nbefore importing other modules. For example:\n```text\n\nimport sys\nsys.path.insert(0, \"/usr/home/joe/lib/python\")\nsys.path.insert(0, \"/usr/local/lib/python\")\n```\n(This way, the directory inserted last will be searched first!)\nInstructions for non-Unix systems will vary; check your HTTP server's\ndocumentation (it will usually have a section on CGI scripts).", "python_version": "2.2", "length": 2030, "url": "https://docs.python.org/2.2/lib/node300.html"} {"title": "11.2.8 Testing your CGI script", "text": "node300.html | module-cgi.html | node302.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.8 Testing your CGI script\nUnfortunately, a CGI script will generally not run when you try it\nfrom the command line, and a script that works perfectly from the\ncommand line may fail mysteriously when run from the server. There's\none reason why you should still test your script from the command\nline: if it contains a syntax error, the Python interpreter won't\nexecute it at all, and the HTTP server will most likely send a cryptic\nerror to the client.\nAssuming your script has no syntax errors, yet it does not work, you\nhave no choice but to read the next section.", "python_version": "2.2", "length": 698, "url": "https://docs.python.org/2.2/lib/node301.html"} {"title": "11.2.9 Debugging CGI scripts", "text": "node301.html | module-cgi.html | node303.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.9 Debugging CGI scripts\nFirst of all, check for trivial installation errors -- reading the\nsection above on installing your CGI script carefully can save you a\nlot of time. If you wonder whether you have understood the\ninstallation procedure correctly, try installing a copy of this module\nfile (cgi.py) as a CGI script. When invoked as a script, the file\nwill dump its environment and the contents of the form in HTML form.\nGive it the right mode etc, and send it a request. If it's installed\nin the standard cgi-bin directory, it should be possible to send it a\nrequest by entering a URL into your browser of the form:\n```text\n\nhttp://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home\n```\nIf this gives an error of type 404, the server cannot find the script\n- perhaps you need to install it in a different directory. If it\ngives another error, there's an installation problem that\nyou should fix before trying to go any further. If you get a nicely\nformatted listing of the environment and form content (in this\nexample, the fields should be listed as ``addr'' with value ``At Home''\nand ``name'' with value ``Joe Blow''), the cgi.py script has been\ninstalled correctly. If you follow the same procedure for your own\nscript, you should now be able to debug it.\nThe next step could be to call the cgi module's\ntest() function from your script: replace its main code\nwith the single statement\n```text\n\ncgi.test()\n```\nThis should produce the same results as those gotten from installing\nthe cgi.py file itself.\nWhen an ordinary Python script raises an unhandled exception (for\nwhatever reason: of a typo in a module name, a file that can't be\nopened, etc.), the Python interpreter prints a nice traceback and\nexits. While the Python interpreter will still do this when your CGI\nscript raises an exception, most likely the traceback will end up in\none of the HTTP server's log files, or be discarded altogether.\nFortunately, once you have managed to get your script to execute\nsome code, you can easily send tracebacks to the Web browser\nusing the cgitb (module-cgitb.html) module. If you haven't done so already,\njust add the line:\n```text\n\nimport cgitb; cgitb.enable()\n```\nto the top of your script. Then try running it again; when a\nproblem occurs, you should see a detailed report that will\nlikely make apparent the cause of the crash.\nIf you suspect that there may be a problem in importing the\ncgitb (module-cgitb.html) module, you can use an even more robust approach\n(which only uses built-in modules):\n```text\n\nimport sys\nsys.stderr = sys.stdout\nprint \"Content-Type: text/plain\"\nprint\n...your code here...\n```\nThis relies on the Python interpreter to print the traceback. The\ncontent type of the output is set to plain text, which disables all\nHTML processing. If your script works, the raw HTML will be displayed\nby your client. If it raises an exception, most likely after the\nfirst two lines have been printed, a traceback will be displayed.\nBecause no HTML interpretation is going on, the traceback will be\nreadable.", "python_version": "2.2", "length": 3166, "url": "https://docs.python.org/2.2/lib/node302.html"} {"title": "11.2.10 Common problems and solutions", "text": "node302.html | module-cgi.html | module-cgitb.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.10 Common problems and solutions", "python_version": "2.2", "length": 170, "url": "https://docs.python.org/2.2/lib/node303.html"} {"title": "11.4.2 Examples", "text": "urlopener-objs.html | module-urllib.html | module-urllib2.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.4.2 Examples\nHere is an example session that uses the \"GET\" method to retrieve\na URL containing parameters:\n```text\n\n>>> import urllib\n>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n>>> f = urllib.urlopen(\"http://www.musi-cal.com/cgi-bin/query?%s\" % params)\n>>> print f.read()\n```\nThe following example uses the \"POST\" method instead:", "python_version": "2.2", "length": 501, "url": "https://docs.python.org/2.2/lib/node307.html"} {"title": "11.5.1 HTTP Objects", "text": "module-httplib.html | module-httplib.html | httplib-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.1 HTTP Objects\nHTTP instances have the following methods:", "python_version": "2.2", "length": 210, "url": "https://docs.python.org/2.2/lib/node312.html"} {"title": "11.20.7 Convenience Functions", "text": "protocol-error-objects.html | module-xmlrpclib.html | xmlrpc-client-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.7 Convenience Functions", "python_version": "2.2", "length": 192, "url": "https://docs.python.org/2.2/lib/node365.html"} {"title": "12.2.2.1 Parser class API", "text": "module-email.Parser.html | module-email.Parser.html | node381.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 12.2.2.1 Parser class API\nThe other public Parser methods are:\nSince creating a message object tree from a string or a file object is\nsuch a common task, two functions are provided as a convenience. They\nare available in the top-level email package namespace.\nHere's an example of how you might use this at an interactive Python\nprompt:\n```text\n\n>>> import email\n>>> msg = email.message_from_string(myString)\n```", "python_version": "2.2", "length": 562, "url": "https://docs.python.org/2.2/lib/node380.html"} {"title": "12.2.2.2 Additional notes", "text": "node380.html | module-email.Parser.html | module-email.Generator.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 12.2.2.2 Additional notes\nHere are some notes on the parsing semantics:\n- Most non-multipart type messages are parsed as a single\nmessage object with a string payload. These objects will return\n0 for is_multipart().\n- One exception is for message/delivery-status type\nmessages. Because the body of such messages consist of\nblocks of headers, Parser will create a non-multipart\nobject containing non-multipart subobjects for each header\nblock.\n- Another exception is for message/* types (more\ngeneral than message/delivery-status). These are\ntypically message/rfc822 messages, represented as a\nnon-multipart object containing a singleton payload which is\nanother non-multipart Message instance.", "python_version": "2.2", "length": 846, "url": "https://docs.python.org/2.2/lib/node381.html"} {"title": "12.2.4 Creating email and MIME objects from scratch", "text": "module-email.Generator.html | module-email.html | module-email.Encoders.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.4 Creating email and MIME objects from scratch\nOrdinarily, you get a message object tree by passing some text to a\nparser, which parses the text and returns the root of the message\nobject tree. However you can also build a complete object tree from\nscratch, or even individual Message objects by hand. In fact,\nyou can also take an existing tree and add new Message\nobjects, move them around, etc. This makes a very convenient\ninterface for slicing-and-dicing MIME messages.\nYou can create a new object tree by creating Message\ninstances, adding payloads and all the appropriate headers manually.\nFor MIME messages though, the email package provides some\nconvenient classes to make things easier. Each of these classes\nshould be imported from a module with the same name as the class, from\nwithin the email package. E.g.:\n```text\n\nimport email.MIMEImage.MIMEImage\n```\nor\n```text\n\nfrom email.MIMEText import MIMEText\n```\nHere are the classes:", "python_version": "2.2", "length": 1105, "url": "https://docs.python.org/2.2/lib/node383.html"} {"title": "12.2.9 Differences from mimelib", "text": "module-email.Iterators.html | module-email.html | node389.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.9 Differences from mimelib\nThe email package was originally prototyped as a separate\nlibrary called\nmimelib (http://mimelib.sf.net/).\nChanges have been made so that\nmethod names are more consistent, and some methods or modules have\neither been added or removed. The semantics of some of the methods\nhave also changed. For the most part, any functionality available in\nmimelib is still available in the email (module-email.html) package,\nalbeit often in a different way.\nHere is a brief description of the differences between the\nmimelib and the email (module-email.html) packages, along with hints on\nhow to port your applications.\nOf course, the most visible difference between the two packages is\nthat the package name has been changed to email (module-email.html). In\naddition, the top-level package has the following differences:\n- messageFromString() has been renamed to\nmessage_from_string().\n- messageFromFile() has been renamed to\nmessage_from_file().\nThe Message class has the following differences:\n- The method asString() was renamed to as_string().\n- The method ismultipart() was renamed to\nis_multipart().\n- The get_payload() method has grown a decode\noptional argument.\n- The method getall() was renamed to get_all().\n- The method addheader() was renamed to add_header().\n- The method gettype() was renamed to get_type().\n- The methodgetmaintype() was renamed to\nget_main_type().\n- The method getsubtype() was renamed to\nget_subtype().\n- The method getparams() was renamed to\nget_params().\nAlso, whereas getparams() returned a list of strings,\nget_params() returns a list of 2-tuples, effectively\nthe key/value pairs of the parameters, split on the \"=\"\nsign.\n- The method getparam() was renamed to get_param().\n- The method getcharsets() was renamed to\nget_charsets().\n- The method getfilename() was renamed to\nget_filename().\n- The method getboundary() was renamed to\nget_boundary().\n- The method setboundary() was renamed to\nset_boundary().\n- The method getdecodedpayload() was removed. To get\nsimilar functionality, pass the value 1 to the decode flag\nof the get_payload() method.\n- The method getpayloadastext() was removed. Similar\nfunctionality\nis supported by the DecodedGenerator class in the\nemail.Generator (module-email.Generator.html) module.\n- The method getbodyastext() was removed. You can get\nsimilar functionality by creating an iterator with\ntyped_subpart_iterator() in the\nemail.Iterators (module-email.Iterators.html) module.\nThe Parser class has no differences in its public interface.\nIt does have some additional smarts to recognize\nmessage/delivery-status type messages, which it represents as\na Message instance containing separate Message\nsubparts for each header block in the delivery status\nnotification12.4 (#foot36813).\nThe Generator class has no differences in its public\ninterface. There is a new class in the email.Generator (module-email.Generator.html)\nmodule though, called DecodedGenerator which provides most of\nthe functionality previously available in the\nMessage.getpayloadastext() method.\nThe following modules and classes have been changed:\n- The MIMEBase class constructor arguments _major\nand _minor have changed to _maintype and\n_subtype respectively.\n- The `Image` class/module has been renamed to\n`MIMEImage`. The _minor argument has been renamed to\n_subtype.\n- The `Text` class/module has been renamed to\n`MIMEText`. The _minor argument has been renamed to\n_subtype.\n- The `MessageRFC822` class/module has been renamed to\n`MIMEMessage`. Note that an earlier version of\nmimelib called this class/module `RFC822`, but\nthat clashed with the Python standard library module\nrfc822 (module-rfc822.html) on some case-insensitive file systems.\nAlso, the MIMEMessage class now represents any kind of\nMIME message with main type message. It takes an\noptional argument _subtype which is used to set the MIME\nsubtype. _subtype defaults to rfc822.\nmimelib provided some utility functions in its\naddress and date modules. All of these functions\nhave been moved to the email.Utils (module-email.Utils.html) module.\nThe `MsgReader` class/module has been removed. Its functionality\nis most closely supported in the body_line_iterator()\nfunction in the email.Iterators (module-email.Iterators.html) module.", "python_version": "2.2", "length": 4401, "url": "https://docs.python.org/2.2/lib/node388.html"} {"title": "12.2.10 Examples", "text": "node388.html | module-email.html | module-mailcap.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.2.10 Examples\nHere are a few examples of how to use the email package to\nread, write, and send simple email messages, as well as more complex\nMIME messages.\nFirst, let's see how to create and send a simple text message:\n```text\n\n# Import smtplib for the actual sending function\nimport smtplib\n\n# Here are the email pacakge modules we'll need\nfrom email import Encoders\nfrom email.MIMEText import MIMEText\n\n# Open a plain text file for reading\nfp = open(textfile)\n# Create a text/plain message, using Quoted-Printable encoding for non-ASCII\n# characters.\nmsg = MIMEText(fp.read(), _encoder=Encoders.encode_quopri)\nfp.close()\n\n# me == the sender's email address\n# you == the recipient's email address\nmsg['Subject'] = 'The contents of \\%s' \\% textfile\nmsg['From'] = me\nmsg['To'] = you\n\n# Send the message via our own SMTP server. Use msg.as_string() with\n# unixfrom=0 so as not to confuse SMTP.\ns = smtplib.SMTP()\ns.connect()\ns.sendmail(me, [you], msg.as_string(0))\ns.close()\n```\nHere's an example of how to send a MIME message containing a bunch of\nfamily pictures:\n```text\n\n# Import smtplib for the actual sending function\nimport smtplib\n\n# Here are the email pacakge modules we'll need\nfrom email.MIMEImage import MIMEImage\nfrom email.MIMEBase import MIMEBase\n\nCOMMASPACE = ', '\n\n# Create the container (outer) email message.\n# me == the sender's email address\n# family = the list of all recipients' email addresses\nmsg = MIMEBase('multipart', 'mixed')\nmsg['Subject'] = 'Our family reunion'\nmsg['From'] = me\nmsg['To'] = COMMASPACE.join(family)\nmsg.preamble = 'Our family reunion'\n# Guarantees the message ends in a newline\nmsg.epilogue = ''\n\n# Assume we know that the image files are all in PNG format\nfor file in pngfiles:\n# Open the files in binary mode. Let the MIMEIMage class automatically\n# guess the specific image type.\nfp = open(file, 'rb')\nimg = MIMEImage(fp.read())\nfp.close()\nmsg.attach(img)\n\n# Send the email via our own SMTP server.\ns = smtplib.SMTP()\ns.connect()\ns.sendmail(me, family, msg.as_string(unixfrom=0))\ns.close()\n```\nHere's an example12.5 (#foot36805) of how to send the entire contents\nof a directory as an email message:\n```text\n\n#!/usr/bin/env python\n\n\"\"\"Send the contents of a directory as a MIME message.\n\nUsage: dirmail [options] from to [to ...]*\n\nOptions:\n-h / --help\nPrint this message and exit.\n\n-d directory\n--directory=directory\nMail the contents of the specified directory, otherwise use the\ncurrent directory. Only the regular files in the directory are sent,\nand we don't recurse to subdirectories.\n\n`from' is the email address of the sender of the message.\n\n`to' is the email address of the recipient of the message, and multiple\nrecipients may be given.\n\nThe email is sent by forwarding to your local SMTP server, which then does the\nnormal delivery process. Your local machine must be running an SMTP server.\n\"\"\"\n\nimport sys\nimport os\nimport getopt\nimport smtplib\n# For guessing MIME type based on file name extension\nimport mimetypes\n\nfrom email import Encoders\nfrom email.Message import Message\nfrom email.MIMEAudio import MIMEAudio\nfrom email.MIMEBase import MIMEBase\nfrom email.MIMEImage import MIMEImage\nfrom email.MIMEText import MIMEText\n\nCOMMASPACE = ', '\n\ndef usage(code, msg=''):\nprint >> sys.stderr, __doc__\nif msg:\nprint >> sys.stderr, msg\nsys.exit(code)\n\ndef main():\ntry:\nopts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory='])\nexcept getopt.error, msg:\nusage(1, msg)\n\ndir = os.curdir\nfor opt, arg in opts:\nif opt in ('-h', '--help'):\nusage(0)\nelif opt in ('-d', '--directory'):\ndir = arg\n\nif len(args) < 2:\nusage(1)\n\nsender = args[0]\nrecips = args[1:]\n\n# Create the enclosing (outer) message\nouter = MIMEBase('multipart', 'mixed')\nouter['Subject'] = 'Contents of directory \\%s' \\% os.path.abspath(dir)\nouter['To'] = sender\nouter['From'] = COMMASPACE.join(recips)\nouter.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\n# To guarantee the message ends with a newline\nouter.epilogue = ''\n\nfor filename in os.listdir(dir):\npath = os.path.join(dir, filename)\nif not os.path.isfile(path):\ncontinue\n# Guess the Content-Type: based on the file's extension. Encoding\n# will be ignored, although we should check for simple things like\n# gzip'd or compressed files\nctype, encoding = mimetypes.guess_type(path)\nif ctype is None or encoding is not None:\n# No guess could be made, or the file is encoded (compressed), so\n# use a generic bag-of-bits type.\nctype = 'application/octet-stream'\nmaintype, subtype = ctype.split('/', 1)\nif maintype == 'text':\nfp = open(path)\n# Note: we should handle calculating the charset\nmsg = MIMEText(fp.read(), _subtype=subtype)\nfp.close()\nelif maintype == 'image':\nfp = open(path, 'rb')\nmsg = MIMEImage(fp.read(), _subtype=subtype)\nfp.close()\nelif maintype == 'audio':\nfp = open(path, 'rb')\nmsg = MIMEAudio(fp.read(), _subtype=subtype)\nfp.close()\nelse:\nfp = open(path, 'rb')\nmsg = MIMEBase(maintype, subtype)\nmsg.add_payload(fp.read())\nfp.close()\n# Encode the payload using Base64\nEncoders.encode_base64(msg)\n# Set the filename parameter\nmsg.add_header('Content-Disposition', 'attachment', filename=filename)\nouter.attach(msg)\n\nfp = open('/tmp/debug.pck', 'w')\nimport cPickle\ncPickle.dump(outer, fp)\nfp.close()\n# Now send the message\ns = smtplib.SMTP()\ns.connect()\ns.sendmail(sender, recips, outer.as_string(0))\ns.close()\n\nif __name__ == '__main__':\nmain()\n```\nAnd finally, here's an example of how to unpack a MIME message like\nthe one above, into a directory of files:", "python_version": "2.2", "length": 5621, "url": "https://docs.python.org/2.2/lib/node389.html"} {"title": "13.5.1 Module Contents", "text": "module-xml.dom.html | module-xml.dom.html | node393.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.5.1 Module Contents\nThe xml.dom contains the following functions:\nIn addition, xml.dom contains the Node, and the DOM\nexceptions.", "python_version": "2.2", "length": 271, "url": "https://docs.python.org/2.2/lib/node392.html"} {"title": "13.5.2 Objects in the DOM", "text": "node392.html | module-xml.dom.html | dom-implementation-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.5.2 Objects in the DOM\nThe definitive documentation for the DOM is the DOM specification from\nthe W3C.\nNote that DOM attributes may also be manipulated as nodes instead of\nas simple strings. It is fairly rare that you must do this, however,\nso this usage is not yet documented.\nAn additional section describes the exceptions defined for working\nwith the DOM in Python.", "python_version": "2.2", "length": 522, "url": "https://docs.python.org/2.2/lib/node393.html"} {"title": "3.4.2 Limitations and other considerations", "text": "fpectl-example.html | module-fpectl.html | module-atexit.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.4.2 Limitations and other considerations\nSetting up a given processor to trap IEEE-754 floating point\nerrors currently requires custom code on a per-architecture basis.\nYou may have to modify fpectl to control your particular hardware.\nConversion of an IEEE-754 exception to a Python exception requires\nthat the wrapper macros `PyFPE_START_PROTECT` and\n`PyFPE_END_PROTECT` be inserted into your code in an appropriate\nfashion. Python itself has been modified to support the\nfpectl module, but many other codes of interest to numerical\nanalysts have not.\nThe fpectl module is not thread-safe.", "python_version": "2.2", "length": 737, "url": "https://docs.python.org/2.2/lib/node40.html"} {"title": "3.4.2 Limitations and other considerations", "text": "fpectl-example.html | module-fpectl.html | module-atexit.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.4.2 Limitations and other considerations\nSetting up a given processor to trap IEEE-754 floating point\nerrors currently requires custom code on a per-architecture basis.\nYou may have to modify fpectl to control your particular hardware.\nConversion of an IEEE-754 exception to a Python exception requires\nthat the wrapper macros `PyFPE_START_PROTECT` and\n`PyFPE_END_PROTECT` be inserted into your code in an appropriate\nfashion. Python itself has been modified to support the\nfpectl module, but many other codes of interest to numerical\nanalysts have not.\nThe fpectl module is not thread-safe.", "python_version": "2.2", "length": 737, "url": "https://docs.python.org/2.2/lib/node41.html"} {"title": "13.6.1 Module Contents", "text": "module-xml.dom.html | module-xml.dom.html | node438.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.6.1 Module Contents\nThe xml.dom contains the following functions:\nSome convenience constants are also provided:\nIn addition, xml.dom contains a base Node class and\nthe DOM exception classes. The Node class provided by this\nmodule does not implement any of the methods or attributes defined by\nthe DOM specification; concrete DOM implementations must provide\nthose. The Node class provided as part of this module does\nprovide the constants used for the nodeType attribute on\nconcrete Node objects; they are located within the class\nrather than at the module level to conform with the DOM\nspecifications.", "python_version": "2.2", "length": 744, "url": "https://docs.python.org/2.2/lib/node437.html"} {"title": "13.6.2 Objects in the DOM", "text": "node437.html | module-xml.dom.html | dom-implementation-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.6.2 Objects in the DOM\nThe definitive documentation for the DOM is the DOM specification from\nthe W3C.\nNote that DOM attributes may also be manipulated as nodes instead of\nas simple strings. It is fairly rare that you must do this, however,\nso this usage is not yet documented.\nAn additional section describes the exceptions defined for working\nwith the DOM in Python.", "python_version": "2.2", "length": 522, "url": "https://docs.python.org/2.2/lib/node438.html"} {"title": "16.1.1 An example", "text": "module-rexec.html | module-rexec.html | module-Bastion.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.1.1 An example\nLet us say that we want a slightly more relaxed policy than the\nstandard RExec class. For example, if we're willing to allow\nfiles in /tmp to be written, we can subclass the RExec\nclass:", "python_version": "2.2", "length": 346, "url": "https://docs.python.org/2.2/lib/node454.html"} {"title": "17.1.6.1 Emulation of compile()", "text": "AST_Examples.html | AST_Examples.html | node465.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 17.1.6.1 Emulation of compile()\nWhile many useful operations may take place between parsing and\nbytecode generation, the simplest operation is to do nothing. For\nthis purpose, using the parser module to produce an\nintermediate data structure is equivalent to the code\n```text\n\n>>> code = compile('a + 5', 'file.py', 'eval')\n>>> a = 5\n>>> eval(code)\n10\n```\nThe equivalent operation using the parser module is somewhat\nlonger, and allows the intermediate internal parse tree to be retained\nas an AST object:\n```text\n\n>>> import parser\n>>> ast = parser.expr('a + 5')\n>>> code = ast.compile('file.py')\n>>> a = 5\n>>> eval(code)\n10\n```\nAn application which needs both AST and code objects can package this\ncode into readily available functions:\n```text\n\nimport parser\n\ndef load_suite(source_string):\nast = parser.suite(source_string)\nreturn ast, ast.compile()\n\ndef load_expression(source_string):\nast = parser.expr(source_string)\nreturn ast, ast.compile()\n```", "python_version": "2.2", "length": 1089, "url": "https://docs.python.org/2.2/lib/node464.html"} {"title": "17.1.6.2 Information Discovery", "text": "node464.html | AST_Examples.html | module-symbol.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 17.1.6.2 Information Discovery\nSome applications benefit from direct access to the parse tree. The\nremainder of this section demonstrates how the parse tree provides\naccess to module documentation defined in\ndocstringswithout\nrequiring that the code being examined be loaded into a running\ninterpreter via import. This can be very useful for\nperforming analyses of untrusted code.\nGenerally, the example will demonstrate how the parse tree may be\ntraversed to distill interesting information. Two functions and a set\nof classes are developed which provide programmatic access to high\nlevel function and class definitions provided by a module. The\nclasses extract information from the parse tree and provide access to\nthe information at a useful semantic level, one function provides a\nsimple low-level pattern matching capability, and the other function\ndefines a high-level interface to the classes by handling file\noperations on behalf of the caller. All source files mentioned here\nwhich are not part of the Python installation are located in the\nDemo/parser/ directory of the distribution.\nThe dynamic nature of Python allows the programmer a great deal of\nflexibility, but most modules need only a limited measure of this when\ndefining classes, functions, and methods. In this example, the only\ndefinitions that will be considered are those which are defined in the\ntop level of their context, e.g., a function defined by a def\nstatement at column zero of a module, but not a function defined\nwithin a branch of an if ... else construct, though\nthere are some good reasons for doing so in some situations. Nesting\nof definitions will be handled by the code developed in the example.\nTo construct the upper-level extraction methods, we need to know what\nthe parse tree structure looks like and how much of it we actually\nneed to be concerned about. Python uses a moderately deep parse tree\nso there are a large number of intermediate nodes. It is important to\nread and understand the formal grammar used by Python. This is\nspecified in the file Grammar/Grammar in the distribution.\nConsider the simplest case of interest when searching for docstrings:\na module consisting of a docstring and nothing else. (See file\ndocstring.py.)\n```text\n\n\"\"\"Some documentation.\n\"\"\"\n```\nUsing the interpreter to take a look at the parse tree, we find a\nbewildering mass of numbers and parentheses, with the documentation\nburied deep in nested tuples.\n```text\n\n>>> import parser\n>>> import pprint\n>>> ast = parser.suite(open('docstring.py').read())\n>>> tup = ast.totuple()\n>>> pprint.pprint(tup)\n(257,\n(264,\n(265,\n(266,\n(267,\n(307,\n(287,\n(288,\n(289,\n(290,\n(292,\n(293,\n(294,\n(295,\n(296,\n(297,\n(298,\n(299,\n(300, (3, '\"\"\"Some documentation.\\n\"\"\"'))))))))))))))))),\n(4, ''))),\n(4, ''),\n(0, ''))\n```\nThe numbers at the first element of each node in the tree are the node\ntypes; they map directly to terminal and non-terminal symbols in the\ngrammar. Unfortunately, they are represented as integers in the\ninternal representation, and the Python structures generated do not\nchange that. However, the symbol (module-symbol.html) and token (module-token.html) modules\nprovide symbolic names for the node types and dictionaries which map\nfrom the integers to the symbolic names for the node types.\nIn the output presented above, the outermost tuple contains four\nelements: the integer `257` and three additional tuples. Node\ntype `257` has the symbolic name file_input. Each of\nthese inner tuples contains an integer as the first element; these\nintegers, `264`, `4`, and `0`, represent the node types\nstmt, NEWLINE, and ENDMARKER,\nrespectively.\nNote that these values may change depending on the version of Python\nyou are using; consult symbol.py and token.py for\ndetails of the mapping. It should be fairly clear that the outermost\nnode is related primarily to the input source rather than the contents\nof the file, and may be disregarded for the moment. The stmt\nnode is much more interesting. In particular, all docstrings are\nfound in subtrees which are formed exactly as this node is formed,\nwith the only difference being the string itself. The association\nbetween the docstring in a similar tree and the defined entity (class,\nfunction, or module) which it describes is given by the position of\nthe docstring subtree within the tree defining the described\nstructure.\nBy replacing the actual docstring with something to signify a variable\ncomponent of the tree, we allow a simple pattern matching approach to\ncheck any given subtree for equivalence to the general pattern for\ndocstrings. Since the example demonstrates information extraction, we\ncan safely require that the tree be in tuple form rather than list\nform, allowing a simple variable representation to be\n`['variable_name']`. A simple recursive function can implement\nthe pattern matching, returning a boolean and a dictionary of variable\nname to value mappings. (See file example.py.)\n```text\n\nfrom types import ListType, TupleType\n\ndef match(pattern, data, vars=None):\nif vars is None:\nvars = {}\nif type(pattern) is ListType:\nvars[pattern[0]] = data\nreturn 1, vars\nif type(pattern) is not TupleType:\nreturn (pattern == data), vars\nif len(data) != len(pattern):\nreturn 0, vars\nfor pattern, data in map(None, pattern, data):\nsame, vars = match(pattern, data, vars)\nif not same:\nbreak\nreturn same, vars\n```\nUsing this simple representation for syntactic variables and the symbolic\nnode types, the pattern for the candidate docstring subtrees becomes\nfairly readable. (See file example.py.)\n```text\n\nimport symbol\nimport token\n\nDOCSTRING_STMT_PATTERN = (\nsymbol.stmt,\n(symbol.simple_stmt,\n(symbol.small_stmt,\n(symbol.expr_stmt,\n(symbol.testlist,\n(symbol.test,\n(symbol.and_test,\n(symbol.not_test,\n(symbol.comparison,\n(symbol.expr,\n(symbol.xor_expr,\n(symbol.and_expr,\n(symbol.shift_expr,\n(symbol.arith_expr,\n(symbol.term,\n(symbol.factor,\n(symbol.power,\n(symbol.atom,\n(token.STRING, ['docstring'])\n)))))))))))))))),\n(token.NEWLINE, '')\n))\n```\nUsing the match() function with this pattern, extracting the\nmodule docstring from the parse tree created previously is easy:\n```text\n\n>>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1])\n>>> found\n1\n>>> vars\n{'docstring': '\"\"\"Some documentation.\\n\"\"\"'}\n```\nOnce specific data can be extracted from a location where it is\nexpected, the question of where information can be expected\nneeds to be answered. When dealing with docstrings, the answer is\nfairly simple: the docstring is the first stmt node in a code\nblock (file_input or suite node types). A module\nconsists of a single file_input node, and class and function\ndefinitions each contain exactly one suite node. Classes and\nfunctions are readily identified as subtrees of code block nodes which\nstart with `(stmt, (compound_stmt, (classdef, ...` or\n`(stmt, (compound_stmt, (funcdef, ...`. Note that these subtrees\ncannot be matched by match() since it does not support multiple\nsibling nodes to match without regard to number. A more elaborate\nmatching function could be used to overcome this limitation, but this\nis sufficient for the example.\nGiven the ability to determine whether a statement might be a\ndocstring and extract the actual string from the statement, some work\nneeds to be performed to walk the parse tree for an entire module and\nextract information about the names defined in each context of the\nmodule and associate any docstrings with the names. The code to\nperform this work is not complicated, but bears some explanation.\nThe public interface to the classes is straightforward and should\nprobably be somewhat more flexible. Each ``major'' block of the\nmodule is described by an object providing several methods for inquiry\nand a constructor which accepts at least the subtree of the complete\nparse tree which it represents. The ModuleInfo constructor\naccepts an optional name parameter since it cannot\notherwise determine the name of the module.\nThe public classes include ClassInfo, FunctionInfo,\nand ModuleInfo. All objects provide the\nmethods get_name(), get_docstring(),\nget_class_names(), and get_class_info(). The\nClassInfo objects support get_method_names() and\nget_method_info() while the other classes provide\nget_function_names() and get_function_info().\nWithin each of the forms of code block that the public classes\nrepresent, most of the required information is in the same form and is\naccessed in the same way, with classes having the distinction that\nfunctions defined at the top level are referred to as ``methods.''\nSince the difference in nomenclature reflects a real semantic\ndistinction from functions defined outside of a class, the\nimplementation needs to maintain the distinction.\nHence, most of the functionality of the public classes can be\nimplemented in a common base class, SuiteInfoBase, with the\naccessors for function and method information provided elsewhere.\nNote that there is only one class which represents function and method\ninformation; this parallels the use of the def statement to\ndefine both types of elements.\nMost of the accessor functions are declared in SuiteInfoBase\nand do not need to be overridden by subclasses. More importantly, the\nextraction of most information from a parse tree is handled through a\nmethod called by the SuiteInfoBase constructor. The example\ncode for most of the classes is clear when read alongside the formal\ngrammar, but the method which recursively creates new information\nobjects requires further examination. Here is the relevant part of\nthe SuiteInfoBase definition from example.py:\n```text\n\nclass SuiteInfoBase:\n_docstring = ''\n_name = ''\n\ndef __init__(self, tree = None):\nself._class_info = {}\nself._function_info = {}\nif tree:\nself._extract_info(tree)\n\ndef _extract_info(self, tree):\n# extract docstring\nif len(tree) == 2:\nfound, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])\nelse:\nfound, vars = match(DOCSTRING_STMT_PATTERN, tree[3])\nif found:\nself._docstring = eval(vars['docstring'])\n# discover inner definitions\nfor node in tree[1:]:\nfound, vars = match(COMPOUND_STMT_PATTERN, node)\nif found:\ncstmt = vars['compound']\nif cstmt[0] == symbol.funcdef:\nname = cstmt[2][1]\nself._function_info[name] = FunctionInfo(cstmt)\nelif cstmt[0] == symbol.classdef:\nname = cstmt[2][1]\nself._class_info[name] = ClassInfo(cstmt)\n```\nAfter initializing some internal state, the constructor calls the\n_extract_info() method. This method performs the bulk of the\ninformation extraction which takes place in the entire example. The\nextraction has two distinct phases: the location of the docstring for\nthe parse tree passed in, and the discovery of additional definitions\nwithin the code block represented by the parse tree.\nThe initial if test determines whether the nested suite is of\nthe ``short form'' or the ``long form.'' The short form is used when\nthe code block is on the same line as the definition of the code\nblock, as in\n```text\n\ndef square(x): \"Square an argument.\"; return x ** 2\n```\nwhile the long form uses an indented block and allows nested\ndefinitions:\n```text\n\ndef make_power(exp):\n\"Make a function that raises an argument to the exponent `exp'.\"\ndef raiser(x, y=exp):\nreturn x ** y\nreturn raiser\n```\nWhen the short form is used, the code block may contain a docstring as\nthe first, and possibly only, small_stmt element. The\nextraction of such a docstring is slightly different and requires only\na portion of the complete pattern used in the more common case. As\nimplemented, the docstring will only be found if there is only\none small_stmt node in the simple_stmt node.\nSince most functions and methods which use the short form do not\nprovide a docstring, this may be considered sufficient. The\nextraction of the docstring proceeds using the match() function\nas described above, and the value of the docstring is stored as an\nattribute of the SuiteInfoBase object.\nAfter docstring extraction, a simple definition discovery\nalgorithm operates on the stmt nodes of the\nsuite node. The special case of the short form is not\ntested; since there are no stmt nodes in the short form,\nthe algorithm will silently skip the single simple_stmt\nnode and correctly not discover any nested definitions.\nEach statement in the code block is categorized as\na class definition, function or method definition, or\nsomething else. For the definition statements, the name of the\nelement defined is extracted and a representation object\nappropriate to the definition is created with the defining subtree\npassed as an argument to the constructor. The representation objects\nare stored in instance variables and may be retrieved by name using\nthe appropriate accessor methods.\nThe public classes provide any accessors required which are more\nspecific than those provided by the SuiteInfoBase class, but\nthe real extraction algorithm remains common to all forms of code\nblocks. A high-level function can be used to extract the complete set\nof information from a source file. (See file example.py.)\n```text\n\ndef get_docs(fileName):\nimport os\nimport parser\n\nsource = open(fileName).read()\nbasename = os.path.basename(os.path.splitext(fileName)[0])\nast = parser.suite(source)\nreturn ModuleInfo(ast.totuple(), basename)\n```", "python_version": "2.2", "length": 13286, "url": "https://docs.python.org/2.2/lib/node465.html"} {"title": "16.1.1 Tkinter Modules", "text": "module-Tkinter.html | module-Tkinter.html | node501.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.1.1 Tkinter Modules\nMost of the time, the Tkinter (module-Tkinter.html) module is all you really\nneed, but a number of additional modules are available as well. The\nTk interface is located in a binary module named _tkinter.\nThis module contains the low-level interface to Tk, and should never\nbe used directly by application programmers. It is usually a shared\nlibrary (or DLL), but might in some cases be statically linked with\nthe Python interpreter.\nIn addition to the Tk interface module, Tkinter (module-Tkinter.html) includes a\nnumber of Python modules. The two most important modules are the\nTkinter (module-Tkinter.html) module itself, and a module called\nTkconstants. The former automatically imports the latter, so\nto use Tkinter, all you need to do is to import one module:\n```text\n\nimport Tkinter\n```\nOr, more often:\n```text\n\nfrom Tkinter import *\n```\nOther modules that provide Tk support include:\nScrolledText (module-ScrolledText.html): Text widget with a vertical scroll bar built in.\ntkColorChooser: Dialog to let the user choose a color.\ntkCommonDialog: Base class for the dialogs defined in the other modules listed here.\ntkFileDialog: Common dialogs to allow the user to specify a file to open or save.\ntkFont: Utilities to help work with fonts.\ntkMessageBox: Access to standard Tk dialog boxes.\ntkSimpleDialog: Basic dialogs and convenience functions.\nTkdnd: Drag-and-drop support for Tkinter (module-Tkinter.html).\nThis is experimental and should become deprecated when it is replaced\nwith the Tk DND.\nturtle (module-turtle.html): Turtle graphics in a Tk window.", "python_version": "2.2", "length": 1726, "url": "https://docs.python.org/2.2/lib/node500.html"} {"title": "16.1.2 Tkinter Life Preserver", "text": "node500.html | module-Tkinter.html | node502.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.1.2 Tkinter Life Preserver\nThis section is not designed to be an exhaustive tutorial on either\nTk or Tkinter. Rather, it is intended as a stop gap, providing some\nintroductory orientation on the system.\nCredits:\n- Tkinter was written by Steen Lumholt and Guido van Rossum.\n- Tk was written by John Ousterhout while at Berkeley.\n- This Life Preserver was written by Matt Conway at\nthe University of Virginia.\n- The html rendering, and some liberal editing, was\nproduced from a FrameMaker version by Ken Manheimer.\n- Fredrik Lundh elaborated and revised the class interface descriptions,\nto get them current with Tk 4.2.\n- Mike Clarkson converted the documentation to LATEX, and compiled the\nUser Interface chapter of the reference manual.", "python_version": "2.2", "length": 872, "url": "https://docs.python.org/2.2/lib/node501.html"} {"title": "16.1.2.1 How To Use This Section", "text": "node501.html | node501.html | node503.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.2.1 How To Use This Section\nThis section is designed in two parts: the first half (roughly) covers\nbackground material, while the second half can be taken to the\nkeyboard as a handy reference.\nWhen trying to answer questions of the form ``how do I do blah'', it\nis often best to find out how to do``blah'' in straight Tk, and then\nconvert this back into the corresponding Tkinter (module-Tkinter.html) call.\nPython programmers can often guess at the correct Python command by\nlooking at the Tk documentation. This means that in order to use\nTkinter, you will have to know a little bit about Tk. This document\ncan't fulfill that role, so the best we can do is point you to the\nbest documentation that exists. Here are some hints:\n- The authors strongly suggest getting a copy of the Tk man\npages. Specifically, the man pages in the `mann` directory are most\nuseful. The `man3` man pages describe the C interface to the Tk\nlibrary and thus are not especially helpful for script writers.\n- Addison-Wesley publishes a book called Tcl and the\nTk Toolkit by John Ousterhout (ISBN 0-201-63337-X) which is a good\nintroduction to Tcl and Tk for the novice. The book is not\nexhaustive, and for many details it defers to the man pages.\n- Tkinter.py is a last resort for most, but can be a good\nplace to go when nothing else makes sense.\nSee Also:", "python_version": "2.2", "length": 1466, "url": "https://docs.python.org/2.2/lib/node502.html"} {"title": "16.1.2.2 A Simple Hello World Program", "text": "node502.html | node501.html | node504.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.2.2 A Simple Hello World Program\n```text\n\nfrom Tkinter import * 1\n2\nclass Application(Frame): 3\ndef say_hi(self): 4\nprint \"hi there, everyone!\" 5\n6\ndef createWidgets(self): 7\nself.QUIT = Button(self) 8\nself.QUIT[\"text\"] = \"QUIT\" 9\nself.QUIT[\"fg\"] = \"red\" 10\nself.QUIT[\"command\"] = self.quit 11\n12\nself.QUIT.pack({\"side\": \"left\"}) 13\n14\nself.hi_there = Button(self) 15\nself.hi_there[\"text\"] = \"Hello\", 16\nself.hi_there[\"command\"] = self.say_hi 17\n18\nself.hi_there.pack({\"side\": \"left\"}) 19\n20\n21\ndef __init__(self, master=None): 22\nFrame.__init__(self, master) 23\nself.pack() 24\nself.createWidgets() 25\n26\napp = Application() 27\napp.mainloop() 28\n```", "python_version": "2.2", "length": 780, "url": "https://docs.python.org/2.2/lib/node503.html"} {"title": "16.1.3 A (Very) Quick Look at Tcl/Tk", "text": "node503.html | module-Tkinter.html | tkinter-basic-mapping.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.1.3 A (Very) Quick Look at Tcl/Tk\nThe class hierarchy looks complicated, but in actual practice,\napplication programmers almost always refer to the classes at the very\nbottom of the hierarchy.\nNotes:\n- These classes are provided for the purposes of\norganizing certain functions under one namespace. They aren't meant to\nbe instantiated independently.\n- The Tk class is meant to be instantiated only once in\nan application. Application programmers need not instantiate one\nexplicitly, the system creates one whenever any of the other classes\nare instantiated.\n- The Widget class is not meant to be instantiated, it\nis meant only for subclassing to make ``real'' widgets (in C++, this\nis called an `abstract class').\nTo make use of this reference material, there will be times when you\nwill need to know how to read short passages of Tk and how to identify\nthe various parts of a Tk command.\n(See section 16.1.4 (tkinter-basic-mapping.html#tkinter-basic-mapping) for the\nTkinter (module-Tkinter.html) equivalents of what's below.)\nTk scripts are Tcl programs. Like all Tcl programs, Tk scripts are\njust lists of tokens separated by spaces. A Tk widget is just its\nclass, the options that help configure it, and the\nactions that make it do useful things.\nTo make a widget in Tk, the command is always of the form:\n```text\n\nclassCommand newPathname options\n```\nclassCommand: denotes which kind of widget to make (a button, a label, a menu...)\nnewPathname: is the new name for this widget. All names in Tk must be unique. To\nhelp enforce this, widgets in Tk are named with pathnames, just\nlike files in a file system. The top level widget, the root,\nis called `.` (period) and children are delimited by more\nperiods. For example, `.myApp.controlPanel.okButton` might be\nthe name of a widget.\noptions: configure the widget's appearance and in some cases, its\nbehavior. The options come in the form of a list of flags and values.\nFlags are proceeded by a `-', like unix shell command flags, and\nvalues are put in quotes if they are more than one word.\nFor example:\n```text\n\nbutton .fred -fg red -text \"hi there\"\n^ ^ \\_____________________/\n| | |\nclass new options\ncommand widget (-opt val -opt val ...)\n```\nOnce created, the pathname to the widget becomes a new command. This\nnew widget command is the programmer's handle for getting the new\nwidget to perform some action. In C, you'd express this as\nsomeAction(fred, someOptions), in C++, you would express this as\nfred.someAction(someOptions), and in Tk, you say:\n```text\n\n.fred someAction someOptions\n```\nNote that the object name, `.fred`, starts with a dot.\nAs you'd expect, the legal values for someAction will depend on\nthe widget's class: `.fred disable` works if fred is a\nbutton (fred gets greyed out), but does not work if fred is a label\n(disabling of labels is not supported in Tk).\nThe legal values of someOptions is action dependent. Some\nactions, like `disable`, require no arguments, others, like\na text-entry box's `delete` command, would need arguments\nto specify what range of text to delete.", "python_version": "2.2", "length": 3204, "url": "https://docs.python.org/2.2/lib/node504.html"} {"title": "16.1.5 How Tk and Tkinter are Related", "text": "tkinter-basic-mapping.html | module-Tkinter.html | node507.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.1.5 How Tk and Tkinter are Related\nNote:\nThis was derived from a graphical image; the image will be used\nmore directly in a subsequent version of this document.\nFrom the top down:\nYour App Here (Python): A Python application makes a Tkinter (module-Tkinter.html) call.\nTkinter (Python Module): This call (say, for example, creating a button widget), is\nimplemented in the Tkinter module, which is written in\nPython. This Python function will parse the commands and the\narguments and convert them into a form that makes them look as if they\nhad come from a Tk script instead of a Python script.\ntkinter (C): These commands and their arguments will be passed to a C function\nin the tkinter - note the lowercase - extension module.\nTk Widgets (C and Tcl): This C function is able to make calls into other C modules,\nincluding the C functions that make up the Tk library. Tk is\nimplemented in C and some Tcl. The Tcl part of the Tk widgets is used\nto bind certain default behaviors to widgets, and is executed once at\nthe point where the Python Tkinter (module-Tkinter.html) module is\nimported. (The user never sees this stage).\nTk (C): The Tk part of the Tk Widgets implement the final mapping to ...\nXlib (C): the Xlib library to draw graphics on the screen.", "python_version": "2.2", "length": 1405, "url": "https://docs.python.org/2.2/lib/node506.html"} {"title": "16.1.6 Handy Reference", "text": "node506.html | module-Tkinter.html | tkinter-setting-options.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.1.6 Handy Reference", "python_version": "2.2", "length": 170, "url": "https://docs.python.org/2.2/lib/node507.html"} {"title": "16.1.6.2 The Packer", "text": "tkinter-setting-options.html | node507.html | node510.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.2 The Packer\nThe packer is one of Tk's geometry-management mechanisms. See also\nthe Packer class interface (classes/ClassPacker.html).\nGeometry managers are used to specify the relative positioning of the\npositioning of widgets within their container - their mutual\nmaster. In contrast to the more cumbersome placer\n(which is used less commonly, and we do not cover here), the packer\ntakes qualitative relationship specification - above, to\nthe left of, filling, etc - and works everything out to\ndetermine the exact placement coordinates for you.\nThe size of any master widget is determined by the size of\nthe \"slave widgets\" inside. The packer is used to control where slave\nwidgets appear inside the master into which they are packed. You can\npack widgets into frames, and frames into other frames, in order to\nachieve the kind of layout you desire. Additionally, the arrangement\nis dynamically adjusted to accomodate incremental changes to the\nconfiguration, once it is packed.\nNote that widgets do not appear until they have had their geometry\nspecified with a geometry manager. It's a common early mistake to\nleave out the geometry specification, and then be surprised when the\nwidget is created but nothing appears. A widget will appear only\nafter it has had, for example, the packer's pack() method\napplied to it.\nThe pack() method can be called with keyword-option/value pairs that\ncontrol where the widget is to appear within its container, and how it\nis to behave when the main application window is resized. Here are\nsome examples:\n```text\n\nfred.pack() # defaults to side = \"top\"\nfred.pack(side = \"left\")\nfred.pack(expand = 1)\n```", "python_version": "2.2", "length": 1791, "url": "https://docs.python.org/2.2/lib/node509.html"} {"title": "16.1.6.3 Packer Options", "text": "node509.html | node507.html | node511.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.3 Packer Options\nFor more extensive information on the packer and the options that it\ncan take, see the man pages and page 183 of John Ousterhout's book.\nanchor: Anchor type. Denotes where the packer is to place each slave in its\nparcel.\nexpand: Boolean, `0` or `1`.\nfill: Legal values: `'x'`, `'y'`, `'both'`, `'none'`.\nipadx and ipady: A distance - designating internal padding on each side of the slave\nwidget.\npadx and pady: A distance - designating external padding on each side of the slave\nwidget.\nside: Legal values are: `'left'`, `'right'`, `'top'`,\n`'bottom'`.", "python_version": "2.2", "length": 703, "url": "https://docs.python.org/2.2/lib/node510.html"} {"title": "16.1.6.4 Coupling Widget Variables", "text": "node510.html | node507.html | node512.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.4 Coupling Widget Variables\nThe current-value setting of some widgets (like text entry widgets)\ncan be connected directly to application variables by using special\noptions. These options are `variable`, `textvariable`,\n`onvalue`, `offvalue`, and `value`. This\nconnection works both ways: if the variable changes for any reason,\nthe widget it's connected to will be updated to reflect the new value.\nUnfortunately, in the current implementation of Tkinter (module-Tkinter.html) it is\nnot possible to hand over an arbitrary Python variable to a widget\nthrough a `variable` or `textvariable` option. The only\nkinds of variables for which this works are variables that are\nsubclassed from a class called Variable, defined in the\nTkinter (module-Tkinter.html) module.\nThere are many useful subclasses of Variable already defined:\nStringVar, IntVar, DoubleVar, and\nBooleanVar. To read the current value of such a variable,\ncall the get() method on\nit, and to change its value you call the set() method. If\nyou follow this protocol, the widget will always track the value of\nthe variable, with no further intervention on your part.\nFor example:\n```text\n\nclass App(Frame):\ndef __init__(self, master=None):\nFrame.__init__(self, master)\nself.pack()\n\nself.entrythingy = Entry()\nself.entrythingy.pack()\n\nself.button.pack()\n# here is the application variable\nself.contents = StringVar()\n# set it to some value\nself.contents.set(\"this is a variable\")\n# tell the entry widget to watch this variable\nself.entrythingy[\"textvariable\"] = self.contents\n\n# and here we get a callback when the user hits return.\n# we will have the program print out the value of the\n# application variable when the user hits return\nself.entrythingy.bind('',\nself.print_contents)\n\ndef print_contents(self, event):\nprint \"hi. contents of entry is now ---->\", \\\nself.contents.get()\n```", "python_version": "2.2", "length": 1988, "url": "https://docs.python.org/2.2/lib/node511.html"} {"title": "16.1.6.5 The Window Manager", "text": "node511.html | node507.html | node513.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.5 The Window Manager\nIn Tk, there is a utility command, `wm`, for interacting with the\nwindow manager. Options to the `wm` command allow you to control\nthings like titles, placement, icon bitmaps, and the like. In\nTkinter (module-Tkinter.html), these commands have been implemented as methods\non the Wm class. Toplevel widgets are subclassed from the\nWm class, and so can call the Wm methods directly.\nTo get at the toplevel window that contains a given widget, you can\noften just refer to the widget's master. Of course if the widget has\nbeen packed inside of a frame, the master won't represent a toplevel\nwindow. To get at the toplevel window that contains an arbitrary\nwidget, you can call the _root() method. This\nmethod begins with an underscore to denote the fact that this function\nis part of the implementation, and not an interface to Tk functionality.\nHere are some examples of typical usage:\n```text\n\nimport Tkinter\nclass App(Frame):\ndef __init__(self, master=None):\nFrame.__init__(self, master)\nself.pack()\n\n# create the application\nmyapp = App()\n\n#\n# here are method calls to the window manager class\n#\nmyapp.master.title(\"My Do-Nothing Application\")\nmyapp.master.maxsize(1000, 400)\n\n# start the program\nmyapp.mainloop()\n```", "python_version": "2.2", "length": 1371, "url": "https://docs.python.org/2.2/lib/node512.html"} {"title": "16.1.6.6 Tk Option Data Types", "text": "node512.html | node507.html | node514.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.6 Tk Option Data Types\nanchor: Legal values are points of the compass: `\"n\"`,\n`\"ne\"`, `\"e\"`, `\"se\"`, `\"s\"`,\n`\"sw\"`, `\"w\"`, `\"nw\"`, and also\n`\"center\"`.\nbitmap: There are eight built-in, named bitmaps: `'error'`, `'gray25'`,\n`'gray50'`, `'hourglass'`, `'info'`, `'questhead'`,\n`'question'`, `'warning'`. To specify an X bitmap\nfilename, give the full path to the file, preceded with an `@`,\nas in `\"@/usr/contrib/bitmap/gumby.bit\"`.\nboolean: You can pass integers 0 or 1 or the stings `\"yes\"` or `\"no\"` .\ncallback: This is any Python function that takes no arguments. For example:\n```text\n\ndef print_it():\nprint \"hi there\"\nfred[\"command\"] = print_it\n```\ncolor: Colors can be given as the names of X colors in the rgb.txt file,\nor as strings representing RGB values in 4 bit: `\"#RGB\"`, 8\nbit: `\"#RRGGBB\"`, 12 bit\" `\"#RRRGGGBBB\"`, or 16 bit\n`\"#RRRRGGGGBBBB\"` ranges, where R,G,B here represent any\nlegal hex digit. See page 160 of Ousterhout's book for details.\ncursor: The standard X cursor names from cursorfont.h can be used,\nwithout the `XC_` prefix. For example to get a hand cursor\n(XC_hand2), use the string `\"hand2\"`. You can also\nspecify a bitmap and mask file of your own. See page 179 of\nOusterhout's book.\ndistance: Screen distances can be specified in either pixels or absolute\ndistances. Pixels are given as numbers and absolute distances as\nstrings, with the trailing character denoting units: `c`\nfor centimeters, `i` for inches, `m` for millimeters,\n`p` for printer's points. For example, 3.5 inches is expressed\nas `\"3.5i\"`.\nfont: Tk uses a list font name format, such as `{courier 10 bold}`.\nFont sizes with positive numbers are measured in points;\nsizes with negative numbers are measured in pixels.\ngeometry: This is a string of the form \"widthxheight\", where\nwidth and height are measured in pixels for most widgets (in\ncharacters for widgets displaying text). For example:\n`fred[\"geometry\"] = \"200x100\"`.\njustify: Legal values are the strings: `\"left\"`,\n`\"center\"`, `\"right\"`, and `\"fill\"`.\nregion: This is a string with four space-delimited elements, each of\nwhich is a legal distance (see above). For example: `\"2 3 4\n5\"` and `\"3i 2i 4.5i 2i\"` and `\"3c 2c 4c 10.43c\"`\nare all legal regions.\nrelief: Determines what the border style of a widget will be. Legal\nvalues are: `\"raised\"`, `\"sunken\"`,\n`\"flat\"`, `\"groove\"`, and `\"ridge\"`.\nscrollcommand: This is almost always the set() method of some scrollbar\nwidget, but can be any widget method that takes a single argument.\nRefer to the file Demo/tkinter/matt/canvas-with-scrollbars.py\nin the Python source distribution for an example.\nwrap:: Must be one of: `\"none\"`, `\"char\"`, or `\"word\"`.", "python_version": "2.2", "length": 2793, "url": "https://docs.python.org/2.2/lib/node513.html"} {"title": "16.1.6.7 Bindings and Events", "text": "node513.html | node507.html | node515.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.7 Bindings and Events\nThe bind method from the widget command allows you to watch for\ncertain events and to have a callback function trigger when that event\ntype occurs. The form of the bind method is:\n```text\n\ndef bind(self, sequence, func, add=''):\n```\nwhere:\nsequence: is a string that denotes the target kind of event. (See the bind\nman page and page 201 of John Ousterhout's book for details).\nfunc: is a Python function, taking one argument, to be invoked when the\nevent occurs. An Event instance will be passed as the argument.\n(Functions deployed this way are commonly known as callbacks.)\nadd: is optional, either \"\" or \"+\". Passing an empty string\ndenotes that this binding is to replace any other bindings that this\nevent is associated with. Preceeding with a \"+\" means that this\nfunction is to be added to the list of functions bound to this event type.\nFor example:\n```text\n\ndef turnRed(self, event):\nevent.widget[\"activeforeground\"] = \"red\"\n\nself.button.bind(\"\", self.turnRed)\n```\nNotice how the widget field of the event is being accesed in the\nturnRed() callback. This field contains the widget that\ncaught the X event. The following table lists the other event fields\nyou can access, and how they are denoted in Tk, which can be useful\nwhen referring to the Tk man pages.\n```text\n\nTk Tkinter Event Field Tk Tkinter Event Field\n-- ------------------- -- -------------------\n%f focus %A char\n%h height %E send_event\n%k keycode %K keysym\n%s state %N keysym_num\n%t time %T type\n%w width %W widget\n%x x %X x_root\n%y y %Y y_root\n```", "python_version": "2.2", "length": 1683, "url": "https://docs.python.org/2.2/lib/node514.html"} {"title": "16.1.6.8 The index Parameter", "text": "node514.html | node507.html | module-Tix.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.8 The index Parameter\nA number of widgets require``index'' parameters to be passed. These\nare used to point at a specific place in a Text widget, or to\nparticular characters in an Entry widget, or to particular menu items\nin a Menu widget.\nEntry widget indexes (index, view index, etc.): Entry widgets have options that refer to character positions in the\ntext being displayed. You can use these Tkinter (module-Tkinter.html) functions\nto access these special points in text widgets:\nAtEnd(): refers to the last position in the text\nAtInsert(): refers to the point where the text cursor is\nAtSelFirst(): indicates the beginning point of the selected text\nAtSelLast(): denotes the last point of the selected text and finally\nAt(x[, y]): refers to the character at pixel location x, y (with\ny not used in the case of a text entry widget, which contains a\nsingle line of text).\nText widget indexes: The index notation for Text widgets is very rich and is best described\nin the Tk man pages.\nMenu indexes (menu.invoke(), menu.entryconfig(), etc.): Some options and methods for menus manipulate specific menu entries.\nAnytime a menu index is needed for an option or a parameter, you may\npass in:\n- an integer which refers to the numeric position of the entry in\nthe widget, counted from the top, starting with 0;\n- the string `'active'`, which refers to the menu position that is\ncurrently under the cursor;\n- the string `\"last\"` which refers to the last menu\nitem;\n- An integer preceded by `@`, as in `@6`, where the integer is\ninterpreted as a y pixel coordinate in the menu's coordinate system;\n- the string `\"none\"`, which indicates no menu entry at all, most\noften used with menu.activate() to deactivate all entries, and\nfinally,\n- a text string that is pattern matched against the label of the\nmenu entry, as scanned from the top of the menu to the bottom. Note\nthat this index type is considered after all the others, which means\nthat matches for menu items labelled `last`, `active`, or\n`none` may be interpreted as the above literals, instead.", "python_version": "2.2", "length": 2184, "url": "https://docs.python.org/2.2/lib/node515.html"} {"title": "16.2.1 Using Tix", "text": "module-Tix.html | module-Tix.html | node518.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.2.1 Using Tix\nTo use Tix (module-Tix.html), you must have the Tix (module-Tix.html) widgets installed,\nusually alongside your installation of the Tk widgets.\nTo test your installation, try the following:\n```text\n\nimport Tix\nroot = Tix.Tk()\nroot.tk.eval('package require Tix')\n```\nIf this fails, you have a Tk installation problem which must be\nresolved before proceeding. Use the environment variable TIX_LIBRARY\nto point to the installed Tix (module-Tix.html) library directory, and\nmake sure you have the dynamic object library (tix8183.dll or\nlibtix8183.so) in the same directory that contains your Tk\ndynamic object library (tk8183.dll or libtk8183.so). The\ndirectory with the dynamic object library should also have a file\ncalled pkgIndex.tcl (case sensitive), which contains the line:\n```text\n\npackage ifneeded Tix 8.1 [list load \"[file join $dir tix8183.dll]\" Tix]\n```", "python_version": "2.2", "length": 1009, "url": "https://docs.python.org/2.2/lib/node517.html"} {"title": "16.2.2 Tix Widgets", "text": "node517.html | module-Tix.html | node519.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.2.2 Tix Widgets\nTix (http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm)\nintroduces over 40 widget classes to the Tkinter (module-Tkinter.html)\nrepertoire. There is a demo of all the Tix (module-Tix.html) widgets in the\nDemo/tix directory of the standard distribution.", "python_version": "2.2", "length": 417, "url": "https://docs.python.org/2.2/lib/node518.html"} {"title": "16.2.2.1 Basic Widgets", "text": "node518.html | node518.html | node520.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.1 Basic Widgets", "python_version": "2.2", "length": 148, "url": "https://docs.python.org/2.2/lib/node519.html"} {"title": "16.2.2.2 File Selectors", "text": "node519.html | node518.html | node521.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.2 File Selectors", "python_version": "2.2", "length": 149, "url": "https://docs.python.org/2.2/lib/node520.html"} {"title": "16.2.2.3 Hierachical ListBox", "text": "node520.html | node518.html | node522.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.3 Hierachical ListBox", "python_version": "2.2", "length": 154, "url": "https://docs.python.org/2.2/lib/node521.html"} {"title": "16.2.2.4 Tabular ListBox", "text": "node521.html | node518.html | node523.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.4 Tabular ListBox", "python_version": "2.2", "length": 150, "url": "https://docs.python.org/2.2/lib/node522.html"} {"title": "16.2.2.5 Manager Widgets", "text": "node522.html | node518.html | node524.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.5 Manager Widgets", "python_version": "2.2", "length": 150, "url": "https://docs.python.org/2.2/lib/node523.html"} {"title": "16.2.2.6 Image Types", "text": "node523.html | node518.html | node525.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.6 Image Types\nThe Tix (module-Tix.html) module adds:\n- pixmap (http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm)\ncapabilities to all Tix (module-Tix.html) and Tkinter (module-Tkinter.html) widgets to\ncreate color images from XPM files.\n- Compound (http://tix.sourceforge.net/dist/current/man/html/TixCmd/compound.html)\nimage types can be used to create images that consists of multiple\nhorizontal lines; each line is composed of a series of items (texts,\nbitmaps, images or spaces) arranged from left to right. For example, a\ncompound image can be used to display a bitmap and a text string\nsimutaneously in a Tk Button widget.", "python_version": "2.2", "length": 778, "url": "https://docs.python.org/2.2/lib/node524.html"} {"title": "16.2.2.7 Miscellaneous Widgets", "text": "node524.html | node518.html | node526.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.7 Miscellaneous Widgets", "python_version": "2.2", "length": 156, "url": "https://docs.python.org/2.2/lib/node525.html"} {"title": "16.2.2.8 Form Geometry Manager", "text": "node525.html | node518.html | node527.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.2.2.8 Form Geometry Manager\nIn addition, Tix (module-Tix.html) augments Tkinter (module-Tkinter.html) by providing:", "python_version": "2.2", "length": 244, "url": "https://docs.python.org/2.2/lib/node526.html"} {"title": "16.2.3 Tix Commands", "text": "node526.html | module-Tix.html | module-ScrolledText.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.2.3 Tix Commands", "python_version": "2.2", "length": 159, "url": "https://docs.python.org/2.2/lib/node527.html"} {"title": "16.5.1 Menus", "text": "idle.html | idle.html | node533.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.5.1 Menus", "python_version": "2.2", "length": 131, "url": "https://docs.python.org/2.2/lib/node532.html"} {"title": "16.5.1.1 File menu", "text": "node532.html | node532.html | node534.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.5.1.1 File menu\nNew window: create a new editing window\nOpen...: open an existing file\nOpen module...: open an existing module (searches sys.path)\nClass browser: show classes and methods in current file\nPath browser: show sys.path directories, modules, classes and methods\nSave: save current window to the associated file (unsaved\nwindows have a * before and after the window title)\nSave As...: save current window to new file, which becomes\nthe associated file\nSave Copy As...: save current window to different file\nwithout changing the associated file\nClose: close current window (asks to save if unsaved)\nExit: close all windows and quit IDLE (asks to save if unsaved)", "python_version": "2.2", "length": 800, "url": "https://docs.python.org/2.2/lib/node533.html"} {"title": "16.5.1.2 Edit menu", "text": "node533.html | node532.html | node535.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.5.1.2 Edit menu\nUndo: Undo last change to current window (max 1000 changes)\nRedo: Redo last undone change to current window\nCut: Copy selection into system-wide clipboard; then delete selection\nCopy: Copy selection into system-wide clipboard\nPaste: Insert system-wide clipboard into window\nSelect All: Select the entire contents of the edit buffer\nFind...: Open a search dialog box with many options\nFind again: Repeat last search\nFind selection: Search for the string in the selection\nFind in Files...: Open a search dialog box for searching files\nReplace...: Open a search-and-replace dialog box\nGo to line: Ask for a line number and show that line\nIndent region: Shift selected lines right 4 spaces\nDedent region: Shift selected lines left 4 spaces\nComment out region: Insert ## in front of selected lines\nUncomment region: Remove leading # or ## from selected lines\nTabify region: Turns leading stretches of spaces into tabs\nUntabify region: Turn all tabs into the right number of spaces\nExpand word: Expand the word you have typed to match another\nword in the same buffer; repeat to get a different expansion\nFormat Paragraph: Reformat the current blank-line-separated paragraph\nImport module: Import or reload the current module\nRun script: Execute the current file in the __main__ namespace", "python_version": "2.2", "length": 1426, "url": "https://docs.python.org/2.2/lib/node534.html"} {"title": "16.5.1.3 Windows menu", "text": "node534.html | node532.html | node536.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.5.1.3 Windows menu\nZoom Height: toggles the window between normal size (24x80)\nand maximum height.\nThe rest of this menu lists the names of all open windows; select one\nto bring it to the foreground (deiconifying it if necessary).", "python_version": "2.2", "length": 359, "url": "https://docs.python.org/2.2/lib/node535.html"} {"title": "16.5.1.4 Debug menu (in the Python Shell window only)", "text": "node535.html | node532.html | node537.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.5.1.4 Debug menu (in the Python Shell window only)\nGo to file/line: look around the insert point for a filename\nand linenumber, open the file, and show the line.\nOpen stack viewer: show the stack traceback of the last exception\nDebugger toggle: Run commands in the shell under the debugger\nJIT Stack viewer toggle: Open stack viewer on traceback", "python_version": "2.2", "length": 474, "url": "https://docs.python.org/2.2/lib/node536.html"} {"title": "16.5.2 Basic editing and navigation", "text": "node536.html | idle.html | node538.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.5.2 Basic editing and navigation\n- Backspace deletes to the left; Del deletes to the right\n- Arrow keys and Page Up/Page Down to move around\n- Home/End go to begin/end of line\n- C-Home/C-End go to begin/end of file\n- Some Emacs bindings may also work, including C-B,\nC-P, C-A, C-E, C-D, C-L", "python_version": "2.2", "length": 415, "url": "https://docs.python.org/2.2/lib/node537.html"} {"title": "16.5.2.1 Automatic indentation", "text": "node537.html | node537.html | node539.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.5.2.1 Automatic indentation\nAfter a block-opening statement, the next line is indented by 4 spaces\n(in the Python Shell window by one tab). After certain keywords\n(break, return etc.) the next line is dedented. In leading\nindentation, Backspace deletes up to 4 spaces if they are there.\nTab inserts 1-4 spaces (in the Python Shell window one tab).\nSee also the indent/dedent region commands in the edit menu.", "python_version": "2.2", "length": 537, "url": "https://docs.python.org/2.2/lib/node538.html"} {"title": "16.5.2.2 Python Shell window", "text": "node538.html | node537.html | node540.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.5.2.2 Python Shell window\n- C-C interrupts executing command\n- C-D sends end-of-file; closes window if typed at\na \"»> \" prompt\n- Alt-p retrieves previous command matching what you have typed\n- Alt-n retrieves next\n- Return while on any previous command retrieves that command\n- Alt-/ (Expand word) is also useful here", "python_version": "2.2", "length": 446, "url": "https://docs.python.org/2.2/lib/node539.html"} {"title": "16.5.3 Syntax colors", "text": "node539.html | idle.html | node541.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.5.3 Syntax colors\nThe coloring is applied in a background ``thread,'' so you may\noccasionally see uncolorized text. To change the color\nscheme, edit the `[Colors]` section in config.txt.\nPython syntax colors:: Keywords: orange\nStrings: green\nComments: red\nDefinitions: blue\nShell colors:: Console output: brown\nstdout: blue\nstderr: dark green\nstdin: black", "python_version": "2.2", "length": 480, "url": "https://docs.python.org/2.2/lib/node540.html"} {"title": "16.5.3.1 Command line usage", "text": "node540.html | node540.html | other-gui-packages.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.5.3.1 Command line usage\n```text\n\nidle.py [-c command] [-d] [-e] [-s] [-t title] [arg] ...\n\n-c command run this command\n-d enable debugger\n-e edit mode; arguments are files to be edited\n-s run $IDLESTARTUP or $PYTHONSTARTUP first\n-t title set title of shell window\n```\nIf there are arguments:\n1. If -e is used, arguments are files opened for\nediting and `sys.argv` reflects the arguments passed to\nIDLE itself.\n2. Otherwise, if -c is used, all arguments are\nplaced in `sys.argv[1:...]`, with `sys.argv[0]` set\nto `'-c'`.\n3. Otherwise, if neither -e nor -c is\nused, the first argument is a script which is executed with\nthe remaining arguments in `sys.argv[1:...]` and\n`sys.argv[0]` set to the script name. If the script name\nis '-', no script is executed but an interactive Python\nsession is started; the arguments are still available in\n`sys.argv`.", "python_version": "2.2", "length": 989, "url": "https://docs.python.org/2.2/lib/node541.html"} {"title": "17.1.3 An example", "text": "rexec-extension.html | module-rexec.html | module-Bastion.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.3 An example\nLet us say that we want a slightly more relaxed policy than the\nstandard RExec class. For example, if we're willing to allow\nfiles in /tmp to be written, we can subclass the RExec\nclass:", "python_version": "2.2", "length": 349, "url": "https://docs.python.org/2.2/lib/node547.html"} {"title": "18.1.1 Creating AST Objects", "text": "module-parser.html | module-parser.html | node552.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.1.1 Creating AST Objects\nAST objects may be created from source code or from a parse tree.\nWhen creating an AST object from source, different functions are used\nto create the `'eval'` and `'exec'` forms.", "python_version": "2.2", "length": 343, "url": "https://docs.python.org/2.2/lib/node551.html"} {"title": "18.1.2 Converting AST Objects", "text": "node551.html | module-parser.html | node553.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.1.2 Converting AST Objects\nAST objects, regardless of the input used to create them, may be\nconverted to parse trees represented as list- or tuple- trees, or may\nbe compiled into executable code objects. Parse trees may be\nextracted with or without line numbering information.", "python_version": "2.2", "length": 410, "url": "https://docs.python.org/2.2/lib/node552.html"} {"title": "18.1.3 Queries on AST Objects", "text": "node552.html | module-parser.html | node554.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.1.3 Queries on AST Objects\nTwo functions are provided which allow an application to determine if\nan AST was created as an expression or a suite. Neither of these\nfunctions can be used to determine if an AST was created from source\ncode via expr() or suite() or from a parse tree\nvia sequence2ast().", "python_version": "2.2", "length": 432, "url": "https://docs.python.org/2.2/lib/node553.html"} {"title": "18.1.4 Exceptions and Error Handling", "text": "node553.html | module-parser.html | node555.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.1.4 Exceptions and Error Handling\nThe parser module defines a single exception, but may also pass other\nbuilt-in exceptions from other portions of the Python runtime\nenvironment. See each function for information about the exceptions\nit can raise.\nNote that the functions compileast(), expr(), and\nsuite() may throw exceptions which are normally thrown by the\nparsing and compilation process. These include the built in\nexceptions MemoryError, OverflowError,\nSyntaxError, and SystemError. In these cases, these\nexceptions carry all the meaning normally associated with them. Refer\nto the descriptions of each function for detailed information.", "python_version": "2.2", "length": 777, "url": "https://docs.python.org/2.2/lib/node554.html"} {"title": "18.1.5 AST Objects", "text": "node554.html | module-parser.html | node556.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.1.5 AST Objects\nOrdered and equality comparisons are supported between AST objects.\nPickling of AST objects (using the pickle (module-pickle.html) module) is also\nsupported.\nAST objects have the following methods:", "python_version": "2.2", "length": 347, "url": "https://docs.python.org/2.2/lib/node555.html"} {"title": "18.1.6 Examples", "text": "node555.html | module-parser.html | node557.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.1.6 Examples\nThe parser modules allows operations to be performed on the parse tree\nof Python source code before the bytecode is generated, and provides\nfor inspection of the parse tree for information gathering purposes.\nTwo examples are presented. The simple example demonstrates emulation\nof the compile()built-in function and\nthe complex example shows the use of a parse tree for information\ndiscovery.", "python_version": "2.2", "length": 540, "url": "https://docs.python.org/2.2/lib/node556.html"} {"title": "18.1.6.1 Emulation of compile()", "text": "node556.html | node556.html | node558.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 18.1.6.1 Emulation of compile()\nWhile many useful operations may take place between parsing and\nbytecode generation, the simplest operation is to do nothing. For\nthis purpose, using the parser module to produce an\nintermediate data structure is equivalent to the code\n```text\n\n>>> code = compile('a + 5', 'file.py', 'eval')\n>>> a = 5\n>>> eval(code)\n10\n```\nThe equivalent operation using the parser module is somewhat\nlonger, and allows the intermediate internal parse tree to be retained\nas an AST object:\n```text\n\n>>> import parser\n>>> ast = parser.expr('a + 5')\n>>> code = ast.compile('file.py')\n>>> a = 5\n>>> eval(code)\n10\n```\nAn application which needs both AST and code objects can package this\ncode into readily available functions:\n```text\n\nimport parser\n\ndef load_suite(source_string):\nast = parser.suite(source_string)\nreturn ast, ast.compile()\n\ndef load_expression(source_string):\nast = parser.expr(source_string)\nreturn ast, ast.compile()\n```", "python_version": "2.2", "length": 1079, "url": "https://docs.python.org/2.2/lib/node557.html"} {"title": "18.1.6.2 Information Discovery", "text": "node557.html | node556.html | module-symbol.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 18.1.6.2 Information Discovery\nSome applications benefit from direct access to the parse tree. The\nremainder of this section demonstrates how the parse tree provides\naccess to module documentation defined in\ndocstringswithout\nrequiring that the code being examined be loaded into a running\ninterpreter via import. This can be very useful for\nperforming analyses of untrusted code.\nGenerally, the example will demonstrate how the parse tree may be\ntraversed to distill interesting information. Two functions and a set\nof classes are developed which provide programmatic access to high\nlevel function and class definitions provided by a module. The\nclasses extract information from the parse tree and provide access to\nthe information at a useful semantic level, one function provides a\nsimple low-level pattern matching capability, and the other function\ndefines a high-level interface to the classes by handling file\noperations on behalf of the caller. All source files mentioned here\nwhich are not part of the Python installation are located in the\nDemo/parser/ directory of the distribution.\nThe dynamic nature of Python allows the programmer a great deal of\nflexibility, but most modules need only a limited measure of this when\ndefining classes, functions, and methods. In this example, the only\ndefinitions that will be considered are those which are defined in the\ntop level of their context, e.g., a function defined by a def\nstatement at column zero of a module, but not a function defined\nwithin a branch of an if ... else construct, though\nthere are some good reasons for doing so in some situations. Nesting\nof definitions will be handled by the code developed in the example.\nTo construct the upper-level extraction methods, we need to know what\nthe parse tree structure looks like and how much of it we actually\nneed to be concerned about. Python uses a moderately deep parse tree\nso there are a large number of intermediate nodes. It is important to\nread and understand the formal grammar used by Python. This is\nspecified in the file Grammar/Grammar in the distribution.\nConsider the simplest case of interest when searching for docstrings:\na module consisting of a docstring and nothing else. (See file\ndocstring.py.)\n```text\n\n\"\"\"Some documentation.\n\"\"\"\n```\nUsing the interpreter to take a look at the parse tree, we find a\nbewildering mass of numbers and parentheses, with the documentation\nburied deep in nested tuples.\n```text\n\n>>> import parser\n>>> import pprint\n>>> ast = parser.suite(open('docstring.py').read())\n>>> tup = ast.totuple()\n>>> pprint.pprint(tup)\n(257,\n(264,\n(265,\n(266,\n(267,\n(307,\n(287,\n(288,\n(289,\n(290,\n(292,\n(293,\n(294,\n(295,\n(296,\n(297,\n(298,\n(299,\n(300, (3, '\"\"\"Some documentation.\\n\"\"\"'))))))))))))))))),\n(4, ''))),\n(4, ''),\n(0, ''))\n```\nThe numbers at the first element of each node in the tree are the node\ntypes; they map directly to terminal and non-terminal symbols in the\ngrammar. Unfortunately, they are represented as integers in the\ninternal representation, and the Python structures generated do not\nchange that. However, the symbol (module-symbol.html) and token (module-token.html) modules\nprovide symbolic names for the node types and dictionaries which map\nfrom the integers to the symbolic names for the node types.\nIn the output presented above, the outermost tuple contains four\nelements: the integer `257` and three additional tuples. Node\ntype `257` has the symbolic name file_input. Each of\nthese inner tuples contains an integer as the first element; these\nintegers, `264`, `4`, and `0`, represent the node types\nstmt, NEWLINE, and ENDMARKER,\nrespectively.\nNote that these values may change depending on the version of Python\nyou are using; consult symbol.py and token.py for\ndetails of the mapping. It should be fairly clear that the outermost\nnode is related primarily to the input source rather than the contents\nof the file, and may be disregarded for the moment. The stmt\nnode is much more interesting. In particular, all docstrings are\nfound in subtrees which are formed exactly as this node is formed,\nwith the only difference being the string itself. The association\nbetween the docstring in a similar tree and the defined entity (class,\nfunction, or module) which it describes is given by the position of\nthe docstring subtree within the tree defining the described\nstructure.\nBy replacing the actual docstring with something to signify a variable\ncomponent of the tree, we allow a simple pattern matching approach to\ncheck any given subtree for equivalence to the general pattern for\ndocstrings. Since the example demonstrates information extraction, we\ncan safely require that the tree be in tuple form rather than list\nform, allowing a simple variable representation to be\n`['variable_name']`. A simple recursive function can implement\nthe pattern matching, returning a Boolean and a dictionary of variable\nname to value mappings. (See file example.py.)\n```text\n\nfrom types import ListType, TupleType\n\ndef match(pattern, data, vars=None):\nif vars is None:\nvars = {}\nif type(pattern) is ListType:\nvars[pattern[0]] = data\nreturn 1, vars\nif type(pattern) is not TupleType:\nreturn (pattern == data), vars\nif len(data) != len(pattern):\nreturn 0, vars\nfor pattern, data in map(None, pattern, data):\nsame, vars = match(pattern, data, vars)\nif not same:\nbreak\nreturn same, vars\n```\nUsing this simple representation for syntactic variables and the symbolic\nnode types, the pattern for the candidate docstring subtrees becomes\nfairly readable. (See file example.py.)\n```text\n\nimport symbol\nimport token\n\nDOCSTRING_STMT_PATTERN = (\nsymbol.stmt,\n(symbol.simple_stmt,\n(symbol.small_stmt,\n(symbol.expr_stmt,\n(symbol.testlist,\n(symbol.test,\n(symbol.and_test,\n(symbol.not_test,\n(symbol.comparison,\n(symbol.expr,\n(symbol.xor_expr,\n(symbol.and_expr,\n(symbol.shift_expr,\n(symbol.arith_expr,\n(symbol.term,\n(symbol.factor,\n(symbol.power,\n(symbol.atom,\n(token.STRING, ['docstring'])\n)))))))))))))))),\n(token.NEWLINE, '')\n))\n```\nUsing the match() function with this pattern, extracting the\nmodule docstring from the parse tree created previously is easy:\n```text\n\n>>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1])\n>>> found\n1\n>>> vars\n{'docstring': '\"\"\"Some documentation.\\n\"\"\"'}\n```\nOnce specific data can be extracted from a location where it is\nexpected, the question of where information can be expected\nneeds to be answered. When dealing with docstrings, the answer is\nfairly simple: the docstring is the first stmt node in a code\nblock (file_input or suite node types). A module\nconsists of a single file_input node, and class and function\ndefinitions each contain exactly one suite node. Classes and\nfunctions are readily identified as subtrees of code block nodes which\nstart with `(stmt, (compound_stmt, (classdef, ...` or\n`(stmt, (compound_stmt, (funcdef, ...`. Note that these subtrees\ncannot be matched by match() since it does not support multiple\nsibling nodes to match without regard to number. A more elaborate\nmatching function could be used to overcome this limitation, but this\nis sufficient for the example.\nGiven the ability to determine whether a statement might be a\ndocstring and extract the actual string from the statement, some work\nneeds to be performed to walk the parse tree for an entire module and\nextract information about the names defined in each context of the\nmodule and associate any docstrings with the names. The code to\nperform this work is not complicated, but bears some explanation.\nThe public interface to the classes is straightforward and should\nprobably be somewhat more flexible. Each ``major'' block of the\nmodule is described by an object providing several methods for inquiry\nand a constructor which accepts at least the subtree of the complete\nparse tree which it represents. The ModuleInfo constructor\naccepts an optional name parameter since it cannot\notherwise determine the name of the module.\nThe public classes include ClassInfo, FunctionInfo,\nand ModuleInfo. All objects provide the\nmethods get_name(), get_docstring(),\nget_class_names(), and get_class_info(). The\nClassInfo objects support get_method_names() and\nget_method_info() while the other classes provide\nget_function_names() and get_function_info().\nWithin each of the forms of code block that the public classes\nrepresent, most of the required information is in the same form and is\naccessed in the same way, with classes having the distinction that\nfunctions defined at the top level are referred to as ``methods.''\nSince the difference in nomenclature reflects a real semantic\ndistinction from functions defined outside of a class, the\nimplementation needs to maintain the distinction.\nHence, most of the functionality of the public classes can be\nimplemented in a common base class, SuiteInfoBase, with the\naccessors for function and method information provided elsewhere.\nNote that there is only one class which represents function and method\ninformation; this parallels the use of the def statement to\ndefine both types of elements.\nMost of the accessor functions are declared in SuiteInfoBase\nand do not need to be overridden by subclasses. More importantly, the\nextraction of most information from a parse tree is handled through a\nmethod called by the SuiteInfoBase constructor. The example\ncode for most of the classes is clear when read alongside the formal\ngrammar, but the method which recursively creates new information\nobjects requires further examination. Here is the relevant part of\nthe SuiteInfoBase definition from example.py:\n```text\n\nclass SuiteInfoBase:\n_docstring = ''\n_name = ''\n\ndef __init__(self, tree = None):\nself._class_info = {}\nself._function_info = {}\nif tree:\nself._extract_info(tree)\n\ndef _extract_info(self, tree):\n# extract docstring\nif len(tree) == 2:\nfound, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])\nelse:\nfound, vars = match(DOCSTRING_STMT_PATTERN, tree[3])\nif found:\nself._docstring = eval(vars['docstring'])\n# discover inner definitions\nfor node in tree[1:]:\nfound, vars = match(COMPOUND_STMT_PATTERN, node)\nif found:\ncstmt = vars['compound']\nif cstmt[0] == symbol.funcdef:\nname = cstmt[2][1]\nself._function_info[name] = FunctionInfo(cstmt)\nelif cstmt[0] == symbol.classdef:\nname = cstmt[2][1]\nself._class_info[name] = ClassInfo(cstmt)\n```\nAfter initializing some internal state, the constructor calls the\n_extract_info() method. This method performs the bulk of the\ninformation extraction which takes place in the entire example. The\nextraction has two distinct phases: the location of the docstring for\nthe parse tree passed in, and the discovery of additional definitions\nwithin the code block represented by the parse tree.\nThe initial if test determines whether the nested suite is of\nthe ``short form'' or the ``long form.'' The short form is used when\nthe code block is on the same line as the definition of the code\nblock, as in\n```text\n\ndef square(x): \"Square an argument.\"; return x ** 2\n```\nwhile the long form uses an indented block and allows nested\ndefinitions:\n```text\n\ndef make_power(exp):\n\"Make a function that raises an argument to the exponent `exp'.\"\ndef raiser(x, y=exp):\nreturn x ** y\nreturn raiser\n```\nWhen the short form is used, the code block may contain a docstring as\nthe first, and possibly only, small_stmt element. The\nextraction of such a docstring is slightly different and requires only\na portion of the complete pattern used in the more common case. As\nimplemented, the docstring will only be found if there is only\none small_stmt node in the simple_stmt node.\nSince most functions and methods which use the short form do not\nprovide a docstring, this may be considered sufficient. The\nextraction of the docstring proceeds using the match() function\nas described above, and the value of the docstring is stored as an\nattribute of the SuiteInfoBase object.\nAfter docstring extraction, a simple definition discovery\nalgorithm operates on the stmt nodes of the\nsuite node. The special case of the short form is not\ntested; since there are no stmt nodes in the short form,\nthe algorithm will silently skip the single simple_stmt\nnode and correctly not discover any nested definitions.\nEach statement in the code block is categorized as\na class definition, function or method definition, or\nsomething else. For the definition statements, the name of the\nelement defined is extracted and a representation object\nappropriate to the definition is created with the defining subtree\npassed as an argument to the constructor. The representation objects\nare stored in instance variables and may be retrieved by name using\nthe appropriate accessor methods.\nThe public classes provide any accessors required which are more\nspecific than those provided by the SuiteInfoBase class, but\nthe real extraction algorithm remains common to all forms of code\nblocks. A high-level function can be used to extract the complete set\nof information from a source file. (See file example.py.)\n```text\n\ndef get_docs(fileName):\nimport os\nimport parser\n\nsource = open(fileName).read()\nbasename = os.path.basename(os.path.splitext(fileName)[0])\nast = parser.suite(source)\nreturn ModuleInfo(ast.totuple(), basename)\n```", "python_version": "2.2", "length": 13281, "url": "https://docs.python.org/2.2/lib/node558.html"} {"title": "19.2 Limitations", "text": "module-compiler.html | compiler.html | node574.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 19.2 Limitations\nThere are some problems with the error checking of the compiler\npackage. The interpreter detects syntax errors in two distinct\nphases. One set of errors is detected by the interpreter's parser,\nthe other set by the compiler. The compiler package relies on the\ninterpreter's parser, so it get the first phases of error checking for\nfree. It implements the second phase itself, and that implement is\nincomplete. For example, the compiler package does not raise an error\nif a name appears more than once in an argument list:\n`def f(x, x): ...`\nA future version of the compiler should fix these problems.", "python_version": "2.2", "length": 750, "url": "https://docs.python.org/2.2/lib/node573.html"} {"title": "19.3 Python Abstract Syntax", "text": "node573.html | compiler.html | module-compiler.ast.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 19.3 Python Abstract Syntax\nThe compiler.ast module defines an abstract syntax for\nPython. In the abstract syntax tree, each node represents a syntactic\nconstruct. The root of the tree is Module object.\nThe abstract syntax offers a higher level interface to parsed Python\nsource code. The parser (http://www.python.org/doc/current/lib/module-parser.html)\nmodule and the compiler written in C for the Python interpreter use a\nconcrete syntax tree. The concrete syntax is tied closely to the\ngrammar description used for the Python parser. Instead of a single\nnode for a construct, there are often several levels of nested nodes\nthat are introduced by Python's precedence rules.\nThe abstract syntax tree is created by the\ncompiler.transformer module. The transformer relies on the\nbuiltin Python parser to generate a concrete syntax tree. It\ngenerates an abstract syntax tree from the concrete tree.\nThe transformer module was created by Greg\nSteinand Bill Tuttfor an\nexperimental Python-to-C compiler. The current version contains a\nnumber of modifications and improvements, but the basic form of the\nabstract syntax and of the transformer are due to Stein and Tutt.", "python_version": "2.2", "length": 1302, "url": "https://docs.python.org/2.2/lib/node574.html"} {"title": "19.3.2 Assignment nodes", "text": "module-compiler.ast.html | node574.html | node577.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 19.3.2 Assignment nodes\nThere is a collection of nodes used to represent assignments. Each\nassignment statement in the source code becomes a single\nAssign node in the AST. The nodes attribute is a\nlist that contains a node for each assignment target. This is\nnecessary because assignment can be chained, e.g. `a = b = 2`.\nEach Node in the list will be one of the following classes:\nAssAttr, AssList, AssName, or\nAssTuple.\nEach target assignment node will describe the kind of object being\nassigned to: AssName for a simple name, e.g. `a = 1`.\nAssAttr for an attribute assigned, e.g. `a.x = 1`.\nAssList and AssTuple for list and tuple expansion\nrespectively, e.g. `a, b, c = a_tuple`.\nThe target assignment nodes also have a flags attribute that\nindicates whether the node is being used for assignment or in a delete\nstatement. The AssName is also used to represent a delete\nstatement, e.g. del x.\nWhen an expression contains several attribute references, an\nassignment or delete statement will contain only one AssAttr\nnode - for the final attribute reference. The other attribute\nreferences will be represented as Getattr nodes in the\nexpr attribute of the AssAttr instance.", "python_version": "2.2", "length": 1312, "url": "https://docs.python.org/2.2/lib/node576.html"} {"title": "19.3.3 Examples", "text": "node576.html | node574.html | module-compiler.visitor.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 19.3.3 Examples\nThis section shows several simple examples of ASTs for Python source\ncode. The examples demonstrate how to use the parse()\nfunction, what the repr of an AST looks like, and how to access\nattributes of an AST node.\nThe first module defines a single function. Assume it is stored in\n/tmp/doublelib.py.\n```text\n\n\"\"\"This is an example module.\n\nThis is the docstring.\n\"\"\"\n\ndef double(x):\n\"Return twice the argument\"\nreturn x * 2\n```\nIn the interactive interpreter session below, I have reformatted the\nlong AST reprs for readability. The AST reprs use unqualified class\nnames. If you want to create an instance from a repr, you must import\nthe class names from the compiler.ast module.\n```text\n\n>>> import compiler\n>>> mod = compiler.parseFile(\"/tmp/doublelib.py\")\n>>> mod\nModule('This is an example module.\\n\\nThis is the docstring.\\n',\nStmt([Function('double', ['x'], [], 0, 'Return twice the argument',\nStmt([Return(Mul((Name('x'), Const(2))))]))]))\n>>> from compiler.ast import *\n>>> Module('This is an example module.\\n\\nThis is the docstring.\\n',\n... Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',\n... Stmt([Return(Mul((Name('x'), Const(2))))]))]))\nModule('This is an example module.\\n\\nThis is the docstring.\\n',\nStmt([Function('double', ['x'], [], 0, 'Return twice the argument',\nStmt([Return(Mul((Name('x'), Const(2))))]))]))\n>>> mod.doc\n'This is an example module.\\n\\nThis is the docstring.\\n'\n>>> for node in mod.node.nodes:\n... print node\n...\nFunction('double', ['x'], [], 0, 'Return twice the argument',\nStmt([Return(Mul((Name('x'), Const(2))))]))\n>>> func = mod.node.nodes[0]\n>>> func.code\nStmt([Return(Mul((Name('x'), Const(2))))])\n```", "python_version": "2.2", "length": 1823, "url": "https://docs.python.org/2.2/lib/node577.html"} {"title": "19.5 Bytecode Generation", "text": "module-compiler.visitor.html | compiler.html | sgi.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 19.5 Bytecode Generation\nThe code generator is a visitor that emits bytecodes. Each visit method\ncan call the emit() method to emit a new bytecode. The basic\ncode generator is specialized for modules, classes, and functions. An\nassembler converts that emitted instructions to the low-level bytecode\nformat. It handles things like generator of constant lists of code\nobjects and calculation of jump offsets.", "python_version": "2.2", "length": 543, "url": "https://docs.python.org/2.2/lib/node579.html"} {"title": "20.4.1 Functions Defined in Module fl", "text": "module-fl.html | module-fl.html | form-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 20.4.1 Functions Defined in Module fl\nModule fl defines the following functions. For more\ninformation about what they do, see the description of the equivalent\nC function in the FORMS documentation:", "python_version": "2.2", "length": 332, "url": "https://docs.python.org/2.2/lib/node589.html"} {"title": "3.14.1 Relationship to other Python modules", "text": "module-pickle.html | module-pickle.html | node60.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.14.1 Relationship to other Python modules\nThe pickle module has an optimized cousin called the\ncPickle module. As its name implies, cPickle is\nwritten in C, so it can be up to 1000 times faster than\npickle. However it does not support subclassing of the\nPickler() and Unpickler() classes, because in\ncPickle these are functions, not classes. Most applications\nhave no need for this functionality, and can benefit from the improved\nperformance of cPickle. Other than that, the interfaces of\nthe two modules are nearly identical; the common interface is\ndescribed in this manual and differences are pointed out where\nnecessary. In the following discussions, we use the term ``pickle''\nto collectively describe the pickle and\ncPickle modules.\nThe data streams the two modules produce are guaranteed to be\ninterchangeable.\nPython has a more primitive serialization module called\nmarshal (module-marshal.html), but in general\npickle should always be the preferred way to serialize Python\nobjects. marshal exists primarily to support Python's\n.pyc files.\nThe pickle module differs from marshal (module-marshal.html) several\nsignificant ways:\n- The pickle module keeps track of the objects it has\nalready serialized, so that later references to the same object\nwon't be serialized again. marshal doesn't do this.\nThis has implications both for recursive objects and object\nsharing. Recursive objects are objects that contain references\nto themselves. These are not handled by marshal, and in fact,\nattempting to marshal recursive objects will crash your Python\ninterpreter. Object sharing happens when there are multiple\nreferences to the same object in different places in the object\nhierarchy being serialized. pickle stores such objects\nonly once, and ensures that all other references point to the\nmaster copy. Shared objects remain shared, which can be very\nimportant for mutable objects.\n- marshal cannot be used to serialize user-defined\nclasses and their instances. pickle can save and\nrestore class instances transparently, however the class\ndefinition must be importable and live in the same module as\nwhen the object was stored.\n- The marshal serialization format is not guaranteed to\nbe portable across Python versions. Because its primary job in\nlife is to support .pyc files, the Python implementers\nreserve the right to change the serialization format in\nnon-backwards compatible ways should the need arise. The\npickle serialization format is guaranteed to be\nbackwards compatible across Python releases.\n- The pickle module doesn't handle code objects, which\nthe marshal module does. This avoids the possibility\nof smuggling Trojan horses into a program through the\npickle module3.3 (#foot6913).\nNote that serialization is a more primitive notion than persistence;\nalthough\npickle reads and writes file objects, it does not handle the\nissue of naming persistent objects, nor the (even more complicated)\nissue of concurrent access to persistent objects. The pickle\nmodule can transform a complex object into a byte stream and it can\ntransform the byte stream into an object with the same internal\nstructure. Perhaps the most obvious thing to do with these byte\nstreams is to write them onto a file, but it is also conceivable to\nsend them across a network or store them in a database. The module\nshelve (module-shelve.html) provides a simple interface\nto pickle and unpickle objects on DBM-style database files.", "python_version": "2.2", "length": 3557, "url": "https://docs.python.org/2.2/lib/node59.html"} {"title": "3.14.2 Data stream format", "text": "node59.html | module-pickle.html | node61.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.14.2 Data stream format\nThe data format used by pickle is Python-specific. This has\nthe advantage that there are no restrictions imposed by external\nstandards such as XDR(which can't represent pointer sharing); however it means that\nnon-Python programs may not be able to reconstruct pickled Python\nobjects.\nBy default, the pickle data format uses a printable ASCII\nrepresentation. This is slightly more voluminous than a binary\nrepresentation. The big advantage of using printable ASCII (and of\nsome other characteristics of pickle's representation) is that\nfor debugging or recovery purposes it is possible for a human to read\nthe pickled file with a standard text editor.\nA binary format, which is slightly more efficient, can be chosen by\nspecifying a true value for the bin argument to the\nPickler constructor or the dump() and dumps()\nfunctions.", "python_version": "2.2", "length": 982, "url": "https://docs.python.org/2.2/lib/node60.html"} {"title": "22. MS Windows Specific Services", "text": "module-sunaudiodev-constants.html | lib.html | module-msvcrt.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 22. MS Windows Specific Services\nThis chapter describes modules that are only available on MS Windows\nplatforms.", "python_version": "2.2", "length": 259, "url": "https://docs.python.org/2.2/lib/node604.html"} {"title": "3.14.3 Usage", "text": "node60.html | module-pickle.html | node62.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.14.3 Usage\nTo serialize an object hierarchy, you first create a pickler, then you\ncall the pickler's dump() method. To de-serialize a data\nstream, you first create an unpickler, then you call the unpickler's\nload() method. The pickle module provides the\nfollowing functions to make this process more convenient:\nThe pickle module also defines three exceptions:\nThe pickle module also exports two callables3.4 (#foot6918), Pickler and\nUnpickler:\nPickler objects define one (or two) public methods:\nIt is possible to make multiple calls to the dump() method of\nthe same Pickler instance. These must then be matched to the\nsame number of calls to the load() method of the\ncorresponding Unpickler instance. If the same object is\npickled by multiple dump() calls, the load() will\nall yield references to the same object3.5 (#foot6920).\nUnpickler objects are defined as:\nUnpickler objects have one (or two) public methods:", "python_version": "2.2", "length": 1047, "url": "https://docs.python.org/2.2/lib/node61.html"} {"title": "A.1 Frameworks", "text": "undoc.html | undoc.html | node614.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# A.1 Frameworks\nFrameworks tend to be harder to document, but are well worth the\neffort spent.\ntest: -- Regression testing framework. This is used for the Python\nregression test, but is useful for other Python libraries as well.\nThis is a package rather than a single module.", "python_version": "2.2", "length": 394, "url": "https://docs.python.org/2.2/lib/node613.html"} {"title": "A.2 Miscellaneous useful utilities", "text": "node613.html | undoc.html | node615.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# A.2 Miscellaneous useful utilities\nSome of these are very old and/or not very robust; marked with ``hmm.''\nbdb: -- A generic Python debugger base class (used by pdb).\nihooks: -- Import hook support (for rexec (module-rexec.html); may become obsolete).\nsmtpd: -- An SMTP daemon implementation which meets the minimum requirements\nfor RFC 821 (http://www.faqs.org/rfcs/rfc821.html) conformance.", "python_version": "2.2", "length": 514, "url": "https://docs.python.org/2.2/lib/node614.html"} {"title": "A.3 Platform specific modules", "text": "node614.html | undoc.html | node616.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# A.3 Platform specific modules\nThese modules are used to implement the os.path (module-os.path.html) module,\nand are not documented beyond this mention. There's little need to\ndocument these.\ndospath: -- Implementation of os.path on MS-DOS.\nntpath: -- Implementation on os.path on Win32, Win64, WinCE, and\nOS/2 platforms.\nposixpath: -- Implementation on os.path on POSIX.", "python_version": "2.2", "length": 492, "url": "https://docs.python.org/2.2/lib/node615.html"} {"title": "A.4 Multimedia", "text": "node615.html | undoc.html | obsolete-modules.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# A.4 Multimedia\naudiodev: -- Platform-independent API for playing audio data.\nsunaudio: -- Interpret Sun audio headers (may become obsolete or a tool/demo).\ntoaiff: -- Convert \"arbitrary\" sound files to AIFF files; should probably\nbecome a tool or demo. Requires the external program sox.", "python_version": "2.2", "length": 418, "url": "https://docs.python.org/2.2/lib/node616.html"} {"title": "A.6 SGI-specific Extension modules", "text": "obsolete-modules.html | undoc.html | reporting-bugs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# A.6 SGI-specific Extension modules\nThe following are SGI specific, and may be out of touch with the\ncurrent version of reality.\ncl: -- Interface to the SGI compression library.\nsv: -- Interface to the ``simple video'' board on SGI Indigo\n(obsolete hardware).", "python_version": "2.2", "length": 396, "url": "https://docs.python.org/2.2/lib/node618.html"} {"title": "3.14.4 What can be pickled and unpickled?", "text": "node61.html | module-pickle.html | pickle-protocol.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.14.4 What can be pickled and unpickled?\nThe following types can be pickled:\n- `None`\n- integers, long integers, floating point numbers, complex numbers\n- normal and Unicode strings\n- tuples, lists, and dictionaries containing only picklable objects\n- functions defined at the top level of a module\n- built-in functions defined at the top level of a module\n- classes that are defined at the top level of a module\n- instances of such classes whose __dict__ or\n__setstate__() is picklable (see\nsection 3.14.5 (pickle-protocol.html#pickle-protocol) for details)\nAttempts to pickle unpicklable objects will raise the\nPicklingError exception; when this happens, an unspecified\nnumber of bytes may have already been written to the underlying file.\nNote that functions (built-in and user-defined) are pickled by ``fully\nqualified'' name reference, not by value. This means that only the\nfunction name is pickled, along with the name of module the function\nis defined in. Neither the function's code, nor any of its function\nattributes are pickled. Thus the defining module must be importable\nin the unpickling environment, and the module must contain the named\nobject, otherwise an exception will be raised3.6 (#foot6921).\nSimilarly, classes are pickled by named reference, so the same\nrestrictions in the unpickling environment apply. Note that none of\nthe class's code or data is pickled, so in the following example the\nclass attribute `attr` is not restored in the unpickling\nenvironment:\n```text\n\nclass Foo:\nattr = 'a class attr'\n\npicklestring = pickle.dumps(Foo)\n```\nThese restrictions are why picklable functions and classes must be\ndefined in the top level of a module.\nSimilarly, when class instances are pickled, their class's code and\ndata are not pickled along with them. Only the instance data are\npickled. This is done on purpose, so you can fix bugs in a class or\nadd methods to the class and still load objects that were created with\nan earlier version of the class. If you plan to have long-lived\nobjects that will see many versions of a class, it may be worthwhile\nto put a version number in the objects so that suitable conversions\ncan be made by the class's __setstate__() method.", "python_version": "2.2", "length": 2332, "url": "https://docs.python.org/2.2/lib/node62.html"} {"title": "C. History and License", "text": "reporting-bugs.html | lib.html | node621.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# C. History and License", "python_version": "2.2", "length": 149, "url": "https://docs.python.org/2.2/lib/node620.html"} {"title": "C.1 History of the software", "text": "node620.html | node620.html | node622.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# C.1 History of the software\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands\nas a successor of a language called ABC. Guido remains Python's\nprincipal author, although it includes many contributions from others.\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)\nin Reston, Virginia where he released several versions of the\nsoftware.\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team. In October of the same\nyear, the PythonLabs team moved to Zope Corporation (then Digital\nCreations; see http://www.zope.com/). In 2001, the Python\nSoftware Foundation (PSF, see http://www.python.org/psf/) was\nformed, a non-profit organization created specifically to own\nPython-related Intellectual Property. Digital Creations is a\nsponsoring member of the PSF.\nAll Python releases are Open Source (see\nhttp://www.opensource.org/ for the Open Source Definition).\nHistorically, most, but not all, Python releases have also been\nGPL-compatible; the table below summarizes the various releases.\nNote:\nGPL-compatible doesn't mean that we're distributing\nPython under the GPL. All Python licenses, unlike the GPL, let you\ndistribute a modified version without making your changes open source.\nThe GPL-compatible licenses make it possible to combine Python with\nother software that is released under the GPL; the others don't.\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.", "python_version": "2.2", "length": 1782, "url": "https://docs.python.org/2.2/lib/node621.html"} {"title": "C.2 Terms and conditions for accessing or otherwise using Python", "text": "node621.html | node620.html | modindex.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# C.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.2\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.2 software in source or binary\nform and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, PSF\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python\n2.2 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001 Python Software Foundation; All Rights\nReserved'' are retained in Python 2.2 alone or in any\nderivative version prepared by Licensee.\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 2.2 or any part thereof, and wants to\nmake the derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 2.2.\n4. PSF is making Python 2.2 available to Licensee on an ``AS IS''\nbasis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE\nPOSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee. This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n8. By copying, installing or otherwise using Python 2.2, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (``Licensee'') accessing and otherwise\nusing this software in source or binary form and its associated\ndocumentation (``the Software'').\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n3. BeOpen is making the Software available to Licensee on an ``AS IS''\nbasis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions. Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee. This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party. As an exception, the ``BeOpen Python'' logos available\nat http://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (``CNRI''), and the Individual or Organization\n(``Licensee'') accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., ``Copyright\n© 1995-2001 Corporation for National Research Initiatives;\nAll Rights Reserved'' are retained in Python 1.6.1 alone or in any\nderivative version prepared by Licensee. Alternately, in lieu of\nCNRI's License Agreement, Licensee may substitute the following text\n(omitting the quotes): ``Python 1.6.1 is made available subject to the\nterms and conditions in CNRI's License Agreement. This Agreement\ntogether with Python 1.6.1 may be located on the Internet using the\nfollowing unique, persistent identifier (known as a handle):\n1895.22/1013. This Agreement may also be obtained from a proxy server\non the Internet using the following URL:\nhttp://hdl.handle.net/1895.22/1013.''\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''\nbasis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement. Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee. This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n8. By clicking on the ``ACCEPT'' button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\nACCEPT\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\nCopyright © 1991 - 1995, Stichting Mathematisch Centrum\nAmsterdam, The Netherlands. All rights reserved.\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", "python_version": "2.2", "length": 9788, "url": "https://docs.python.org/2.2/lib/node622.html"} {"title": "3.14.5.2 Pickling and unpickling extension types", "text": "pickle-inst.html | pickle-protocol.html | node66.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 3.14.5.2 Pickling and unpickling extension types\nWhen the Pickler encounters an object of a type it knows\nnothing about -- such as an extension type -- it looks in two places\nfor a hint of how to pickle it. One alternative is for the object to\nimplement a __reduce__() method. If provided, at pickling\ntime __reduce__() will be called with no arguments, and it\nmust return either a string or a tuple.\nIf a string is returned, it names a global variable whose contents are\npickled as normal. When a tuple is returned, it must be of length two\nor three, with the following semantics:\n- A callable object, which in the unpickling environment must be\neither a class, a callable registered as a ``safe constructor''\n(see below), or it must have an attribute\n__safe_for_unpickling__ with a true value. Otherwise,\nan UnpicklingError will be raised in the unpickling\nenvironment. Note that as usual, the callable itself is pickled\nby name.\n- A tuple of arguments for the callable object, or `None`.\n- Optionally, the object's state, which will be passed to\nthe object's __setstate__() method as described in\nsection 3.14.5 (pickle-inst.html#pickle-inst). If the object has no\n__setstate__() method, then, as above, the value must\nbe a dictionary and it will be added to the object's\n__dict__.\nUpon unpickling, the callable will be called (provided that it meets\nthe above criteria), passing in the tuple of arguments; it should\nreturn the unpickled object. If the second item was `None`, then\ninstead of calling the callable directly, its __basicnew__()\nmethod is called without arguments. It should also return the\nunpickled object.\nAn alternative to implementing a __reduce__() method on the\nobject to be pickled, is to register the callable with the\ncopy_reg (module-copyreg.html) module. This module provides a way\nfor programs to register ``reduction functions'' and constructors for\nuser-defined types. Reduction functions have the same semantics and\ninterface as the __reduce__() method described above, except\nthat they are called with a single argument, the object to be pickled.\nThe registered constructor is deemed a ``safe constructor'' for purposes\nof unpickling as described above.", "python_version": "2.2", "length": 2324, "url": "https://docs.python.org/2.2/lib/node65.html"} {"title": "3.14.5.3 Pickling and unpickling external objects", "text": "node65.html | pickle-protocol.html | pickle-sec.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 3.14.5.3 Pickling and unpickling external objects\nFor the benefit of object persistence, the pickle module\nsupports the notion of a reference to an object outside the pickled\ndata stream. Such objects are referenced by a ``persistent id'',\nwhich is just an arbitrary string of printable ASCII characters.\nThe resolution of such names is not defined by the pickle\nmodule; it will delegate this resolution to user defined functions on\nthe pickler and unpickler3.9 (#foot6929).\nTo define external persistent id resolution, you need to set the\npersistent_id attribute of the pickler object and the\npersistent_load attribute of the unpickler object.\nTo pickle objects that have an external persistent id, the pickler\nmust have a custom persistent_id() method that takes an\nobject as an argument and returns either `None` or the persistent\nid for that object. When `None` is returned, the pickler simply\npickles the object as normal. When a persistent id string is\nreturned, the pickler will pickle that string, along with a marker\nso that the unpickler will recognize the string as a persistent id.\nTo unpickle external objects, the unpickler must have a custom\npersistent_load() function that takes a persistent id\nstring and returns the referenced object.\nHere's a silly example that might shed more light:\n```text\n\nimport pickle\nfrom cStringIO import StringIO\n\nsrc = StringIO()\np = pickle.Pickler(src)\n\ndef persistent_id(obj):\nif hasattr(obj, 'x'):\nreturn 'the value %d' % obj.x\nelse:\nreturn None\n\np.persistent_id = persistent_id\n\nclass Integer:\ndef __init__(self, x):\nself.x = x\ndef __str__(self):\nreturn 'My name is integer %d' % self.x\n\ni = Integer(7)\nprint i\np.dump(i)\n\ndatastream = src.getvalue()\nprint repr(datastream)\ndst = StringIO(datastream)\n\nup = pickle.Unpickler(dst)\n\nclass FancyInteger(Integer):\ndef __str__(self):\nreturn 'I am the integer %d' % self.x\n\ndef persistent_load(persid):\nif persid.startswith('the value '):\nvalue = int(persid.split()[2])\nreturn FancyInteger(value)\nelse:\nraise pickle.UnpicklingError, 'Invalid persistent id'\n\nup.persistent_load = persistent_load\n\nj = up.load()\nprint j\n```\nIn the cPickle module, the unpickler's\npersistent_load attribute can also be set to a Python\nlist, in which case, when the unpickler reaches a persistent id, the\npersistent id string will simply be appended to this list. This\nfunctionality exists so that a pickle data stream can be ``sniffed''\nfor object references without actually instantiating all the objects\nin a pickle3.10 (#foot6824). Setting\npersistent_load to a list is usually used in conjunction with\nthe noload() method on the Unpickler.", "python_version": "2.2", "length": 2750, "url": "https://docs.python.org/2.2/lib/node66.html"} {"title": "3.24.1 PrettyPrinter Objects", "text": "module-pprint.html | module-pprint.html | module-repr.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.24.1 PrettyPrinter Objects\nPrettyPrinter instances have the following methods:\nThe following methods provide the implementations for the\ncorresponding functions of the same names. Using these methods on an\ninstance is slightly more efficient since new PrettyPrinter\nobjects don't need to be created.", "python_version": "2.2", "length": 442, "url": "https://docs.python.org/2.2/lib/node85.html"} {"title": "4.2.3 Module Contents", "text": "matching-searching.html | module-re.html | re-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.2.3 Module Contents\nThe module defines the following functions and constants, and an exception:", "python_version": "2.2", "length": 238, "url": "https://docs.python.org/2.2/lib/node99.html"} {"title": "A.5 Obsolete", "text": "node616.html | undoc.html | node618.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# A.5 Obsolete\nThese modules are not normally available for import; additional work\nmust be done to make them available.\nThose which are written in Python will be installed into the directory\nlib-old/ installed as part of the standard library. To use\nthese, the directory must be added to `sys.path`, possibly using\nPYTHONPATH.\nObsolete extension modules written in C are not built by default.\nUnder Unix, these must be enabled by uncommenting the appropriate\nlines in Modules/Setup in the build tree and either rebuilding\nPython if the modules are statically linked, or building and\ninstalling the shared object if using dynamically-loaded extensions.\naddpack: -- Alternate approach to packages. Use the built-in package support\ninstead.\ncmp: -- File comparison function. Use the newer filecmp (module-filecmp.html) instead.\ncmpcache: -- Caching version of the obsolete cmp module. Use the\nnewer filecmp (module-filecmp.html) instead.\ncodehack: -- Extract function name or line number from a function\ncode object (these are now accessible as attributes:\nco.co_name, func.func_name,\nco.co_firstlineno).\ndircmp: -- Class to build directory diff tools on (may become a demo or tool).\nDeprecated since release 2.0.\nThe filecmp (module-filecmp.html) module replaces\ndircmp.\ndump: -- Print python code that reconstructs a variable.\nfmt: -- Text formatting abstractions (too slow).\nlockfile: -- Wrapper around FCNTL file locking (use\nfcntl.lockf()/flock() instead; see fcntl (module-fcntl.html)).\nnewdir: -- New dir() function (the standard dir() is\nnow just as good).\nPara: -- Helper for fmt.\npoly: -- Polynomials.\nregex: -- Emacs-style regular expression support; may still be used in some\nold code (extension module). Refer to the\nPython\n1.6 Documentation (http://www.python.org/doc/1.6/lib/module-regex.html) for documentation.\nregsub: -- Regular expression based string replacement utilities, for use\nwith regex (extension module). Refer to the\nPython\n1.6 Documentation (http://www.python.org/doc/1.6/lib/module-regsub.html) for documentation.\ntb: -- Print tracebacks, with a dump of local variables (use\npdb.pm() or traceback (module-traceback.html) instead).\ntiming: -- Measure time intervals to high resolution (use\ntime.clock() instead). (This is an extension module.)\ntzparse: -- Parse a timezone specification (unfinished; may disappear in the\nfuture, and does not work when the TZ environment variable is\nnot set).\nutil: -- Useful functions that don't fit elsewhere.\nwhatsound: -- Recognize sound files; use sndhdr (module-sndhdr.html) instead.\nzmod: -- Compute properties of mathematical ``fields.''\nThe following modules are obsolete, but are likely to re-surface as\ntools or scripts:\nfind: -- Find files matching pattern in directory tree.\ngrep: -- grep implementation in Python.\npackmail: -- Create a self-unpacking Unix shell archive.\nThe following modules were documented in previous versions of this\nmanual, but are now considered obsolete. The source for the\ndocumentation is still available as part of the documentation source\narchive.\nni: -- Import modules in ``packages.'' Basic package support is now\nbuilt in. The built-in support is very similar to what is provided in\nthis module.\nrand: -- Old interface to the random number generator.\nsoundex: -- Algorithm for collapsing names which sound similar to a shared\nkey. The specific algorithm doesn't seem to match any published\nalgorithm. (This is an extension module.)", "python_version": "2.2", "length": 3557, "url": "https://docs.python.org/2.2/lib/obsolete-modules.html"} {"title": "11.5.2 OpenerDirector Objects", "text": "request-objects.html | module-urllib2.html | base-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.2 OpenerDirector Objects\nOpenerDirector instances have the following methods:", "python_version": "2.2", "length": 235, "url": "https://docs.python.org/2.2/lib/opener-director-objects.html"} {"title": "3.10.1 Mapping Operators to Functions", "text": "module-operator.html | module-operator.html | module-inspect.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.10.1 Mapping Operators to Functions\nThis table shows how abstract operations correspond to operator\nsymbols in the Python syntax and the functions in the\noperator (module-operator.html) module.", "python_version": "2.2", "length": 343, "url": "https://docs.python.org/2.2/lib/operator-map.html"} {"title": "5.3.1 Organizing test code", "text": "module-unittest.html | module-unittest.html | legacy-unit-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.3.1 Organizing test code\nThe basic building blocks of unit testing are test cases --\nsingle scenarios that must be set up and checked for correctness. In\nPyUnit, test cases are represented by instances of the\nTestCase class in the unittest (module-unittest.html) module. To make\nyour own test cases you must write subclasses of TestCase, or\nuse FunctionTestCase.\nAn instance of a TestCase-derived class is an object that can\ncompletely run a single test method, together with optional set-up\nand tidy-up code.\nThe testing code of a TestCase instance should be entirely\nself contained, such that it can be run either in isolation or in\narbitrary combination with any number of other test cases.\nThe simplest test case subclass will simply override the\nrunTest() method in order to perform specific testing code:\n```text\n\nimport unittest\n\nclass DefaultWidgetSizeTestCase(unittest.TestCase):\ndef runTest(self):\nwidget = Widget(\"The widget\")\nself.failUnless(widget.size() == (50,50), 'incorrect default size')\n```\nNote that in order to test something, we use the one of the\nassert*() or fail*() methods provided by the\nTestCase base class. If the test fails when the test case\nruns, an exception will be raised, and the testing framework will\nidentify the test case as a failure. Other exceptions that do\nnot arise from checks made through the assert*() and\nfail*() methods are identified by the testing framework as\ndfnerrors.\nThe way to run a test case will be described later. For now, note\nthat to construct an instance of such a test case, we call its\nconstructor without arguments:\n```text\n\ntestCase = DefaultWidgetSizeTestCase()\n```\nNow, such test cases can be numerous, and their set-up can be\nrepetitive. In the above case, constructing a ``Widget'' in each of\n100 Widget test case subclasses would mean unsightly duplication.\nLuckily, we can factor out such set-up code by implementing a method\ncalled setUp(), which the testing framework will\nautomatically call for us when we run the test:\n```text\n\nimport unittest\n\nclass SimpleWidgetTestCase(unittest.TestCase):\ndef setUp(self):\nself.widget = Widget(\"The widget\")\n\nclass DefaultWidgetSizeTestCase(SimpleWidgetTestCase):\ndef runTest(self):\nself.failUnless(self.widget.size() == (50,50),\n'incorrect default size')\n\nclass WidgetResizeTestCase(SimpleWidgetTestCase):\ndef runTest(self):\nself.widget.resize(100,150)\nself.failUnless(self.widget.size() == (100,150),\n'wrong size after resize')\n```\nIf the setUp() method raises an exception while the test is\nrunning, the framework will consider the test to have suffered an\nerror, and the runTest() method will not be executed.\nSimilarly, we can provide a tearDown() method that tidies up\nafter the runTest() method has been run:\n```text\n\nimport unittest\n\nclass SimpleWidgetTestCase(unittest.TestCase):\ndef setUp(self):\nself.widget = Widget(\"The widget\")\n\ndef tearDown(self):\nself.widget.dispose()\nself.widget = None\n```\nIf setUp() succeeded, the tearDown() method will be\nrun regardless of whether or not runTest() succeeded.\nSuch a working environment for the testing code is called a\nfixture.\nOften, many small test cases will use the same fixture. In this case,\nwe would end up subclassing SimpleWidgetTestCase into many\nsmall one-method classes such as\nDefaultWidgetSizeTestCase. This is time-consuming and\ndiscouraging, so in the same vein as JUnit, PyUnit provides a simpler\nmechanism:\n```text\n\nimport unittest\n\nclass WidgetTestCase(unittest.TestCase):\ndef setUp(self):\nself.widget = Widget(\"The widget\")\n\ndef tearDown(self):\nself.widget.dispose()\nself.widget = None\n\ndef testDefaultSize(self):\nself.failUnless(self.widget.size() == (50,50),\n'incorrect default size')\n\ndef testResize(self):\nself.widget.resize(100,150)\nself.failUnless(self.widget.size() == (100,150),\n'wrong size after resize')\n```\nHere we have not provided a runTest() method, but have\ninstead provided two different test methods. Class instances will now\neach run one of the test*() methods, with `self.widget`\ncreated and destroyed separately for each instance. When creating an\ninstance we must specify the test method it is to run. We do this by\npassing the method name in the constructor:\n```text\n\ndefaultSizeTestCase = WidgetTestCase(\"testDefaultSize\")\nresizeTestCase = WidgetTestCase(\"testResize\")\n```\nTest case instances are grouped together according to the features\nthey test. PyUnit provides a mechanism for this: the test\nsuite, represented by the class TestSuite in the\nunittest (module-unittest.html) module:\n```text\n\nwidgetTestSuite = unittest.TestSuite()\nwidgetTestSuite.addTest(WidgetTestCase(\"testDefaultSize\"))\nwidgetTestSuite.addTest(WidgetTestCase(\"testResize\"))\n```\nFor the ease of running tests, as we will see later, it is a good\nidea to provide in each test module a callable object that returns a\npre-built test suite:\n```text\n\ndef suite():\nsuite = unittest.TestSuite()\nsuite.addTest(WidgetTestCase(\"testDefaultSize\"))\nsuite.addTest(WidgetTestCase(\"testResize\"))\nreturn suite\n```\nor even:\n```text\n\nclass WidgetTestSuite(unittest.TestSuite):\ndef __init__(self):\nunittest.TestSuite.__init__(self,map(WidgetTestCase,\n(\"testDefaultSize\",\n\"testResize\")))\n```\n(The latter is admittedly not for the faint-hearted!)\nSince it is a common pattern to create a TestCase subclass\nwith many similarly named test functions, there is a convenience\nfunction called makeSuite() provided in the\nunittest (module-unittest.html) module that constructs a test suite that\ncomprises all of the test cases in a test case class:\n```text\n\nsuite = unittest.makeSuite(WidgetTestCase,'test')\n```\nNote that when using the makeSuite() function, the order in\nwhich the various test cases will be run by the test suite is the\norder determined by sorting the test function names using the\ncmp() built-in function.\nOften it is desirable to group suites of test cases together, so as to\nrun tests for the whole system at once. This is easy, since\nTestSuite instances can be added to a TestSuite just\nas TestCase instances can be added to a TestSuite:\n```text\n\nsuite1 = module1.TheTestSuite()\nsuite2 = module2.TheTestSuite()\nalltests = unittest.TestSuite((suite1, suite2))\n```\nYou can place the definitions of test cases and test suites in the\nsame modules as the code they are to test (e.g. widget.py),\nbut there are several advantages to placing the test code in a\nseparate module, such as widgettests.py:\n- The test module can be run standalone from the command line.\n- The test code can more easily be separated from shipped code.\n- There is less temptation to change test code to fit the code.\nit tests without a good reason.\n- Test code should be modified much less frequently than the\ncode it tests.\n- Tested code can be refactored more easily.\n- Tests for modules written in C must be in separate modules\nanyway, so why not be consistent?\n- If the testing strategy changes, there is no need to change\nthe source code.", "python_version": "2.2", "length": 7042, "url": "https://docs.python.org/2.2/lib/organizing-tests.html"} {"title": "6.1.3 File Descriptor Operations", "text": "os-newstreams.html | module-os.html | os-file-dir.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.1.3 File Descriptor Operations\nThese functions operate on I/O streams referred to\nusing file descriptors.\nThe following data items are available for use in constructing the\nflags parameter to the open() function.", "python_version": "2.2", "length": 351, "url": "https://docs.python.org/2.2/lib/os-fd-ops.html"} {"title": "6.1.4 Files and Directories", "text": "os-fd-ops.html | module-os.html | os-process.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.1.4 Files and Directories", "python_version": "2.2", "length": 159, "url": "https://docs.python.org/2.2/lib/os-file-dir.html"} {"title": "6.1.2 File Object Creation", "text": "os-procinfo.html | module-os.html | os-fd-ops.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.1.2 File Object Creation\nThese functions create new file objects.\nFor each of these popen() variants, if bufsize is\nspecified, it specifies the buffer size for the I/O pipes.\nmode, if provided, should be the string `'b'` or\n`'t'`; on Windows this is needed to determine whether the file\nobjects should be opened in binary or text mode. The default value\nfor mode is `'t'`.\nThese methods do not make it possible to retrieve the return code from\nthe child processes. The only way to control the input and output\nstreams and also retrieve the return codes is to use the\nPopen3 and Popen4 classes from the popen2 (module-popen2.html)\nmodule; these are only available on Unix.\nThis functionality is also available in the popen2 (module-popen2.html) module\nusing functions of the same names, but the return values of those\nfunctions have a different order.", "python_version": "2.2", "length": 985, "url": "https://docs.python.org/2.2/lib/os-newstreams.html"} {"title": "6.1.6 Miscellaneous System Information", "text": "os-process.html | module-os.html | module-os.path.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.1.6 Miscellaneous System Information\nThe follow data values are used to support path manipulation\noperations. These are defined for all platforms.\nHigher-level operations on pathnames are defined in the\nos.path (module-os.path.html) module.", "python_version": "2.2", "length": 379, "url": "https://docs.python.org/2.2/lib/os-path.html"} {"title": "6.1.5 Process Management", "text": "os-file-dir.html | module-os.html | os-path.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.1.5 Process Management\nThese functions may be used to create and manage processes.\nThe various exec*() functions take a list of arguments for\nthe new program loaded into the process. In each case, the first of\nthese arguments is passed to the new program as its own name rather\nthan as an argument a user may have typed on a command line. For the\nC programmer, this is the `argv[0]` passed to a program's\nmain(). For example, \"os.execv('/bin/echo', ['foo',\n'bar'])\" will only print \"bar\" on standard output; \"foo\"will seem to be ignored.\nThe following functions take a process status code as returned by\nsystem(), wait(), or waitpid() as a\nparameter. They may be used to determine the disposition of a\nprocess.", "python_version": "2.2", "length": 843, "url": "https://docs.python.org/2.2/lib/os-process.html"} {"title": "6.1.1 Process Parameters", "text": "module-os.html | module-os.html | os-newstreams.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.1.1 Process Parameters\nThese functions and data items provide information and operate on the\ncurrent process and user.", "python_version": "2.2", "length": 255, "url": "https://docs.python.org/2.2/lib/os-procinfo.html"} {"title": "16.6 Other Graphical User Interface Packages", "text": "node541.html | tkinter.html | restricted.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 16.6 Other Graphical User Interface Packages\nThere are an number of extension widget sets to Tkinter (module-Tkinter.html).\nTk is not the only GUI for Python, but is however the\nmost commonly used one.", "python_version": "2.2", "length": 328, "url": "https://docs.python.org/2.2/lib/other-gui-packages.html"} {"title": "16.4.1 Pen and RawPen Objects", "text": "module-turtle.html | module-turtle.html | idle.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.4.1 Pen and RawPen Objects\nPen and RawPen objects have all the global functions\ndescribed above, except for demo() as methods, which\nmanipulate the given pen.\nThe only method which is more powerful as a method is\ndegrees().", "python_version": "2.2", "length": 360, "url": "https://docs.python.org/2.2/lib/pen-rawpen-objects.html"} {"title": "3.14.7 Example", "text": "pickle-sec.html | module-pickle.html | module-cPickle.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.14.7 Example\nHere's a simple example of how to modify pickling behavior for a\nclass. The TextReader class opens a text file, and returns\nthe line number and line contents each time its readline()\nmethod is called. If a TextReader instance is pickled, all\nattributes except the file object member are saved. When the\ninstance is unpickled, the file is reopened, and reading resumes from\nthe last location. The __setstate__() and\n__getstate__() methods are used to implement this behavior.\n```text\n\nclass TextReader:\n\"\"\"Print and number lines in a text file.\"\"\"\ndef __init__(self, file):\nself.file = file\nself.fh = open(file)\nself.lineno = 0\n\ndef readline(self):\nself.lineno = self.lineno + 1\nline = self.fh.readline()\nif not line:\nreturn None\nif line.endswith(\"\\n\"):\nline = line[:-1]\nreturn \"%d: %s\" % (self.lineno, line)\n\ndef __getstate__(self):\nodict = self.__dict__.copy() # copy the dict since we change it\ndel odict['fh'] # remove filehandle entry\nreturn odict\n\ndef __setstate__(self,dict):\nfh = open(dict['file']) # reopen file\ncount = dict['lineno'] # read from file...\nwhile count: # until line count is restored\nfh.readline()\ncount = count - 1\nself.__dict__.update(dict) # update attributes\nself.fh = fh # save the file object\n```\nA sample usage might be something like this:\n```text\n\n>>> import TextReader\n>>> obj = TextReader.TextReader(\"TextReader.py\")\n>>> obj.readline()\n'1: #!/usr/local/bin/python'\n>>> # (more invocations of obj.readline() here)\n... obj.readline()\n'7: class TextReader:'\n>>> import pickle\n>>> pickle.dump(obj,open('save.p','w'))\n```\nIf you want to see that pickle (module-pickle.html) works across Python\nprocesses, start another Python session, before continuing. What\nfollows can happen from either the same process or a new process.\n```text\n\n>>> import pickle\n>>> reader = pickle.load(open('save.p'))\n>>> reader.readline()\n'8: \"Print and number lines in a text file.\"'\n```\nSee Also:", "python_version": "2.2", "length": 2059, "url": "https://docs.python.org/2.2/lib/pickle-example.html"} {"title": "3.14.5.1 Pickling and unpickling normal class instances", "text": "pickle-protocol.html | pickle-protocol.html | node65.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 3.14.5.1 Pickling and unpickling normal class\ninstances\nWhen a pickled class instance is unpickled, its __init__()\nmethod is normally not invoked. If it is desirable that the\n__init__() method be called on unpickling, a class can define\na method __getinitargs__(), which should return a\ntuple containing the arguments to be passed to the class\nconstructor (i.e. __init__()). The\n__getinitargs__() method is called at\npickle time; the tuple it returns is incorporated in the pickle for\nthe instance.\nClasses can further influence how their instances are pickled; if the\nclass defines the method __getstate__(), it is called and the\nreturn state is pickled as the contents for the instance, instead of\nthe contents of the instance's dictionary. If there is no\n__getstate__() method, the instance's __dict__ is\npickled.\nUpon unpickling, if the class also defines the method\n__setstate__(), it is called with the unpickled\nstate3.7 (#foot6781). If there is no __setstate__() method, the\npickled object must be a dictionary and its items are assigned to the\nnew instance's dictionary. If a class defines both\n__getstate__() and __setstate__(), the state object\nneedn't be a dictionary and these methods can do what they\nwant3.8 (#foot6928).", "python_version": "2.2", "length": 1376, "url": "https://docs.python.org/2.2/lib/pickle-inst.html"} {"title": "3.14.5 The pickle protocol", "text": "node62.html | module-pickle.html | pickle-inst.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.14.5 The pickle protocol\nThis section describes the ``pickling protocol'' that defines the\ninterface between the pickler/unpickler and the objects that are being\nserialized. This protocol provides a standard way for you to define,\ncustomize, and control how your objects are serialized and\nde-serialized. The description in this section doesn't cover specific\ncustomizations that you can employ to make the unpickling environment\nsafer from untrusted pickle data streams; see section 3.14.6 (pickle-sec.html#pickle-sec)\nfor more details.", "python_version": "2.2", "length": 673, "url": "https://docs.python.org/2.2/lib/pickle-protocol.html"} {"title": "3.14.6 Security", "text": "node66.html | module-pickle.html | pickle-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.14.6 Security\nMost of the security issues surrounding the pickle and\ncPickle module involve unpickling. There are no known\nsecurity vulnerabilities\nrelated to pickling because you (the programmer) control the objects\nthat pickle will interact with, and all it produces is a\nstring.\nHowever, for unpickling, it is never a good idea to unpickle\nan untrusted string whose origins are dubious, for example, strings\nread from a socket. This is because unpickling can create unexpected\nobjects and even potentially run methods of those objects, such as\ntheir class constructor or destructor3.11 (#foot6931).\nYou can defend against this by customizing your unpickler so that you\ncan control exactly what gets unpickled and what gets called.\nUnfortunately, exactly how you do this is different depending on\nwhether you're using pickle or cPickle.\nOne common feature that both modules implement is the\n__safe_for_unpickling__ attribute. Before calling a callable\nwhich is not a class, the unpickler will check to make sure that the\ncallable has either been registered as a safe callable via the\ncopy_reg (module-copyreg.html) module, or that it has an\nattribute __safe_for_unpickling__ with a true value. This\nprevents the unpickling environment from being tricked into doing\nevil things like call `os.unlink()` with an arbitrary file name.\nSee section 3.14.5 (pickle-protocol.html#pickle-protocol) for more details.\nFor safely unpickling class instances, you need to control exactly\nwhich classes will get created. Be aware that a class's constructor\ncould be called (if the pickler found a __getinitargs__()\nmethod) and the the class's destructor (i.e. its __del__() method)\nmight get called when the object is garbage collected. Depending on\nthe class, it isn't very heard to trick either method into doing bad\nthings, such as removing a file. The way to\ncontrol the classes that are safe to instantiate differs in\npickle and cPickle3.12 (#foot6932).\nIn the pickle module, you need to derive a subclass from\nUnpickler, overriding the load_global()\nmethod. load_global() should read two lines from the pickle\ndata stream where the first line will the the name of the module\ncontaining the class and the second line will be the name of the\ninstance's class. It then look up the class, possibly importing the\nmodule and digging out the attribute, then it appends what it finds to\nthe unpickler's stack. Later on, this class will be assigned to the\n__class__ attribute of an empty class, as a way of magically\ncreating an instance without calling its class's __init__().\nYou job (should you choose to accept it), would be to have\nload_global() push onto the unpickler's stack, a known safe\nversion of any class you deem safe to unpickle. It is up to you to\nproduce such a class. Or you could raise an error if you want to\ndisallow all unpickling of instances. If this sounds like a hack,\nyou're right. UTSL.\nThings are a little cleaner with cPickle, but not by much.\nTo control what gets unpickled, you can set the unpickler's\nfind_global attribute to a function or `None`. If it is\n`None` then any attempts to unpickle instances will raise an\nUnpicklingError. If it is a function,\nthen it should accept a module name and a class name, and return the\ncorresponding class object. It is responsible for looking up the\nclass, again performing any necessary imports, and it may raise an\nerror to prevent instances of the class from being unpickled.\nThe moral of the story is that you should be really careful about the\nsource of the strings your application unpickles.", "python_version": "2.2", "length": 3693, "url": "https://docs.python.org/2.2/lib/pickle-sec.html"} {"title": "20.3.1 Player Objects", "text": "module-cd.html | module-cd.html | cd-parser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 20.3.1 Player Objects\nPlayer objects (returned by open()) have the following\nmethods:", "python_version": "2.2", "length": 224, "url": "https://docs.python.org/2.2/lib/player-objects.html"} {"title": "7.3.1 Polling Objects", "text": "module-select.html | module-select.html | module-thread.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.3.1 Polling Objects\nThe poll() system call, supported on most Unix systems,\nprovides better scalability for network servers that service many,\nmany clients at the same time.\npoll() scales better because the system call only\nrequires listing the file descriptors of interest, while select()\nbuilds a bitmap, turns on bits for the fds of interest, and then\nafterward the whole bitmap has to be linearly scanned again.\nselect() is O(highest file descriptor), while\npoll() is O(number of file descriptors).", "python_version": "2.2", "length": 647, "url": "https://docs.python.org/2.2/lib/poll-objects.html"} {"title": "11.9.2 POP3 Example", "text": "pop3-objects.html | module-poplib.html | module-imaplib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.9.2 POP3 Example\nHere is a minimal example (without error checking) that opens a\nmailbox and retrieves and prints all messages:\n```text\n\nimport getpass, poplib\n\nM = poplib.POP3('localhost')\nM.user(getpass.getuser())\nM.pass_(getpass.getpass())\nnumMessages = len(M.list()[1])\nfor i in range(numMessages):\nfor j in M.retr(i+1)[1]:\nprint j\n```", "python_version": "2.2", "length": 485, "url": "https://docs.python.org/2.2/lib/pop3-example.html"} {"title": "11.9.1 POP3 Objects", "text": "module-poplib.html | module-poplib.html | pop3-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.9.1 POP3 Objects\nAll POP3 commands are represented by methods of the same name,\nin lower-case; most return the response text sent by the server.\nAn POP3 instance has the following methods:", "python_version": "2.2", "length": 333, "url": "https://docs.python.org/2.2/lib/pop3-objects.html"} {"title": "6.8.1 Popen3 and Popen4 Objects", "text": "module-popen2.html | module-popen2.html | module-time.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.8.1 Popen3 and Popen4 Objects\nInstances of the Popen3 and Popen4 classes have the\nfollowing methods:\nThe following attributes are also available:", "python_version": "2.2", "length": 288, "url": "https://docs.python.org/2.2/lib/popen3-objects.html"} {"title": "8.1.2 Module Contents", "text": "posix-large-files.html | module-posix.html | module-pwd.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.1.2 Module Contents\nModule posix defines the following data item:", "python_version": "2.2", "length": 210, "url": "https://docs.python.org/2.2/lib/posix-contents.html"} {"title": "8.1.1 Large File Support", "text": "module-posix.html | module-posix.html | posix-contents.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.1.1 Large File Support\nSeveral operating systems (including AIX, HPUX, Irix and Solaris)\nprovide support for files that are larger than 2 Gb from a C\nprogramming model where int and long are 32-bit\nvalues. This is typically accomplished by defining the relevant size\nand offset types as 64-bit values. Such files are sometimes referred\nto as large files.\nLarge file support is enabled in Python when the size of an\noff_t is larger than a long and the long long\ntype is available and is at least as large as an off_t. Python\nlongs are then used to represent file sizes, offsets and other values\nthat can exceed the range of a Python int. It may be necessary to\nconfigure and compile Python with certain compiler flags to enable\nthis mode. For example, it is enabled by default with recent versions\nof Irix, but with Solaris 2.6 and 2.7 you need to do something like:\n```text\n\nCFLAGS=\"`getconf LFS_CFLAGS`\" OPT=\"-g -O2 $CFLAGS\" \\\n./configure\n```\nOn large-file-capable Linux systems, this might work:\n```text\n\nCFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT=\"-g -O2 $CFLAGS\" \\\n./configure\n```", "python_version": "2.2", "length": 1243, "url": "https://docs.python.org/2.2/lib/posix-large-files.html"} {"title": "3.24.1 PrettyPrinter Objects", "text": "module-pprint.html | module-pprint.html | module-repr.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.24.1 PrettyPrinter Objects\nPrettyPrinter instances have the following methods:\nThe following methods provide the implementations for the\ncorresponding functions of the same names. Using these methods on an\ninstance is slightly more efficient since new PrettyPrinter\nobjects don't need to be created.", "python_version": "2.2", "length": 442, "url": "https://docs.python.org/2.2/lib/PrettyPrinter_Objects.html"} {"title": "10.7 Calibration", "text": "profile-limits.html | profile.html | node289.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.7 Calibration\nThe profiler subtracts a constant from each\nevent handling time to compensate for the overhead of calling the time\nfunction, and socking away the results. By default, the constant is 0.\nThe following procedure can\nbe used to obtain a better constant for a given platform (see discussion\nin section Limitations above).\n```text\n\nimport profile\npr = profile.Profile()\nfor i in range(5):\nprint pr.calibrate(10000)\n```\nThe method executes the number of Python calls given by the argument,\ndirectly and again under the profiler, measuring the time for both.\nIt then computes the hidden overhead per profiler event, and returns\nthat as a float. For example, on an 800 MHz Pentium running\nWindows 2000, and using Python's time.clock() as the timer,\nthe magical number is about 12.5e-6.\nThe object of this exercise is to get a fairly consistent result.\nIf your computer is very fast, or your timer function has poor\nresolution, you might have to pass 100000, or even 1000000, to get\nconsistent results.\nWhen you have a consistent answer,\nthere are three ways you can use it:10.3 (#foot28895)\n```text\n\nimport profile\n\n# 1. Apply computed bias to all Profile instances created hereafter.\nprofile.Profile.bias = your_computed_bias\n\n# 2. Apply computed bias to a specific Profile instance.\npr = profile.Profile()\npr.bias = your_computed_bias\n\n# 3. Specify computed bias in instance constructor.\npr = profile.Profile(bias=your_computed_bias)\n```\nIf you have a choice, you are better off choosing a smaller constant, and\nthen your results will ``less often'' show up as negative in profile\nstatistics.", "python_version": "2.2", "length": 1734, "url": "https://docs.python.org/2.2/lib/profile-calibration.html"} {"title": "10.8.2 HotProfile Class", "text": "profile-old.html | Profiler_Extensions.html | internet.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 10.8.2 HotProfile Class\nThis profiler is the fastest derived profile example. It does not\ncalculate caller-callee relationships, and does not calculate\ncumulative time under a function. It only calculates time spent in a\nfunction, so it runs very quickly (re: very low overhead). In truth,\nthe basic profiler is so fast, that is probably not worth the savings\nto give up the data, but this class still provides a nice example.\n```text\n\nclass HotProfile(Profile):\n\ndef trace_dispatch_exception(self, frame, t):\nrt, rtt, rfn, rframe, rcur = self.cur\nif rcur and not rframe is frame:\nreturn self.trace_dispatch_return(rframe, t)\nreturn 0\n\ndef trace_dispatch_call(self, frame, t):\nself.cur = (t, 0, frame, self.cur)\nreturn 1\n\ndef trace_dispatch_return(self, frame, t):\nrt, rtt, frame, rcur = self.cur\n\nrfn = `frame.f_code`\n\npt, ptt, pframe, pcur = rcur\nself.cur = pt, ptt+rt, pframe, pcur\n\nif self.timings.has_key(rfn):\nnc, tt = self.timings[rfn]\nself.timings[rfn] = nc + 1, rt + rtt + tt\nelse:\nself.timings[rfn] = 1, rt + rtt\n\nreturn 1\n\ndef snapshot_stats(self):\nself.stats = {}\nfor func in self.timings.keys():\nnc, tt = self.timings[func]\nnor_func = self.func_normalize(func)\nself.stats[nor_func] = nc, nc, tt, 0, {}\n```", "python_version": "2.2", "length": 1360, "url": "https://docs.python.org/2.2/lib/profile-HotProfile.html"} {"title": "10.3 Instant Users Manual", "text": "node282.html | profile.html | node284.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.3 Instant Users Manual\nThis section is provided for users that ``don't want to read the\nmanual.'' It provides a very brief overview, and allows a user to\nrapidly perform profiling on an existing application.\nTo profile an application with a main entry point of \"foo()\", you\nwould add the following to your module:\n```text\n\nimport profile\nprofile.run('foo()')\n```\nThe above action would cause \"foo()\" to be run, and a series of\ninformative lines (the profile) to be printed. The above approach is\nmost useful when working with the interpreter. If you would like to\nsave the results of a profile into a file for later examination, you\ncan supply a file name as the second argument to the run()\nfunction:\n```text\n\nimport profile\nprofile.run('foo()', 'fooprof')\n```\nThe file profile.py can also be invoked as\na script to profile another script. For example:\n```text\n\npython /usr/local/lib/python1.5/profile.py myscript.py\n```\nWhen you wish to review the profile, you should use the methods in the\npstats module. Typically you would load the statistics data as\nfollows:\n```text\n\nimport pstats\np = pstats.Stats('fooprof')\n```\nThe class Stats (the above code just created an instance of\nthis class) has a variety of methods for manipulating and printing the\ndata that was just read into \"p\". When you ran\nprofile.run() above, what was printed was the result of three\nmethod calls:\n```text\n\np.strip_dirs().sort_stats(-1).print_stats()\n```\nThe first method removed the extraneous path from all the module\nnames. The second method sorted all the entries according to the\nstandard module/line/name string that is printed (this is to comply\nwith the semantics of the old profiler). The third method printed out\nall the statistics. You might try the following sort calls:\n```text\n\np.sort_stats('name')\np.print_stats()\n```\nThe first call will actually sort the list by function name, and the\nsecond call will print out the statistics. The following are some\ninteresting calls to experiment with:\n```text\n\np.sort_stats('cumulative').print_stats(10)\n```\nThis sorts the profile by cumulative time in a function, and then only\nprints the ten most significant lines. If you want to understand what\nalgorithms are taking time, the above line is what you would use.\nIf you were looking to see what functions were looping a lot, and\ntaking a lot of time, you would do:\n```text\n\np.sort_stats('time').print_stats(10)\n```\nto sort according to time spent within each function, and then print\nthe statistics for the top ten functions.\nYou might also try:\n```text\n\np.sort_stats('file').print_stats('__init__')\n```\nThis will sort all the statistics by file name, and then print out\nstatistics for only the class init methods ('cause they are spelled\nwith \"__init__\" in them). As one final example, you could try:\n```text\n\np.sort_stats('time', 'cum').print_stats(.5, 'init')\n```\nThis line sorts statistics with a primary key of time, and a secondary\nkey of cumulative time, and then prints out some of the statistics.\nTo be specific, the list is first culled down to 50% (re: \".5\")\nof its original size, then only lines containing `init` are\nmaintained, and that sub-sub-list is printed.\nIf you wondered what functions called the above functions, you could\nnow (\"p\" is still sorted according to the last criteria) do:\n```text\n\np.print_callers(.5, 'init')\n```\nand you would get a list of callers for each of the listed functions.\nIf you want more functionality, you're going to have to read the\nmanual, or guess what the following functions do:\n```text\n\np.print_callees()\np.add('fooprof')\n```\nInvoked as a script, the pstats module is a statistics\nbrowser for reading and examining profile dumps. It has a simple\nline-oriented interface (implemented using cmd (module-cmd.html)) and\ninteractive help.", "python_version": "2.2", "length": 3896, "url": "https://docs.python.org/2.2/lib/profile-instant.html"} {"title": "10.6 Limitations", "text": "profile-stats.html | profile.html | profile-calibration.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.6 Limitations\nThere are two fundamental limitations on this profiler. The first is\nthat it relies on the Python interpreter to dispatch call,\nreturn, and exception events. Compiled C code does not\nget interpreted, and hence is ``invisible'' to the profiler. All time\nspent in C code (including built-in functions) will be charged to the\nPython function that invoked the C code. If the C code calls out\nto some native Python code, then those calls will be profiled\nproperly.\nThe second limitation has to do with accuracy of timing information.\nThere is a fundamental problem with deterministic profilers involving\naccuracy. The most obvious restriction is that the underlying ``clock''\nis only ticking at a rate (typically) of about .001 seconds. Hence no\nmeasurements will be more accurate that that underlying clock. If\nenough measurements are taken, then the ``error'' will tend to average\nout. Unfortunately, removing this first error induces a second source\nof error...\nThe second problem is that it ``takes a while'' from when an event is\ndispatched until the profiler's call to get the time actually\ngets the state of the clock. Similarly, there is a certain lag\nwhen exiting the profiler event handler from the time that the clock's\nvalue was obtained (and then squirreled away), until the user's code\nis once again executing. As a result, functions that are called many\ntimes, or call many functions, will typically accumulate this error.\nThe error that accumulates in this fashion is typically less than the\naccuracy of the clock (less than one clock tick), but it\ncan accumulate and become very significant. This profiler\nprovides a means of calibrating itself for a given platform so that\nthis error can be probabilistically (on the average) removed.\nAfter the profiler is calibrated, it will be more accurate (in a least\nsquare sense), but it will sometimes produce negative numbers (when\ncall counts are exceptionally low, and the gods of probability work\nagainst you :-). ) Do not be alarmed by negative numbers in\nthe profile. They should only appear if you have calibrated\nyour profiler, and the results are actually better than without\ncalibration.", "python_version": "2.2", "length": 2310, "url": "https://docs.python.org/2.2/lib/profile-limits.html"} {"title": "10.8.1 OldProfile Class", "text": "Profiler_Extensions.html | Profiler_Extensions.html | profile-HotProfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 10.8.1 OldProfile Class\nThe following derived profiler simulates the old style profiler,\nproviding errant results on recursive functions. The reason for the\nusefulness of this profiler is that it runs faster (i.e., less\noverhead) than the old profiler. It still creates all the caller\nstats, and is quite useful when there is no recursion in the\nuser's code. It is also a lot more accurate than the old profiler, as\nit does not charge all its overhead time to the user's code.\n```text\n\nclass OldProfile(Profile):\n\ndef trace_dispatch_exception(self, frame, t):\nrt, rtt, rct, rfn, rframe, rcur = self.cur\nif rcur and not rframe is frame:\nreturn self.trace_dispatch_return(rframe, t)\nreturn 0\n\ndef trace_dispatch_call(self, frame, t):\nfn = `frame.f_code`\n\nself.cur = (t, 0, 0, fn, frame, self.cur)\nif self.timings.has_key(fn):\ntt, ct, callers = self.timings[fn]\nself.timings[fn] = tt, ct, callers\nelse:\nself.timings[fn] = 0, 0, {}\nreturn 1\n\ndef trace_dispatch_return(self, frame, t):\nrt, rtt, rct, rfn, frame, rcur = self.cur\nrtt = rtt + t\nsft = rtt + rct\n\npt, ptt, pct, pfn, pframe, pcur = rcur\nself.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur\n\ntt, ct, callers = self.timings[rfn]\nif callers.has_key(pfn):\ncallers[pfn] = callers[pfn] + 1\nelse:\ncallers[pfn] = 1\nself.timings[rfn] = tt+rtt, ct + sft, callers\n\nreturn 1\n\ndef snapshot_stats(self):\nself.stats = {}\nfor func in self.timings.keys():\ntt, ct, callers = self.timings[func]\nnor_func = self.func_normalize(func)\nnor_callers = {}\nnc = 0\nfor func_caller in callers.keys():\nnor_callers[self.func_normalize(func_caller)] = \\\ncallers[func_caller]\nnc = nc + callers[func_caller]\nself.stats[nor_func] = nc, nc, tt, ct, nor_callers\n```", "python_version": "2.2", "length": 1841, "url": "https://docs.python.org/2.2/lib/profile-old.html"} {"title": "10.5.1 The Stats Class", "text": "module-profile.html | module-profile.html | profile-limits.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 10.5.1 The Stats Class\nStats objects have the following methods:", "python_version": "2.2", "length": 210, "url": "https://docs.python.org/2.2/lib/profile-stats.html"} {"title": "10. The Python Profiler", "text": "debugger-hooks.html | lib.html | node281.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10. The Python Profiler\nCopyright © 1994, by InfoSeek Corporation, all rights reserved.\nWritten by James Roskind.10.1 (#foot28675)\nPermission to use, copy, modify, and distribute this Python software\nand its associated documentation for any purpose (subject to the\nrestriction in the following sentence) without fee is hereby granted,\nprovided that the above copyright notice appears in all copies, and\nthat both that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of InfoSeek not be used in\nadvertising or publicity pertaining to distribution of the software\nwithout specific, written prior permission. This permission is\nexplicitly restricted to the copying and modification of the software\nto remain in Python, compiled Python, or other languages (such as C)\nwherein the modified or derived code is exclusively imported into a\nPython module.\nINFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\nSOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY\nSPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER\nRESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF\nCONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\nCONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\nThe profiler was written after only programming in Python for 3 weeks.\nAs a result, it is probably clumsy code, but I don't know for sure yet\n'cause I'm a beginner :-). I did work hard to make the code run fast,\nso that profiling would be a reasonable thing to do. I tried not to\nrepeat code fragments, but I'm sure I did some stuff in really awkward\nways at times. Please send suggestions for improvements to:\njar@netscape.com. I won't promise any support. ...but\nI'd appreciate the feedback.\n---\n#### Footnotes", "python_version": "2.2", "length": 1996, "url": "https://docs.python.org/2.2/lib/profile.html"} {"title": "10.2 How Is This Profiler Different From The Old Profiler?", "text": "Profiler_Introduction.html | profile.html | profile-instant.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.2 How Is This Profiler Different From The Old Profiler?\n(This section is of historical importance only; the old profiler\ndiscussed here was last seen in Python 1.1.)\nThe big changes from old profiling module are that you get more\ninformation, and you pay less CPU time. It's not a trade-off, it's a\ntrade-up.\nTo be specific:\nBugs removed:: Local stack frame is no longer molested, execution time is now charged\nto correct functions.\nAccuracy increased:: Profiler execution time is no longer charged to user's code,\ncalibration for platform is supported, file reads are not done by\nprofiler during profiling (and charged to user's code!).\nSpeed increased:: Overhead CPU cost was reduced by more than a factor of two (perhaps a\nfactor of five), lightweight profiler module is all that must be\nloaded, and the report generating module (pstats) is not needed\nduring profiling.\nRecursive functions support:: Cumulative times in recursive functions are correctly calculated;\nrecursive entries are counted.\nLarge growth in report generating UI:: Distinct profiles runs can be added together forming a comprehensive\nreport; functions that import statistics take arbitrary lists of\nfiles; sorting criteria is now based on keywords (instead of 4 integer\noptions); reports shows what functions were profiled as well as what\nprofile file was referenced; output format has been improved.", "python_version": "2.2", "length": 1523, "url": "https://docs.python.org/2.2/lib/Profiler_Changes.html"} {"title": "10.8 Extensions -- Deriving Better Profilers", "text": "profile-calibration.html | profile.html | profile-old.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.8 Extensions -- Deriving Better Profilers\nThe Profile class of module profile was written so that\nderived classes could be developed to extend the profiler. Rather\nthan describing all the details of such an effort, I'll just present\nthe following two examples of derived classes that can be used to do\nprofiling. If the reader is an avid Python programmer, then it should\nbe possible to use these as a model and create similar (and perchance\nbetter) profile classes.\nIf all you want to do is change how the timer is called, or which\ntimer function is used, then the basic class has an option for that in\nthe constructor for the class. Consider passing the name of a\nfunction to call into the constructor:\n```text\n\npr = profile.Profile(your_time_func)\n```\nThe resulting profiler will call `your_time_func()` instead of\nos.times(). The function should return either a single number\nor a list of numbers (like what os.times() returns). If the\nfunction returns a single time number, or the list of returned numbers\nhas length 2, then you will get an especially fast version of the\ndispatch routine.\nBe warned that you should calibrate the profiler class for the\ntimer function that you choose. For most machines, a timer that\nreturns a lone integer value will provide the best results in terms of\nlow overhead during profiling. (os.times() is\npretty bad, 'cause it returns a tuple of floating point values,\nso all arithmetic is floating point in the profiler!). If you want to\nsubstitute a better timer in the cleanest fashion, you should derive a\nclass, and simply put in the replacement dispatch method that better\nhandles your timer call, along with the appropriate calibration\nconstant :-).", "python_version": "2.2", "length": 1833, "url": "https://docs.python.org/2.2/lib/Profiler_Extensions.html"} {"title": "10.1 Introduction to the profiler", "text": "profile.html | profile.html | Profiler_Changes.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 10.1 Introduction to the profiler\nA profiler is a program that describes the run time performance\nof a program, providing a variety of statistics. This documentation\ndescribes the profiler functionality provided in the modules\nprofile and pstats. This profiler provides\ndeterministic profiling of any Python programs. It also\nprovides a series of report generation tools to allow users to rapidly\nexamine the results of a profile operation.", "python_version": "2.2", "length": 573, "url": "https://docs.python.org/2.2/lib/Profiler_Introduction.html"} {"title": "11.20.6 ProtocolError Objects", "text": "fault-objects.html | module-xmlrpclib.html | node365.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.6 ProtocolError Objects\nA ProtocolError object describes a protocol error in the\nunderlying transport layer (such as a 404 `not found' error if the\nserver named by the URI does not exist). It has the following\nmembers:", "python_version": "2.2", "length": 364, "url": "https://docs.python.org/2.2/lib/protocol-error-objects.html"} {"title": "11.5.9 ProxyBasicAuthHandler Objects", "text": "http-basic-auth-handler.html | module-urllib2.html | abstract-digest-auth-handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.9 ProxyBasicAuthHandler Objects", "python_version": "2.2", "length": 205, "url": "https://docs.python.org/2.2/lib/proxy-basic-auth-handler.html"} {"title": "11.5.12 ProxyDigestAuthHandler Objects", "text": "http-digest-auth-handler.html | module-urllib2.html | http-handler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.12 ProxyDigestAuthHandler Objects", "python_version": "2.2", "length": 200, "url": "https://docs.python.org/2.2/lib/proxy-digest-auth-handler.html"} {"title": "11.5.5 ProxyHandler Objects", "text": "http-redirect-handler.html | module-urllib2.html | http-password-mgr.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.5 ProxyHandler Objects", "python_version": "2.2", "length": 183, "url": "https://docs.python.org/2.2/lib/proxy-handler.html"} {"title": "18.7.1 Class Descriptor Objects", "text": "module-pyclbr.html | module-pyclbr.html | module-pycompile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 18.7.1 Class Descriptor Objects\nThe class descriptor objects used as values in the dictionary returned\nby readmodule() provide the following data members:", "python_version": "2.2", "length": 300, "url": "https://docs.python.org/2.2/lib/pyclbr-class-objects.html"} {"title": "3. Python Runtime Services", "text": "module-exceptions.html | lib.html | module-sys.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 3. Python Runtime Services\nThe modules described in this chapter provide a wide range of services\nrelated to the Python interpreter and its interaction with its\nenvironment. Here's an overview:", "python_version": "2.2", "length": 326, "url": "https://docs.python.org/2.2/lib/python.html"} {"title": "7.15.2 PyZipFile Objects", "text": "zipfile-objects.html | module-zipfile.html | zipinfo-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.15.2 PyZipFile Objects\nThe PyZipFile constructor takes the same parameters as the\nZipFile constructor. Instances have one method in addition to\nthose of ZipFile objects.", "python_version": "2.2", "length": 319, "url": "https://docs.python.org/2.2/lib/pyzipfile-objects.html"} {"title": "17.1.3 Queries on AST Objects", "text": "Converting_ASTs.html | module-parser.html | AST_Errors.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.3 Queries on AST Objects\nTwo functions are provided which allow an application to determine if\nan AST was created as an expression or a suite. Neither of these\nfunctions can be used to determine if an AST was created from source\ncode via expr() or suite() or from a parse tree\nvia sequence2ast().", "python_version": "2.2", "length": 443, "url": "https://docs.python.org/2.2/lib/Querying_ASTs.html"} {"title": "7.6.1 Queue Objects", "text": "module-Queue.html | module-Queue.html | module-mmap.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.6.1 Queue Objects\nClass Queue implements queue objects and has the methods\ndescribed below. This class can be derived from in order to implement\nother queue organizations (e.g. stack) but the inheritable interface\nis not described here. See the source code for details. The public\nmethods are:", "python_version": "2.2", "length": 434, "url": "https://docs.python.org/2.2/lib/QueueObjects.html"} {"title": "4.2.4 Regular Expression Objects", "text": "node99.html | module-re.html | match-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.2.4 Regular Expression Objects\nCompiled regular expression objects support the following methods and\nattributes:", "python_version": "2.2", "length": 246, "url": "https://docs.python.org/2.2/lib/re-objects.html"} {"title": "4.2.1 Regular Expression Syntax", "text": "module-re.html | module-re.html | matching-searching.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.2.1 Regular Expression Syntax\nA regular expression (or RE) specifies a set of strings that matches\nit; the functions in this module let you check if a particular string\nmatches a given regular expression (or if a given regular expression\nmatches a particular string, which comes down to the same thing).\nRegular expressions can be concatenated to form new regular\nexpressions; if A and B are both regular expressions,\nthen AB is also a regular expression. If a string p\nmatches A and another string q matches B, the string pq\nwill match AB if A and B do no specify boundary\nconditions that are no longer satisfied by pq. Thus, complex\nexpressions can easily be constructed from simpler primitive\nexpressions like the ones described here. For details of the theory\nand implementation of regular expressions, consult the Friedl book\nreferenced below, or almost any textbook about compiler construction.\nA brief explanation of the format of regular expressions follows. For\nfurther information and a gentler presentation, consult the Regular\nExpression HOWTO, accessible from http://www.python.org/doc/howto/.\nRegular expressions can contain both special and ordinary characters.\nMost ordinary characters, like \"A\", \"a\", or\n\"0\", are the simplest regular expressions; they simply match\nthemselves. You can concatenate ordinary characters, so last\nmatches the string `'last'`. (In the rest of this section, we'll\nwrite RE's in this special style, usually without quotes, and\nstrings to be matched `'in single quotes'`.)\nSome characters, like \"|\" or \"(\", are special.\nSpecial characters either stand for classes of ordinary characters, or\naffect how the regular expressions around them are interpreted.\nThe special characters are:\nThe special sequences consist of \"\\\" and a character from the\nlist below. If the ordinary character is not on the list, then the\nresulting RE will match the second character. For example,\n\\$ matches the character \"$\".", "python_version": "2.2", "length": 2084, "url": "https://docs.python.org/2.2/lib/re-syntax.html"} {"title": "7.16.1 Example", "text": "module-readline.html | module-readline.html | module-rlcompleter.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.16.1 Example\nThe following example demonstrates how to use the\nreadline module's history reading and writing functions to\nautomatically load and save a history file named .pyhist from\nthe user's home directory. The code below would normally be executed\nautomatically during interactive sessions from the user's\nPYTHONSTARTUP file.", "python_version": "2.2", "length": 484, "url": "https://docs.python.org/2.2/lib/readline-example.html"} {"title": "B. Reporting Bugs", "text": "node618.html | lib.html | node620.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# B. Reporting Bugs\nPython is a mature programming language which has established a\nreputation for stability. In order to maintain this reputation, the\ndevelopers would like to know of any deficiencies you find in Python\nor its documentation.\nAll bug reports should be submitted via the Python Bug Tracker on\nSourceForge (http://sourceforge.net/bugs/?group_id=5470). The\nbug tracker offers a Web form which allows pertinent information to be\nentered and submitted to the developers.\nBefore submitting a report, please log into SourceForge if you are a\nmember; this will make it possible for the developers to contact you\nfor additional information if needed. If you are not a SourceForge\nmember but would not mind the developers contacting you, you may\ninclude your email address in your bug description. In this case,\nplease realize that the information is publically available and cannot\nbe protected.\nThe first step in filing a report is to determine whether the problem\nhas already been reported. The advantage in doing so, aside from\nsaving the developers time, is that you learn what has been done to\nfix it; it may be that the problem has already been fixed for the next\nrelease, or additional information is needed (in which case you are\nwelcome to provide it if you can!). To do this, search the bug\ndatabase using the search box near the bottom of the page.\nIf the problem you're reporting is not already in the bug tracker, go\nback to the Python Bug Tracker\n(http://sourceforge.net/bugs/?group_id=5470). Select the\n``Submit a Bug'' link at the top of the page to open the bug reporting\nform.\nThe submission form has a number of fields. The only fields that are\nrequired are the ``Summary'' and ``Details'' fields. For the summary,\nenter a very short description of the problem; less than ten\nwords is good. In the Details field, describe the problem in detail,\nincluding what you expected to happen and what did happen. Be sure to\ninclude the version of Python you used, whether any extension modules\nwere involved, and what hardware and software platform you were using\n(including version information as appropriate).\nThe only other field that you may want to set is the ``Category''\nfield, which allows you to place the bug report into a broad category\n(such as ``Documentation'' or ``Library'').\nEach bug report will be assigned to a developer who will determine\nwhat needs to be done to correct the problem. If you have a\nSourceForge account and logged in to report the problem, you will\nreceive an update each time action is taken on the bug.\nSee Also:", "python_version": "2.2", "length": 2686, "url": "https://docs.python.org/2.2/lib/reporting-bugs.html"} {"title": "3.25.1 Repr Objects", "text": "module-repr.html | module-repr.html | subclassing-reprs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.25.1 Repr Objects\nRepr instances provide several members which can be used to\nprovide size limits for the representations of different object types,\nand methods which format specific object types.", "python_version": "2.2", "length": 341, "url": "https://docs.python.org/2.2/lib/Repr-objects.html"} {"title": "11.5.1 Request Objects", "text": "module-urllib2.html | module-urllib2.html | opener-director-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.1 Request Objects\nThe following methods describe all of Request's public interface,\nand so all must be overridden in subclasses.", "python_version": "2.2", "length": 288, "url": "https://docs.python.org/2.2/lib/request-objects.html"} {"title": "17. Restricted Execution", "text": "other-gui-packages.html | lib.html | module-rexec.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 17. Restricted Execution\nIn general, Python programs have complete access to the underlying\noperating system throug the various functions and classes, For\nexample, a Python program can open any file for reading and writing by\nusing the open() built-in function (provided the underlying\noperating system gives you permission!). This is exactly what you want\nfor most applications.\nThere exists a class of applications for which this ``openness'' is\ninappropriate. Take Grail: a Web browser that accepts ``applets,''\nsnippets of Python code, from anywhere on the Internet for execution\non the local system. This can be used to improve the user interface\nof forms, for instance. Since the originator of the code is unknown,\nit is obvious that it cannot be trusted with the full resources of the\nlocal machine.\nRestricted execution is the basic framework in Python that allows\nfor the segregation of trusted and untrusted code. It is based on the\nnotion that trusted Python code (a supervisor) can create a\n``padded cell' (or environment) with limited permissions, and run the\nuntrusted code within this cell. The untrusted code cannot break out\nof its cell, and can only interact with sensitive system resources\nthrough interfaces defined and managed by the trusted code. The term\n``restricted execution'' is favored over ``safe-Python''\nsince true safety is hard to define, and is determined by the way the\nrestricted environment is created. Note that the restricted\nenvironments can be nested, with inner cells creating subcells of\nlesser, but never greater, privilege.\nAn interesting aspect of Python's restricted execution model is that\nthe interfaces presented to untrusted code usually have the same names\nas those presented to trusted code. Therefore no special interfaces\nneed to be learned to write code designed to run in a restricted\nenvironment. And because the exact nature of the padded cell is\ndetermined by the supervisor, different restrictions can be imposed,\ndepending on the application. For example, it might be deemed\n``safe'' for untrusted code to read any file within a specified\ndirectory, but never to write a file. In this case, the supervisor\nmay redefine the built-in open() function so that it raises\nan exception whenever the mode parameter is `'w'`. It\nmight also perform a chroot()-like operation on the\nfilename parameter, such that root is always relative to some\nsafe ``sandbox'' area of the filesystem. In this case, the untrusted\ncode would still see an built-in open() function in its\nenvironment, with the same calling interface. The semantics would be\nidentical too, with IOErrors being raised when the\nsupervisor determined that an unallowable parameter is being used.\nThe Python run-time determines whether a particular code block is\nexecuting in restricted execution mode based on the identity of the\n`__builtins__` object in its global variables: if this is (the\ndictionary of) the standard __builtin__ (module-builtin.html) module,\nthe code is deemed to be unrestricted, else it is deemed to be\nrestricted.\nPython code executing in restricted mode faces a number of limitations\nthat are designed to prevent it from escaping from the padded cell.\nFor instance, the function object attribute func_globals and\nthe class and instance object attribute __dict__ are\nunavailable.\nTwo modules provide the framework for setting up restricted execution\nenvironments:\nrexec (module-rexec.html) | Basic restricted execution framework.\nBastion (module-Bastion.html) | Providing restricted access to objects.", "python_version": "2.2", "length": 3673, "url": "https://docs.python.org/2.2/lib/restricted.html"} {"title": "17.1.2 Defining restricted environments", "text": "rexec-objects.html | module-rexec.html | node547.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.2 Defining restricted environments\nThe RExec class has the following class attributes, which are\nused by the __init__() method. Changing them on an existing\ninstance won't have any effect; instead, create a subclass of\nRExec and assign them new values in the class definition.\nInstances of the new class will then use those new values. All these\nattributes are tuples of strings.", "python_version": "2.2", "length": 520, "url": "https://docs.python.org/2.2/lib/rexec-extension.html"} {"title": "17.1.1 RExec Objects", "text": "module-rexec.html | module-rexec.html | rexec-extension.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 17.1.1 RExec Objects\nRExec instances support the following methods:\nMethods whose names begin with \"s_\" are similar to the functions\nbeginning with \"r_\", but the code will be granted access to\nrestricted versions of the standard I/O streams `sys.stdin`,\n`sys.stderr`, and `sys.stdout`.\nRExec objects must also support various methods which will be\nimplicitly called by code executing in the restricted environment.\nOverriding these methods in a subclass is used to change the policies\nenforced by a restricted environment.\nAnd their equivalents with access to restricted standard I/O streams:", "python_version": "2.2", "length": 735, "url": "https://docs.python.org/2.2/lib/rexec-objects.html"} {"title": "7.5.2 RLock Objects", "text": "lock-objects.html | module-threading.html | condition-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.5.2 RLock Objects\nA reentrant lock is a synchronization primitive that may be\nacquired multiple times by the same thread. Internally, it uses\nthe concepts of ``owning thread'' and ``recursion level'' in\naddition to the locked/unlocked state used by primitive locks. In\nthe locked state, some thread owns the lock; in the unlocked\nstate, no thread owns it.\nTo lock the lock, a thread calls its acquire() method; this\nreturns once the thread owns the lock. To unlock the lock, a\nthread calls its release() method.\nacquire()/release() call pairs may be nested; only\nthe final release() (the release() of the outermost\npair) resets the lock to unlocked and allows another thread blocked in\nacquire() to proceed.", "python_version": "2.2", "length": 858, "url": "https://docs.python.org/2.2/lib/rlock-objects.html"} {"title": "13.10.4 ErrorHandler Objects", "text": "entity-resolver-objects.html | module-xml.sax.handler.html | module-xml.sax.saxutils.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.10.4 ErrorHandler Objects\nObjects with this interface are used to receive error and warning\ninformation from the XMLReader. If you create an object that\nimplements this interface, then register the object with your\nXMLReader, the parser will call the methods in your object to\nreport all warnings and errors. There are three levels of errors\navailable: warnings, (possibly) recoverable errors, and unrecoverable\nerrors. All methods take a SAXParseException as the only\nparameter. Errors and warnings may be converted to an exception by\nraising the passed-in exception object.", "python_version": "2.2", "length": 750, "url": "https://docs.python.org/2.2/lib/sax-error-handler.html"} {"title": "13.9.1 SAXException Objects", "text": "module-xml.sax.html | module-xml.sax.html | module-xml.sax.handler.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.9.1 SAXException Objects\nThe SAXException exception class supports the following\nmethods:", "python_version": "2.2", "length": 246, "url": "https://docs.python.org/2.2/lib/sax-exception-objects.html"} {"title": "6.10.1 Scheduler Objects", "text": "module-sched.html | module-sched.html | module-mutex.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.10.1 Scheduler Objects\nscheduler instances have the following methods:", "python_version": "2.2", "length": 212, "url": "https://docs.python.org/2.2/lib/scheduler-objects.html"} {"title": "7.5.4.1 Semaphore Example", "text": "semaphore-objects.html | semaphore-objects.html | event-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 7.5.4.1 Semaphore Example\nSemaphores are often used to guard resources with limited capacity, for\nexample, a database server. In any situation where the size of the resource\nsize is fixed, you should use a bounded semaphore. Before spawning any\nworker threads, your main thread would initialize the semaphore:\n```text\n\nmaxconnections = 5\n...\npool_sema = BoundedSemaphore(value=maxconnections)\n```\nOnce spawned, worker threads call the semaphore's acquire and release\nmethods when they need to connect to the server:\n```text\n\npool_sema.acquire()\nconn = connectdb()\n... use connection ...\nconn.close()\npool_sema.release()\n```\nThe use of a bounded semaphore reduces the chance that a programming error\nwhich causes the semaphore to be released more than it's acquired will go\nundetected.", "python_version": "2.2", "length": 936, "url": "https://docs.python.org/2.2/lib/semaphore-examples.html"} {"title": "7.5.4 Semaphore Objects", "text": "condition-objects.html | module-threading.html | semaphore-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.5.4 Semaphore Objects\nThis is one of the oldest synchronization primitives in the history of\ncomputer science, invented by the early Dutch computer scientist\nEdsger W. Dijkstra (he used P() and V() instead of\nacquire() and release()).\nA semaphore manages an internal counter which is decremented by each\nacquire() call and incremented by each release()\ncall. The counter can never go below zero; when acquire()\nfinds that it is zero, it blocks, waiting until some other thread\ncalls release().", "python_version": "2.2", "length": 650, "url": "https://docs.python.org/2.2/lib/semaphore-objects.html"} {"title": "4.4.1 SequenceMatcher Objects", "text": "module-difflib.html | module-difflib.html | sequencematcher-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.4.1 SequenceMatcher Objects\nThe SequenceMatcher class has this constructor:\nSequenceMatcher objects have the following methods:\nSequenceMatcher computes and caches detailed information about\nthe second sequence, so if you want to compare one sequence against\nmany sequences, use set_seq2() to set the commonly used\nsequence once and call set_seq1() repeatedly, once for each\nof the other sequences.\nThe three methods that return the ratio of matching to total characters\ncan give different results due to differing levels of approximation,\nalthough quick_ratio() and real_quick_ratio() are always\nat least as large as ratio():\n```text\n\n>>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n>>> s.ratio()\n0.75\n>>> s.quick_ratio()\n0.75\n>>> s.real_quick_ratio()\n1.0\n```", "python_version": "2.2", "length": 916, "url": "https://docs.python.org/2.2/lib/sequence-matcher.html"} {"title": "4.4.2 SequenceMatcher Examples", "text": "sequence-matcher.html | module-difflib.html | differ-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 4.4.2 SequenceMatcher Examples\nThis example compares two strings, considering blanks to be ``junk:''\n```text\n\n>>> s = SequenceMatcher(lambda x: x == \" \",\n... \"private Thread currentThread;\",\n... \"private volatile Thread currentThread;\")\n```\nratio() returns a float in [0, 1], measuring the similarity\nof the sequences. As a rule of thumb, a ratio() value over\n0.6 means the sequences are close matches:\n```text\n\n>>> print round(s.ratio(), 3)\n0.866\n```\nIf you're only interested in where the sequences match,\nget_matching_blocks() is handy:\n```text\n\n>>> for block in s.get_matching_blocks():\n... print \"a[%d] and b[%d] match for %d elements\" % block\na[0] and b[0] match for 8 elements\na[8] and b[17] match for 6 elements\na[14] and b[23] match for 15 elements\na[29] and b[38] match for 0 elements\n```\nNote that the last tuple returned by get_matching_blocks() is\nalways a dummy, `(len( a ), len( b ), 0)`, and this is\nthe only case in which the last tuple element (number of elements\nmatched) is `0`.\nIf you want to know how to change the first sequence into the second,\nuse get_opcodes():\n```text\n\n>>> for opcode in s.get_opcodes():\n... print \"%6s a[%d:%d] b[%d:%d]\" % opcode\nequal a[0:8] b[0:8]\ninsert a[8:8] b[8:17]\nequal a[8:14] b[17:23]\nequal a[14:29] b[23:38]\n```\nSee also the function get_close_matches() in this module,\nwhich shows how simple code building on SequenceMatcher can be\nused to do useful work.", "python_version": "2.2", "length": 1560, "url": "https://docs.python.org/2.2/lib/sequencematcher-examples.html"} {"title": "11.20.1 Server Objects", "text": "module-xmlrpclib.html | module-xmlrpclib.html | boolean-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.1 Server Objects\nA Server instance proxy object has a method corresponding to\neach remote procedure call accepted by the XML-RPC server. Calling\nthe method performs an RPC, dispatched by both name and argument\nsignature (e.g. the same method name can be overloaded with multiple\nargument signatures). The RPC finishes by returning a value, which\nmay be either returned data in a conformant type or a Fault or\nProtocolError object indicating an error.\nServers that support the XML introspection API support some common\nmethods grouped under the reserved system member:\nIntrospection methods are currently supported by servers written in\nPHP, C and Microsoft .NET. Partial introspection support is included\nin recent updates to UserLand Frontier. Introspection support for\nPerl, Python and Java is available at the XML-RPC Hacks page.", "python_version": "2.2", "length": 989, "url": "https://docs.python.org/2.2/lib/server-objects.html"} {"title": "20. SGI IRIX Specific Services", "text": "node579.html | lib.html | module-al.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 20. SGI IRIX Specific Services\nThe modules described in this chapter provide interfaces to features\nthat are unique to SGI's IRIX operating system (versions 4 and 5).", "python_version": "2.2", "length": 288, "url": "https://docs.python.org/2.2/lib/sgi.html"} {"title": "5.15.1 shlex Objects", "text": "module-shlex.html | module-shlex.html | allos.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.15.1 shlex Objects\nA shlex instance has the following methods:\nInstances of shlex subclasses have some public instance\nvariables which either control lexical analysis or can be used for\ndebugging:\nNote that any character not declared to be a word character,\nwhitespace, or a quote will be returned as a single-character token.\nQuote and comment characters are not recognized within words. Thus,\nthe bare words \"ain't\" and \"ain#t\" would be returned as single\ntokens by the default parser.", "python_version": "2.2", "length": 622, "url": "https://docs.python.org/2.2/lib/shlex-objects.html"} {"title": "6.23.1 Example", "text": "module-shutil.html | module-shutil.html | module-locale.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 6.23.1 Example\nThis example is the implementation of the copytree()\nfunction, described above, with the docstring omitted. It\ndemonstrates many of the other functions provided by this module.", "python_version": "2.2", "length": 334, "url": "https://docs.python.org/2.2/lib/shutil-example.html"} {"title": "7.1.1 Example", "text": "module-signal.html | module-signal.html | module-socket.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.1.1 Example\nHere is a minimal example program. It uses the alarm()\nfunction to limit the time spent waiting to open a file; this is\nuseful if the file is for a serial device that may not be turned on,\nwhich would normally cause the os.open() to hang\nindefinitely. The solution is to set a 5-second alarm before opening\nthe file; if the operation takes too long, the alarm signal will be\nsent, and the handler raises an exception.", "python_version": "2.2", "length": 574, "url": "https://docs.python.org/2.2/lib/Signal_Example.html"} {"title": "11.21.1 SimpleXMLRPCServer Objects", "text": "module-SimpleXMLRPCServer.html | module-SimpleXMLRPCServer.html | module-asyncore.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.21.1 SimpleXMLRPCServer Objects\nThe SimpleXMLRPCServer class provides two methods that an\napplication can use to register functions that can be called via the\nXML-RPC protocol via the request handler.", "python_version": "2.2", "length": 372, "url": "https://docs.python.org/2.2/lib/simple-xmlrpc-servers.html"} {"title": "11.12.2 SMTP Example", "text": "SMTP-objects.html | module-smtplib.html | module-telnetlib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.12.2 SMTP Example\nThis example prompts the user for addresses needed in the message\nenvelope (`To' and `From' addresses), and the message to be\ndelivered. Note that the headers to be included with the message must\nbe included in the message as entered; this example doesn't do any\nprocessing of the RFC 822 (http://www.faqs.org/rfcs/rfc822.html) headers. In particular, the `To' and\n`From' addresses must be included in the message headers explicitly.", "python_version": "2.2", "length": 600, "url": "https://docs.python.org/2.2/lib/SMTP-example.html"} {"title": "11.12.1 SMTP Objects", "text": "module-smtplib.html | module-smtplib.html | SMTP-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.12.1 SMTP Objects\nAn SMTP instance has the following methods:\nLow-level methods corresponding to the standard SMTP/ESMTP commands\n\"HELP\", \"RSET\", \"NOOP\", \"MAIL\", \"RCPT\", and\n\"DATA\" are also supported. Normally these do not need to be\ncalled directly, so they are not documented here. For details,\nconsult the module code.", "python_version": "2.2", "length": 468, "url": "https://docs.python.org/2.2/lib/SMTP-objects.html"} {"title": "7.2.3 Example", "text": "ssl-objects.html | module-socket.html | module-select.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.2.3 Example\nHere are four minimal example programs using the TCP/IP protocol: a\nserver that echoes all data that it receives back (servicing only one\nclient), and a client using it. Note that a server must perform the\nsequence socket(), bind(), listen(),\naccept() (possibly repeating the accept() to service\nmore than one client), while a client only needs the sequence\nsocket(), connect(). Also note that the server\ndoes not send()/recv() on the\nsocket it is listening on but on the new socket returned by\naccept().\nThe first two examples support IPv4 only.\n```text\n\n# Echo server program\nimport socket\n\nHOST = '' # Symbolic name meaning the local host\nPORT = 50007 # Arbitrary non-privileged port\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((HOST, PORT))\ns.listen(1)\nconn, addr = s.accept()\nprint 'Connected by', addr\nwhile 1:\ndata = conn.recv(1024)\nif not data: break\nconn.send(data)\nconn.close()\n```\n```text\n\n# Echo client program\nimport socket\n\nHOST = 'daring.cwi.nl' # The remote host\nPORT = 50007 # The same port as used by the server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST, PORT))\ns.send('Hello, world')\ndata = s.recv(1024)\ns.close()\nprint 'Received', `data`\n```\nThe next two examples are identical to the above two, but support both\nIPv4 and IPv6.\nThe server side will listen to the first address family available\n(it should listen to both instead).\nOn most of IPv6-ready systems, IPv6 will take precedence\nand the server may not accept IPv4 traffic.\nThe client side will try to connect to the all addresses returned as a result\nof the name resolution, and sends traffic to the first one connected\nsuccessfully.\n```text\n\n# Echo server program\nimport socket\nimport sys\n\nHOST = '' # Symbolic name meaning the local host\nPORT = 50007 # Arbitrary non-privileged port\ns = None\nfor res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):\naf, socktype, proto, canonname, sa = res\ntry:\ns = socket.socket(af, socktype, proto)\nexcept socket.error, msg:\ns = None\ncontinue\ntry:\ns.bind(sa)\ns.listen(1)\nexcept socket.error, msg:\ns.close()\ns = None\ncontinue\nbreak\nif s is None:\nprint 'could not open socket'\nsys.exit(1)\nconn, addr = s.accept()\nprint 'Connected by', addr\nwhile 1:\ndata = conn.recv(1024)\nif not data: break\nconn.send(data)\nconn.close()\n```", "python_version": "2.2", "length": 2482, "url": "https://docs.python.org/2.2/lib/socket-example.html"} {"title": "7.2.1 Socket Objects", "text": "module-socket.html | module-socket.html | ssl-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.2.1 Socket Objects\nSocket objects have the following methods. Except for\nmakefile() these correspond to Unix system calls\napplicable to sockets.\nNote that there are no methods read() or write();\nuse recv() and send() without flags argument\ninstead.", "python_version": "2.2", "length": 391, "url": "https://docs.python.org/2.2/lib/socket-objects.html"} {"title": "7. Optional Operating System Services", "text": "node211.html | lib.html | module-signal.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 7. Optional Operating System Services\nThe modules described in this chapter provide interfaces to operating\nsystem features that are available on selected operating systems only.\nThe interfaces are generally modeled after the Unix or C\ninterfaces but they are available on some other systems as well\n(e.g. Windows or NT). Here's an overview:", "python_version": "2.2", "length": 467, "url": "https://docs.python.org/2.2/lib/someos.html"} {"title": "2.2.10 Special Attributes", "text": "typesinternal.html | types.html | module-exceptions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.10 Special Attributes\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant:", "python_version": "2.2", "length": 273, "url": "https://docs.python.org/2.2/lib/specialattrs.html"} {"title": "7.2.2 SSL Objects", "text": "socket-objects.html | module-socket.html | socket-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.2.2 SSL Objects\nSSL objects have the following methods.", "python_version": "2.2", "length": 202, "url": "https://docs.python.org/2.2/lib/ssl-objects.html"} {"title": "4.8.1.3 StreamReader Objects", "text": "stream-writer-objects.html | node113.html | stream-reader-writer.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 4.8.1.3 StreamReader Objects\nThe StreamReader class is a subclass of Codec and\ndefines the following methods which every stream reader must define in\norder to be compatible to the Python codec registry.\nIn addition to the above methods, the StreamReader must also\ninherit all other methods and attribute from the underlying stream.\nThe next two base classes are included for convenience. They are not\nneeded by the codec registry, but may provide useful in practice.", "python_version": "2.2", "length": 619, "url": "https://docs.python.org/2.2/lib/stream-reader-objects.html"} {"title": "4.8.1.4 StreamReaderWriter Objects", "text": "stream-reader-objects.html | node113.html | stream-recoder-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 4.8.1.4 StreamReaderWriter Objects\nThe StreamReaderWriter allows wrapping streams which work in\nboth read and write modes.\nThe design is such that one can use the factory functions returned by\nthe lookup() function to construct the instance.\nStreamReaderWriter instances define the combined interfaces of\nStreamReader and StreamWriter classes. They inherit\nall other methods and attribute from the underlying stream.", "python_version": "2.2", "length": 571, "url": "https://docs.python.org/2.2/lib/stream-reader-writer.html"} {"title": "4.8.1.5 StreamRecoder Objects", "text": "stream-reader-writer.html | node113.html | module-unicodedata.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 4.8.1.5 StreamRecoder Objects\nThe StreamRecoder provide a frontend - backend view of\nencoding data which is sometimes useful when dealing with different\nencoding environments.\nThe design is such that one can use the factory functions returned by\nthe lookup() function to construct the instance.", "python_version": "2.2", "length": 444, "url": "https://docs.python.org/2.2/lib/stream-recoder-objects.html"} {"title": "4.8.1.2 StreamWriter Objects", "text": "codec-objects.html | node113.html | stream-reader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 4.8.1.2 StreamWriter Objects\nThe StreamWriter class is a subclass of Codec and\ndefines the following methods which every stream writer must define in\norder to be compatible to the Python codec registry.\nIn addition to the above methods, the StreamWriter must also\ninherit all other methods and attribute from the underlying stream.", "python_version": "2.2", "length": 477, "url": "https://docs.python.org/2.2/lib/stream-writer-objects.html"} {"title": "2.2.6.1 String Methods", "text": "typesseq.html | typesseq.html | typesseq-strings.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.6.1 String Methods\nThese are the string methods which both 8-bit strings and Unicode\nobjects support:", "python_version": "2.2", "length": 242, "url": "https://docs.python.org/2.2/lib/string-methods.html"} {"title": "4. String Services", "text": "module-main.html | lib.html | module-string.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 4. String Services\nThe modules described in this chapter provide a wide range of string\nmanipulation operations. Here's an overview:\nstring (module-string.html) | Common string operations.\nre (module-re.html) | Regular expression search and match operations with a\nPerl-style expression syntax.\nstruct (module-struct.html) | Interpret strings as packed binary data.\ndifflib (module-difflib.html) | Helpers for computing differences between objects.\nfpformat (module-fpformat.html) | General floating point formatting functions.\nStringIO (module-StringIO.html) | Read and write strings as if they were files.\ncStringIO (module-cStringIO.html) | Faster version of StringIO, but not\nsubclassable.\ncodecs (module-codecs.html) | Encode and decode data and streams.\nunicodedata (module-unicodedata.html) | Access the Unicode Database.", "python_version": "2.2", "length": 958, "url": "https://docs.python.org/2.2/lib/strings.html"} {"title": "3.25.2 Subclassing Repr Objects", "text": "Repr-objects.html | module-repr.html | module-new.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.25.2 Subclassing Repr Objects\nThe use of dynamic dispatching by Repr.repr1() allows\nsubclasses of Repr to add support for additional built-in\nobject types or to modify the handling of types already supported.\nThis example shows how special support for file objects could be\nadded:", "python_version": "2.2", "length": 419, "url": "https://docs.python.org/2.2/lib/subclassing-reprs.html"} {"title": "21. SunOS Specific Services", "text": "module-jpeg.html | lib.html | module-sunaudiodev.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 21. SunOS Specific Services\nThe modules described in this chapter provide interfaces to features\nthat are unique to the SunOS operating system (versions 4 and 5; the\nlatter is also known as Solaris version 2).", "python_version": "2.2", "length": 344, "url": "https://docs.python.org/2.2/lib/sunos.html"} {"title": "11.13.2 Telnet Example", "text": "telnet-objects.html | module-telnetlib.html | module-urlparse.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.13.2 Telnet Example\nA simple example illustrating typical use:", "python_version": "2.2", "length": 214, "url": "https://docs.python.org/2.2/lib/telnet-example.html"} {"title": "11.13.1 Telnet Objects", "text": "module-telnetlib.html | module-telnetlib.html | telnet-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.13.1 Telnet Objects\nTelnet instances have the following methods:", "python_version": "2.2", "length": 217, "url": "https://docs.python.org/2.2/lib/telnet-objects.html"} {"title": "8.13.1 Template Objects", "text": "module-pipes.html | module-pipes.html | module-posixfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.13.1 Template Objects\nTemplate objects following methods:", "python_version": "2.2", "length": 203, "url": "https://docs.python.org/2.2/lib/template-objects.html"} {"title": "8.8.1 Example", "text": "module-termios.html | module-termios.html | module-TERMIOSuppercase.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 8.8.1 Example\nHere's a function that prompts for a password with echoing turned\noff. Note the technique using a separate tcgetattr() call\nand a try ... finally statement to ensure that the\nold tty attributes are restored exactly no matter what happens:\n```text\n\ndef getpass(prompt = \"Password: \"):\nimport termios, sys\nfd = sys.stdin.fileno()\nold = termios.tcgetattr(fd)\nnew = termios.tcgetattr(fd)\nnew[3] = new[3] & ~termios.ECHO # lflags\ntry:\ntermios.tcsetattr(fd, termios.TCSADRAIN, new)\npasswd = raw_input(prompt)\nfinally:\ntermios.tcsetattr(fd, termios.TCSADRAIN, old)\nreturn passwd\n```", "python_version": "2.2", "length": 744, "url": "https://docs.python.org/2.2/lib/termios_Example.html"} {"title": "5.2.1 Organizing test code", "text": "module-unittest.html | module-unittest.html | legacy-unit-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.1 Organizing test code\nThe basic building blocks of unit testing are test cases --\nsingle scenarios that must be set up and checked for correctness. In\nPyUnit, test cases are represented by instances of the\nTestCase class in the unittest (module-unittest.html) module. To make\nyour own test cases you must write subclasses of TestCase, or\nuse FunctionTestCase.\nAn instance of a TestCase-derived class is an object that can\ncompletely run a single test method, together with optional set-up\nand tidy-up code.\nThe testing code of a TestCase instance should be entirely\nself contained, such that it can be run either in isolation or in\narbitrary combination with any number of other test cases.\nThe simplest test case subclass will simply override the\nrunTest() method in order to perform specific testing code:\n```text\n\nimport unittest\n\nclass DefaultWidgetSizeTestCase(unittest.TestCase):\ndef runTest(self):\nwidget = Widget(\"The widget\")\nself.failUnless(widget.size() == (50,50), 'incorrect default size')\n```\nNote that in order to test something, we use the one of the\nassert*() or fail*() methods provided by the\nTestCase base class. If the test fails when the test case\nruns, an exception will be raised, and the testing framework will\nidentify the test case as a failure. Other exceptions that do\nnot arise from checks made through the assert*() and\nfail*() methods are identified by the testing framework as\ndfnerrors.\nThe way to run a test case will be described later. For now, note\nthat to construct an instance of such a test case, we call its\nconstructor without arguments:\n```text\n\ntestCase = DefaultWidgetSizeTestCase()\n```\nNow, such test cases can be numerous, and their set-up can be\nrepetitive. In the above case, constructing a ``Widget'' in each of\n100 Widget test case subclasses would mean unsightly duplication.\nLuckily, we can factor out such set-up code by implementing a method\ncalled setUp(), which the testing framework will\nautomatically call for us when we run the test:\n```text\n\nimport unittest\n\nclass SimpleWidgetTestCase(unittest.TestCase):\ndef setUp(self):\nself.widget = Widget(\"The widget\")\n\nclass DefaultWidgetSizeTestCase(SimpleWidgetTestCase):\ndef runTest(self):\nself.failUnless(self.widget.size() == (50,50),\n'incorrect default size')\n\nclass WidgetResizeTestCase(SimpleWidgetTestCase):\ndef runTest(self):\nself.widget.resize(100,150)\nself.failUnless(self.widget.size() == (100,150),\n'wrong size after resize')\n```\nIf the setUp() method raises an exception while the test is\nrunning, the framework will consider the test to have suffered an\nerror, and the runTest() method will not be executed.\nSimilarly, we can provide a tearDown() method that tidies up\nafter the runTest() method has been run:\n```text\n\nimport unittest\n\nclass SimpleWidgetTestCase(unittest.TestCase):\ndef setUp(self):\nself.widget = Widget(\"The widget\")\n\ndef tearDown(self):\nself.widget.dispose()\nself.widget = None\n```\nIf setUp() succeeded, the tearDown() method will be\nrun regardless of whether or not runTest() succeeded.\nSuch a working environment for the testing code is called a\nfixture.\nOften, many small test cases will use the same fixture. In this case,\nwe would end up subclassing SimpleWidgetTestCase into many\nsmall one-method classes such as\nDefaultWidgetSizeTestCase. This is time-consuming and\ndiscouraging, so in the same vein as JUnit, PyUnit provides a simpler\nmechanism:\n```text\n\nimport unittest\n\nclass WidgetTestCase(unittest.TestCase):\ndef setUp(self):\nself.widget = Widget(\"The widget\")\n\ndef tearDown(self):\nself.widget.dispose()\nself.widget = None\n\ndef testDefaultSize(self):\nself.failUnless(self.widget.size() == (50,50),\n'incorrect default size')\n\ndef testResize(self):\nself.widget.resize(100,150)\nself.failUnless(self.widget.size() == (100,150),\n'wrong size after resize')\n```\nHere we have not provided a runTest() method, but have\ninstead provided two different test methods. Class instances will now\neach run one of the test*() methods, with `self.widget`\ncreated and destroyed separately for each instance. When creating an\ninstance we must specify the test method it is to run. We do this by\npassing the method name in the constructor:\n```text\n\ndefaultSizeTestCase = WidgetTestCase(\"testDefaultSize\")\nresizeTestCase = WidgetTestCase(\"testResize\")\n```\nTest case instances are grouped together according to the features\nthey test. PyUnit provides a mechanism for this: the test\nsuite, represented by the class TestSuite in the\nunittest (module-unittest.html) module:\n```text\n\nwidgetTestSuite = unittest.TestSuite()\nwidgetTestSuite.addTest(WidgetTestCase(\"testDefaultSize\"))\nwidgetTestSuite.addTest(WidgetTestCase(\"testResize\"))\n```\nFor the ease of running tests, as we will see later, it is a good\nidea to provide in each test module a callable object that returns a\npre-built test suite:\n```text\n\ndef suite():\nsuite = unittest.TestSuite()\nsuite.addTest(WidgetTestCase(\"testDefaultSize\"))\nsuite.addTest(WidgetTestCase(\"testResize\"))\nreturn suite\n```\nor even:\n```text\n\nclass WidgetTestSuite(unittest.TestSuite):\ndef __init__(self):\nunittest.TestSuite.__init__(self,map(WidgetTestCase,\n(\"testDefaultSize\",\n\"testResize\")))\n```\n(The latter is admittedly not for the faint-hearted!)\nSince it is a common pattern to create a TestCase subclass\nwith many similarly named test functions, there is a convenience\nfunction called makeSuite() provided in the\nunittest (module-unittest.html) module that constructs a test suite that\ncomprises all of the test cases in a test case class:\n```text\n\nsuite = unittest.makeSuite(WidgetTestCase,'test')\n```\nNote that when using the makeSuite() function, the order in\nwhich the various test cases will be run by the test suite is the\norder determined by sorting the test function names using the\ncmp() built-in function.\nOften it is desirable to group suites of test cases together, so as to\nrun tests for the whole system at once. This is easy, since\nTestSuite instances can be added to a TestSuite just\nas TestCase instances can be added to a TestSuite:\n```text\n\nsuite1 = module1.TheTestSuite()\nsuite2 = module2.TheTestSuite()\nalltests = unittest.TestSuite((suite1, suite2))\n```\nYou can place the definitions of test cases and test suites in the\nsame modules as the code they are to test (e.g. widget.py),\nbut there are several advantages to placing the test code in a\nseparate module, such as widgettests.py:\n- The test module can be run standalone from the command line.\n- The test code can more easily be separated from shipped code.\n- There is less temptation to change test code to fit the code.\nit tests without a good reason.\n- Test code should be modified much less frequently than the\ncode it tests.\n- Tested code can be refactored more easily.\n- Tests for modules written in C must be in separate modules\nanyway, so why not be consistent?\n- If the testing strategy changes, there is no need to change\nthe source code.", "python_version": "2.2", "length": 7042, "url": "https://docs.python.org/2.2/lib/test-concept-classes.html"} {"title": "5.3.4 TestCase Objects", "text": "unittest-contents.html | module-unittest.html | testsuite-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.3.4 TestCase Objects\nEach TestCase instance represents a single test, but each\nconcrete subclass may be used to define multiple tests -- the\nconcrete class represents a single test fixture. The fixture is\ncreated and cleaned up for each test case.\nTestCase instances provide three groups of methods: one group\nused to run the test, another used by the test implementation to\ncheck conditions and report failures, and some inquiry methods\nallowing information about the test itself to be gathered.\nMethods in the first group are:\nThe test code can use any of the following methods to check for and\nreport failures.\nTesting frameworks can use the following methods to collect\ninformation on the test:", "python_version": "2.2", "length": 853, "url": "https://docs.python.org/2.2/lib/testcase-objects.html"} {"title": "5.3.7 TestLoader Objects", "text": "testresult-objects.html | module-unittest.html | module-math.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.3.7 TestLoader Objects\nThe TestLoader class is used to create test suites from\nclasses and modules. Normally, there is no need to create an instance\nof this class; the unittest (module-unittest.html) module provides an instance\nthat can be shared as the `defaultTestLoader` module attribute.\nUsing a subclass or instance would allow customization of some\nconfigurable properties.\nTestLoader objects have the following methods:\nThe following attributes of a TestLoader can be configured\neither by subclassing or assignment on an instance:", "python_version": "2.2", "length": 687, "url": "https://docs.python.org/2.2/lib/testloader-objects.html"} {"title": "5.3.6 TestResult Objects", "text": "testsuite-objects.html | module-unittest.html | testloader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.3.6 TestResult Objects\nA TestResult object stores the results of a set of tests. The\nTestCase and TestSuite classes ensure that results are\nproperly stored; test authors do not need to worry about recording the\noutcome of tests.\nTesting frameworks built on top of unittest (module-unittest.html) may want\naccess to the TestResult object generated by running a set of\ntests for reporting purposes; a TestResult instance is\nreturned by the TestRunner.run() method for this purpose.\nEach instance holds the total number of tests run, and collections of\nfailures and errors that occurred among those test runs. The\ncollections contain tuples of `( testcase , exceptioninfo )`, where exceptioninfo is a tuple as\nreturned by sys.exc_info().\nTestResult instances have the following attributes that will\nbe of interest when inspecting the results of running a set of tests:\nThe following methods of the TestResult class are used to\nmaintain the internal data structures, and mmay be extended in\nsubclasses to support additional reporting requirements. This is\nparticularly useful in building tools which support interactive\nreporting while tests are being run.\nOne additional method is available for TestResult objects:", "python_version": "2.2", "length": 1367, "url": "https://docs.python.org/2.2/lib/testresult-objects.html"} {"title": "5.2.7 TestLoader Objects", "text": "testresult-objects.html | module-unittest.html | module-math.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.2.7 TestLoader Objects\nThe TestLoader class is used to create test suites from\nclasses and modules. Normally, there is no need to create an instance\nof this class; the unittest (module-unittest.html) module provides an instance\nthat can be shared as the `defaultTestLoader` module attribute.\nUsing a subclass or instance would allow customization of some\nconfigurable properties.\nTestLoader objects have the following methods:\nThe following attributes of a TestLoader can be configured\neither by subclassing or assignment on an instance:", "python_version": "2.2", "length": 687, "url": "https://docs.python.org/2.2/lib/testrunner-objects.html"} {"title": "5.3.5 TestSuite Objects", "text": "testcase-objects.html | module-unittest.html | testresult-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.3.5 TestSuite Objects\nTestSuite objects behave much like TestCase objects,\nexcept they do not actually implement a test. Instead, they are used\nto aggregate tests into groups that should be run together. Some\nadditional methods are available to add tests to TestSuite\ninstances:\nThe run() method is also slightly different:\nIn the typical usage of a TestSuite object, the run()\nmethod is invoked by a TestRunner rather than by the end-user\ntest harness.", "python_version": "2.2", "length": 608, "url": "https://docs.python.org/2.2/lib/testsuite-objects.html"} {"title": "7.5.6 Thread Objects", "text": "event-objects.html | module-threading.html | timer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.5.6 Thread Objects\nThis class represents an activity that is run in a separate thread\nof control. There are two ways to specify the activity: by\npassing a callable object to the constructor, or by overriding the\nrun() method in a subclass. No other methods (except for the\nconstructor) should be overridden in a subclass. In other words,\nonly override the __init__() and run()\nmethods of this class.\nOnce a thread object is created, its activity must be started by\ncalling the thread's start() method. This invokes the\nrun() method in a separate thread of control.\nOnce the thread's activity is started, the thread is considered\n'alive' and 'active' (these concepts are almost, but not quite\nexactly, the same; their definition is intentionally somewhat\nvague). It stops being alive and active when its run()\nmethod terminates - either normally, or by raising an unhandled\nexception. The isAlive() method tests whether the thread is\nalive.\nOther threads can call a thread's join() method. This blocks\nthe calling thread until the thread whose join() method is\ncalled is terminated.\nA thread has a name. The name can be passed to the constructor,\nset with the setName() method, and retrieved with the\ngetName() method.\nA thread can be flagged as a ``daemon thread''. The significance\nof this flag is that the entire Python program exits when only\ndaemon threads are left. The initial value is inherited from the\ncreating thread. The flag can be set with the setDaemon()\nmethod and retrieved with the isDaemon() method.\nThere is a ``main thread'' object; this corresponds to the\ninitial thread of control in the Python program. It is not a\ndaemon thread.\nThere is the possibility that ``dummy thread objects'' are\ncreated. These are thread objects corresponding to ``alien\nthreads''. These are threads of control started outside the\nthreading module, such as directly from C code. Dummy thread objects\nhave limited functionality; they are always considered alive,\nactive, and daemonic, and cannot be join()ed. They are never\ndeleted, since it is impossible to detect the termination of alien\nthreads.", "python_version": "2.2", "length": 2246, "url": "https://docs.python.org/2.2/lib/thread-objects.html"} {"title": "7.5.7 Timer Objects", "text": "thread-objects.html | module-threading.html | module-Queue.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.5.7 Timer Objects\nThis class represents an action that should be run only after a certain amount\nof time has passed -- a timer. Timer is a subclass of Thread and\nas such also functions as an example of creating custom threads.\nTimers are started, as with threads, by calling their start() method. The\ntimer can be stopped (before its action has begun) by calling the\ncancel() method. The interval the timer will wait before executing\nits action may not be exactly the same as the interval specified by the\nuser.\nFor example:\n```text\n\ndef hello():\nprint \"hello, world\"\n\nt = Timer(30.0, hello)\nt.start() # after 30 seconds, \"hello, world\" will be printed\n```", "python_version": "2.2", "length": 804, "url": "https://docs.python.org/2.2/lib/timer-objects.html"} {"title": "16.1.4 Mapping Basic Tk into Tkinter", "text": "node504.html | module-Tkinter.html | node506.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 16.1.4 Mapping Basic Tk into Tkinter\nClass commands in Tk correspond to class constructors in Tkinter.\n```text\n\nbutton .fred =====> fred = Button()\n```\nThe master of an object is implicit in the new name given to it at\ncreation time. In Tkinter, masters are specified explicitly.\n```text\n\nbutton .panel.fred =====> fred = Button(panel)\n```\nThe configuration options in Tk are given in lists of hyphened tags\nfollowed by values. In Tkinter, options are specified as\nkeyword-arguments in the instance constructor, and keyword-args for\nconfigure calls or as instance indices, in dictionary style, for\nestablished instances. See section 16.1.6 (tkinter-setting-options.html#tkinter-setting-options) on\nsetting options.\n```text\n\nbutton .fred -fg red =====> fred = Button(panel, fg = \"red\")\n.fred configure -fg red =====> fred[\"fg\"] = red\nOR ==> fred.config(fg = \"red\")\n```\nIn Tk, to perform an action on a widget, use the widget name as a\ncommand, and follow it with an action name, possibly with arguments\n(options). In Tkinter, you call methods on the class instance to\ninvoke actions on the widget. The actions (methods) that a given\nwidget can perform are listed in the Tkinter.py module.\n```text\n\n.fred invoke =====> fred.invoke()\n```\nTo give a widget to the packer (geometry manager), you call pack with\noptional arguments. In Tkinter, the Pack class holds all this\nfunctionality, and the various forms of the pack command are\nimplemented as methods. All widgets in Tkinter (module-Tkinter.html) are\nsubclassed from the Packer, and so inherit all the packing\nmethods. See the Tix (module-Tix.html) module documentation for additional\ninformation on the Form geometry manager.\n```text\n\npack .fred -side left =====> fred.pack(side = \"left\")\n```", "python_version": "2.2", "length": 1875, "url": "https://docs.python.org/2.2/lib/tkinter-basic-mapping.html"} {"title": "16.1.6.1 Setting Options", "text": "node507.html | node507.html | node509.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 16.1.6.1 Setting Options\nOptions control things like the color and border width of a widget.\nOptions can be set in three ways:\nAt object creation time, using keyword arguments: :\n```text\n\nfred = Button(self, fg = \"red\", bg = \"blue\")\n```\nAfter object creation, treating the option name like a dictionary index: :\n```text\n\nfred[\"fg\"] = \"red\"\nfred[\"bg\"] = \"blue\"\n```\nUse the config() method to update multiple attrs subesequent to\nobject creation: :\n```text\n\nfred.config(fg = \"red\", bg = \"blue\")\n```\nFor a complete explanation of a given option and its behavior, see the\nTk man pages for the widget in question.\nNote that the man pages list \"STANDARD OPTIONS\" and \"WIDGET SPECIFIC\nOPTIONS\" for each widget. The former is a list of options that are\ncommon to many widgets, the latter are the options that are\nideosyncratic to that particular widget. The Standard Options are\ndocumented on the options(3) man page.\nNo distinction between standard and widget-specific options is made in\nthis document. Some options don't apply to some kinds of widgets.\nWhether a given widget responds to a particular option depends on the\nclass of the widget; buttons have a `command` option, labels do not.\nThe options supported by a given widget are listed in that widget's\nman page, or can be queried at runtime by calling the\nconfig() method with arguments, or by calling the keys()\nmethod on that widget. The return value of these calls is a dictionary\nwhose key is the name of the option (e.g. relief) and whose\nvalues are 5 tuples.\n(Some options, like bg are synonyms for common options with\nhard-to-type names (bg is shorthand for \"background\").\nPassing the config() method the name of a\nshorthand option will return a 2-tuple, not 5-tuple. The 2-tuple\npassed back will contain the name of the synonym ``real''\noption. (bg, background))\nExample:\n```text\n\n>>> print fred.config()\n{'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}\n```\nOf course, the dictionary printed will include all the options\navailable and their values. This is meant only as an example.", "python_version": "2.2", "length": 2183, "url": "https://docs.python.org/2.2/lib/tkinter-setting-options.html"} {"title": "16. Graphical User Interfaces with Tk", "text": "module-rotor.html | lib.html | module-Tkinter.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 16. Graphical User Interfaces with Tk\nTk/Tcl has long been an integral part of Python. It provides a robust\nand platform independent windowing toolkit, that is available to\nPython programmers using the Tkinter (module-Tkinter.html) module, and its\nextension, the Tix (module-Tix.html) module.\nThe Tkinter (module-Tkinter.html) module is a thin object-oriented layer on top of\nTcl/Tk. To use Tkinter (module-Tkinter.html), you don't need to write Tcl code,\nbut you will need to consult the Tk documentation, and occasionally\nthe Tcl documentation. Tkinter (module-Tkinter.html) is a set of wrappers that\nimplement the Tk widgets as Python classes. In addition, the internal\nmodule _tkinter provides a threadsafe mechanism which allows\nPython and Tcl to interact.\nTk is not the only GUI for Python, but is however the most commonly\nused one; see section #other-gui-modules, ``Other User Interface\nModules and Packages,'' for more information on other GUI toolkits for\nPython.\nTkinter (module-Tkinter.html) | Interface to Tcl/Tk for graphical user interfaces\nTix (module-Tix.html) | Tk Extension Widgets for Tkinter\nScrolledText (module-ScrolledText.html) | Text widget with a vertical scroll bar.\nturtle (module-turtle.html) | An environment for turtle graphics.", "python_version": "2.2", "length": 1392, "url": "https://docs.python.org/2.2/lib/tkinter.html"} {"title": "3.12.1 Traceback Example", "text": "module-traceback.html | module-traceback.html | module-linecache.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.12.1 Traceback Example\nThis simple example implements a basic read-eval-print loop, similar\nto (but less useful than) the standard Python interactive interpreter\nloop. For a more complete implementation of the interpreter loop,\nrefer to the code (module-code.html) module.", "python_version": "2.2", "length": 426, "url": "https://docs.python.org/2.2/lib/traceback-example.html"} {"title": "2.2.1 Truth Value Testing", "text": "types.html | types.html | boolean.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.1 Truth Value Testing\nAny object can be tested for truth value, for use in an if or\nwhile condition or as operand of the Boolean operations below.\nThe following values are considered false:\n- `None`\n- zero of any numeric type, for example, `0`, `0L`,\n`0.0`, `0j`.\n- any empty sequence, for example, `''`, `()`, `[]`.\n- any empty mapping, for example, `{}`.\n- instances of user-defined classes, if the class defines a\n__nonzero__() or __len__() method, when that\nmethod returns zero.2.5 (#foot2493)\nAll other values are considered true -- so objects of many types are\nalways true.\nOperations and built-in functions that have a Boolean result always\nreturn `0` for false and `1` for true, unless otherwise\nstated. (Important exception: the Boolean operations\n\"or\"and \"and\"always return one of\ntheir operands.)", "python_version": "2.2", "length": 932, "url": "https://docs.python.org/2.2/lib/truth.html"} {"title": "2.2.5 Iterator Types", "text": "bitstring-ops.html | types.html | typesseq.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.5 Iterator Types\nNew in version 2.2.\nPython supports a concept of iteration over containers. This is\nimplemented using two distinct methods; these are used to allow\nuser-defined classes to support iteration. Sequences, described below\nin more detail, always support the iteration methods.\nOne method needs to be defined for container objects to provide\niteration support:\nThe iterator objects themselves are required to support the following\ntwo methods, which together form the iterator protocol:\nPython defines several iterator objects to support iteration over\ngeneral and specific sequence types, dictionaries, and other more\nspecialized forms. The specific types are not important beyond their\nimplementation of the iterator protocol.", "python_version": "2.2", "length": 873, "url": "https://docs.python.org/2.2/lib/typeiter.html"} {"title": "2.2 Built-in Types", "text": "built-in-funcs.html | builtin.html | truth.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 2.2 Built-in Types\nThe following sections describe the standard types that are built into\nthe interpreter. These are the numeric types, sequence types, and\nseveral others, including types themselves. There is no explicit\nBoolean type; use integers instead.\nSome operations are supported by several object types; in particular,\nall objects can be compared, tested for truth value, and converted to\na string (with the `` ...`` notation). The latter\nconversion is implicitly used when an object is written by the\nprintstatement.", "python_version": "2.2", "length": 654, "url": "https://docs.python.org/2.2/lib/types.html"} {"title": "2.2.9.3 Functions", "text": "typesobjects.html | typesother.html | typesmethods.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.3 Functions\nFunction objects are created by function definitions. The only\noperation on a function object is to call it:\n`func ( argument-list )`.\nThere are really two flavors of function objects: built-in functions\nand user-defined functions. Both support the same operation (to call\nthe function), but the implementation is different, hence the\ndifferent object types.\nThe implementation adds two special read-only attributes:\n`f .func_code` is a function's code\nobject(see below) and `f .func_globals` is\nthe dictionary used as the function's global namespace (this is the\nsame as `m .__dict__` where m is the module in which\nthe function f was defined).\nFunction objects also support getting and setting arbitrary\nattributes, which can be used to, e.g. attach metadata to functions.\nRegular attribute dot-notation is used to get and set such\nattributes. Note that the current implementation only supports\nfunction attributes on user-defined functions. Function attributes on\nbuilt-in functions may be supported in the future.\nFunctions have another special attribute `f .__dict__`\n(a.k.a. `f .func_dict`) which contains the namespace used to\nsupport function attributes. `__dict__` and `func_dict` can\nbe accessed directly or set to a dictionary object. A function's\ndictionary cannot be deleted.", "python_version": "2.2", "length": 1445, "url": "https://docs.python.org/2.2/lib/typesfunctions.html"} {"title": "2.2.9.9 Internal Objects", "text": "bltin-ellipsis-object.html | typesother.html | specialattrs.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.9 Internal Objects\nSee the Python Reference Manual (../ref/ref.html) for this\ninformation. It describes stack frame objects, traceback objects, and\nslice objects.", "python_version": "2.2", "length": 316, "url": "https://docs.python.org/2.2/lib/typesinternal.html"} {"title": "2.2.7 Mapping Types", "text": "typesseq-mutable.html | types.html | bltin-file-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.7 Mapping Types\nA mapping object maps values of one type (the key type) to\narbitrary objects. Mappings are mutable objects. There is currently\nonly one standard mapping type, the dictionary. A dictionary's keys are\nalmost arbitrary values. The only types of values not acceptable as\nkeys are values containing lists or dictionaries or other mutable\ntypes that are compared by value rather than by object identity.\nNumeric types used for keys obey the normal rules for numeric\ncomparison: if two numbers compare equal (e.g. `1` and\n`1.0`) then they can be used interchangeably to index the same\ndictionary entry.\nDictionaries are created by placing a comma-separated list of\n`key : value` pairs within braces, for example:\n`{'jack': 4098, 'sjoerd': 4127}` or\n`{4098: 'jack', 4127: 'sjoerd'}`.\nThe following operations are defined on mappings (where a and\nb are mappings, k is a key, and v and x are\narbitrary objects):\nNotes:\n(1): Raises a KeyError exception if k is not\nin the map.\n(2): New in version 2.2.\n(3): Keys and values are listed in random order. If\nkeys() and values() are called with no intervening\nmodifications to the dictionary, the two lists will directly\ncorrespond. This allows the creation of `( value , key )` pairs using zip(): \"pairs =\nzip(a.values(), a.keys())\".\n(4): Never raises an exception if k is not in the map,\ninstead it returns x. x is optional; when x is not\nprovided and k is not in the map, `None` is returned.\n(5): setdefault() is like get(), except\nthat if k is missing, x is both returned and inserted into\nthe dictionary as the value of k.\n(6): popitem() is useful to destructively iterate\nover a dictionary, as often used in set algorithms.", "python_version": "2.2", "length": 1826, "url": "https://docs.python.org/2.2/lib/typesmapping.html"} {"title": "2.2.9.4 Methods", "text": "typesfunctions.html | typesother.html | bltin-code-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.4 Methods\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as append() on\nlists) and class instance methods. Built-in methods are described\nwith the types that support them.\nThe implementation adds two special read-only attributes to class\ninstance methods: `m .im_self` is the object on which the\nmethod operates, and `m .im_func` is the function\nimplementing the method. Calling `m ( arg-1 , arg-2 , ..., arg-n )` is completely equivalent to\ncalling `m .im_func( m .im_self, arg-1 , arg-2 , ..., arg-n )`.\nClass instance methods are either bound or unbound,\nreferring to whether the method was accessed through an instance or a\nclass, respectively. When a method is unbound, its `im_self`\nattribute will be `None` and if called, an explicit `self`\nobject must be passed as the first argument. In this case,\n`self` must be an instance of the unbound method's class (or a\nsubclass of that class), otherwise a `TypeError` is raised.\nLike function objects, methods objects support getting\narbitrary attributes. However, since method attributes are actually\nstored on the underlying function object (`meth.im_func`),\nsetting method attributes on either bound or unbound methods is\ndisallowed. Attempting to set a method attribute results in a\n`TypeError` being raised. In order to set a method attribute,\nyou need to explicitly set it on the underlying function object:\n```text\n\nclass C:\ndef method(self):\npass\n\nc = C()\nc.method.im_func.whoami = 'my name is c'\n```\nSee the Python Reference Manual (../ref/ref.html) for more\ninformation.", "python_version": "2.2", "length": 1751, "url": "https://docs.python.org/2.2/lib/typesmethods.html"} {"title": "2.2.9.1 Modules", "text": "typesother.html | typesother.html | typesobjects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.1 Modules\nThe only special operation on a module is attribute access:\n`m . name`, where m is a module and name\naccesses a name defined in m's symbol table. Module attributes\ncan be assigned to. (Note that the import statement is not,\nstrictly speaking, an operation on a module object; `import foo` does not require a module object named foo to exist,\nrather it requires an (external) definition for a module named\nfoo somewhere.)\nA special member of every module is __dict__.\nThis is the dictionary containing the module's symbol table.\nModifying this dictionary will actually change the module's symbol\ntable, but direct assignment to the __dict__ attribute is not\npossible (you can write `m .__dict__['a'] = 1`, which\ndefines `m .a` to be `1`, but you can't write\n`m .__dict__ = {}`.\nModules built into the interpreter are written like this:\n``. If loaded from a file, they are\nwritten as ``.", "python_version": "2.2", "length": 1115, "url": "https://docs.python.org/2.2/lib/typesmodules.html"} {"title": "2.2.4 Numeric Types", "text": "comparisons.html | types.html | bitstring-ops.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.4 Numeric Types\nThere are four numeric types: plain integers, long integers,\nfloating point numbers, and complex numbers.\nPlain integers (also just called integers)\nare implemented using long in C, which gives them at least 32\nbits of precision. Long integers have unlimited precision. Floating\npoint numbers are implemented using double in C. All bets on\ntheir precision are off unless you happen to know the machine you are\nworking with.\nComplex numbers have a real and imaginary part, which are both\nimplemented using double in C. To extract these parts from\na complex number z, use `z .real` and `z .imag`.\nNumbers are created by numeric literals or as the result of built-in\nfunctions and operators. Unadorned integer literals (including hex\nand octal numbers) yield plain integers. Integer literals with an\n\"L\" or \"l\" suffix yield long integers\n(\"L\" is preferred because \"1l\" looks too much like\neleven!). Numeric literals containing a decimal point or an exponent\nsign yield floating point numbers. Appending \"j\" or\n\"J\" to a numeric literal yields a complex number.\nPython fully supports mixed arithmetic: when a binary arithmetic\noperator has operands of different numeric types, the operand with the\n``smaller'' type is converted to that of the other, where plain\ninteger is smaller than long integer is smaller than floating point is\nsmaller than complex.\nComparisons between numbers of mixed type use the same rule.2.6 (#foot2513) The functions int(), long(), float(),\nand complex() can be used\nto coerce numbers to a specific type.\nAll numeric types support the following operations, sorted by\nascending priority (operations in the same box have the same\npriority; all numeric operations have a higher priority than\ncomparison operations):\nNotes:\n(1): For (plain or long) integer division, the result is an integer.\nThe result is always rounded towards minus infinity: 1/2 is 0,\n(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result\nis a long integer if either operand is a long integer, regardless of\nthe numeric value.\n(2): Conversion from floating point to (long or plain) integer may round or\ntruncate as in C; see functions floor() and\nceil() in the math (module-math.html)module\nfor well-defined conversions.\n(3): See section 2.1 (built-in-funcs.html#built-in-funcs), ``Built-in Functions,'' for a full\ndescription.\n---\n#### Footnotes", "python_version": "2.2", "length": 2504, "url": "https://docs.python.org/2.2/lib/typesnumeric.html"} {"title": "2.2.9.2 Classes and Class Instances", "text": "typesmodules.html | typesother.html | typesfunctions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.9.2 Classes and Class Instances\nSee chapters 3 and 7 of the Python\nReference Manual (../ref/ref.html) for these.", "python_version": "2.2", "length": 257, "url": "https://docs.python.org/2.2/lib/typesobjects.html"} {"title": "2.2.9 Other Built-in Types", "text": "bltin-file-objects.html | types.html | typesmodules.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.9 Other Built-in Types\nThe interpreter supports several other kinds of objects.\nMost of these support only one or two operations.", "python_version": "2.2", "length": 272, "url": "https://docs.python.org/2.2/lib/typesother.html"} {"title": "2.2.6.4 Mutable Sequence Types", "text": "typesseq-xrange.html | typesseq.html | typesmapping.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.6.4 Mutable Sequence Types\nList objects support additional operations that allow in-place\nmodification of the object.\nThese operations would be supported by other mutable sequence types\n(when added to the language) as well.\nStrings and tuples are immutable sequence types and such objects cannot\nbe modified once created.\nThe following operations are defined on mutable sequence types (where\nx is an arbitrary object):\nNotes:\n(1): The C implementation of Python has historically accepted\nmultiple parameters and implicitly joined them into a tuple; this\nno longer works in Python 2.0. Use of this misfeature has been\ndeprecated since Python 1.4.\n(2): Raises an exception when x is not a list object. The\nextend() method is experimental and not supported by\nmutable sequence types other than lists.\n(3): Raises ValueError when x is not found in\ns.\n(4): When a negative index is passed as the first parameter to\nthe insert() method, the new element is prepended to the\nsequence.\n(5): The pop() method is only supported by the list and\narray types. The optional argument i defaults to `-1`,\nso that by default the last item is removed and returned.\n(6): The sort() and reverse() methods modify the\nlist in place for economy of space when sorting or reversing a large\nlist. To remind you that they operate by side effect, they don't return\nthe sorted or reversed list.\n(7): The sort() method takes an optional argument\nspecifying a comparison function of two arguments (list items) which\nshould return a negative, zero or positive number depending on whether\nthe first argument is considered smaller than, equal to, or larger\nthan the second argument. Note that this slows the sorting process\ndown considerably; e.g. to sort a list in reverse order it is much\nfaster to use calls to the methods sort() and\nreverse() than to use the built-in function\nsort() with a comparison function that reverses the\nordering of the elements.", "python_version": "2.2", "length": 2067, "url": "https://docs.python.org/2.2/lib/typesseq-mutable.html"} {"title": "2.2.6.2 String Formatting Operations", "text": "string-methods.html | typesseq.html | typesseq-xrange.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.6.2 String Formatting Operations\nString and Unicode objects have one unique built-in operation: the\n`%` operator (modulo). Given `format % values` (where format is a string or Unicode object),\n`%` conversion specifications in format are replaced with\nzero or more elements of values. The effect is similar to the\nusing sprintf() in the C language. If format is a\nUnicode object, or if any of the objects being converted using the\n`%s` conversion are Unicode objects, the result will be a\nUnicode object as well.\nIf format requires a single argument, values may be a\nsingle non-tuple object. 2.8 (#foot1845) Otherwise, values must be a tuple with\nexactly the number of items specified by the format string, or a\nsingle mapping object (for example, a dictionary).\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n1. The \"%\" character, which marks the start of the\nspecifier.\n2. Mapping key value (optional), consisting of an identifier in\nparentheses (for example, `(somename)`).\n3. Conversion flags (optional), which affect the result of some\nconversion types.\n4. Minimum field width (optional). If specified as an\n\"*\" (asterisk), the actual width is read from the\nnext element of the tuple in values, and the object to\nconvert comes after the minimum field width and optional\nprecision.\n5. Precision (optional), given as a \".\" (dot) followed\nby the precision. If specified as \"*\" (an\nasterisk), the actual width is read from the next element of\nthe tuple in values, and the value to convert comes after\nthe precision.\n6. Length modifier (optional).\n7. Conversion type.\nIf the right argument is a dictionary (or any kind of mapping), then\nthe formats in the string must have a parenthesized key into\nthat dictionary inserted immediately after the \"%\"\ncharacter, and each format formats the corresponding entry from the\nmapping. For example:\n```text\n\n>>> count = 2\n>>> language = 'Python'\n>>> print '%(language)s has %(count)03d quote types.' % vars()\nPython has 002 quote types.\n```\nIn this case no `*` specifiers may occur in a format (since they\nrequire a sequential parameter list).\nThe conversion flag characters are:\nThe length modifier may be `h`, `l`, and `L` may be\npresent, but are ignored as they are not necessary for Python.\nThe conversion types are:\nSince Python strings have an explicit length, `%s` conversions\ndo not assume that `'\\0'` is the end of the string.\nFor safety reasons, floating point precisions are clipped to 50;\n`%f` conversions for numbers whose absolute value is over 1e25\nare replaced by `%g` conversions.2.9 (#foot1926) All other errors raise exceptions.\nAdditional string operations are defined in standard modules\nstring (module-string.html)and\nre (module-re.html).", "python_version": "2.2", "length": 2919, "url": "https://docs.python.org/2.2/lib/typesseq-strings.html"} {"title": "2.2.6.3 XRange Type", "text": "typesseq-strings.html | typesseq.html | typesseq-mutable.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n### 2.2.6.3 XRange Type\nThe xrangetype is an immutable sequence which is\ncommonly used for looping. The advantage of the xrange type is that an\nxrange object will always take the same amount of memory, no matter the\nsize of the range it represents. There are no consistent performance\nadvantages.\nXRange objects have very little behavior: they only support indexing\nand the len() function.", "python_version": "2.2", "length": 530, "url": "https://docs.python.org/2.2/lib/typesseq-xrange.html"} {"title": "2.2.6 Sequence Types", "text": "typeiter.html | types.html | string-methods.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 2.2.6 Sequence Types\nThere are six sequence types: strings, Unicode strings, lists,\ntuples, buffers, and xrange objects.\nStrings literals are written in single or double quotes:\n`'xyzzy'`, `\"frobozz\"`. See chapter 2 of the\nPython Reference Manual (../ref/strings.html) for more about\nstring literals. Unicode strings are much like strings, but are\nspecified in the syntax using a preceeding \"u\" character:\n`u'abc'`, `u\"def\"`. Lists are constructed with square brackets,\nseparating items with commas: `[a, b, c]`. Tuples are\nconstructed by the comma operator (not within square brackets), with\nor without enclosing parentheses, but an empty tuple must have the\nenclosing parentheses, e.g., `a, b, c` or `()`. A single\nitem tuple must have a trailing comma, e.g., `(d,)`.\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the builtin function\nbuffer().. They don't support\nconcatenation or repetition.\nXrange objects are similar to buffers in that there is no specific\nsyntax to create them, but they are created using the xrange()\nfunction. They don't support slicing,\nconcatenation or repetition, and using `in`, `not in`,\nmin() or max() on them is inefficient.\nMost sequence types support the following operations. The \"in\" and\n\"not in\" operations have the same priorities as the comparison\noperations. The \"+\" and \"*\" operations have the same\npriority as the corresponding numeric operations.2.7 (#foot1515)\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\ns and t are sequences of the same type; n, i\nand j are integers:\nNotes:\n(1): Values of n less than `0` are treated as\n`0` (which yields an empty sequence of the same type as\ns). Note also that the copies are shallow; nested structures\nare not copied. This often haunts new Python programmers; consider:\n```text\n\n>>> lists = [[]] * 3\n>>> lists\n[[], [], []]\n>>> lists[0].append(3)\n>>> lists\n[[3], [3], [3]]\n```\nWhat has happened is that `lists` is a list containing three\ncopies of the list `[[]]` (a one-element list containing an\nempty list), but the contained list is shared by each copy. You can\ncreate a list of different lists this way:\n```text\n\n>>> lists = [[] for i in range(3)]\n>>> lists[0].append(3)\n>>> lists[1].append(5)\n>>> lists[2].append(7)\n>>> lists\n[[3], [5], [7]]\n```\n(2): If i or j is negative, the index is relative to\nthe end of the string: `len( s ) + i` or\n`len( s ) + j` is substituted. But note that `-0` is\nstill `0`.\n(3): The slice of s from i to j is defined as\nthe sequence of items with index k such that `i <= k < j`. If i or j is greater than\n`len( s )`, use `len( s )`. If i is omitted,\nuse `0`. If j is omitted, use `len( s )`. If\ni is greater than or equal to j, the slice is empty.\n---\n#### Footnotes", "python_version": "2.2", "length": 2952, "url": "https://docs.python.org/2.2/lib/typesseq.html"} {"title": "A. Undocumented Modules", "text": "module-winsound.html | lib.html | node613.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# A. Undocumented Modules\nHere's a quick listing of modules that are currently undocumented, but\nthat should be documented. Feel free to contribute documentation for\nthem! (Send via email to python-docs@python.org.)\nThe idea and original contents for this chapter were taken\nfrom a posting by Fredrik Lundh; the specific contents of this chapter\nhave been substantially revised.", "python_version": "2.2", "length": 504, "url": "https://docs.python.org/2.2/lib/undoc.html"} {"title": "5.3.3 Classes and functions", "text": "legacy-unit-tests.html | module-unittest.html | testcase-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 5.3.3 Classes and functions", "python_version": "2.2", "length": 179, "url": "https://docs.python.org/2.2/lib/unittest-contents.html"} {"title": "8. Unix Specific Services", "text": "completer-objects.html | lib.html | module-posix.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n# 8. Unix Specific Services\nThe modules described in this chapter provide interfaces to features\nthat are unique to the Unix operating system, or in some cases to\nsome or many variants of it. Here's an overview:", "python_version": "2.2", "length": 344, "url": "https://docs.python.org/2.2/lib/unix.html"} {"title": "11.5.19 UnknownHandler Objects", "text": "gopher-handler.html | module-urllib2.html | module-httplib.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.5.19 UnknownHandler Objects", "python_version": "2.2", "length": 176, "url": "https://docs.python.org/2.2/lib/unknown-handler-objects.html"} {"title": "11.3.2 Examples", "text": "urlopener-objs.html | module-urllib.html | module-urllib2.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.3.2 Examples\nHere is an example session that uses the \"GET\" method to retrieve\na URL containing parameters:\n```text\n\n>>> import urllib\n>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n>>> f = urllib.urlopen(\"http://www.musi-cal.com/cgi-bin/query?%s\" % params)\n>>> print f.read()\n```\nThe following example uses the \"POST\" method instead:", "python_version": "2.2", "length": 501, "url": "https://docs.python.org/2.2/lib/Urllib_Examples.html"} {"title": "11.4.1 URLopener Objects", "text": "module-urllib.html | module-urllib.html | node307.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.4.1 URLopener Objects\nURLopener and FancyURLopener objects have the\nfollowing attributes.\nThe FancyURLopener class offers one additional method that\nshould be overloaded to provide the appropriate behavior:", "python_version": "2.2", "length": 346, "url": "https://docs.python.org/2.2/lib/urlopener-objs.html"} {"title": "11.2.2 Using the cgi module", "text": "cgi-intro.html | module-cgi.html | node281.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.2.2 Using the cgi module\nBegin by writing \"import cgi\". Do not use \"from cgi import\n*\" -- the module defines all sorts of names for its own use or for\nbackward compatibility that you don't want in your namespace.\nIt's best to use the FieldStorage class. The other classes\ndefined in this module are provided mostly for backward compatibility.\nInstantiate it exactly once, without arguments. This reads the form\ncontents from standard input or the environment (depending on the\nvalue of various environment variables set according to the CGI\nstandard). Since it may consume standard input, it should be\ninstantiated only once.\nThe FieldStorage instance can be indexed like a Python\ndictionary, and also supports the standard dictionary methods\nhas_key() and keys().\nForm fields containing empty strings are ignored\nand do not appear in the dictionary; to keep such values, provide\nthe optional \"keep_blank_values\" argument when creating the\nFieldStorage instance.\nFor instance, the following code (which assumes that the\n`Content-Type` header and blank line have already been printed)\nchecks that the fields `name` and `addr` are both set to a\nnon-empty string:\n```text\n\nform = cgi.FieldStorage()\nform_ok = 0\nif form.has_key(\"name\") and form.has_key(\"addr\"):\nform_ok = 1\nif not form_ok:\nprint \"

    Error

    \"\nprint \"Please fill in the name and addr fields.\"\nreturn\nprint \"

    name:\", form[\"name\"].value\nprint \"

    addr:\", form[\"addr\"].value\n...further form processing here...\n```\nHere the fields, accessed through \"form[key]\", are\nthemselves instances of FieldStorage (or\nMiniFieldStorage, depending on the form encoding).\nThe value attribute of the instance yields the string value\nof the field. The getvalue() method returns this string value\ndirectly; it also accepts an optional second argument as a default to\nreturn if the requested key is not present.\nIf the submitted form data contains more than one field with the same\nname, the object retrieved by \"form[key]\" is not a\nFieldStorage or MiniFieldStorage\ninstance but a list of such instances. Similarly, in this situation,\n\"form.getvalue(key)\" would return a list of strings.\nIf you expect this possibility\n(i.e., when your HTML form contains multiple fields with the same\nname), use the type() function to determine whether you\nhave a single instance or a list of instances. For example, here's\ncode that concatenates any number of username fields, separated by\ncommas:\n```text\n\nvalue = form.getvalue(\"username\", \"\")\nif type(value) is type([]):\n# Multiple username fields specified\nusernames = \",\".join(value)\nelse:\n# Single or no username field specified\nusernames = value\n```\nIf a field represents an uploaded file, accessing the value via the\nvalue attribute or the getvalue() method reads the\nentire file in memory as a string. This may not be what you want.\nYou can test for an uploaded file by testing either the filename\nattribute or the file attribute. You can then read the data at\nleisure from the file attribute:\n```text\n\nfileitem = form[\"userfile\"]\nif fileitem.file:\n# It's an uploaded file; count lines\nlinecount = 0\nwhile 1:\nline = fileitem.file.readline()\nif not line: break\nlinecount = linecount + 1\n```\nThe file upload draft standard entertains the possibility of uploading\nmultiple files from one field (using a recursive\nmultipart/* encoding). When this occurs, the item will be\na dictionary-like FieldStorage item. This can be determined\nby testing its type attribute, which should be\nmultipart/form-data (or perhaps another MIME type matching\nmultipart/*). In this case, it can be iterated over\nrecursively just like the top-level form object.\nWhen a form is submitted in the ``old'' format (as the query string or\nas a single data part of type\napplication/x-www-form-urlencoded), the items will actually\nbe instances of the class MiniFieldStorage. In this case, the\nlist, file, and filename attributes are\nalways `None`.", "python_version": "2.2", "length": 4033, "url": "https://docs.python.org/2.2/lib/Using_the_cgi_module.html"} {"title": "3.20.1 Warning Categories", "text": "module-warnings.html | module-warnings.html | warning-filter.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.20.1 Warning Categories\nThere are a number of built-in exceptions that represent warning\ncategories. This categorization is useful to be able to filter out\ngroups of warnings. The following warnings category classes are\ncurrently defined:\nWhile these are technically built-in exceptions, they are documented\nhere, because conceptually they belong to the warnings mechanism.\nUser code can define additional warning categories by subclassing one\nof the standard warning categories. A warning category must always be\na subclass of the Warning class.", "python_version": "2.2", "length": 696, "url": "https://docs.python.org/2.2/lib/warning-categories.html"} {"title": "3.20.2 The Warnings Filter", "text": "warning-categories.html | module-warnings.html | warning-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.20.2 The Warnings Filter\nThe warnings filter controls whether warnings are ignored, displayed,\nor turned into errors (raising an exception).\nConceptually, the warnings filter maintains an ordered list of filter\nspecifications; any specific warning is matched against each filter\nspecification in the list in turn until a match is found; the match\ndetermines the disposition of the match. Each entry is a tuple of the\nform (action, message, category, module,\nlineno), where:\n- action is one of the following strings:\n- message is a compiled regular expression that the warning\nmessage must match (the match is case-insensitive)\n- category is a class (a subclass of Warning) of\nwhich the warning category must be a subclass in order to match\n- module is a compiled regular expression that the module\nname must match\n- lineno is an integer that the line number where the\nwarning occurred must match, or `0` to match all line\nnumbers\nSince the Warning class is derived from the built-in\nException class, to turn a warning into an error we simply\nraise `category(message)`.\nThe warnings filter is initialized by -W options passed\nto the Python interpreter command line. The interpreter saves the\narguments for all -W options without interpretation in\n`sys.warnoptions`; the warnings module parses these when\nit is first imported (invalid options are ignored, after printing a\nmessage to `sys.stderr`).", "python_version": "2.2", "length": 1552, "url": "https://docs.python.org/2.2/lib/warning-filter.html"} {"title": "3.20.3 Available Functions", "text": "warning-filter.html | module-warnings.html | module-imp.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.20.3 Available Functions", "python_version": "2.2", "length": 169, "url": "https://docs.python.org/2.2/lib/warning-functions.html"} {"title": "14.5.1 Wave_read Objects", "text": "module-wave.html | module-wave.html | Wave-write-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 14.5.1 Wave_read Objects\nWave_read objects, as returned by open(), have the\nfollowing methods:\nThe following two methods are defined for compatibility with the\naifc (module-aifc.html) module, and don't do anything interesting.\nThe following two methods define a term ``position'' which is compatible\nbetween them, and is otherwise implementation dependent.", "python_version": "2.2", "length": 500, "url": "https://docs.python.org/2.2/lib/Wave-read-objects.html"} {"title": "14.5.2 Wave_write Objects", "text": "Wave-read-objects.html | module-wave.html | module-chunk.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 14.5.2 Wave_write Objects\nWave_write objects, as returned by open(), have the\nfollowing methods:", "python_version": "2.2", "length": 240, "url": "https://docs.python.org/2.2/lib/Wave-write-objects.html"} {"title": "3.3.2 Example", "text": "weakref-objects.html | module-weakref.html | weakref-extension.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.3.2 Example\nThis simple example shows how an application can use objects IDs to\nretrieve objects that it has seen before. The IDs of the objects can\nthen be used in other data structures without forcing the objects to\nremain alive, but the objects can still be retrieved by ID if they\ndo.\n```text\n\nimport weakref\n\n_id2obj_dict = weakref.WeakValueDictionary()\n\ndef remember(obj):\noid = id(obj)\n_id2obj_dict[oid] = obj\nreturn oid\n\ndef id2obj(oid):\nreturn _id2obj_dict[oid]\n```", "python_version": "2.2", "length": 626, "url": "https://docs.python.org/2.2/lib/weakref-example.html"} {"title": "3.3.3 Weak References in Extension Types", "text": "weakref-example.html | module-weakref.html | module-fpectl.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.3.3 Weak References in Extension Types\nOne of the goals of the implementation is to allow any type to\nparticipate in the weak reference mechanism without incurring the\noverhead on those objects which do not benefit by weak referencing\n(such as numbers).\nFor an object to be weakly referencable, the extension must include a\nPyObject* field in the instance structure for the use of the\nweak reference mechanism; it must be initialized to NULL by the\nobject's constructor. It must also set the tp_weaklistoffset\nfield of the corresponding type object to the offset of the field.\nFor example, the instance type is defined with the following structure:\n```text\n\ntypedef struct {\nPyObject_HEAD\nPyClassObject *in_class; /* The class object */\nPyObject *in_dict; /* A dictionary */\nPyObject *in_weakreflist; /* List of weak references */\n} PyInstanceObject;\n```\nThe statically-declared type object for instances is defined this way:\n```text\n\nPyTypeObject PyInstance_Type = {\nPyObject_HEAD_INIT(&PyType_Type)\n0,\n\"module.instance\",\n\n/* Lots of stuff omitted for brevity... */\n\noffsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */\n};\n```\nThe only further addition is that the destructor needs to call the\nweak reference manager to clear any weak references. This should be\ndone before any other parts of the destruction have occurred, but is\nonly required if the weak reference list is non-NULL:", "python_version": "2.2", "length": 1547, "url": "https://docs.python.org/2.2/lib/weakref-extension.html"} {"title": "3.3.1 Weak Reference Objects", "text": "module-weakref.html | module-weakref.html | weakref-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 3.3.1 Weak Reference Objects\nWeak reference objects have no attributes or methods, but do allow the\nreferent to be obtained, if it still exists, by calling it:\n```text\n\n>>> import weakref\n>>> class Object:\n... pass\n...\n>>> o = Object()\n>>> r = weakref.ref(o)\n>>> o2 = r()\n>>> o is o2\n1\n```\nIf the referent no longer exists, calling the reference object returns\n`None`:\n```text\n\n>>> del o, o2\n>>> print r()\nNone\n```\nTesting that a weak reference object is still live should be done\nusing the expression `ref () is not None`. Normally,\napplication code that needs to use a reference object should follow\nthis pattern:\n```text\n\n# r is a weak reference object\no = r()\nif o is None:\n# referent has been garbage collected\nprint \"Object has been allocated; can't frobnicate.\"\nelse:\nprint \"Object is still live!\"\no.do_something_useful()\n```\nUsing a separate test for ``liveness'' creates race conditions in\nthreaded applications; another thread can cause a weak reference to\nbecome invalidated before the weak reference is called; the\nidiom shown above is safe in threaded applications as well as\nsingle-threaded applications.", "python_version": "2.2", "length": 1265, "url": "https://docs.python.org/2.2/lib/weakref-objects.html"} {"title": "12.1.4 Writer Implementations", "text": "writer-interface.html | module-formatter.html | module-email.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.1.4 Writer Implementations\nThree implementations of the writer object interface are provided as\nexamples by this module. Most applications will need to derive new\nwriter classes from the NullWriter class.", "python_version": "2.2", "length": 355, "url": "https://docs.python.org/2.2/lib/writer-impls.html"} {"title": "12.1.3 The Writer Interface", "text": "formatter-impls.html | module-formatter.html | writer-impls.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.1.3 The Writer Interface\nInterfaces to create writers are dependent on the specific writer\nclass being instantiated. The interfaces described below are the\nrequired interfaces which all writers must support once initialized.\nNote that while most applications can use the\nAbstractFormatter class as a formatter, the writer must\ntypically be provided by the application.", "python_version": "2.2", "length": 518, "url": "https://docs.python.org/2.2/lib/writer-interface.html"} {"title": "12.17.3 Exceptions", "text": "xdr-unpacker-objects.html | module-xdrlib.html | module-netrc.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.17.3 Exceptions\nExceptions in this module are coded as class instances:\nHere is an example of how you would catch one of these exceptions:\n```text\n\nimport xdrlib\np = xdrlib.Packer()\ntry:\np.pack_double(8.01)\nexcept xdrlib.ConversionError, instance:\nprint 'packing the double failed:', instance.msg\n```", "python_version": "2.2", "length": 452, "url": "https://docs.python.org/2.2/lib/xdr-exceptions.html"} {"title": "12.17.1 Packer Objects", "text": "module-xdrlib.html | module-xdrlib.html | xdr-unpacker-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.17.1 Packer Objects\nPacker instances have the following methods:\nIn general, you can pack any of the most common XDR data types by\ncalling the appropriate `pack_ type ()` method. Each method\ntakes a single argument, the value to pack. The following simple data\ntype packing methods are supported: pack_uint(),\npack_int(), pack_enum(), pack_bool(),\npack_uhyper(), and pack_hyper().\nThe following methods support packing strings, bytes, and opaque data:\nThe following methods support packing arrays and lists:", "python_version": "2.2", "length": 660, "url": "https://docs.python.org/2.2/lib/xdr-packer-objects.html"} {"title": "12.17.2 Unpacker Objects", "text": "xdr-packer-objects.html | module-xdrlib.html | xdr-exceptions.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 12.17.2 Unpacker Objects\nThe Unpacker class offers the following methods:\nIn addition, every data type that can be packed with a Packer,\ncan be unpacked with an Unpacker. Unpacking methods are of the\nform `unpack_ type ()`, and take no arguments. They return the\nunpacked object.\nIn addition, the following methods unpack strings, bytes, and opaque\ndata:\nThe following methods support unpacking arrays and lists:", "python_version": "2.2", "length": 561, "url": "https://docs.python.org/2.2/lib/xdr-unpacker-objects.html"} {"title": "13.13.1 XML Namespaces", "text": "module-xmllib.html | module-xmllib.html | mmedia.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.13.1 XML Namespaces\nThis module has support for XML namespaces as defined in the XML\nNamespaces proposed recommendation.\nTag and attribute names that are defined in an XML namespace are\nhandled as if the name of the tag or element consisted of the\nnamespace (the URL that defines the namespace) followed by a\nspace and the name of the tag or attribute. For instance, the tag\n`` is treated as if\nthe tag name was `'http://www.w3.org/TR/REC-html40 html'`, and\nthe tag `` inside the above\nmentioned element is treated as if the tag name were\n`'http://www.w3.org/TR/REC-html40 a'` and the attribute name as\nif it were `'http://www.w3.org/TR/REC-html40 href'`.\nAn older draft of the XML Namespaces proposal is also recognized, but\ntriggers a warning.\nSee Also:", "python_version": "2.2", "length": 971, "url": "https://docs.python.org/2.2/lib/xml-namespace.html"} {"title": "13.5.1 XMLParser Objects", "text": "module-xml.parsers.expat.html | module-xml.parsers.expat.html | expaterror-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.5.1 XMLParser Objects\nxmlparser objects have the following methods:\nxmlparser objects have the following attributes:\nThe following attributes contain values relating to the most recent\nerror encountered by an xmlparser object, and will only have\ncorrect values once a call to Parse() or ParseFile()\nhas raised a xml.parsers.expat.ExpatError exception.\nHere is the list of handlers that can be set. To set a handler on an\nxmlparser object o, use\n`o . handlername = func`. handlername must\nbe taken from the following list, and func must be a callable\nobject accepting the correct number of arguments. The arguments are\nall strings, unless otherwise stated.", "python_version": "2.2", "length": 828, "url": "https://docs.python.org/2.2/lib/xmlparser-objects.html"} {"title": "13.12.1 XMLReader Objects", "text": "module-xml.sax.xmlreader.html | module-xml.sax.xmlreader.html | incremental-parser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 13.12.1 XMLReader Objects\nThe XMLReader interface supports the following methods:", "python_version": "2.2", "length": 259, "url": "https://docs.python.org/2.2/lib/xmlreader-objects.html"} {"title": "11.20.8 Example of Client Usage", "text": "node365.html | module-xmlrpclib.html | module-SimpleXMLRPCServer.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 11.20.8 Example of Client Usage", "python_version": "2.2", "length": 183, "url": "https://docs.python.org/2.2/lib/xmlrpc-client-example.html"} {"title": "7.15.1 ZipFile Objects", "text": "module-zipfile.html | module-zipfile.html | pyzipfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.15.1 ZipFile Objects\nThe following data attribute is also available:", "python_version": "2.2", "length": 219, "url": "https://docs.python.org/2.2/lib/zipfile-objects.html"} {"title": "7.15.3 ZipInfo Objects", "text": "pyzipfile-objects.html | module-zipfile.html | module-readline.html | Python Library Reference | contents.html | modindex.html | genindex.html\n---\n## 7.15.3 ZipInfo Objects\nInstances of the ZipInfo class are returned by the\ngetinfo() and infolist() methods of\nZipFile objects. Each object stores information about a\nsingle member of the ZIP archive.\nInstances have the following attributes:", "python_version": "2.2", "length": 390, "url": "https://docs.python.org/2.2/lib/zipinfo-objects.html"} {"title": "About this document ...", "text": "genindex.html | mac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# About this document ...\nMacintosh Library Modules,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | mac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1743, "url": "https://docs.python.org/2.2/mac/about.html"} {"title": "2.12.1 AEServer Objects", "text": "module-MiniAEFrame.html | module-MiniAEFrame.html | module-aepack.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.12.1 AEServer Objects", "python_version": "2.2", "length": 177, "url": "https://docs.python.org/2.2/mac/aeserver-objects.html"} {"title": "2.4.2 Alias Objects", "text": "fsspec-objects.html | module-macfs.html | finfo-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.4.2 Alias Objects\nNote that it is currently not possible to directly manipulate a\nresource as an Alias object. Hence, after calling\nUpdate() or after Resolve() indicates that the alias\nhas changed the Python program is responsible for getting the\ndata value from the Alias object and modifying the\nresource.", "python_version": "2.2", "length": 453, "url": "https://docs.python.org/2.2/mac/alias-objects.html"} {"title": "2.11.1 Application Objects", "text": "module-FrameWork.html | module-FrameWork.html | window-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.11.1 Application Objects\nApplication objects have the following methods, among others:", "python_version": "2.2", "length": 239, "url": "https://docs.python.org/2.2/mac/application-objects.html"} {"title": "1.4 Simulating command line arguments", "text": "creator-code.html | using.html | node10.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.4 Simulating command line arguments\nThere are two ways to simulate command-line arguments with MacPython.\n1. via Interpreter options\n- Hold the option-key down when launching your script. This will\nbring up a dialog box of Python Interpreter options.\n- Click ``Set Unix-style command line..'' button.\n- Type the arguments into the ``Argument'' field.\n- Click ``OK''\n- Click ``Run''.\n2. via drag and drop\nIf you save the script as an applet (see Section 1.6.4 (IDEapplet.html#IDEapplet)), you\ncan also simulate some command-line arguments via\n``Drag-and-Drop''. In this case, the names of the files that were\ndropped onto the applet will be appended to `sys.argv`, so that\nit will appear to the script as though they had been typed on a\ncommand line. As on Unix systems, the first item in `sys.srgv` is\nthe path to the applet, and the rest are the files dropped on the\napplet.", "python_version": "2.2", "length": 1004, "url": "https://docs.python.org/2.2/mac/argv.html"} {"title": "1.7 Configuration", "text": "IDEapplet.html | using.html | EditPythonPrefs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.7 Configuration\nThe MacPython distribution comes with EditPythonPrefs, an\napplet which will help you to customize the MacPython environment for\nyour working habits.", "python_version": "2.2", "length": 299, "url": "https://docs.python.org/2.2/mac/configuration.html"} {"title": "2.3.1 Connection Objects", "text": "module-ctb.html | module-ctb.html | module-macfs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.3.1 Connection Objects\nFor all connection methods that take a timeout argument, a value\nof `-1` is indefinite, meaning that the command runs to completion.", "python_version": "2.2", "length": 294, "url": "https://docs.python.org/2.2/mac/connection-object.html"} {"title": "Contents", "text": "front.html | mac.html | using.html | Macintosh Library Modules | modindex.html | genindex.html\n---\n## Contents\nTable of Contents\n- Front Matter (front.html)\n 1. Using Python on the Macintosh (using.html)\n - 1.1 Getting and Installing MacPython (getting.html)\n 1.2 Entering the interactive Interpreter (interpreter.html)\n 1.3 How to run a Python script (node6.html)\n - 1.3.1 Drag and drop (node7.html)\n 1.3.2 Set Creator and Double Click (creator-code.html)\n 1.4 Simulating command line arguments (argv.html)\n 1.5 Creating a Python script (node10.html)\n - 1.5.1 In an editor (node11.html)\n 1.6 The IDE (IDE.html)\n - 1.6.1 Using the ``Python Interactive'' window (node15.html)\n 1.6.2 Writing a Python Script (IDEwrite.html)\n 1.6.3 Executing a script from within the IDE (IDEexecution.html)\n 1.6.4 ``Save as'' versus ``Save as Applet'' (IDEapplet.html)\n 1.7 Configuration (configuration.html)\n - 1.7.1 EditPythonPrefs (EditPythonPrefs.html)\n 1.7.2 Adding modules to the Module Search Path (search-path.html)\n 1.7.3 Default startup options (defaults.html)\n 1.8 Mac OS X (node23.html)\n 2. MacPython Modules (macpython-modules.html)\n - 2.1 mac -- Implementations for the os module (module-mac.html)\n 2.2 macpath -- MacOS path manipulation functions (module-macpath.html)\n 2.3 ctb -- Interface to the Communications Tool Box (module-ctb.html)\n - 2.3.1 Connection Objects (connection-object.html)\n 2.4 macfs -- Various file system services (module-macfs.html)\n - 2.4.1 FSSpec objects (fsspec-objects.html)\n 2.4.2 Alias Objects (alias-objects.html)\n 2.4.3 FInfo Objects (finfo-objects.html)\n 2.5 ic -- Access to Internet Config (module-ic.html)\n - 2.5.1 IC Objects (node34.html)\n 2.6 MacOS -- Access to Mac OS interpreter features (module-MacOS.html)\n 2.7 macostools -- Convenience routines for file manipulation (module-macostools.html)\n 2.8 findertools -- The finder's Apple Events interface (module-findertools.html)\n 2.9 macspeech -- Interface to the Macintosh Speech Manager (module-macspeech.html)\n - 2.9.1 Voice Objects (voice-objects.html)\n 2.9.2 Speech Channel Objects (speech-channel-objects.html)\n 2.10 EasyDialogs -- Basic Macintosh dialogs (module-EasyDialogs.html)\n 2.11 FrameWork -- Interactive application framework (module-FrameWork.html)\n - 2.11.1 Application Objects (application-objects.html)\n 2.11.2 Window Objects (window-objects.html)\n 2.11.3 ControlsWindow Object (controlswindow-object.html)\n 2.11.4 ScrolledWindow Object (scrolledwindow-object.html)\n 2.11.5 DialogWindow Objects (dialogwindow-objects.html)\n 2.12 MiniAEFrame -- Open Scripting Architecture server support (module-MiniAEFrame.html)\n - 2.12.1 AEServer Objects (aeserver-objects.html)\n 2.13 aepack -- Conversion between Python variables and AppleEvent data containers (module-aepack.html)\n 2.14 aetypes -- AppleEvent objects (module-aetypes.html)\n 3. MacOS Toolbox Modules (toolbox.html)\n - 3.1 Carbon.AE -- Apple Events (module-Carbon.AE.html)\n 3.2 Carbon.App -- Appearance Manager (module-Carbon.App.html)\n 3.3 Carbon.CF -- Core Foundation (module-Carbon.CF.html)\n 3.4 Carbon.Cm -- Component Manager (module-Carbon.Cm.html)\n 3.5 Carbon.Ctl -- Control Manager (module-Carbon.Ctl.html)\n 3.6 Carbon.Dlg -- Dialog Manager (module-Carbon.Dlg.html)\n 3.7 Carbon.Evt -- Event Manager (module-Carbon.Evt.html)\n 3.8 Carbon.Fm -- Font Manager (module-Carbon.Fm.html)\n 3.9 Carbon.Help -- Help Manager (module-Carbon.Help.html)\n 3.10 Carbon.List -- List Manager (module-Carbon.List.html)\n 3.11 Carbon.Menu -- Menu Manager (module-Carbon.Menu.html)\n 3.12 Carbon.Mlte -- MultiLingual Text Editor (module-Carbon.Mlte.html)\n 3.13 Carbon.Qd -- QuickDraw (module-Carbon.Qd.html)\n 3.14 Carbon.Qdoffs -- QuickDraw Offscreen (module-Carbon.Qdoffs.html)\n 3.15 Carbon.Qt -- QuickTime (module-Carbon.Qt.html)\n 3.16 Carbon.Res -- Resource Manager and Handles (module-Carbon.Res.html)\n 3.17 Carbon.Scrap -- Scrap Manager (module-Carbon.Scrap.html)\n 3.18 Carbon.Snd -- Sound Manager (module-Carbon.Snd.html)\n 3.19 Carbon.TE -- TextEdit (module-Carbon.TE.html)\n 3.20 Carbon.Win -- Window Manager (module-Carbon.Win.html)\n 3.21 ColorPicker -- Color selection dialog (module-ColorPicker.html)\n 4. Undocumented Modules (undocumented-modules.html)\n - 4.1 applesingle -- AppleSingle decoder (module-applesingle.html)\n 4.2 buildtools -- Helper module for BuildApplet and Friends (module-buildtools.html)\n 4.3 py_resource -- Resources from Python code (module-pyresource.html)\n 4.4 cfmfile -- Code Fragment Resource module (module-cfmfile.html)\n 4.5 icopen -- Internet Config replacement for open() (module-icopen.html)\n 4.6 macerrors -- Mac OS Errors (module-macerrors.html)\n 4.7 macfsn -- NavServices calls (module-macfsn.html)\n 4.8 macresource -- Locate script resources (module-macresource.html)\n 4.9 Nav -- NavServices calls (module-Nac.html)\n 4.10 mactty -- Serial line connections (module-mactty.html)\n 4.11 mkcwproject -- Create CodeWarrior projects (module-mkcwproject.html)\n 4.12 nsremote -- Wrapper around Netscape OSA modules (module-nsremote.html)\n 4.13 PixMapWrapper -- Wrapper for PixMap objects (module-PixMapWrapper.html)\n 4.14 preferences -- Application preferences manager (module-preferences.html)\n 4.15 pythonprefs -- Preferences manager for Python (module-pythonprefs.html)\n 4.16 quietconsole -- non-visible stdout output (module-quietconsole.html)\n 4.17 videoreader -- read QuickTime movies (module-videoreader.html)\n 4.18 W -- Widgets built on FrameWork (module-W.html)\n 4.19 waste -- non-Apple TextEdit replacement (module-waste.html)\n A. History and License (node94.html)\n - A.1 History of the software (node95.html)\n A.2 Terms and conditions for accessing or otherwise using Python (node96.html)\n Module Index (modindex.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.2", "length": 5855, "url": "https://docs.python.org/2.2/mac/contents.html"} {"title": "2.11.3 ControlsWindow Object", "text": "window-objects.html | module-FrameWork.html | scrolledwindow-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.11.3 ControlsWindow Object\nControlsWindow objects have the following methods besides those of\n`Window` objects:", "python_version": "2.2", "length": 269, "url": "https://docs.python.org/2.2/mac/controlswindow-object.html"} {"title": "1.3.2 Set Creator and Double Click", "text": "node7.html | node6.html | argv.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.3.2 Set Creator and Double Click\nIf the script that you want to launch has the appropriate Creator Code\nand File Type you can simply double-click on the script to launch it.\nTo be ``double-clickable'' a file needs to be of type \"TEXT\",\nwith a creator code of \"Pyth\".\nSetting the creator code and filetype can be done with the IDE (see\nsections 1.6.2 (node16.html#IDEwrite) and 1.6.4 (IDEapplet.html#IDEapplet)), with an editor with a\nPython mode (BBEdit) - see section\n1.5.1 (scripting-with-BBedit.html#scripting-with-BBedit), or with assorted other Mac utilities, but\na script (fixfiletypes.py) has been included in the MacPython\ndistribution, making it possible to set the proper Type and Creator\nCodes with Python.\nThe fixfiletypes.py script will change the file type and\ncreator codes for the indicated directory. To use\nfixfiletypes.py:\n1. Locate it in the scripts folder of the Mac folder of the\nMacPython distribution.\n2. Put all of the scripts that you want to fix in a folder with nothing\nelse in it.\n3. Double-click on the fixfiletypes.py icon.\n4. Navigate into the folder of files you want to fix, and press the\n``Select current folder'' button.", "python_version": "2.2", "length": 1277, "url": "https://docs.python.org/2.2/mac/creator-code.html"} {"title": "1.7.3 Default startup options", "text": "search-path.html | configuration.html | node23.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.7.3 Default startup options\nThe ``Default startup options...'' button in the\nEditPythonPrefs dialog box gives you many options including\nthe ability to keep the ``Output'' window open after the script\nterminates, and the ability to enter interactive mode after the\ntermination of the run script. The latter can be very helpful if you\nwant to examine the objects that were created during your script.", "python_version": "2.2", "length": 536, "url": "https://docs.python.org/2.2/mac/defaults.html"} {"title": "2.11.5 DialogWindow Objects", "text": "scrolledwindow-object.html | module-FrameWork.html | module-MiniAEFrame.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.11.5 DialogWindow Objects\nDialogWindow objects have the following methods besides those of\n`Window` objects:", "python_version": "2.2", "length": 270, "url": "https://docs.python.org/2.2/mac/dialogwindow-objects.html"} {"title": "2.4.1 DNR Result Objects", "text": "module-macdnr.html | module-macdnr.html | module-macfs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.4.1 DNR Result Objects\nSince the DNR calls all execute asynchronously you do not get the\nresults back immediately. Instead, you get a dnr result object. You\ncan check this object to see whether the query is complete, and access\nits attributes to obtain the information when it is.\nAlternatively, you can also reference the result attributes directly,\nthis will result in an implicit wait for the query to complete.\nThe rtnCode and cname attributes are always\navailable, the others depend on the type of query (address, hinfo or\nmx).\nThe simplest way to use the module to convert names to dotted-decimal\nstrings, without worrying about idle time, etc:", "python_version": "2.2", "length": 795, "url": "https://docs.python.org/2.2/mac/dnr-result-object.html"} {"title": "1.7.1 EditPythonPrefs", "text": "configuration.html | configuration.html | search-path.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.7.1 EditPythonPrefs\nEditPythonPrefs gives you the capability to configure Python\nto behave the way you want it to. There are two ways to use\nEditPythonPrefs, you can use it to set the preferences in\ngeneral, or you can drop a particular Python engine onto it to\ncustomize only that version. The latter can be handy if, for example,\nyou want to have a second copy of the PythonInterpreter that\nkeeps the output window open on a normal exit even though you prefer\nto normally not work that way.\nTo change the default preferences, simply double-click on\nEditPythonPrefs. To change the preferences only for one copy\nof the Interpreter, drop the icon for that copy onto\nEditPythonPrefs. You can also use EditPythonPrefs\nin this fashion to set the preferences of the Python IDE and\nany applets you create - see section 1.6.4 (IDEapplet.html#IDEapplet).", "python_version": "2.2", "length": 990, "url": "https://docs.python.org/2.2/mac/EditPythonPrefs.html"} {"title": "2.4.3 FInfo Objects", "text": "alias-objects.html | module-macfs.html | module-ic.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.4.3 FInfo Objects\nSee Inside Macintosh: Files for a complete description of what\nthe various fields mean.", "python_version": "2.2", "length": 246, "url": "https://docs.python.org/2.2/mac/finfo-objects.html"} {"title": "Front Matter", "text": "mac.html | mac.html | contents.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# Front Matter\nCopyright © 2001 Python Software Foundation.\nAll rights reserved.\nCopyright © 2000 BeOpen.com.\nAll rights reserved.\nCopyright © 1995-2000 Corporation for National Research Initiatives.\nAll rights reserved.\nCopyright © 1991-1995 Stichting Mathematisch Centrum.\nAll rights reserved.\nSee the end of this document for complete license and permissions\ninformation.\n### Abstract:\nThis library reference manual documents Python's extensions for the\nMacintosh. It should be used in conjunction with the\nPython Library Reference (../lib/lib.html), which documents\nthe standard library and built-in types.\nThis manual assumes basic knowledge about the Python language. For an\ninformal introduction to Python, see the\nPython Tutorial (../tut/tut.html); the\nPython Reference Manual (../ref/ref.html) remains the\nhighest authority on syntactic and semantic questions. Finally, the\nmanual entitled Extending and Embedding\nthe Python Interpreter (../ext/ext.html) describes how to add new extensions to Python\nand how to embed it in other applications.", "python_version": "2.2", "length": 1168, "url": "https://docs.python.org/2.2/mac/front.html"} {"title": "2.4.1 FSSpec objects", "text": "module-macfs.html | module-macfs.html | alias-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.4.1 FSSpec objects", "python_version": "2.2", "length": 162, "url": "https://docs.python.org/2.2/mac/fsspec-objects.html"} {"title": "Index", "text": "modindex.html | mac.html | about.html | Macintosh Library Modules | contents.html | modindex.html\n---\n## Index\n---\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\nl (#letter-l) |\nm (#letter-m) |\nn (#letter-n) |\no (#letter-o) |\np (#letter-p) |\nq (#letter-q) |\nr (#letter-r) |\ns (#letter-s) |\nt (#letter-t) |\nu (#letter-u) |\nv (#letter-v) |\nw (#letter-w) |\nx (#letter-x)\n---\n## _ (underscore)\n---\n## A\n---\n## B\n---\n## C\n---\n## D\n---\n## E\n---\n## F\n---\n## G\n---\n## H\n---\n## I\n---\n## L\n---\n## M\n---\n## N\n---\n## O\n---\n## P\n---\n## Q\n---\n## R\n---\n## S\n---\n## T\n---\n## U\n---\n## V\n---\n## W\n---\n## X", "python_version": "2.2", "length": 700, "url": "https://docs.python.org/2.2/mac/genindex.html"} {"title": "1.1 Getting and Installing MacPython", "text": "using.html | using.html | interpreter.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.1 Getting and Installing MacPython\nThe most recent release version as well as possible newer experimental\nversions are best found at the MacPython page maintained by Jack\nJansen: http://www.cwi.nl/~jack/macpython.html.\nPlease refer to the README included with your distribution for\nthe most up-to-date instructions.", "python_version": "2.2", "length": 442, "url": "https://docs.python.org/2.2/mac/getting.html"} {"title": "1.6 The IDE", "text": "scripting-with-BBedit.html | using.html | node15.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.6 The IDE\nThe Python IDE (Integrated Development Environment) is a\nseparate application that acts as a text editor for your Python code,\na class browser, a graphical debugger, and more.", "python_version": "2.2", "length": 323, "url": "https://docs.python.org/2.2/mac/IDE.html"} {"title": "1.6.4 ``Save as'' versus ``Save as Applet''", "text": "IDEexecution.html | IDE.html | configuration.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.6.4 ``Save as'' versus ``Save as Applet''\nWhen you are done writing your Python script you have the option of\nsaving it as an ``applet'' (by selecting ``Save as applet'' from the\n``File'' menu). This has a significant advantage in that you can drop\nfiles or folders onto it, to pass them to the applet the way\ncommand-line users would type them onto the command-line to pass them\nas arguments to the script. However, you should make sure to save the\napplet as a separate file, do not overwrite the script you are\nwriting, because you will not be able to edit it again.\nAccessing the items passed to the applet via ``drag-and-drop'' is done\nusing the standard sys.argv mechanism. See the general\ndocumentation for more\nNote that saving a script as an applet will not make it runnable on a\nsystem without a Python installation.", "python_version": "2.2", "length": 960, "url": "https://docs.python.org/2.2/mac/IDEapplet.html"} {"title": "1.6.3 Executing a script from within the IDE", "text": "IDEwrite.html | IDE.html | IDEapplet.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.6.3 Executing a script from within the IDE\nYou can run the script in the frontmost window of the Python\nIDE by hitting the run all button. You should be aware, however that\nif you use the Python convention \"if __name__ == \"__main__\":\" the\nscript will not be ``__main__'' by default. To get that\nbehaviour you must select the ``Run as __main__'' option from the\nsmall black triangle on the top right of the document window. Note\nthat this option is associated with the file not the\napplication. It will stay active after a save, however; to shut\nthis feature off simply select it again.", "python_version": "2.2", "length": 712, "url": "https://docs.python.org/2.2/mac/IDEexecution.html"} {"title": "1.6.2 Writing a Python Script", "text": "node15.html | IDE.html | IDEexecution.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.6.2 Writing a Python Script\nIn addition to using the Python IDE interactively, you can\nalso type out a complete Python program, saving it incrementally, and\nexecute it or smaller selections of it.\nYou can create a new script, open a previously saved script, and save\nyour currently open script by selecting the appropriate item in the\n``File'' menu. Dropping a Python script onto the\nPython IDE will open it for editting.\nIf you try to open a script with the Python IDE but either\ncan't locate it from the ``Open'' dialog box, or you get an error\nmessage like ``Can't open file of type ...'' see section\n1.3.2 (creator-code.html#creator-code).\nWhen the Python IDE saves a script, it uses the creator code\nsettings which are available by clicking on the small black triangle\non the top right of the document window, and selecting ``save\noptions''. The default is to save the file with the Python\nIDE as the creator, this means that you can open the file for editing\nby simply double-clicking on its icon. You might want to change this\nbehaviour so that it will be opened by the\nPythonInterpreter, and run. To do this simply choose\n``Python Interpreter'' from the ``save options''. Note that these\noptions are associated with the file not the application.", "python_version": "2.2", "length": 1381, "url": "https://docs.python.org/2.2/mac/IDEwrite.html"} {"title": "Macintosh Library Modules", "text": "../index.html | front.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# Macintosh Library Modules\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 249, "url": "https://docs.python.org/2.2/mac/index.html"} {"title": "1.2 Entering the interactive Interpreter", "text": "getting.html | using.html | node6.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.2 Entering the interactive Interpreter\nThe interactive interpreter that you will see used in Python\ndocumentation is started by double-clicking the\nPythonInterpreter icon, which looks like a 16-ton weight\nfalling. You should see the version information and the\n\">`>`> \" prompt. Use it exactly as described in the\nstandard documentation.", "python_version": "2.2", "length": 459, "url": "https://docs.python.org/2.2/mac/interpreter.html"} {"title": "Macintosh Library Modules", "text": "../index.html | front.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# Macintosh Library Modules\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 249, "url": "https://docs.python.org/2.2/mac/mac.html"} {"title": "2. MacPython Modules", "text": "node23.html | mac.html | module-mac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2. MacPython Modules\nThe following modules are only available on the Macintosh, and are\ndocumented here:\nmac (module-mac.html) | Implementations for the os module.\nmacpath (module-macpath.html) | MacOS path manipulation functions.\nctb (module-ctb.html) | Interfaces to the Communications Tool Box. Only the\nConnection Manager is supported.\nmacfs (module-macfs.html) | Support for FSSpec, the Alias Manager,\nfinder aliases, and the Standard File package.\nic (module-ic.html) | Access to Internet Config.\nMacOS (module-MacOS.html) | Access to Mac OS-specific interpreter features.\nmacostools (module-macostools.html) | Convenience routines for file manipulation.\nfindertools (module-findertools.html) | Wrappers around the finder's Apple Events interface.\nmacspeech (module-macspeech.html) | Interface to the Macintosh Speech Manager.\nEasyDialogs (module-EasyDialogs.html) | Basic Macintosh dialogs.\nFrameWork (module-FrameWork.html) | Interactive application framework.\nMiniAEFrame (module-MiniAEFrame.html) | Support to act as an Open Scripting Architecture (OSA) server\n(``Apple Events'').\naepack (module-aepack.html) | Conversion between Python variables and AppleEvent\ndata containers.\naetypes (module-aetypes.html) | Python representation of the Apple Event Object Model.", "python_version": "2.2", "length": 1398, "url": "https://docs.python.org/2.2/mac/macpython-modules.html"} {"title": "Module Index", "text": "node96.html | mac.html | genindex.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## Module Index\nThis index only lists modules documented in this manual.\nThe Global Module\nIndex (../modindex.html) lists all modules that are documented in this set\nof manuals.\nSome module names are followed by an annotation indicating what\nplatform they are available on.", "python_version": "2.2", "length": 392, "url": "https://docs.python.org/2.2/mac/modindex.html"} {"title": "3.1 AE -- Apple Events", "text": "toolbox.html | toolbox.html | module-Cm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.1 AE -- Apple Events\nAvailability: Macintosh.", "python_version": "2.2", "length": 174, "url": "https://docs.python.org/2.2/mac/module-AE.html"} {"title": "2.13 aepack -- Conversion between Python variables and AppleEvent data containers", "text": "aeserver-objects.html | macpython-modules.html | module-aetypes.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.13 aepack --\nConversion between Python variables and AppleEvent data containers\nAvailability: Macintosh.\nThe aepack module defines functions for converting (packing)\nPython variables to AppleEvent descriptors and back (unpacking).\nWithin Python the AppleEvent descriptor is handled by Python objects\nof built-in type AEDesc, defined in module AE (module-AE.html).\nThe aepack module defines the following functions:", "python_version": "2.2", "length": 567, "url": "https://docs.python.org/2.2/mac/module-aepack.html"} {"title": "2.14 aetypes -- AppleEvent objects", "text": "module-aepack.html | macpython-modules.html | toolbox.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.14 aetypes --\nAppleEvent objects\nAvailability: Macintosh.\nThe aetypes defines classes used to represent Apple Event\nobject specifiers. An object specifier is essentially an address of an\nobject implemented in a Apple Event server. An Apple Event specifier\nis used as the direct object for an Apple Event or as the argument of\nan optional parameter. In AppleScript an object specifier is\nrepresented by a phrase such as:\n`character 23 of document \"Semprini\"`. The classes defined in\nthis module allow this specifier to be represented by a Python object\nwhich is initialized as follows:\n`res = Document(1).Character(23)`\nThe AEObjects module defines the following class:", "python_version": "2.2", "length": 811, "url": "https://docs.python.org/2.2/mac/module-aetypes.html"} {"title": "4.1 applesingle -- AppleSingle decoder", "text": "undocumented-modules.html | undocumented-modules.html | module-buildtools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.1 applesingle -- AppleSingle decoder\nAvailability: Macintosh.", "python_version": "2.2", "length": 224, "url": "https://docs.python.org/2.2/mac/module-applesingle.html"} {"title": "4.2 buildtools -- Helper module for BuildApplet and Friends", "text": "module-applesingle.html | undocumented-modules.html | module-pyresource.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.2 buildtools -- Helper module for BuildApplet and Friends\nAvailability: Macintosh.", "python_version": "2.2", "length": 243, "url": "https://docs.python.org/2.2/mac/module-buildtools.html"} {"title": "3.1 Carbon.AE -- Apple Events", "text": "toolbox.html | toolbox.html | module-Carbon.App.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.1 Carbon.AE -- Apple Events\nAvailability: Macintosh.", "python_version": "2.2", "length": 189, "url": "https://docs.python.org/2.2/mac/module-Carbon.AE.html"} {"title": "3.2 Carbon.App -- Appearance Manager", "text": "module-Carbon.AE.html | toolbox.html | module-Carbon.CF.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.2 Carbon.App -- Appearance Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 204, "url": "https://docs.python.org/2.2/mac/module-Carbon.App.html"} {"title": "3.3 Carbon.CF -- Core Foundation", "text": "module-Carbon.App.html | toolbox.html | module-Carbon.Cm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.3 Carbon.CF -- Core Foundation\nAvailability: Macintosh.\nThis module is only available under Carbon MacPython. The\n`CFBase`, `CFArray`, `CFData`, `CFDictionary`,\n`CFString` and `CFURL` objects are supported, some\nonly partially.", "python_version": "2.2", "length": 373, "url": "https://docs.python.org/2.2/mac/module-Carbon.CF.html"} {"title": "3.4 Carbon.Cm -- Component Manager", "text": "module-Carbon.CF.html | toolbox.html | module-Carbon.Ctl.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.4 Carbon.Cm -- Component Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 203, "url": "https://docs.python.org/2.2/mac/module-Carbon.Cm.html"} {"title": "3.5 Carbon.Ctl -- Control Manager", "text": "module-Carbon.Cm.html | toolbox.html | module-Carbon.Dlg.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.5 Carbon.Ctl -- Control Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 202, "url": "https://docs.python.org/2.2/mac/module-Carbon.Ctl.html"} {"title": "3.6 Carbon.Dlg -- Dialog Manager", "text": "module-Carbon.Ctl.html | toolbox.html | module-Carbon.Evt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.6 Carbon.Dlg -- Dialog Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 202, "url": "https://docs.python.org/2.2/mac/module-Carbon.Dlg.html"} {"title": "3.7 Carbon.Evt -- Event Manager", "text": "module-Carbon.Dlg.html | toolbox.html | module-Carbon.Fm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.7 Carbon.Evt -- Event Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 200, "url": "https://docs.python.org/2.2/mac/module-Carbon.Evt.html"} {"title": "3.8 Carbon.Fm -- Font Manager", "text": "module-Carbon.Evt.html | toolbox.html | module-Carbon.Help.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.8 Carbon.Fm -- Font Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 200, "url": "https://docs.python.org/2.2/mac/module-Carbon.Fm.html"} {"title": "3.9 Carbon.Help -- Help Manager", "text": "module-Carbon.Fm.html | toolbox.html | module-Carbon.List.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.9 Carbon.Help -- Help Manager\nAvailability: Macintosh.\nThis module is only available under MacOS9 and earlier in\nclassic PPC MacPython.", "python_version": "2.2", "length": 282, "url": "https://docs.python.org/2.2/mac/module-Carbon.Help.html"} {"title": "3.10 Carbon.List -- List Manager", "text": "module-Carbon.Help.html | toolbox.html | module-Carbon.Menu.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.10 Carbon.List -- List Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 204, "url": "https://docs.python.org/2.2/mac/module-Carbon.List.html"} {"title": "3.11 Carbon.Menu -- Menu Manager", "text": "module-Carbon.List.html | toolbox.html | module-Carbon.Mlte.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.11 Carbon.Menu -- Menu Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 204, "url": "https://docs.python.org/2.2/mac/module-Carbon.Menu.html"} {"title": "3.12 Carbon.Mlte -- MultiLingual Text Editor", "text": "module-Carbon.Menu.html | toolbox.html | module-Carbon.Qd.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.12 Carbon.Mlte -- MultiLingual Text Editor\nAvailability: Macintosh.", "python_version": "2.2", "length": 214, "url": "https://docs.python.org/2.2/mac/module-Carbon.Mlte.html"} {"title": "3.13 Carbon.Qd -- QuickDraw", "text": "module-Carbon.Mlte.html | toolbox.html | module-Carbon.Qdoffs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.13 Carbon.Qd -- QuickDraw\nAvailability: Macintosh.", "python_version": "2.2", "length": 201, "url": "https://docs.python.org/2.2/mac/module-Carbon.Qd.html"} {"title": "3.14 Carbon.Qdoffs -- QuickDraw Offscreen", "text": "module-Carbon.Qd.html | toolbox.html | module-Carbon.Qt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.14 Carbon.Qdoffs -- QuickDraw Offscreen\nAvailability: Macintosh.", "python_version": "2.2", "length": 209, "url": "https://docs.python.org/2.2/mac/module-Carbon.Qdoffs.html"} {"title": "3.15 Carbon.Qt -- QuickTime", "text": "module-Carbon.Qdoffs.html | toolbox.html | module-Carbon.Res.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.15 Carbon.Qt -- QuickTime\nAvailability: Macintosh.", "python_version": "2.2", "length": 200, "url": "https://docs.python.org/2.2/mac/module-Carbon.Qt.html"} {"title": "3.16 Carbon.Res -- Resource Manager and Handles", "text": "module-Carbon.Qt.html | toolbox.html | module-Carbon.Scrap.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.16 Carbon.Res -- Resource Manager and Handles\nAvailability: Macintosh.", "python_version": "2.2", "length": 218, "url": "https://docs.python.org/2.2/mac/module-Carbon.Res.html"} {"title": "3.17 Carbon.Scrap -- Scrap Manager", "text": "module-Carbon.Res.html | toolbox.html | module-Carbon.Snd.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.17 Carbon.Scrap -- Scrap Manager\nAvailability: Macintosh.\nThis module is only fully available on MacOS9 and earlier under classic PPC\nMacPython. Very limited functionality is available under Carbon MacPython.\nSee Also:", "python_version": "2.2", "length": 365, "url": "https://docs.python.org/2.2/mac/module-Carbon.Scrap.html"} {"title": "3.18 Carbon.Snd -- Sound Manager", "text": "module-Carbon.Scrap.html | toolbox.html | module-Carbon.TE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.18 Carbon.Snd -- Sound Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 203, "url": "https://docs.python.org/2.2/mac/module-Carbon.Snd.html"} {"title": "3.19 Carbon.TE -- TextEdit", "text": "module-Carbon.Snd.html | toolbox.html | module-Carbon.Win.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.19 Carbon.TE -- TextEdit\nAvailability: Macintosh.", "python_version": "2.2", "length": 196, "url": "https://docs.python.org/2.2/mac/module-Carbon.TE.html"} {"title": "3.20 Carbon.Win -- Window Manager", "text": "module-Carbon.TE.html | toolbox.html | module-ColorPicker.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.20 Carbon.Win -- Window Manager\nAvailability: Macintosh.\n---\nmodule-Carbon.TE.html | toolbox.html | module-ColorPicker.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 407, "url": "https://docs.python.org/2.2/mac/module-Carbon.Win.html"} {"title": "4.4 cfmfile -- Code Fragment Resource module", "text": "module-pyresource.html | undocumented-modules.html | module-icopen.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.4 cfmfile -- Code Fragment Resource module\nAvailability: Macintosh.\ncfmfile is a module that understands Code Fragments and the\naccompanying ``cfrg'' resources. It can parse them and merge them, and is\nused by BuildApplication to combine all plugin modules to a single\nexecutable.", "python_version": "2.2", "length": 436, "url": "https://docs.python.org/2.2/mac/module-cfmfile.html"} {"title": "3.2 Cm -- Component Manager", "text": "module-AE.html | toolbox.html | module-Ctl.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.2 Cm -- Component Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 182, "url": "https://docs.python.org/2.2/mac/module-Cm.html"} {"title": "3.21 ColorPicker -- Color selection dialog", "text": "module-Carbon.Win.html | toolbox.html | undocumented-modules.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.21 ColorPicker --\nColor selection dialog\nAvailability: Macintosh.\nThe ColorPicker module provides access to the standard color\npicker dialog.", "python_version": "2.2", "length": 291, "url": "https://docs.python.org/2.2/mac/module-ColorPicker.html"} {"title": "2.3 ctb -- Interface to the Communications Tool Box", "text": "module-macpath.html | macpython-modules.html | connection-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.3 ctb --\nInterface to the Communications Tool Box\nAvailability: Macintosh.\nThis module provides a partial interface to the Macintosh\nCommunications Toolbox. Currently, only Connection Manager tools are\nsupported.\nThis module is only available under MacOS9 or earlier, in classic PPC\nMacPython.", "python_version": "2.2", "length": 447, "url": "https://docs.python.org/2.2/mac/module-ctb.html"} {"title": "3.3 Ctl -- Control Manager", "text": "module-Cm.html | toolbox.html | module-Dlg.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.3 Ctl -- Control Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 181, "url": "https://docs.python.org/2.2/mac/module-Ctl.html"} {"title": "3.4 Dlg -- Dialog Manager", "text": "module-Ctl.html | toolbox.html | module-Evt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.4 Dlg -- Dialog Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 181, "url": "https://docs.python.org/2.2/mac/module-Dlg.html"} {"title": "2.10 EasyDialogs -- Basic Macintosh dialogs", "text": "speech-channel-objects.html | macpython-modules.html | module-FrameWork.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.10 EasyDialogs --\nBasic Macintosh dialogs\nAvailability: Macintosh.\nThe EasyDialogs module contains some simple dialogs for\nthe Macintosh. All routines have an optional parameter id with\nwhich you can override the DLOG resource used for the dialog, as long\nas the item numbers correspond. See the source for details.\nThe EasyDialogs module defines the following functions:", "python_version": "2.2", "length": 532, "url": "https://docs.python.org/2.2/mac/module-EasyDialogs.html"} {"title": "3.5 Evt -- Event Manager", "text": "module-Dlg.html | toolbox.html | module-Fm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.5 Evt -- Event Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 179, "url": "https://docs.python.org/2.2/mac/module-Evt.html"} {"title": "2.8 findertools -- The finder's Apple Events interface", "text": "module-macostools.html | macpython-modules.html | module-macspeech.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.8 findertools --\nThe finder's Apple Events interface\nAvailability: Macintosh.\nThis module contains routines that give Python programs access to some\nfunctionality provided by the finder. They are implemented as wrappers\naround the AppleEventinterface to the finder.\nAll file and folder parameters can be specified either as full\npathnames or as FSSpec objects.\nThe findertools module defines the following functions:", "python_version": "2.2", "length": 572, "url": "https://docs.python.org/2.2/mac/module-findertools.html"} {"title": "3.6 Fm -- Font Manager", "text": "module-Evt.html | toolbox.html | module-List.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.6 Fm -- Font Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 179, "url": "https://docs.python.org/2.2/mac/module-Fm.html"} {"title": "2.11 FrameWork -- Interactive application framework", "text": "module-EasyDialogs.html | macpython-modules.html | application-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.11 FrameWork --\nInteractive application framework\nAvailability: Macintosh.\nThe FrameWork module contains classes that together provide a\nframework for an interactive Macintosh application. The programmer\nbuilds an application by creating subclasses that override various\nmethods of the bases classes, thereby implementing the functionality\nwanted. Overriding functionality can often be done on various\ndifferent levels, i.e. to handle clicks in a single dialog window in a\nnon-standard way it is not necessary to override the complete event\nhandling.\nThe FrameWork is still very much work-in-progress, and the\ndocumentation describes only the most important functionality, and not\nin the most logical manner at that. Examine the source or the examples\nfor more details. The following are some comments posted on the\nMacPython newsgroup about the strengths and limitations of\nFrameWork:\n> The strong point of FrameWork is that it allows you to break\n> into the control-flow at many different places. W (module-W.html), for\n> instance, uses a different way to enable/disable menus and that plugs\n> right in leaving the rest intact. The weak points of\n> FrameWork are that it has no abstract command interface (but\n> that shouldn't be difficult), that it's dialog support is minimal and\n> that it's control/toolbar support is non-existent.\nThe FrameWork module defines the following functions:", "python_version": "2.2", "length": 1550, "url": "https://docs.python.org/2.2/mac/module-FrameWork.html"} {"title": "2.5 ic -- Access to Internet Config", "text": "finfo-objects.html | macpython-modules.html | node34.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.5 ic --\nAccess to Internet Config\nAvailability: Macintosh.\nThis module provides access to Macintosh Internet\nConfigpackage,\nwhich stores preferences for Internet programs such as mail address,\ndefault homepage, etc. Also, Internet Config contains an elaborate set\nof mappings from Macintosh creator/type codes to foreign filename\nextensions plus information on how to transfer files (binary, ascii,\netc.). Since MacOS 9, this module is a control panel named Internet.\nThere is a low-level companion module\nicgluewhich provides the basic\nInternet Config access functionality. This low-level module is not\ndocumented, but the docstrings of the routines document the parameters\nand the routine names are the same as for the Pascal or C API to\nInternet Config, so the standard IC programmers' documentation can be\nused if this module is needed.\nThe ic module defines the error exception and\nsymbolic names for all error codes Internet Config can produce; see\nthe source for details.\nThe ic module defines the following class and function:", "python_version": "2.2", "length": 1176, "url": "https://docs.python.org/2.2/mac/module-ic.html"} {"title": "4.5 icopen -- Internet Config replacement for open()", "text": "module-cfmfile.html | undocumented-modules.html | module-macerrors.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.5 icopen -- Internet Config replacement for open()\nAvailability: Macintosh.\nImporting icopen will replace the builtin open()\nwith a version that uses Internet Config to set file type and creator\nfor new files.", "python_version": "2.2", "length": 365, "url": "https://docs.python.org/2.2/mac/module-icopen.html"} {"title": "3.7 List -- List Manager", "text": "module-Fm.html | toolbox.html | module-Menu.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.7 List -- List Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 180, "url": "https://docs.python.org/2.2/mac/module-List.html"} {"title": "2.1 mac -- Implementations for the os module", "text": "macpython-modules.html | macpython-modules.html | module-macpath.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.1 mac --\nImplementations for the os module\nAvailability: Macintosh.\nThis module implements the operating system dependent functionality\nprovided by the standard module os. It is\nbest accessed through the os module.\nThe following functions are available in this module:\nchdir(),\nclose(),\ndup(),\nfdopen(),\ngetcwd(),\nlseek(),\nlistdir(),\nmkdir(),\nopen(),\nread(),\nrename(),\nrmdir(),\nstat(),\nsync(),\nunlink(),\nwrite(),\nas well as the exception error. Note that the times\nreturned by stat() are floating-point values, like all time\nvalues in MacPython.\nOne additional function is available:", "python_version": "2.2", "length": 737, "url": "https://docs.python.org/2.2/mac/module-mac.html"} {"title": "2.4 macdnr -- Interface to the Macintosh Domain Name Resolver", "text": "connection-object.html | macpython-modules.html | dnr-result-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.4 macdnr --\nInterface to the Macintosh Domain Name Resolver\nAvailability: Macintosh.\nThis module provides an interface to the Macintosh Domain Name\nResolver. It is usually used in conjunction with the mactcp (module-mactcp.html)\nmodule, to map hostnames to IP addresses. It may not be available in\nall Mac Python versions.\nThe macdnr module defines the following functions:", "python_version": "2.2", "length": 530, "url": "https://docs.python.org/2.2/mac/module-macdnr.html"} {"title": "4.6 macerrors -- Mac OS Errors", "text": "module-icopen.html | undocumented-modules.html | module-macfsn.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.6 macerrors -- Mac OS Errors\nAvailability: Macintosh.\nmacerrors cotains constant definitions for many Mac OS error codes.", "python_version": "2.2", "length": 273, "url": "https://docs.python.org/2.2/mac/module-macerrors.html"} {"title": "2.4 macfs -- Various file system services", "text": "connection-object.html | macpython-modules.html | fsspec-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.4 macfs --\nVarious file system services\nAvailability: Macintosh.\nThis module provides access to Macintosh FSSpec handling, the Alias\nManager, finder aliases and the Standard File package.\nWhenever a function or method expects a file argument, this\nargument can be one of three things: (1) a full or partial Macintosh\npathname, (2) an FSSpec object or (3) a 3-tuple\n`( wdRefNum , parID , name )` as described in\nInside Macintosh: Files. A description of aliases and the\nStandard File package can also be found there.\nNote:\nA module, macfsn (module-macfsn.html), is auto-imported to replace\nStandardFile calls in macfs with NavServices calls.", "python_version": "2.2", "length": 794, "url": "https://docs.python.org/2.2/mac/module-macfs.html"} {"title": "4.7 macfsn -- NavServices calls", "text": "module-macerrors.html | undocumented-modules.html | module-macresource.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.7 macfsn -- NavServices calls\nAvailability: Macintosh.\nmacfsn contains wrapper functions that have the same API as the macfs\nStandardFile calls, but are implemented with Navigation Services through the\nNav (module-Nav.html)module. Importing it\nwill replace the methods in macfs (module-macfs.html)with these,\nif Navigation Services is\navailable on your machine.", "python_version": "2.2", "length": 521, "url": "https://docs.python.org/2.2/mac/module-macfsn.html"} {"title": "2.6 MacOS -- Access to Mac OS interpreter features", "text": "node34.html | macpython-modules.html | module-macostools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.6 MacOS --\nAccess to Mac OS interpreter features\nAvailability: Macintosh.\nThis module provides access to MacOS specific functionality in the\nPython interpreter, such as how the interpreter eventloop functions\nand the like. Use with care.\nNote the capitalization of the module name; this is a historical\nartifact.", "python_version": "2.2", "length": 458, "url": "https://docs.python.org/2.2/mac/module-MacOS.html"} {"title": "2.7 macostools -- Convenience routines for file manipulation", "text": "module-MacOS.html | macpython-modules.html | module-findertools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.7 macostools --\nConvenience routines for file manipulation\nAvailability: Macintosh.\nThis module contains some convenience routines for file-manipulation\non the Macintosh.\nThe macostools module defines the following functions:\nNote that the process of creating finder aliases is not specified in\nthe Apple documentation. Hence, aliases created with mkalias()\ncould conceivably have incompatible behaviour in some cases.", "python_version": "2.2", "length": 571, "url": "https://docs.python.org/2.2/mac/module-macostools.html"} {"title": "2.2 macpath -- MacOS path manipulation functions", "text": "module-mac.html | macpython-modules.html | module-ctb.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.2 macpath --\nMacOS path manipulation functions\nThis module is the Macintosh implementation of the os.path\nmodule. It is most portably accessed as\nos.path. Refer to the\nPython Library Reference (../lib/lib.html) for\ndocumentation of os.path.", "python_version": "2.2", "length": 383, "url": "https://docs.python.org/2.2/mac/module-macpath.html"} {"title": "4.8 macresource -- Locate script resources", "text": "module-macfsn.html | undocumented-modules.html | module-Nac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.8 macresource -- Locate script resources\nAvailability: Macintosh.\nmacresource helps scripts finding their resources, such as\ndialogs and menus, without requiring special case code for when the\nscript is run under MacPython, as a MacPython applet or under OSX Python.", "python_version": "2.2", "length": 415, "url": "https://docs.python.org/2.2/mac/module-macresource.html"} {"title": "2.9 macspeech -- Interface to the Macintosh Speech Manager", "text": "module-findertools.html | macpython-modules.html | voice-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.9 macspeech --\nInterface to the Macintosh Speech Manager\nAvailability: Macintosh.\nThis module provides an interface to the Macintosh Speech Manager,\nallowing you to let the Macintosh utter phrases. You need a version of\nthe Speech Manager extension (version 1 and 2 have been tested) in\nyour Extensions folder for this to work. The module does not\nprovide full access to all features of the Speech Manager.\nThis module is only available on MacOS9 and earlier in classic PPC\nMacPython.", "python_version": "2.2", "length": 638, "url": "https://docs.python.org/2.2/mac/module-macspeech.html"} {"title": "2.10 mactcp -- The MacTCP interfaces", "text": "module-findertools.html | macpython-modules.html | node41.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.10 mactcp --\nThe MacTCP interfaces\nAvailability: Macintosh.\nThis module provides an interface to the Macintosh TCP/IP driverMacTCP. There is an accompanying module,\nmacdnr (module-macdnr.html), which provides an interface\nto the name-server (allowing you to translate hostnames to IP\naddresses), a module MACTCPconstwhich has symbolic names for constants constants used by MacTCP. Since\nthe built-in module socketis also\navailable on the Macintosh it is usually easier to use sockets instead\nof the Macintosh-specific MacTCP API.\nA complete description of the MacTCP interface can be found in the\nApple MacTCP API documentation.", "python_version": "2.2", "length": 775, "url": "https://docs.python.org/2.2/mac/module-mactcp.html"} {"title": "4.10 mactty -- Serial line connections", "text": "module-Nac.html | undocumented-modules.html | module-mkcwproject.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.10 mactty -- Serial line connections\nAvailability: Macintosh.\nThis module is only available under Mac OS 9 or earlier in classic PPC\nMacPython.", "python_version": "2.2", "length": 297, "url": "https://docs.python.org/2.2/mac/module-mactty.html"} {"title": "3.8 Menu -- Menu Manager", "text": "module-List.html | toolbox.html | module-Qd.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.8 Menu -- Menu Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 180, "url": "https://docs.python.org/2.2/mac/module-Menu.html"} {"title": "2.12 MiniAEFrame -- Open Scripting Architecture server support", "text": "dialogwindow-objects.html | macpython-modules.html | aeserver-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 2.12 MiniAEFrame --\nOpen Scripting Architecture server support\nAvailability: Macintosh.\nThe module MiniAEFrame provides a framework for an application\nthat can function as an Open Scripting Architecture\n(OSA) server, i.e. receive and process\nAppleEvents. It can be used in conjunction with\nFrameWork (module-FrameWork.html)or standalone. As an\nexample, it is used in PythonCGISlave.\nThe MiniAEFrame module defines the following classes:", "python_version": "2.2", "length": 593, "url": "https://docs.python.org/2.2/mac/module-MiniAEFrame.html"} {"title": "4.11 mkcwproject -- Create CodeWarrior projects", "text": "module-mactty.html | undocumented-modules.html | module-nsremote.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.11 mkcwproject -- Create CodeWarrior projects\nAvailability: Macintosh.\nmkcwproject creates project files for the Metrowerks CodeWarrior\ndevelopment environment. It is a helper module for\ndistutils (module-distutils.html)but can be used separately for more\ncontrol.", "python_version": "2.2", "length": 418, "url": "https://docs.python.org/2.2/mac/module-mkcwproject.html"} {"title": "4.9 Nav -- NavServices calls", "text": "module-macresource.html | undocumented-modules.html | module-mactty.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.9 Nav -- NavServices calls\nAvailability: Macintosh.\nA low-level interface to Navigation Services.", "python_version": "2.2", "length": 254, "url": "https://docs.python.org/2.2/mac/module-Nac.html"} {"title": "4.12 nsremote -- Wrapper around Netscape OSA modules", "text": "module-mkcwproject.html | undocumented-modules.html | module-PixMapWrapper.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.12 nsremote -- Wrapper around Netscape OSA modules\nAvailability: Macintosh.\nnsremote is a wrapper around the Netscape OSA modules that\nallows you to easily send your browser to a given URL. A related\nmodule that may be of interest is the webbrowser module,\ndocumented in the Python Library\nReference (../lib/lib.html).", "python_version": "2.2", "length": 482, "url": "https://docs.python.org/2.2/mac/module-nsremote.html"} {"title": "4.13 PixMapWrapper -- Wrapper for PixMap objects", "text": "module-nsremote.html | undocumented-modules.html | module-preferences.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.13 PixMapWrapper -- Wrapper for PixMap objects\nAvailability: Macintosh.\nPixMapWrapper wraps a PixMap object with a Python object that\nallows access to the fields by name. It also has methods to convert\nto and from PIL images.", "python_version": "2.2", "length": 384, "url": "https://docs.python.org/2.2/mac/module-PixMapWrapper.html"} {"title": "4.14 preferences -- Application preferences manager", "text": "module-PixMapWrapper.html | undocumented-modules.html | module-pythonprefs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.14 preferences -- Application preferences manager\nAvailability: Macintosh.\nThe preferences module allows storage of user preferences in\nthe system-wide preferences folder, with defaults coming from the\napplication itself and the possibility to override preferences for\nspecific situations.", "python_version": "2.2", "length": 453, "url": "https://docs.python.org/2.2/mac/module-preferences.html"} {"title": "4.3 py_resource -- Resources from Python code", "text": "module-buildtools.html | undocumented-modules.html | module-cfmfile.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.3 py_resource -- Resources from Python code\nAvailability: Macintosh.\nThis module is primarily used as a help module for\nBuildApplet and BuildApplication. It is able to\nstore compiled Python code as 'PYC ' resources in a file.", "python_version": "2.2", "length": 382, "url": "https://docs.python.org/2.2/mac/module-pyresource.html"} {"title": "4.15 pythonprefs -- Preferences manager for Python", "text": "module-preferences.html | undocumented-modules.html | module-quietconsole.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.15 pythonprefs -- Preferences manager for Python\nAvailability: Macintosh.\nThis module is a specialization of the preferences (module-preferences.html) module\nthat allows reading and writing of the preferences for the Python\ninterpreter.", "python_version": "2.2", "length": 399, "url": "https://docs.python.org/2.2/mac/module-pythonprefs.html"} {"title": "3.9 Qd -- QuickDraw", "text": "module-Menu.html | toolbox.html | module-Qt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.9 Qd -- QuickDraw\nAvailability: Macintosh.", "python_version": "2.2", "length": 175, "url": "https://docs.python.org/2.2/mac/module-Qd.html"} {"title": "3.10 Qt -- QuickTime", "text": "module-Qd.html | toolbox.html | module-Res.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.10 Qt -- QuickTime\nAvailability: Macintosh.", "python_version": "2.2", "length": 175, "url": "https://docs.python.org/2.2/mac/module-Qt.html"} {"title": "4.16 quietconsole -- non-visible stdout output", "text": "module-pythonprefs.html | undocumented-modules.html | module-videoreader.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.16 quietconsole -- non-visible stdout output\nAvailability: Macintosh.\nquietconsole allows you to keep stdio output in a buffer\nwithout displaying it (or without displaying the stdout window\naltogether, if set with EditPythonPrefs) until you try to read from\nstdin or disable the buffering, at which point all the saved output is\nsent to the window. Good for programs with graphical user interfaces\nthat do want to display their output at a crash.", "python_version": "2.2", "length": 608, "url": "https://docs.python.org/2.2/mac/module-quietconsole.html"} {"title": "3.11 Res -- Resource Manager and Handles", "text": "module-Qt.html | toolbox.html | module-Scrap.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.11 Res -- Resource Manager and Handles\nAvailability: Macintosh.", "python_version": "2.2", "length": 197, "url": "https://docs.python.org/2.2/mac/module-Res.html"} {"title": "3.12 Scrap -- Scrap Manager", "text": "module-Res.html | toolbox.html | module-Snd.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.12 Scrap -- Scrap Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 183, "url": "https://docs.python.org/2.2/mac/module-Scrap.html"} {"title": "3.13 Snd -- Sound Manager", "text": "module-Scrap.html | toolbox.html | module-TE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.13 Snd -- Sound Manager\nAvailability: Macintosh.", "python_version": "2.2", "length": 182, "url": "https://docs.python.org/2.2/mac/module-Snd.html"} {"title": "3.14 TE -- TextEdit", "text": "module-Snd.html | toolbox.html | module-waste.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.14 TE -- TextEdit\nAvailability: Macintosh.", "python_version": "2.2", "length": 177, "url": "https://docs.python.org/2.2/mac/module-TE.html"} {"title": "4.17 videoreader -- read QuickTime movies", "text": "module-quietconsole.html | undocumented-modules.html | module-W.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.17 videoreader -- read QuickTime movies\nAvailability: Macintosh.\nvideoreader reads and decodes QuickTime movies and passes\na stream of images to your program. It also provides some support for\naudio tracks.", "python_version": "2.2", "length": 359, "url": "https://docs.python.org/2.2/mac/module-videoreader.html"} {"title": "4.18 W -- Widgets built on FrameWork", "text": "module-videoreader.html | undocumented-modules.html | module-waste.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.18 W -- Widgets built on FrameWork\nAvailability: Macintosh.\nThe W widgets are used extensively in the IDE.", "python_version": "2.2", "length": 262, "url": "https://docs.python.org/2.2/mac/module-W.html"} {"title": "4.19 waste -- non-Apple TextEdit replacement", "text": "module-W.html | undocumented-modules.html | node94.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4.19 waste -- non-Apple TextEdit replacement\nAvailability: Macintosh.\nSee Also:", "python_version": "2.2", "length": 217, "url": "https://docs.python.org/2.2/mac/module-waste.html"} {"title": "3.16 Win -- Window Manager", "text": "module-waste.html | toolbox.html | module-ColorPicker.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3.16 Win -- Window Manager\nAvailability: Macintosh.\n---\nmodule-waste.html | toolbox.html | module-ColorPicker.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\nRelease 2.1, documentation updated on April 15, 2001.", "python_version": "2.2", "length": 389, "url": "https://docs.python.org/2.2/mac/module-Win.html"} {"title": "1.5 Creating a Python script", "text": "argv.html | using.html | node11.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.5 Creating a Python script\nSince Python scripts are simply text files, they can be created in any\nway that text files can be created, but some special tools also exist\nwith extra features.", "python_version": "2.2", "length": 309, "url": "https://docs.python.org/2.2/mac/node10.html"} {"title": "1.5.1 In an editor", "text": "node10.html | node10.html | node12.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.5.1 In an editor\nYou can create a text file with any word processing program such as\nMSWord or AppleWorks but you need to make sure\nthat the file is saved as ``ASCII'' or ``plain text''.", "python_version": "2.2", "length": 311, "url": "https://docs.python.org/2.2/mac/node11.html"} {"title": "1.5.1.1 Editors with Python modes", "text": "node11.html | node11.html | scripting-with-BBedit.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n### 1.5.1.1 Editors with Python modes\nSeveral text editors have additional features that add functionality\nwhen you are creating a Python script. These can include coloring\nPython keywords to make your code easier to read, module browsing, or\na built-in debugger. These include Alpha, Pepper,\nand BBedit, and the MacPython IDE (Section 1.6 (IDE.html#IDE)).", "python_version": "2.2", "length": 491, "url": "https://docs.python.org/2.2/mac/node12.html"} {"title": "1.6.1 Using the ``Python Interactive'' window", "text": "IDE.html | IDE.html | IDEwrite.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.6.1 Using the ``Python Interactive'' window\nUse this window like you would the PythonInterpreter, except\nthat you cannot use the ``Drag and drop'' method above. Instead,\ndropping a script onto the Python IDE icon will open the\nfile in a separate script window (which you can then execute manually\n- see section 1.6.3 (IDEexecution.html#IDEexecution)).", "python_version": "2.2", "length": 472, "url": "https://docs.python.org/2.2/mac/node15.html"} {"title": "1.8 Mac OS X", "text": "defaults.html | using.html | macpython-modules.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.8 Mac OS X\nAt the time of this writing Mac OS X had just been released as a\nPublic Beta. Efforts are under way to bring MacPython to Mac OS X. The\nMacPython release 2.21.5.2c1 runs quite well within the\n``Classic'' environment. A ``Carbon'' port of the MacPython code is\nbeing prepared for release, and several people have made a command\nline version available to the ``Darwin'' layer (which is accessible\nvia Terminal.app).", "python_version": "2.2", "length": 560, "url": "https://docs.python.org/2.2/mac/node23.html"} {"title": "2.5.1 IC Objects", "text": "module-ic.html | module-ic.html | module-MacOS.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.5.1 IC Objects\nIC objects have a mapping interface, hence to obtain the mail\naddress you simply get `ic ['MailAddress']`. Assignment also\nworks, and changes the option in the configuration file.\nThe module knows about various datatypes, and converts the internal IC\nrepresentation to a ``logical'' Python data structure. Running the\nic module standalone will run a test program that lists all\nkeys and values in your IC database, this will have to serve as\ndocumentation.\nIf the module does not know how to represent the data it returns an\ninstance of the `ICOpaqueData` type, with the raw data in its\ndata attribute. Objects of this type are also acceptable values\nfor assignment.\nBesides the dictionary interface, IC objects have the\nfollowing methods:", "python_version": "2.2", "length": 891, "url": "https://docs.python.org/2.2/mac/node34.html"} {"title": "2.6.1 IC Objects", "text": "module-ic.html | module-ic.html | module-MacOS.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.6.1 IC Objects\nIC objects have a mapping interface, hence to obtain the mail\naddress you simply get `ic ['MailAddress']`. Assignment also\nworks, and changes the option in the configuration file.\nThe module knows about various datatypes, and converts the internal IC\nrepresentation to a ``logical'' Python data structure. Running the\nic module standalone will run a test program that lists all\nkeys and values in your IC database, this will have to serve as\ndocumentation.\nIf the module does not know how to represent the data it returns an\ninstance of the `ICOpaqueData` type, with the raw data in its\ndata attribute. Objects of this type are also acceptable values\nfor assignment.\nBesides the dictionary interface, IC objects have the\nfollowing methods:", "python_version": "2.2", "length": 891, "url": "https://docs.python.org/2.2/mac/node36.html"} {"title": "2.10.1 TCP Stream Objects", "text": "module-mactcp.html | module-mactcp.html | node42.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.10.1 TCP Stream Objects", "python_version": "2.2", "length": 162, "url": "https://docs.python.org/2.2/mac/node41.html"} {"title": "2.10.2 TCP Status Objects", "text": "node41.html | module-mactcp.html | node43.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.10.2 TCP Status Objects\nThis object has no methods, only some members holding information on\nthe connection. A complete description of all fields in this objects\ncan be found in the Apple documentation. The most interesting ones are:", "python_version": "2.2", "length": 365, "url": "https://docs.python.org/2.2/mac/node42.html"} {"title": "2.10.3 UDP Stream Objects", "text": "node42.html | module-mactcp.html | module-macspeech.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.10.3 UDP Stream Objects\nNote that, unlike the name suggests, there is nothing stream-like\nabout UDP.", "python_version": "2.2", "length": 242, "url": "https://docs.python.org/2.2/mac/node43.html"} {"title": "1.3 How to run a Python script", "text": "interpreter.html | using.html | node7.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1.3 How to run a Python script\nThere are several ways to run an existing Python script; two common\nways to run a Python script are ``drag and drop'' and ``double\nclicking''. Other ways include running it from within the IDE (see\nSection 1.6 (IDE.html#IDE)), or launching via AppleScript.", "python_version": "2.2", "length": 412, "url": "https://docs.python.org/2.2/mac/node6.html"} {"title": "1.3.1 Drag and drop", "text": "node6.html | node6.html | creator-code.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.3.1 Drag and drop\nOne of the easiest ways to launch a Python script is via ``Drag and\nDrop''. This is just like launching a text file in the Finder by\n``dragging'' it over your word processor's icon and ``dropping'' it\nthere. Make sure that you use an icon referring to the\nPythonInterpreter, not the IDE or Idle\nicons which have different behaviour which is described below.\nSome things that might have gone wrong:\n- A window flashes after dropping the script onto the\nPythonInterpreter, but then disappears. Most likely this is a\nconfiguration issue; your PythonInterpreter is setup to exit\nimmediately upon completion, but your script assumes that if it prints\nsomething that text will stick around for a while. To fix this, see\nsection 1.7.3 (defaults.html#defaults).\n- After dropping the script onto the PythonInterpreter, a\nwindow appeared which said: ``File contains `\\r` characters\n(incorrect line endings?)''. That script probably originated on a\nUnix or Windows machine. You will need to change the line endings\nto the standard Mac usage. One way to do this is to open the file in\nBBedit\n(http://www.barebones.com/products/bbedit_lite.html) which can\neasily change the line endings between Mac, DOS, and Unix styles.\n- When you waved the script icon over the PythonInterpreter,\nthe PythonInterpreter icon did not hilight. Most likely the\nCreator code and document type is unset (or set incorrectly) - this\noften happens when a file originates on a non-Mac computer. See\nsection 1.3.2 (creator-code.html#creator-code) for more details.", "python_version": "2.2", "length": 1673, "url": "https://docs.python.org/2.2/mac/node7.html"} {"title": "A. History and License", "text": "module-waste.html | mac.html | node95.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# A. History and License", "python_version": "2.2", "length": 147, "url": "https://docs.python.org/2.2/mac/node94.html"} {"title": "A.1 History of the software", "text": "node94.html | node94.html | node96.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# A.1 History of the software\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands\nas a successor of a language called ABC. Guido remains Python's\nprincipal author, although it includes many contributions from others.\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)\nin Reston, Virginia where he released several versions of the\nsoftware.\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team. In October of the same\nyear, the PythonLabs team moved to Zope Corporation (then Digital\nCreations; see http://www.zope.com/). In 2001, the Python\nSoftware Foundation (PSF, see http://www.python.org/psf/) was\nformed, a non-profit organization created specifically to own\nPython-related Intellectual Property. Digital Creations is a\nsponsoring member of the PSF.\nAll Python releases are Open Source (see\nhttp://www.opensource.org/ for the Open Source Definition).\nHistorically, most, but not all, Python releases have also been\nGPL-compatible; the table below summarizes the various releases.\nNote:\nGPL-compatible doesn't mean that we're distributing\nPython under the GPL. All Python licenses, unlike the GPL, let you\ndistribute a modified version without making your changes open source.\nThe GPL-compatible licenses make it possible to combine Python with\nother software that is released under the GPL; the others don't.\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.", "python_version": "2.2", "length": 1780, "url": "https://docs.python.org/2.2/mac/node95.html"} {"title": "A.2 Terms and conditions for accessing or otherwise using Python", "text": "node95.html | node94.html | modindex.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# A.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.2\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.2 software in source or binary\nform and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, PSF\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python\n2.2 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001 Python Software Foundation; All Rights\nReserved'' are retained in Python 2.2 alone or in any\nderivative version prepared by Licensee.\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 2.2 or any part thereof, and wants to\nmake the derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 2.2.\n4. PSF is making Python 2.2 available to Licensee on an ``AS IS''\nbasis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE\nPOSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee. This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n8. By copying, installing or otherwise using Python 2.2, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (``Licensee'') accessing and otherwise\nusing this software in source or binary form and its associated\ndocumentation (``the Software'').\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n3. BeOpen is making the Software available to Licensee on an ``AS IS''\nbasis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions. Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee. This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party. As an exception, the ``BeOpen Python'' logos available\nat http://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (``CNRI''), and the Individual or Organization\n(``Licensee'') accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., ``Copyright\n© 1995-2001 Corporation for National Research Initiatives;\nAll Rights Reserved'' are retained in Python 1.6.1 alone or in any\nderivative version prepared by Licensee. Alternately, in lieu of\nCNRI's License Agreement, Licensee may substitute the following text\n(omitting the quotes): ``Python 1.6.1 is made available subject to the\nterms and conditions in CNRI's License Agreement. This Agreement\ntogether with Python 1.6.1 may be located on the Internet using the\nfollowing unique, persistent identifier (known as a handle):\n1895.22/1013. This Agreement may also be obtained from a proxy server\non the Internet using the following URL:\nhttp://hdl.handle.net/1895.22/1013.''\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''\nbasis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement. Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee. This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n8. By clicking on the ``ACCEPT'' button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\nACCEPT\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\nCopyright © 1991 - 1995, Stichting Mathematisch Centrum\nAmsterdam, The Netherlands. All rights reserved.\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", "python_version": "2.2", "length": 9787, "url": "https://docs.python.org/2.2/mac/node96.html"} {"title": "1.5.1.2 BBedit", "text": "node12.html | node11.html | IDE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n### 1.5.1.2 BBedit\nIf you use BBEdit to create your scripts you will want to tell it about the Python creator code so that\nyou can simply double click on the saved file to launch it.\n- Launch BBEdit.\n- Select ``Preferences'' from the ``Edit'' menu.\n- Select ``File Types'' from the scrolling list.\n- click on the ``Add...'' button and navigate to\nPythonInterpreter in the main directory of the\nMacPython distribution; click ``open''.\n- Click on the ``Save'' button in the Preferences panel.", "python_version": "2.2", "length": 607, "url": "https://docs.python.org/2.2/mac/scripting-with-BBedit.html"} {"title": "2.11.4 ScrolledWindow Object", "text": "controlswindow-object.html | module-FrameWork.html | dialogwindow-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.11.4 ScrolledWindow Object\nScrolledWindow objects are ControlsWindow objects with the following\nextra methods:", "python_version": "2.2", "length": 274, "url": "https://docs.python.org/2.2/mac/scrolledwindow-object.html"} {"title": "1.7.2 Adding modules to the Module Search Path", "text": "EditPythonPrefs.html | configuration.html | defaults.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 1.7.2 Adding modules to the Module Search Path\nWhen executing an import statement, Python looks for modules\nin places defined by the sys.path To edit the\nsys.path on a Mac, launch EditPythonPrefs, and\nenter them into the largish field at the top (one per line).\nSince MacPython defines a main Python directory, the easiest thing is\nto add folders to search within the main Python directory. To add a\nfolder of scripts that you created called ``My Folder'' located in the\nmain Python Folder, enter \"$(PYTHON):My Folder\" onto a new line.\nTo add the Desktop under OS 9 or below, add\n\"StartupDriveName:Desktop Folder\" on a new line.", "python_version": "2.2", "length": 769, "url": "https://docs.python.org/2.2/mac/search-path.html"} {"title": "2.9.2 Speech Channel Objects", "text": "voice-objects.html | module-macspeech.html | module-EasyDialogs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.9.2 Speech Channel Objects\nA Speech Channel object allows you to speak strings with slightly more\ncontrol than SpeakString(), and allows you to use multiple\nspeakers at the same time. Please note that channel pitch and rate are\ninterrelated in some way, so that to make your Macintosh sing you will\nhave to adjust both.", "python_version": "2.2", "length": 473, "url": "https://docs.python.org/2.2/mac/speech-channel-objects.html"} {"title": "3. MacOS Toolbox Modules", "text": "module-aetypes.html | mac.html | module-Carbon.AE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 3. MacOS Toolbox Modules\nThere are a set of modules that provide interfaces to various MacOS\ntoolboxes. If applicable the module will define a number of Python\nobjects for the various structures declared by the toolbox, and\noperations will be implemented as methods of the object. Other\noperations will be implemented as functions in the module. Not all\noperations possible in C will also be possible in Python (callbacks\nare often a problem), and parameters will occasionally be different in\nPython (input and output buffers, especially). All methods and\nfunctions have a __doc__ string describing their arguments\nand return values, and for additional description you are referred to\nInside\nMacintosh (http://developer.apple.com/techpubs/macos8/mac8.html) or similar works.\nThese modules all live in a package called Carbon. Despite the\nname Carbon they are also available under classic PPC MacPython.\nThe normal use pattern is\n```text\n\nfrom Carbon import AE\n```\nWarning! These modules are not yet documented. If you\nwish to contribute documentation of any of these modules, please get\nin touch with python-docs@python.org.\nCarbon.AE (module-Carbon.AE.html) | Interface to the Apple Events toolbox\nCarbon.App (module-Carbon.App.html) | Interface to the Appearance Manager\nCarbon.CF (module-Carbon.CF.html) | Interface to the Core Foundation\nCarbon.Cm (module-Carbon.Cm.html) | Interface to the Component Manager\nCarbon.Ctl (module-Carbon.Ctl.html) | Interface to the Control Manager\nCarbon.Dlg (module-Carbon.Dlg.html) | Interface to the Dialog Manager\nCarbon.Evt (module-Carbon.Evt.html) | Interface to the Event Manager\nCarbon.Fm (module-Carbon.Fm.html) | Interface to the Font Manager\nCarbon.Help (module-Carbon.Help.html) | Interface to the Balloon Help Manager\nCarbon.List (module-Carbon.List.html) | Interface to the List Manager\nCarbon.Menu (module-Carbon.Menu.html) | Interface to the Menu Manager\nCarbon.Mlte (module-Carbon.Mlte.html) | Interface to the MultiLingual Text Editor\nCarbon.Qd (module-Carbon.Qd.html) | Interface to the QuickDraw toolbox\nCarbon.Qdoffs (module-Carbon.Qdoffs.html) | Interface to the QuickDraw Offscreen APIs\nCarbon.Qt (module-Carbon.Qt.html) | Interface to the QuickTime toolbox\nCarbon.Res (module-Carbon.Res.html) | Interface to the Resource Manager and Handles\nCarbon.Scrap (module-Carbon.Scrap.html) | The Scrap Manager provides basic services for\nimplementing cut & paste and clipboard operations.\nCarbon.Snd (module-Carbon.Snd.html) | Interface to the Sound Manager\nCarbon.TE (module-Carbon.TE.html) | Interface to TextEdit\nCarbon.Win (module-Carbon.Win.html) | Interface to the Window Manager\nColorPicker (module-ColorPicker.html) | Interface to the standard color selection dialog.", "python_version": "2.2", "length": 2863, "url": "https://docs.python.org/2.2/mac/toolbox.html"} {"title": "4. Undocumented Modules", "text": "module-ColorPicker.html | mac.html | module-applesingle.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 4. Undocumented Modules\nThe modules in this chapter are poorly documented (if at all). If you\nwish to contribute documentation of any of these modules, please get in\ntouch with\npython-docs@python.org (mailto:python-docs@python.org).\napplesingle (module-applesingle.html) | Rudimentary decoder for AppleSingle format files\nbuildtools (module-buildtools.html) | Helper module for BuildApplet, BuildApplication and\nmacfreeze\npy_resource (module-pyresource.html) | Helper to create 'PYC ' resources for compiled\napplications\ncfmfile (module-cfmfile.html) | Code Fragment Resource module\nicopen (module-icopen.html) | Internet Config replacement for open()\nmacerrors (module-macerrors.html) | Constant definitions for many Mac OS error codes\nmacfsn (module-macfsn.html) | NavServices versions of StandardFile calls\nmacresource (module-macresource.html) | Locate script resources\nNac (module-Nac.html) | Interface to Navigation Services\nmactty (module-mactty.html) | Easy access serial to line connections\nmkcwproject (module-mkcwproject.html) | Create CodeWarrior projects\nnsremote (module-nsremote.html) | Wrapper around Netscape OSA modules\nPixMapWrapper (module-PixMapWrapper.html) | Wrapper for PixMap objects\npreferences (module-preferences.html) | Nice application preferences manager with support for\ndefaults\npythonprefs (module-pythonprefs.html) | Specialized preferences manager for the Python\ninterpreter\nquietconsole (module-quietconsole.html) | buffered, non-visible stdout output\nvideoreader (module-videoreader.html) | read QuickTime movies frame by frame for further processing\nW (module-W.html) | Widgets for the Mac, built on top of FrameWork\nwaste (module-waste.html) | Interface to the ``WorldScript-Aware Styled Text Engine.''", "python_version": "2.2", "length": 1885, "url": "https://docs.python.org/2.2/mac/undocumented-modules.html"} {"title": "1. Using Python on the Macintosh", "text": "contents.html | mac.html | getting.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n# 1. Using Python on the Macintosh\nUsing Python on the Macintosh can seem like something completely\ndifferent than using it on a Unix-like or Windows system. Most of the\nPython documentation, both the ``official'' documentation and\npublished books, describe only how Python is used on these systems,\ncausing confusion for the new user of MacPython. This chapter gives a\nbrief introduction to the specifics of using Python on a Macintosh.", "python_version": "2.2", "length": 557, "url": "https://docs.python.org/2.2/mac/using.html"} {"title": "2.9.1 Voice Objects", "text": "module-macspeech.html | module-macspeech.html | speech-channel-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.9.1 Voice Objects\nVoice objects contain the description of a voice. It is currently not\nyet possible to access the parameters of a voice.", "python_version": "2.2", "length": 298, "url": "https://docs.python.org/2.2/mac/voice-objects.html"} {"title": "2.11.2 Window Objects", "text": "application-objects.html | module-FrameWork.html | controlswindow-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\n---\n## 2.11.2 Window Objects\nWindow objects have the following methods, among others:", "python_version": "2.2", "length": 239, "url": "https://docs.python.org/2.2/mac/window-objects.html"} {"title": "Global Module Index", "text": "./ | Global Module Index\n---\n## Global Module Index\nSome module names are followed by an annotation indicating what\nplatform they are available on.", "python_version": "2.2", "length": 147, "url": "https://docs.python.org/2.2/modindex.html"} {"title": "About this document ...", "text": "genindex.html | ref.html | Python Reference Manual | contents.html | genindex.html\n---\n# About this document ...\nPython Reference Manual,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | ref.html | Python Reference Manual | contents.html | genindex.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1705, "url": "https://docs.python.org/2.2/ref/about.html"} {"title": "6.2 Assert statements", "text": "exprstmts.html | simple.html | assignment.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.2 Assert statements\nAssert statementsare a convenient way to insert\ndebugging assertionsinto a program:\n`assert_statement` | ::= | `\"assert\" expression [\",\" expression ]`\nDownload entire grammar as text. (grammar.txt)\nThe simple form, \"assert expression\", is equivalent to\n```text\n\nif __debug__:\nif not expression: raise AssertionError\n```\nThe extended form, \"assert expression1, expression2\", is\nequivalent to\n```text\n\nif __debug__:\nif not expression1: raise AssertionError, expression2\n```\nThese equivalences assume that `__debug__`and\nAssertionErrorrefer to the built-in\nvariables with those names. In the current implementation, the\nbuilt-in variable `__debug__` is 1 under normal circumstances, 0\nwhen optimization is requested (command line option -O). The current\ncode generator emits no code for an assert statement when optimization\nis requested at compile time. Note that it is unnecessary to include\nthe source code for the expression that failed in the error message;\nit will be displayed as part of the stack trace.\nAssignments to `__debug__` are illegal. The value for the\nbuilt-in variable is determined when the interpreter starts.", "python_version": "2.2", "length": 1260, "url": "https://docs.python.org/2.2/ref/assert.html"} {"title": "6.3 Assignment statements", "text": "assert.html | simple.html | augassign.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.3 Assignment statements\nAssignment statementsare used to\n(re)bind names to values and to modify attributes or items of mutable\nobjects:\n`assignment_stmt` | ::= | `( target_list \"=\")+ expression_list`\n`target_list` | ::= | `target (\",\" target )* [\",\"]`\n`target` | ::= | `identifier | \"(\" target_list \")\"\n| \"[\" target_list \"]\"\n| attributeref | subscription | slicing`\nDownload entire grammar as text. (grammar.txt)\n(See section 5.3 (primaries.html#primaries) for the syntax definitions for the last\nthree symbols.)\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable. The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section 3.2 (types.html#types)).\nAssignment of an object to a target list is recursively defined as\nfollows.\n- If the target list is a single target: The object is assigned to that\ntarget.\n- If the target list is a comma-separated list of targets: The object\nmust be a sequence with the same number of items as the there are\ntargets in the target list, and the items are assigned, from left to\nright, to the corresponding targets. (This rule is relaxed as of\nPython 1.5; in earlier versions, the object had to be a tuple. Since\nstrings are sequences, an assignment like \"a, b = \"xy\"\" is\nnow legal as long as the string has the right length.)\nAssignment of an object to a single target is recursively defined as\nfollows.\n- If the target is an identifier (name):\n- If the name does not occur in a global statement in the current\ncode block: the name is bound to the object in the current local\nnamespace.\n- Otherwise: the name is bound to the object in the current global\nnamespace.\nThe name is rebound if it was already bound. This may cause the\nreference count for the object previously bound to the name to reach\nzero, causing the object to be deallocated and its\ndestructor(if it has one) to be called.\n- If the target is a target list enclosed in parentheses or in square\nbrackets: The object must be a sequence with the same number of items\nas there are targets in the target list, and its items are assigned,\nfrom left to right, to the corresponding targets.\n- If the target is an attribute reference: The primary expression in the\nreference is evaluated. It should yield an object with assignable\nattributes; if this is not the case, TypeError is raised. That\nobject is then asked to assign the assigned object to the given\nattribute; if it cannot perform the assignment, it raises an exception\n(usually but not necessarily AttributeError).\n- If the target is a subscription: The primary expression in the\nreference is evaluated. It should yield either a mutable sequence\nobject (e.g., a list) or a mapping object (e.g., a dictionary). Next,\nthe subscript expression is evaluated.\nIf the primary is a mutable sequence object (e.g., a list), the subscript\nmust yield a plain integer. If it is negative, the sequence's length\nis added to it. The resulting value must be a nonnegative integer\nless than the sequence's length, and the sequence is asked to assign\nthe assigned object to its item with that index. If the index is out\nof range, IndexError is raised (assignment to a subscripted\nsequence cannot add new items to a list).\nIf the primary is a mapping object (e.g., a dictionary), the subscript must\nhave a type compatible with the mapping's key type, and the mapping is\nthen asked to create a key/datum pair which maps the subscript to\nthe assigned object. This can either replace an existing key/value\npair with the same key value, or insert a new key/value pair (if no\nkey with the same value existed).\n- If the target is a slicing: The primary expression in the reference is\nevaluated. It should yield a mutable sequence object (e.g., a list). The\nassigned object should be a sequence object of the same type. Next,\nthe lower and upper bound expressions are evaluated, insofar they are\npresent; defaults are zero and the sequence's length. The bounds\nshould evaluate to (small) integers. If either bound is negative, the\nsequence's length is added to it. The resulting bounds are clipped to\nlie between zero and the sequence's length, inclusive. Finally, the\nsequence object is asked to replace the slice with the items of the\nassigned sequence. The length of the slice may be different from the\nlength of the assigned sequence, thus changing the length of the\ntarget sequence, if the object allows it.\n(In the current implementation, the syntax for targets is taken\nto be the same as for expressions, and invalid syntax is rejected\nduring the code generation phase, causing less detailed error\nmessages.)\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are `safe' (e.g.,\n\"a, b = b, a\" swaps two variables), overlaps within the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints \"[0, 2]\":\n```text\n\nx = [0, 1]\ni = 0\ni, x[i] = 1, 2\nprint x\n```", "python_version": "2.2", "length": 5578, "url": "https://docs.python.org/2.2/ref/assignment.html"} {"title": "5.2.1 Identifiers (Names)", "text": "atoms.html | atoms.html | atom-literals.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.1 Identifiers (Names)\nAn identifier occurring as an atom is a reference to a local, global\nor built-in name binding. If a name is assigned to anywhere in a code\nblock (even in unreachable code), and is not mentioned in a\nglobal statement in that code block, then it refers to a local\nname throughout that code block. When it is not assigned to anywhere\nin the block, or when it is assigned to but also explicitly listed in\na global statement, it refers to a global name if one exists,\nelse to a built-in name (and this binding may dynamically\nchange).5.1 (#foot3570)\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a NameError exception.\nPrivate name mangling:when an identifier that textually occurs in a class definition begins\nwith two or more underscore characters and does not end in two or more\nunderscores, it is considered a private name of that class.\nPrivate names are transformed to a longer form before code is\ngenerated for them. The transformation inserts the class name in\nfront of the name, with leading underscores removed, and a single\nunderscore inserted in front of the class name. For example, the\nidentifier `__spam` occurring in a class named `Ham` will be\ntransformed to `_Ham__spam`. This transformation is independent\nof the syntactical context in which the identifier is used. If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen. If the class name\nconsists only of underscores, no transformation is done.", "python_version": "2.2", "length": 1701, "url": "https://docs.python.org/2.2/ref/atom-identifiers.html"} {"title": "5.2.2 Literals", "text": "atom-identifiers.html | atoms.html | parenthesized.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.2 Literals\nPython supports string literals and various numeric literals:\n`literal` | ::= | `stringliteral | integer | longinteger | floatnumber | imagnumber`\nDownload entire grammar as text. (grammar.txt)\nEvaluation of a literal yields an object of the given type (string,\ninteger, long integer, floating point number, complex number) with the\ngiven value. The value may be approximated in the case of floating\npoint and imaginary (complex) literals. See section 2.4 (literals.html#literals)\nfor details.\nAll literals correspond to immutable data types, and hence the\nobject's identity is less important than its value. Multiple\nevaluations of literals with the same value (either the same\noccurrence in the program text or a different occurrence) may obtain\nthe same object or a different object with the same value.", "python_version": "2.2", "length": 942, "url": "https://docs.python.org/2.2/ref/atom-literals.html"} {"title": "5.2 Atoms", "text": "conversions.html | expressions.html | atom-identifiers.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.2 Atoms\nAtoms are the most basic elements of expressions. The simplest atoms\nare identifiers or literals. Forms enclosed in\nreverse quotes or in parentheses, brackets or braces are also\ncategorized syntactically as atoms. The syntax for atoms is:\n`atom` | ::= | `identifier | literal | enclosure`\n`enclosure` | ::= | `parenth_form | list_display | dict_display | string_conversion`\nDownload entire grammar as text. (grammar.txt)", "python_version": "2.2", "length": 554, "url": "https://docs.python.org/2.2/ref/atoms.html"} {"title": "3.3.2 Customizing attribute access", "text": "customization.html | specialnames.html | callable-types.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.2 Customizing attribute access\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of `x.name`)\nfor class instances.\nFor performance reasons, these methods are cached in the class object\nat class definition time; therefore, they cannot be changed after the\nclass definition is executed.", "python_version": "2.2", "length": 482, "url": "https://docs.python.org/2.2/ref/attribute-access.html"} {"title": "5.3.1 Attribute references", "text": "primaries.html | primaries.html | subscriptions.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.1 Attribute references\nAn attribute reference is a primary followed by a period and a name:\n`attributeref` | ::= | `primary \".\" identifier`\nDownload entire grammar as text. (grammar.txt)\nThe primary must evaluate to an object of a type that supports\nattribute references, e.g., a module, list, or an instance. This\nobject is then asked to produce the attribute whose name is the\nidentifier. If this attribute is not available, the exception\nAttributeErroris raised.\nOtherwise, the type and value of the object produced is determined by\nthe object. Multiple evaluations of the same attribute reference may\nyield different objects.", "python_version": "2.2", "length": 751, "url": "https://docs.python.org/2.2/ref/attribute-references.html"} {"title": "6.3.1 Augmented Assignment statements", "text": "assignment.html | assignment.html | pass.html | Python Reference Manual | contents.html | genindex.html\n---\n## 6.3.1 Augmented Assignment statements\nAugmented assignment is the combination, in a single statement, of a binary\noperation and an assignment statement:\n`augmented_assignment_stmt` | ::= | `target augop expression_list`\n`augop` | ::= | `\"+=\" | \"-=\" | \"*=\" | \"/=\" | \"%=\" | \"**=\"\n| \"»=\" | \"«=\" | \"&=\" | \"^=\" | \"|=\"`\n`target` | ::= | `identifier | \"(\" target_list \")\"\n| \"[\" target_list \"]\"\n| attributeref | subscription | slicing`\nDownload entire grammar as text. (grammar.txt)\n(See section 5.3 (primaries.html#primaries) for the syntax definitions for the last\nthree symbols.)\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original\ntarget. The target is only evaluated once.\nAn augmented assignment expression like `x += 1` can be rewritten as\n`x = x + 1` to achieve a similar, but not exactly equal effect. In the\naugmented version, `x` is only evaluated once. Also, when possible, the\nactual operation is performed in-place, meaning that rather than\ncreating a new object and assigning that to the target, the old object is\nmodified instead.\nWith the exception of assigning to tuples and multiple targets in a single\nstatement, the assignment done by augmented assignment statements is handled\nthe same way as normal assignments. Similarly, with the exception of the\npossible in-place behavior, the binary operation performed by\naugmented assignment is the same as the normal binary operations.", "python_version": "2.2", "length": 1714, "url": "https://docs.python.org/2.2/ref/augassign.html"} {"title": "5.6 Binary arithmetic operations", "text": "unary.html | expressions.html | shifting.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.6 Binary arithmetic operations\nThe binary arithmetic operations have the conventional priority\nlevels. Note that some of these operations also apply to certain\nnon-numeric types. Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n`m_expr` | ::= | `u_expr | m_expr \"*\" u_expr | m_expr \"/\" u_expr | m_expr \"%\" u_expr`\n`a_expr` | ::= | `m_expr | aexpr \"+\" m_expr aexpr \"-\" m_expr`\nDownload entire grammar as text. (grammar.txt)\nThe `*` (multiplication) operator yields the product of its\narguments. The arguments must either both be numbers, or one argument\nmust be an integer (plain or long) and the other must be a sequence.\nIn the former case, the numbers are converted to a common type and\nthen multiplied together. In the latter case, sequence repetition is\nperformed; a negative repetition factor yields an empty sequence.\nThe `/` (division) operator yields the quotient of its\narguments. The numeric arguments are first converted to a common\ntype. Plain or long integer division yields an integer of the same\ntype; the result is that of mathematical division with the `floor'\nfunction applied to the result. Division by zero raises the\nZeroDivisionError exception.\nThe `%` (modulo) operator yields the remainder from the\ndivision of the first argument by the second. The numeric arguments\nare first converted to a common type. A zero right argument raises\nthe ZeroDivisionError exception. The arguments may be floating\npoint numbers, e.g., `3.14%0.7` equals `0.34` (since\n`3.14` equals `4*0.7 + 0.34`.) The modulo operator always\nyields a result with the same sign as its second operand (or zero);\nthe absolute value of the result is strictly smaller than the second\noperand.\nThe integer division and modulo operators are connected by the\nfollowing identity: `x == (x/y)*y + (x%y)`. Integer division and\nmodulo are also connected with the built-in function divmod():\n`divmod(x, y) == (x/y, x%y)`. These identities don't hold for\nfloating point and complex numbers; there similar identities hold\napproximately where `x/y` is replaced by `floor(x/y)`) or\n`floor(x/y) - 1` (for floats),5.2 (#foot3686) or `floor((x/y).real)` (for\ncomplex).\nThe `+` (addition) operator yields the sum of its arguments.\nThe arguments must either both be numbers or both sequences of the\nsame type. In the former case, the numbers are converted to a common\ntype and then added together. In the latter case, the sequences are\nconcatenated.\nThe `-` (subtraction) operator yields the difference of its\narguments. The numeric arguments are first converted to a common\ntype.", "python_version": "2.2", "length": 2734, "url": "https://docs.python.org/2.2/ref/binary.html"} {"title": "5.8 Binary bit-wise operations", "text": "shifting.html | expressions.html | comparisons.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.8 Binary bit-wise operations\nEach of the three bitwise operations has a different priority level:\n`and_expr` | ::= | `shift_expr | and_expr \"&\" shift_expr`\n`xor_expr` | ::= | `and_expr | xor_expr \"^\" and_expr`\n`or_expr` | ::= | `xor_expr | or_expr \"|\" xor_expr`\nDownload entire grammar as text. (grammar.txt)\nThe `&` operator yields the bitwise AND of its arguments, which\nmust be plain or long integers. The arguments are converted to a\ncommon type.\nThe `^` operator yields the bitwise XOR (exclusive OR) of its\narguments, which must be plain or long integers. The arguments are\nconverted to a common type.\nThe `|` operator yields the bitwise (inclusive) OR of its\narguments, which must be plain or long integers. The arguments are\nconverted to a common type.", "python_version": "2.2", "length": 878, "url": "https://docs.python.org/2.2/ref/bitwise.html"} {"title": "2.1.6 Blank lines", "text": "implicit-joining.html | line-structure.html | indentation.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.6 Blank lines\nA logical line that contains only spaces, tabs, formfeeds and possibly\na comment, is ignored (i.e., no NEWLINE token is generated). During\ninteractive input of statements, handling of a blank line may differ\ndepending on the implementation of the read-eval-print loop. In the\nstandard implementation, an entirely blank logical line (i.e. one\ncontaining not even whitespace or a comment) terminates a multi-line\nstatement.", "python_version": "2.2", "length": 567, "url": "https://docs.python.org/2.2/ref/blank-lines.html"} {"title": "6.10 The break statement", "text": "raise.html | simple.html | continue.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.10 The break statement\n`break_stmt` | ::= | `\"break\"`\nDownload entire grammar as text. (grammar.txt)\nbreak may only occur syntactically nested in a for\nor while loop, but not nested in a function or class definition\nwithin that loop.\nIt terminates the nearest enclosing loop, skipping the optional\nelse clause if the loop has one.\nIf a for loop is terminated by break, the loop control\ntarget keeps its current value.\nWhen break passes control out of a try statement\nwith a finally clause, that finally clause is executed\nbefore really leaving the loop.", "python_version": "2.2", "length": 660, "url": "https://docs.python.org/2.2/ref/break.html"} {"title": "3.3.3 Emulating callable objects", "text": "attribute-access.html | specialnames.html | sequence-types.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.3 Emulating callable objects", "python_version": "2.2", "length": 161, "url": "https://docs.python.org/2.2/ref/callable-types.html"} {"title": "5.3.4 Calls", "text": "slicings.html | primaries.html | power.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.4 Calls\nA call calls a callable object (e.g., a function) with a possibly empty\nseries of arguments:\n`call` | ::= | `primary \"(\" [ argument_list [\",\"]] \")\"`\n`argument_list` | ::= | `positional_arguments [\",\" keyword_arguments [\",\" \"*\" expression [\",\" \"**\" expression ]]]\n| keyword_arguments [\",\" \"*\" expression [\",\" \"**\" expression ]]\n| \"*\" expression [\",\" \"**\" expression ]\n| \"**\" expression`\n`positional_arguments` | ::= | `expression (\",\" expression )*`\n`keyword_arguments` | ::= | `keyword_item (\",\" keyword_item )*`\n`keyword_item` | ::= | `identifier \"=\" expression`\nDownload entire grammar as text. (grammar.txt)\nA trailing comma may be present after an argument list but does not\naffect the semantics.\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and certain class instances\nthemselves are callable; extensions may define additional callable\nobject types). All argument expressions are evaluated before the call\nis attempted. Please refer to section 7.5 (function.html#function) for the syntax\nof formal parameter lists.\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows. First, a list of unfilled slots is\ncreated for the formal parameters. If there are N positional\narguments, they are placed in the first N slots. Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on). If the slot is\nalready filled, a TypeError exception is raised.\nOtherwise, the value of the argument is placed in the slot, filling it\n(even if the expression is `None`, it fills the slot). When all\narguments have been processed, the slots that are still unfilled are\nfilled with the corresponding default value from the function\ndefinition. (Default values are calculated, once, when the function\nis defined; thus, a mutable object such as a list or dictionary used\nas default value will be shared by all calls that don't specify an\nargument value for the corresponding slot; this should usually be\navoided.) If there are any unfilled slots for which no default value\nis specified, a TypeError exception is raised. Otherwise,\nthe list of filled slots is used as the argument list for the call.\nIf there are more positional arguments than there are formal parameter\nslots, a TypeError exception is raised, unless a formal\nparameter using the syntax \"*identifier\" is present; in this\ncase, that formal parameter receives a tuple containing the excess\npositional arguments (or an empty tuple if there were no excess\npositional arguments).\nIf any keyword argument does not correspond to a formal parameter\nname, a TypeError exception is raised, unless a formal\nparameter using the syntax \"**identifier\" is present; in this\ncase, that formal parameter receives a dictionary containing the\nexcess keyword arguments (using the keywords as keys and the argument\nvalues as corresponding values), or a (new) empty dictionary if there\nwere no excess keyword arguments.\nIf the syntax \"*expression\" appears in the function call,\n\"expression\" must evaluate to a sequence. Elements from this\nsequence are treated as if they were additional positional arguments;\nif there are postional arguments x1,...,xN , and\n\"expression\" evaluates to a sequence y1,...,yM, this\nis equivalent to a call with M+N positional arguments\nx1,...,xN,y1,...,yM.\nA consequence of this is that although the \"*expression\" syntax\nappears after any keyword arguments, it is processed\nbefore the keyword arguments (and the\n\"**expression\" argument, if any - see below). So:\n```text\n\n>>> def f(a, b):\n... print a, b\n...\n>>> f(b=1, *(2,))\n2 1\n>>> f(a=1, *(2,))\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: f() got multiple values for keyword argument 'a'\n>>> f(1, *(2,))\n1 2\n```\nIt is unusual for both keyword arguments and the\n\"*expression\" syntax to be used in the same call, so in practice\nthis confusion does not arise.\nIf the syntax \"**expression\" appears in the function call,\n\"expression\" must evaluate to a (subclass of) dictionary, the\ncontents of which are treated as additional keyword arguments. In the\ncase of a keyword appearing in both \"expression\" and as an\nexplicit keyword argument, a TypeError exception is\nraised.\nFormal parameters using the syntax \"*identifier\" or\n\"**identifier\" cannot be used as positional argument slots or\nas keyword argument names. Formal parameters using the syntax\n\"(sublist)\" cannot be used as keyword argument names; the\noutermost sublist corresponds to a single unnamed argument slot, and\nthe argument value is assigned to the sublist using the usual tuple\nassignment rules after all other parameter processing is done.\nA call always returns some value, possibly `None`, unless it\nraises an exception. How this value is computed depends on the type\nof the callable object.\nIf it is--\na user-defined function:: The code block for the function is\nexecuted, passing it the argument list. The first thing the code\nblock will do is bind the formal parameters to the arguments; this is\ndescribed in section 7.5 (function.html#function). When the code block executes a\nreturn statement, this specifies the return value of the\nfunction call.\na built-in function or method:: The result is up to the\ninterpreter; see the Python\nLibrary Reference (../lib/built-in-funcs.html) for the descriptions of built-in functions and\nmethods.\na class object:: A new instance of that class is returned.\na class instance method:: The corresponding user-defined\nfunction is called, with an argument list that is one longer than the\nargument list of the call: the instance becomes the first argument.\na class instance:: The class must define a __call__()\nmethod; the effect is then the same as if that method was called.", "python_version": "2.2", "length": 6022, "url": "https://docs.python.org/2.2/ref/calls.html"} {"title": "7.6 Class definitions", "text": "function.html | compound.html | top-level.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.6 Class definitions\nA class definition defines a class object (see section 3.2 (types.html#types)):\n`classdef` | ::= | `\"class\" classname [ inheritance ] \":\" suite`\n`inheritance` | ::= | `\"(\" [ expression_list ] \")\"`\n`classname` | ::= | `identifier`\nDownload entire grammar as text. (grammar.txt)\nA class definition is an executable statement. It first evaluates the\ninheritance list, if present. Each item in the inheritance list\nshould evaluate to a class object. The class's suite is then executed\nin a new execution frame (see section 4.1 (execframes.html#execframes)), using a newly\ncreated local namespace and the original global namespace.\n(Usually, the suite contains only function definitions.) When the\nclass's suite finishes execution, its execution frame is discarded but\nits local namespace is saved. A class object is then created using\nthe inheritance list for the base classes and the saved local\nnamespace for the attribute dictionary. The class name is bound to this\nclass object in the original local namespace.", "python_version": "2.2", "length": 1143, "url": "https://docs.python.org/2.2/ref/class.html"} {"title": "2.1.3 Comments", "text": "physical.html | line-structure.html | explicit-joining.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.3 Comments\nA comment starts with a hash character (`#`) that is not part of\na string literal, and ends at the end of the physical line. A comment\nsignifies the end of the logical line unless the implicit line joining\nrules are invoked.\nComments are ignored by the syntax; they are not tokens.", "python_version": "2.2", "length": 421, "url": "https://docs.python.org/2.2/ref/comments.html"} {"title": "5.9 Comparisons", "text": "bitwise.html | expressions.html | lambda.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.9 Comparisons\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation. Also unlike C, expressions like `a < b < c` have the\ninterpretation that is conventional in mathematics:\n`comparison` | ::= | `or_expr ( comp_operator or_expr )*`\n`comp_operator` | ::= | `\"<\" | \">\" | \"==\" | \">=\" | \"<=\" | \"<>\" | \"!=\"\n| \"is\" [\"not\"] | [\"not\"] \"in\"`\nDownload entire grammar as text. (grammar.txt)\nComparisons yield integer values: `1` for true, `0` for false.\nComparisons can be chained arbitrarily, e.g., `x < y <= z` is\nequivalent to `x < y and y <= z`, except that `y` is\nevaluated only once (but in both cases `z` is not evaluated at all\nwhen `x < y` is found to be false).\nFormally, if a, b, c, ..., y, z are\nexpressions and opa, opb, ..., opy are comparison\noperators, then a opa b opb c ...y opy z is equivalent\nto a opa b and b opb c and ...\ny opy z, except that each expression is evaluated at most once.\nNote that a opa b opb c doesn't imply any kind of comparison\nbetween a and c, so that, e.g., `x < y > z` is\nperfectly legal (though perhaps not pretty).\nThe forms `<>` and `!=` are equivalent; for consistency with\nC, `!=` is preferred; where `!=` is mentioned below\n`<>` is also accepted. The `<>` spelling is considered\nobsolescent.\nThe operators `<`, `>`, `==`, `>=`, `<=`, and\n`!=` compare\nthe values of two objects. The objects need not have the same type.\nIf both are numbers, they are coverted to a common type. Otherwise,\nobjects of different types always compare unequal, and are\nordered consistently but arbitrarily.\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the in and\nnot in operators. In the future, the comparison rules for\nobjects of different types are likely to change.)\nComparison of objects of the same type depends on the type:\n- Numbers are compared arithmetically.\n- Strings are compared lexicographically using the numeric equivalents\n(the result of the built-in function ord()) of their\ncharacters. Unicode and 8-bit strings are fully interoperable in this\nbehavior.\n- Tuples and lists are compared lexicographically using comparison of\ncorresponding items.\n- Mappings (dictionaries) compare equal if and only if their sorted\n(key, value) lists compare equal.5.3 (#foot3339)Outcomes other than equality are resolved consistently, but are not\notherwise defined.5.4 (#foot3632)\n- Most other types compare unequal unless they are the same object;\nthe choice whether one object is considered smaller or larger than\nanother one is made arbitrarily but consistently within one\nexecution of a program.\nThe operators in and not in test for set\nmembership. `x in s` evaluates to true if x\nis a member of the set s, and false otherwise. `x not in s` returns the negation of `x in s`.\nThe set membership test has traditionally been bound to sequences; an\nobject is a member of a set if the set is a sequence and contains an\nelement equal to that object. However, it is possible for an object\nto support membership tests without being a sequence. In particular,\ndictionaries support memership testing as a nicer way of spelling\n`key in dict`; other mapping types may follow suit.\nFor the list and tuple types, `x in y` is true if and\nonly if there exists an index i such that\n`x == y [ i ]` is true.\nFor the Unicode and string types, `x in y` is true if\nand only if there exists an index i such that `x == y [ i ]` is true. If `x` is not a string or\nUnicode object of length `1`, a TypeError exception\nis raised.\nFor user-defined classes which define the __contains__() method,\n`x in y` is true if and only if\n`y .__contains__( x )` is true.\nFor user-defined classes which do not define __contains__() and\ndo define __getitem__(), `x in y` is true if\nand only if there is a non-negative integer index i such that\n`x == y [ i ]`, and all lower integer indices\ndo not raise IndexError exception. (If any other exception\nis raised, it is as if in raised that exception).\nThe operator not in is defined to have the inverse true value\nof in.\nThe operators is and is not test for object identity:\n`x is y` is true if and only if x and y\nare the same object. `x is not y` yields the inverse\ntruth value.", "python_version": "2.2", "length": 4370, "url": "https://docs.python.org/2.2/ref/comparisons.html"} {"title": "7. Compound statements", "text": "exec.html | ref.html | if.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7. Compound statements\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way. In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\nThe if, while and for statements implement\ntraditional control flow constructs. try specifies exception\nhandlers and/or cleanup code for a group of statements. Function and\nclass definitions are also syntactically compound statements.\nCompound statements consist of one or more `clauses.' A clause\nconsists of a header and a `suite.' The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon. A suite is a group of statements controlled by a\nclause. A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header's\ncolon, or it can be one or more indented statements on subsequent\nlines. Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn't be\nclear to which if clause a following else clause would\nbelong:\n```text\n\nif test1: if test2: print x\n```\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\nprint statements are executed:\n```text\n\nif x < y < z: print x; print y; print z\n```\nSummarizing:\n`compound_stmt` | ::= | `if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef`\n`suite` | ::= | `stmt_list NEWLINE\n| NEWLINE INDENT statement + DEDENT`\n`statement` | ::= | `stmt_list NEWLINE | compound_stmt`\n`stmt_list` | ::= | `simple_stmt (\";\" simple_stmt )* [\";\"]`\nDownload entire grammar as text. (grammar.txt)\nNote that statements always end in a\n`NEWLINE`possibly followed by a\n`DEDENT`.Also note that optional\ncontinuation clauses always begin with a keyword that cannot start a\nstatement, thus there are no ambiguities (the `dangling\nelse' problem is solved in Python by requiring nested\nif statements to be indented).\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.", "python_version": "2.2", "length": 2367, "url": "https://docs.python.org/2.2/ref/compound.html"} {"title": "Contents", "text": "front.html | ref.html | introduction.html | Python Reference Manual | genindex.html\n---\n## Contents\nTable of Contents\n- Front Matter (front.html)\n 1. Introduction (introduction.html)\n - 1.1 Notation (notation.html)\n 2. Lexical analysis (lexical.html)\n - 2.1 Line structure (line-structure.html)\n - 2.1.1 Logical lines (logical.html)\n 2.1.2 Physical lines (physical.html)\n 2.1.3 Comments (comments.html)\n 2.1.4 Explicit line joining (explicit-joining.html)\n 2.1.5 Implicit line joining (implicit-joining.html)\n 2.1.6 Blank lines (blank-lines.html)\n 2.1.7 Indentation (indentation.html)\n 2.1.8 Whitespace between tokens (whitespace.html)\n 2.2 Other tokens (other-tokens.html)\n 2.3 Identifiers and keywords (identifiers.html)\n - 2.3.1 Keywords (keywords.html)\n 2.3.2 Reserved classes of identifiers (id-classes.html)\n 2.4 Literals (literals.html)\n - 2.4.1 String literals (strings.html)\n 2.4.2 String literal concatenation (string-catenation.html)\n 2.4.3 Numeric literals (numbers.html)\n 2.4.4 Integer and long integer literals (integers.html)\n 2.4.5 Floating point literals (floating.html)\n 2.4.6 Imaginary literals (imaginary.html)\n 2.5 Operators (operators.html)\n 2.6 Delimiters (delimiters.html)\n 3. Data model (datamodel.html)\n - 3.1 Objects, values and types (objects.html)\n 3.2 The standard type hierarchy (types.html)\n 3.3 Special method names (specialnames.html)\n - 3.3.1 Basic customization (customization.html)\n 3.3.2 Customizing attribute access (attribute-access.html)\n 3.3.3 Emulating callable objects (callable-types.html)\n 3.3.4 Emulating container types (sequence-types.html)\n 3.3.5 Additional methods for emulation of sequence types (sequence-methods.html)\n 3.3.6 Emulating numeric types (numeric-types.html)\n 4. Execution model (execmodel.html)\n - 4.1 Code blocks, execution frames, and namespaces (execframes.html)\n 4.2 Exceptions (exceptions.html)\n 5. Expressions (expressions.html)\n - 5.1 Arithmetic conversions (conversions.html)\n 5.2 Atoms (atoms.html)\n - 5.2.1 Identifiers (Names) (atom-identifiers.html)\n 5.2.2 Literals (atom-literals.html)\n 5.2.3 Parenthesized forms (parenthesized.html)\n 5.2.4 List displays (lists.html)\n 5.2.5 Dictionary displays (dict.html)\n 5.2.6 String conversions (string-conversions.html)\n 5.3 Primaries (primaries.html)\n - 5.3.1 Attribute references (attribute-references.html)\n 5.3.2 Subscriptions (subscriptions.html)\n 5.3.3 Slicings (slicings.html)\n 5.3.4 Calls (calls.html)\n 5.4 The power operator (power.html)\n 5.5 Unary arithmetic operations (unary.html)\n 5.6 Binary arithmetic operations (binary.html)\n 5.7 Shifting operations (shifting.html)\n 5.8 Binary bit-wise operations (bitwise.html)\n 5.9 Comparisons (comparisons.html)\n 5.10 Boolean operations (lambda.html)\n 5.11 Expression lists (exprlists.html)\n 5.12 Summary (summary.html)\n 6. Simple statements (simple.html)\n - 6.1 Expression statements (exprstmts.html)\n 6.2 Assert statements (assert.html)\n 6.3 Assignment statements (assignment.html)\n - 6.3.1 Augmented Assignment statements (augassign.html)\n 6.4 The pass statement (pass.html)\n 6.5 The del statement (del.html)\n 6.6 The print statement (print.html)\n 6.7 The return statement (return.html)\n 6.8 The yield statement (yield.html)\n 6.9 The raise statement (raise.html)\n 6.10 The break statement (break.html)\n 6.11 The continue statement (continue.html)\n 6.12 The import statement (import.html)\n 6.13 The global statement (global.html)\n 6.14 The exec statement (exec.html)\n 7. Compound statements (compound.html)\n - 7.1 The if statement (if.html)\n 7.2 The while statement (while.html)\n 7.3 The for statement (for.html)\n 7.4 The try statement (try.html)\n 7.5 Function definitions (function.html)\n 7.6 Class definitions (class.html)\n 8. Top-level components (top-level.html)\n - 8.1 Complete Python programs (programs.html)\n 8.2 File input (file-input.html)\n 8.3 Interactive input (interactive.html)\n 8.4 Expression input (expression-input.html)\n A. Future statements and nested scopes (futures.html)\n - A.1 Future statements (future-statements.html)\n A.2 __future__ -- Future statement definitions (module-future.html)\n A.3 Nested scopes (nested-scopes.html)\n - A.3.1 Definitions and rules (definitions.html)\n A.3.2 Interaction with dynamic features (dynamic-features.html)\n B. History and License (node98.html)\n - B.1 History of the software (node99.html)\n B.2 Terms and conditions for accessing or otherwise using Python (node100.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.2", "length": 4563, "url": "https://docs.python.org/2.2/ref/contents.html"} {"title": "6.11 The continue statement", "text": "break.html | simple.html | import.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.11 The continue statement\n`continue_stmt` | ::= | `\"continue\"`\nDownload entire grammar as text. (grammar.txt)\ncontinue may only occur syntactically nested in a for or\nwhile loop, but not nested in a function or class definition or\ntry statement within that loop.6.1 (#foot4617)It continues with the next cycle of the nearest enclosing loop.", "python_version": "2.2", "length": 445, "url": "https://docs.python.org/2.2/ref/continue.html"} {"title": "5.1 Arithmetic conversions", "text": "expressions.html | expressions.html | atoms.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.1 Arithmetic conversions\nWhen a description of an arithmetic operator below uses the phrase\n``the numeric arguments are converted to a common type,'' the\narguments are coerced using the coercion rules listed at the end of\nchapter 3 (datamodel.html#datamodel). If both arguments are standard numeric\ntypes, the following coercions are applied:\n- If either argument is a complex number, the other is converted\nto complex;\n- otherwise, if either argument is a floating point number,\nthe other is converted to floating point;\n- otherwise, if either argument is a long integer,\nthe other is converted to long integer;\n- otherwise, both must be plain integers and no conversion\nis necessary.\nSome additional rules apply for certain operators (e.g., a string left\nargument to the `%' operator). Extensions can define their own\ncoercions.", "python_version": "2.2", "length": 945, "url": "https://docs.python.org/2.2/ref/conversions.html"} {"title": "3.3.1 Basic customization", "text": "specialnames.html | specialnames.html | attribute-access.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.1 Basic customization", "python_version": "2.2", "length": 152, "url": "https://docs.python.org/2.2/ref/customization.html"} {"title": "3. Data model", "text": "delimiters.html | ref.html | objects.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3. Data model", "python_version": "2.2", "length": 119, "url": "https://docs.python.org/2.2/ref/datamodel.html"} {"title": "A.3.1 Definitions and rules", "text": "nested-scopes.html | nested-scopes.html | dynamic-features.html | Python Reference Manual | contents.html | genindex.html\n---\n## A.3.1 Definitions and rules\nNames refer to objects. Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe binding of that name established in the innermost function block\ncontaining the use.\nA block is a piece of Python program text that is executed as\na unit. The following are blocks: a module, a function body, and a\nclass defintion.\nA scope defines the visibility of a name within a block. If a\nlocal variable is defined in a block, it's scope includes that block.\nIf the definition occurs in a function block, the scope extends to any\nblocks contained within the defining one, unless a contained block\nintroduces a different binding for the name. The scope of names\ndefined in a class block is limited to the class block; it does not\nextend to the code blocks of methods.\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope. The set of all such scopes visible to a code block\nis called the block's environment.\nIf a name is bound in a block, it is a local variable of that block.\nIf a name is bound at the module level, it is a global variable. (The\nvariables of the module code block are local and global.) If a\nvariable is used in a code block but not defined there, it is a\nfree variable.\nThe name binding operations are assignment, class and function\ndefinition, import statements, for statements, and except statements.\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block. This can lead to errors when a name is used within a\nblock before it is bound.\nThe previous rule is a subtle. Python lacks declarations and allows\nname binding operations to occur anywhere within a code block. The\nlocal variables of a code block can be determined by scanning the\nentire text of the block for name binding operations.\nIf the global statement occurs within a block, all uses of the name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtin namespace, the namespace of\nthe module __builtin__. The global namespace is searched\nfirst. If the name is not found there, the builtin namespace is\nsearched. The global statement must precede all uses of the name.\nThe global statement has the same scope as a name binding operation\nin the same block. If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.", "python_version": "2.2", "length": 3206, "url": "https://docs.python.org/2.2/ref/definitions.html"} {"title": "A.3.1 Definitions and rules", "text": "nested-scopes.html | nested-scopes.html | dynamic-features.html | Python Reference Manual | contents.html | genindex.html\n---\n## A.3.1 Definitions and rules\nNames refer to objects. Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe binding of that name established in the innermost function block\ncontaining the use.\nA block is a pice of Python program text that can is executed as\na unit. The following are blocks: a module, a function body, and a\nclass defintion.\nA scope defines the visibility of a name within a block. If a\nlocal variable is defined in a block, it's scope includes that block.\nIf the definition occurs in a function block, the scope extends to any\nblocks contained within the defining one, unless a contained block\nintroduces a different binding for the name. The scope of names\ndefined in a class block is limited to the class block; it does not\nextend to the code blocks of methods.\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope. The set of all such scopes visible to a code block\nis called the block's environment.\nIf a name is bound in a block, it is a local variable of that block.\nIf a name is bound at the module level, it is a global variable. (The\nvariables of the module code block are local and global.) If a\nvariable is used in a code block but not defined there, it is a\nfree variable.\nThe name binding operations are assignment, class and function\ndefinition, import statements, for statements, and except statements.\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block. This can lead to errors when a name is used within a\nblock before it is bound.\nThe previous rule is a subtle. Python lacks declarations and allows\nname binding operations to occur anywhere within a code block. The\nlocal variables of a code block can be determined by scanning the\nentire text of the block for name binding operations.\nIf the global statement occurs within a block, all uses of the name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtin namespace, the namespace of\nthe module __builtin__. The global namespace is searched\nfirst. If the name is not found there, the builtin namespace is\nsearched. The global statement must precede all uses of the name.\nThe global statement has the same scope as a name binding operation\nin the same block. If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.", "python_version": "2.2", "length": 3209, "url": "https://docs.python.org/2.2/ref/defintions.html"} {"title": "6.5 The del statement", "text": "pass.html | simple.html | print.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.5 The del statement\n`del_stmt` | ::= | `\"del\" target_list`\nDownload entire grammar as text. (grammar.txt)\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather that spelling it out in full details, here are some\nhints.\nDeletion of a target list recursively deletes each target, from left\nto right.\nDeletion of a name removes the binding of that name (which must exist)\nfrom the local or global namespace, depending on whether the name\noccurs in a global statement in the same code block.\nDeletion of attribute references, subscriptions and slicings\nis passed to the primary object involved; deletion of a slicing\nis in general equivalent to assignment of an empty slice of the\nright type (but even this is determined by the sliced object).", "python_version": "2.2", "length": 874, "url": "https://docs.python.org/2.2/ref/del.html"} {"title": "2.6 Delimiters", "text": "operators.html | lexical.html | datamodel.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.6 Delimiters\nThe following tokens serve as delimiters in the grammar:\n```text\n\n( ) [ ] { }\n, : . ` = ;\n+= -= *= /= //= %=\n&= |= ^= >>= <<= **=\n```\nThe period can also occur in floating-point and imaginary literals. A\nsequence of three periods has a special meaning as an ellipsis in slices.\nThe second half of the list, the augmented assignment operators, serve\nlexically as delimiters, but also perform an operation.\nThe following printing ASCII characters have special meaning as part\nof other tokens or are otherwise significant to the lexical analyzer:\n```text\n\n' \" # \\\n```\nThe following printing ASCII characters are not used in Python. Their\noccurrence outside string literals and comments is an unconditional\nerror:", "python_version": "2.2", "length": 835, "url": "https://docs.python.org/2.2/ref/delimiters.html"} {"title": "5.2.5 Dictionary displays", "text": "lists.html | atoms.html | string-conversions.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.5 Dictionary displays\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n`dict_display` | ::= | `\"\" [ key_datum_list ] \"\"`\n`key_datum_list` | ::= | `key_datum (\",\" key_datum )* [\",\"]`\n`key_datum` | ::= | `expression \":\" expression`\nDownload entire grammar as text. (grammar.txt)\nA dictionary display yields a new dictionary object.\nThe key/datum pairs are evaluated from left to right to define the\nentries of the dictionary: each key object is used as a key into the\ndictionary to store the corresponding datum.\nRestrictions on the types of the key values are listed earlier in\nsection 3.2 (types.html#types). (To summarize,the key type should be hashable,\nwhich excludes all mutable objects.) Clashes between duplicate keys\nare not detected; the last datum (textually rightmost in the display)\nstored for a given key value prevails.", "python_version": "2.2", "length": 995, "url": "https://docs.python.org/2.2/ref/dict.html"} {"title": "A.3.2 Interaction with dynamic features", "text": "definitions.html | nested-scopes.html | node98.html | Python Reference Manual | contents.html | genindex.html\n---\n## A.3.2 Interaction with dynamic features\nThere are several cases where Python statements are illegal when\nused in conjunction with nested scopes that contain free\nvariables.\nIf a variable is referenced in an enclosing scope, it is illegal\nto delete the name. An error will be reported at compile time.\nIf the wild card form of import -- \"import *\" -- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a SyntaxError.\nIf exec is used in a function and the function contains or is a nested\nblock with free variables, the compiler will raise a SyntaxError\nunless the exec explicitly specifies the local namespace for the exec.\n(In other words, \"exec obj\" would be illegal, but \"exec obj in ns\"\nwould be legal.)\nThe builtin functions eval() and input() can not\naccess free variables unless the variables are also referenced by the\nprogram text of the block that contains the call to eval()\nor input().\nCompatibility note: The compiler for Python 2.1 will issue\nwarnings for uses of nested functions that will behave differently\nwith nested scopes. The warnings will not be issued if nested scopes\nare enabled via a future statement. If a name bound in a function\nscope and the function contains a nested function scope that uses the\nname, the compiler will issue a warning. The name resolution rules\nwill result in different bindings under Python 2.1 than under Python\n2.2. The warning indicates that the program may not run correctly\nwith all versions of Python.", "python_version": "2.2", "length": 1638, "url": "https://docs.python.org/2.2/ref/dynamic-features.html"} {"title": "4.2 Exceptions", "text": "execframes.html | execmodel.html | expressions.html | Python Reference Manual | contents.html | genindex.html\n---\n# 4.2 Exceptions\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is\nraisedat the point where the error\nis detected; it may be handledby\nthe surrounding code block or by any code block that directly or\nindirectly invoked the code block where the error occurred.\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero). A Python program can also\nexplicitly raise an exception with the raise statement.\nException handlers are specified with the try ... except\nstatement. The try ... finally statement\nspecifies cleanup code which does not handle the exception, but is\nexecuted whether an exception occurred or not in the preceding code.\nPython uses the ``termination'' odel of\nerror handling: an exception handler can find out what happened and\ncontinue execution at an outer level, but it cannot repair the cause\nof the error and retry the failing operation (except by re-entering\nthe offending piece of code from the top).\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop. In\neither case, it prints a stack backtrace, except when the exception is\nSystemExit.\nExceptions are identified by string objects or class instances.\nSelection of a matching except clause is based on object identity\n(i.e., two different string objects with the same value represent\ndifferent exceptions!) For string exceptions, the except\nclause must reference the same string object. For class exceptions,\nthe except clause must reference the same class or a base\nclass of it.\nWhen an exception is raised, an object (maybe `None`) is passed\nas the exception's ``parameter'' or ``value''; this object does not\naffect the selection of an exception handler, but is passed to the\nselected exception handler as additional information. For class\nexceptions, this object must be an instance of the exception class\nbeing raised.", "python_version": "2.2", "length": 2148, "url": "https://docs.python.org/2.2/ref/exceptions.html"} {"title": "6.14 The exec statement", "text": "global.html | simple.html | compound.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.14 The exec statement\n`exec_stmt` | ::= | `\"exec\" expression [\"in\" expression [\",\" expression ]]`\nDownload entire grammar as text. (grammar.txt)\nThis statement supports dynamic execution of Python code. The first\nexpression should evaluate to either a string, an open file object, or\na code object. If it is a string, the string is parsed as a suite of\nPython statements which is then executed (unless a syntax error\noccurs). If it is an open file, the file is parsed until EOF and\nexecuted. If it is a code object, it is simply executed.\nIn all cases, if the optional parts are omitted, the code is executed\nin the current scope. If only the first expression after in\nis specified, it should be a dictionary, which will be used for both\nthe global and the local variables. If two expressions are given,\nboth must be dictionaries and they are used for the global and local\nvariables, respectively.\nAs a side effect, an implementation may insert additional keys into\nthe dictionaries given besides those corresponding to variable names\nset by the executed code. For example, the current implementation\nmay add a reference to the dictionary of the built-in module\n__builtin__ under the key `__builtins__` (!).\nProgrammer's hints:\ndynamic evaluation of expressions is supported by the built-in\nfunction eval(). The built-in functions\nglobals() and locals() return the current global\nand local dictionary, respectively, which may be useful to pass around\nfor use by exec.\nAlso, in the current implementation, multi-line compound statements must\nend with a newline:\n`exec \"for v in seq:\\n\\tprint v\\n\"` works, but\n`exec \"for v in seq:\\n\\tprint v\"` fails with\nSyntaxError.", "python_version": "2.2", "length": 1773, "url": "https://docs.python.org/2.2/ref/exec.html"} {"title": "4.1 Code blocks, execution frames, and namespaces", "text": "execmodel.html | execmodel.html | exceptions.html | Python Reference Manual | contents.html | genindex.html\n---\n# 4.1 Code blocks, execution frames, and namespaces\nA code blockis a piece\nof Python program text that can be executed as a unit, such as a\nmodule, a class definition or a function body. Some code blocks (like\nmodules) are normally executed only once, others (like function\nbodies) may be executed many times. Code blocks may textually contain\nother code blocks. Code blocks may invoke other code blocks (that may\nor may not be textually contained in them) as part of their execution,\ne.g., by invoking (calling) a function.\nThe following are code blocks: A module is a code block. A function\nbody is a code block. A class definition is a code block. Each\ncommand typed interactively is a separate code block; a script file (a\nfile given as standard input to the interpreter or specified on the\ninterpreter command line the first argument) is a code block; a script\ncommand (a command specified on the interpreter command line with the\n`-c' option) is a code block. The file read by the built-in\nfunction execfile() is a code block. The string argument\npassed to the built-in function eval() and to the\nexec statement is a code block. And finally, the expression\nread and evaluated by the built-in function input() is a\ncode block.\nA code block is executed in an execution frame. An execution\nframecontains some administrative\ninformation (used for debugging), determines where and how execution\ncontinues after the code block's execution has completed, and (perhaps\nmost importantly) defines two namespaces, the local and the global\nnamespace, that affect execution of the code block.\nA namespaceis a mapping from names\n(identifiers) to objects. A particular namespace may be referenced by\nmore than one execution frame, and from other places as well. Adding\na name to a namespace is called bindinga\nname (to an object); changing the mapping of a name is called\nrebinding removing a name is\nunbinding Namespaces are functionally\nequivalent to dictionaries (and often implemented as dictionaries).\nThe local namespaceof an execution\nframe determines the default place where names are defined and\nsearched. The\nglobal namespacedetermines the place\nwhere names listed in globalstatements are\ndefined and searched, and where names that are not bound anywhere in\nthe current code block are searched.\nWhether a name is local or global in a code block is determined by\nstatic inspection of the source text for the code block: in the\nabsence of global statements, a name that is bound anywhere\nin the code block is local in the entire code block; all other names\nare considered global. The global statement forces global\ninterpretation of selected names throughout the code block. The\nfollowing constructs bind names: formal parameters to functions,\nimport statements, class and function definitions (these\nbind the class or function name in the defining block), and targets\nthat are identifiers if occurring in an assignment, for loop\nheader, or in the second position of an except clause\nheader. Local names are searched only on the local namespace; global\nnames are searched only in the global and built-in\nnamespace.4.1 (#foot2722)\nA target occurring in a del statement is also considered bound\nfor this purpose (though the actual semantics are to ``unbind'' the\nname).\nWhen a global name is not found in the global namespace, it is\nsearched in the built-in namespace (which is actually the global\nnamespace of the module\n__builtin__. The built-in\nnamespace associated with the execution of a code block is actually\nfound by looking up the name `__builtins__` in its global\nnamespace; this should be a dictionary or a module (in the latter case\nits dictionary is used). Normally, the `__builtins__` namespace\nis the dictionary of the built-in module __builtin__ (note:\nno `s'); if it isn't, restricted\nexecutionmode is in effect. When a\nname is not found at all, a\nNameError exception is raised.\nThe following table lists the meaning of the local and global\nnamespace for various types of code blocks. The namespace for a\nparticular module is automatically created when the module is first\nimported (i.e., when it is loaded). Note that in almost all cases,\nthe global namespace is the namespace of the containing module --\nscopes in Python do not nest!\nNotes:\nn.s.: means namespace\n(1): The main module for a script is always called\n__main__; ``the filename don't enter into it.''\n(2): The global and local namespace for these can be\noverridden with optional extra arguments.\n(3): The exec statement and the eval() and\nexecfile() functions have optional arguments to override\nthe global and local namespace. If only one namespace is specified,\nit is used for both.\nThe built-in functions globals() and locals() returns a\ndictionary representing the current global and local namespace,\nrespectively. The effect of modifications to this dictionary on the\nnamespace are undefined.4.2 (#foot2730)", "python_version": "2.2", "length": 5001, "url": "https://docs.python.org/2.2/ref/execframes.html"} {"title": "4. Execution model", "text": "numeric-types.html | ref.html | execframes.html | Python Reference Manual | contents.html | genindex.html\n---\n# 4. Execution model", "python_version": "2.2", "length": 130, "url": "https://docs.python.org/2.2/ref/execmodel.html"} {"title": "2.1.4 Explicit line joining", "text": "comments.html | line-structure.html | implicit-joining.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.4 Explicit line joining\nTwo or more physical lines may be joined into logical lines using\nbackslash characters (`\\`), as follows: when a physical line ends\nin a backslash that is not part of a string literal or comment, it is\njoined with the following forming a single logical line, deleting the\nbackslash and the following end-of-line character. For example:\n```text\n\nif 1900 < year < 2100 and 1 <= month <= 12 \\\nand 1 <= day <= 31 and 0 <= hour < 24 \\\nand 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date\nreturn 1\n```\nA line ending in a backslash cannot carry a comment. A backslash does\nnot continue a comment. A backslash does not continue a token except\nfor string literals (i.e., tokens other than string literals cannot be\nsplit across physical lines using a backslash). A backslash is\nillegal elsewhere on a line outside a string literal.", "python_version": "2.2", "length": 991, "url": "https://docs.python.org/2.2/ref/explicit-joining.html"} {"title": "8.4 Expression input", "text": "interactive.html | top-level.html | futures.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.4 Expression input\nThere are two forms of expression input. Both ignore leading\nwhitespace.\nThe string argument to eval() must have the following form:\n`eval_input` | ::= | `expression_list NEWLINE*`\nDownload entire grammar as text. (grammar.txt)\nThe input line read by input() must have the following form:\n`input_input` | ::= | `expression_list NEWLINE`\nDownload entire grammar as text. (grammar.txt)\nNote: to read `raw' input line without interpretation, you can use the\nbuilt-in function raw_input() or the readline() method\nof file objects.", "python_version": "2.2", "length": 660, "url": "https://docs.python.org/2.2/ref/expression-input.html"} {"title": "5. Expressions", "text": "exceptions.html | ref.html | conversions.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5. Expressions\nThis chapter explains the meaning of the elements of expressions in\nPython.\nSyntax Notes: In this and the following chapters, extended\nBNFnotation will be used to describe syntax, not lexical\nanalysis. When (one alternative of) a syntax rule has the form\n`name` | ::= | `othername`\nand no semantics are given, the semantics of this form of `name`\nare the same as for `othername`.", "python_version": "2.2", "length": 504, "url": "https://docs.python.org/2.2/ref/expressions.html"} {"title": "5.11 Expression lists", "text": "lambda.html | expressions.html | summary.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.11 Expression lists\n`expression_list` | ::= | `expression ( \",\" expression )* [\",\"]`\nDownload entire grammar as text. (grammar.txt)\nAn expression list containing at least one comma yields a\ntuple. The length of the tuple is the number of expressions in the\nlist. The expressions are evaluated from left to right.\nThe trailing comma is required only to create a single tuple (a.k.a. a\nsingleton); it is optional in all other cases. A single\nexpression without a trailing comma doesn't create a\ntuple, but rather yields the value of that expression.\n(To create an empty tuple, use an empty pair of parentheses:\n`()`.)", "python_version": "2.2", "length": 727, "url": "https://docs.python.org/2.2/ref/exprlists.html"} {"title": "6.1 Expression statements", "text": "simple.html | simple.html | assert.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.1 Expression statements\nExpression statements are used (mostly interactively) to compute and\nwrite a value, or (usually) to call a procedure (a function that\nreturns no meaningful result; in Python, procedures return the value\n`None`). Other uses of expression statements are allowed and\noccasionally useful. The syntax for an expression statement is:\n`expression_stmt` | ::= | `expression_list`\nDownload entire grammar as text. (grammar.txt)\nAn expression statement evaluates the expression list (which may be a\nsingle expression).\nIn interactive mode, if the value is not `None`, it is converted\nto a string using the built-in repr()function and the resulting string is written to standard output (see\nsection 6.6 (print.html#print)) on a line by itself. (Expression statements\nyielding `None` are not written, so that procedure calls do not\ncause any output.)", "python_version": "2.2", "length": 968, "url": "https://docs.python.org/2.2/ref/exprstmts.html"} {"title": "8.2 File input", "text": "programs.html | top-level.html | interactive.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.2 File input\nAll input read from non-interactive files has the same form:\n`file_input` | ::= | `(NEWLINE | statement )*`\nDownload entire grammar as text. (grammar.txt)\nThis syntax is used in the following situations:\n- when parsing a complete Python program (from a file or from a string);\n- when parsing a module;\n- when parsing a string passed to the exec statement;", "python_version": "2.2", "length": 484, "url": "https://docs.python.org/2.2/ref/file-input.html"} {"title": "2.4.5 Floating point literals", "text": "integers.html | literals.html | imaginary.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.5 Floating point literals\nFloating point literals are described by the following lexical\ndefinitions:\n`floatnumber` | ::= | `pointfloat | exponentfloat`\n`pointfloat` | ::= | `[ intpart ] fraction | intpart \".\"`\n`exponentfloat` | ::= | `( intpart | pointfloat ) exponent`\n`intpart` | ::= | `digit +`\n`fraction` | ::= | `\".\" digit +`\n`exponent` | ::= | `(\"e\" | \"E\") [\"+\" | \"-\"] digit +`\nDownload entire grammar as text. (grammar.txt)\nNote that the integer and exponent parts of floating point numbers\ncan look like octal integers, but are interpreted using radix 10. For\nexample, \"077e010\" is legal, and denotes the same number\nas \"77e10\".\nThe allowed range of floating point literals is\nimplementation-dependent.\nSome examples of floating point literals:\n```text\n\n3.14 10. .001 1e100 3.14e-10 0e0\n```\nNote that numeric literals do not include a sign; a phrase like\n`-1` is actually an expression composed of the operator\n`-` and the literal `1`.", "python_version": "2.2", "length": 1060, "url": "https://docs.python.org/2.2/ref/floating.html"} {"title": "7.3 The for statement", "text": "while.html | compound.html | try.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.3 The for statement\nThe for statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n`for_stmt` | ::= | `\"for\" target_list \"in\" expression_list \":\" suite [\"else\" \":\" suite ]`\nDownload entire grammar as text. (grammar.txt)\nThe expression list is evaluated once; it should yield a sequence. The\nsuite is then executed once for each item in the sequence, in the\norder of ascending indices. Each item in turn is assigned to the\ntarget list using the standard rules for assignments, and then the\nsuite is executed. When the items are exhausted (which is immediately\nwhen the sequence is empty), the suite in the else clause, if\npresent, is executed, and the loop terminates.\nA break statement executed in the first suite terminates the\nloop without executing the else clause's suite. A\ncontinue statement executed in the first suite skips the rest\nof the suite and continues with the next item, or with the else\nclause if there was no next item.\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\nThe target list is not deleted when the loop is finished, but if the\nsequence is empty, it will not have been assigned to at all by the\nloop. Hint: the built-in function range() returns a\nsequence of integers suitable to emulate the effect of Pascal's\n`for i := a to b do`;\ne.g., `range(3)` returns the list `[0, 1, 2]`.\nWarning:\nThere is a subtlety when the sequence is being modified\nby the loop (this can only occur for mutable sequences, i.e. lists).\nAn internal counter is used to keep track of which item is used next,\nand this is incremented on each iteration. When this counter has\nreached the length of the sequence the loop terminates. This means that\nif the suite deletes the current (or a previous) item from the\nsequence, the next item will be skipped (since it gets the index of\nthe current item which has already been treated). Likewise, if the\nsuite inserts an item in the sequence before the current item, the\ncurrent item will be treated again the next time through the loop.\nThis can lead to nasty bugs that can be avoided by making a temporary\ncopy using a slice of the whole sequence, e.g.,\n```text\n\nfor x in a[:]:\nif x < 0: a.remove(x)\n```", "python_version": "2.2", "length": 2381, "url": "https://docs.python.org/2.2/ref/for.html"} {"title": "Front Matter", "text": "ref.html | ref.html | contents.html | Python Reference Manual | contents.html | genindex.html\n---\n# Front Matter\nCopyright © 2001 Python Software Foundation.\nAll rights reserved.\nCopyright © 2000 BeOpen.com.\nAll rights reserved.\nCopyright © 1995-2000 Corporation for National Research Initiatives.\nAll rights reserved.\nCopyright © 1991-1995 Stichting Mathematisch Centrum.\nAll rights reserved.\nSee the end of this document for complete license and permissions\ninformation.\n### Abstract:\nPython is an interpreted, object-oriented, high-level programming\nlanguage with dynamic semantics. Its high-level built in data\nstructures, combined with dynamic typing and dynamic binding, make it\nvery attractive for rapid application development, as well as for use\nas a scripting or glue language to connect existing components\ntogether. Python's simple, easy to learn syntax emphasizes\nreadability and therefore reduces the cost of program\nmaintenance. Python supports modules and packages, which encourages\nprogram modularity and code reuse. The Python interpreter and the\nextensive standard library are available in source or binary form\nwithout charge for all major platforms, and can be freely distributed.\nThis reference manual describes the syntax and ``core semantics'' of\nthe language. It is terse, but attempts to be exact and complete.\nThe semantics of non-essential built-in object types and of the\nbuilt-in functions and modules are described in the\nPython Library Reference (../lib/lib.html). For an\ninformal introduction to the language, see the\nPython Tutorial (../tut/tut.html). For C or\nC++ programmers, two additional manuals exist:\nExtending and Embedding the Python\nInterpreter (../ext/ext.html) describes the high-level picture of how to write a Python\nextension module, and the Python/C API\nReference Manual (../api/api.html) describes the interfaces available to\nC/C++ programmers in detail.", "python_version": "2.2", "length": 1905, "url": "https://docs.python.org/2.2/ref/front.html"} {"title": "7.5 Function definitions", "text": "try.html | compound.html | class.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.5 Function definitions\nA function definition defines a user-defined function object (see\nsection 3.2 (types.html#types)):\n`funcdef` | ::= | `\"def\" funcname \"(\" [ parameter_list ] \")\"\n\":\" suite`\n`parameter_list` | ::= | `( defparameter \",\")*\n(\"*\" identifier [, \"**\" identifier ]\n| \"**\" identifier | defparameter [\",\"])`\n`defparameter` | ::= | `parameter [\"=\" expression ]`\n`sublist` | ::= | `parameter (\",\" parameter )* [\",\"]`\n`parameter` | ::= | `identifier | \"(\" sublist \")\"`\n`funcname` | ::= | `identifier`\nDownload entire grammar as text. (grammar.txt)\nA function definition is an executable statement. Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function). This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called.\nWhen one or more top-level parameters have the form parameter\n`=` expression, the function is said to have ``default\nparameter values.'' For a parameter with a\ndefault value, the corresponding argument may be omitted from a call,\nin which case the parameter's default value is substituted. If a\nparameter has a default value, all following parameters must also have\na default value -- this is a syntactic restriction that is not\nexpressed by the grammar.\nDefault parameter values are evaluated when the function\ndefinition is executed. This means that the expression is evaluated\nonce, when the function is defined, and that that same\n``pre-computed'' value is used for each call. This is especially\nimportant to understand when a default parameter is a mutable object,\nsuch as a list or a dictionary: if the function modifies the object\n(e.g. by appending an item to a list), the default value is in effect\nmodified. This is generally not what was intended. A way around this\nis to use `None` as the default, and explicitly test for it in\nthe body of the function, e.g.:\n```text\n\ndef whats_on_the_telly(penguin=None):\nif penguin is None:\npenguin = []\npenguin.append(\"property of the zoo\")\nreturn penguin\n```\nFunction call semantics are described in more detail in section\n5.3.4 (calls.html#calls).\nA function call always assigns values to all parameters mentioned in\nthe parameter list, either from position arguments, from keyword\narguments, or from default values. If the form ```*identifier`''\nis present, it is initialized to a tuple receiving any excess\npositional parameters, defaulting to the empty tuple. If the form\n```**identifier`'' is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a\nnew empty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda forms,\ndescribed in section 5.10 (lambda.html#lambda). Note that the lambda form is\nmerely a shorthand for a simplified function definition; a function\ndefined in a ``def'' statement can be passed around or\nassigned to another name just like a function defined by a lambda\nform. The ``def'' form is actually more powerful since it\nallows the execution of multiple statements.\n\nProgrammer's note: a ```def`'' form executed inside a\nfunction definition defines a local function that can be returned or\npassed around. The semantics of name resolution in the nested\nfunction will change in Python 2.2. See the appendix for a\ndescription of the new semantics.", "python_version": "2.2", "length": 3670, "url": "https://docs.python.org/2.2/ref/function.html"} {"title": "A.1 Future statements", "text": "futures.html | futures.html | module-future.html | Python Reference Manual | contents.html | genindex.html\n---\n# A.1 Future statements\nA future statementis a directive to\nthe compiler that a particular module should be compiled using syntax\nor semantics that will be available in a specified future release of\nPython. The future statement is intended to ease migration to future\nversions of Python that introduce incompatible changes to the\nlanguage. It allows use of the new features on a per-module basis\nbefore the release in which the feature becomes standard.\n```text\n\nfuture_statement: \"from\" \"__future__\" \"import\" feature [\"as\" name]\n(\",\" feature [\"as\" name])*\n\nfeature: identifier\nname: identifier\n```\nA future statement must appear near the top of the module. The only\nlines that can appear before a future statement are:\n- the module docstring (if any),\n- comments,\n- blank lines, and\n- other future statements.\nThe features recognized by Python 2.2 are \"generators\",\n\"division\" and \"nested_scopes\". \"nested_scopes\"\nis redundant in 2.2 as the nested scopes feature is active by default.\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code. It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently. Such decisions cannot be pushed off until\nruntime.\nFor any given release, the compiler knows which feature names have been\ndefined, and raises a compile-time error if a future statement contains\na feature not known to it.\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module __future__, described later, and\nit will be imported in the usual way at the time the future statement\nis executed.\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\nNote that there is nothing special about the statement:\n```text\n\nimport __future__ [as name]\n```\nThat is not a future statement; it's an ordinary import statement with\nno special semantics or syntax restrictions.\nCode compiled by an exec statement or calls to the builtin functions\ncompile() and execfile() that occur in a module\nM containing a future statement will, by default, use the new\nsyntax or semantics associated with the future statement. This can,\nstarting with Python 2.2 be controlled by optional arguments to\ncompile() -- see the documentation of that function in the\nlibrary reference for details.\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session. If an\ninterpreter is started with the -i option, is passed a\nscript name to execute, and the script includes a future statement, it\nwill be in effect in the interactive session started after the script\nis executed.", "python_version": "2.2", "length": 2925, "url": "https://docs.python.org/2.2/ref/future-statements.html"} {"title": "A. Future statements and nested scopes", "text": "expression-input.html | ref.html | future-statements.html | Python Reference Manual | contents.html | genindex.html\n---\n# A. Future statements and nested scopes\nThe semantics of Python's static scoping will change in version 2.2 to\nsupport resolution of unbound local names in enclosing functions'\nnamespaces. The new semantics will be available in Python 2.1 through\nthe use of a future statement. This appendix documents these two\nfeatures for Python 2.1; it will be removed in Python 2.2 and the\nfeatures will be documented in the main sections of this manual.", "python_version": "2.2", "length": 563, "url": "https://docs.python.org/2.2/ref/futures.html"} {"title": "Index", "text": "node100.html | ref.html | about.html | Python Reference Manual | contents.html\n---\n## Index\n---\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\nk (#letter-k) |\nl (#letter-l) |\nm (#letter-m) |\nn (#letter-n) |\no (#letter-o) |\np (#letter-p) |\nq (#letter-q) |\nr (#letter-r) |\ns (#letter-s) |\nt (#letter-t) |\nu (#letter-u) |\nv (#letter-v) |\nw (#letter-w) |\nx (#letter-x) |\ny (#letter-y) |\nz (#letter-z)\n---\n## _ (underscore)\n---\n## A\n---\n## B\n---\n## C\n---\n## D\n---\n## E\n---\n## F\n---\n## G\n---\n## H\n---\n## I\n---\n## K\n---\n## L\n---\n## M\n---\n## N\n---\n## O\n---\n## P\n---\n## Q\n---\n## R\n---\n## S\n---\n## T\n---\n## U\n---\n## V\n---\n## W\n---\n## X\n---\n## Y\n---\n## Z", "python_version": "2.2", "length": 756, "url": "https://docs.python.org/2.2/ref/genindex.html"} {"title": "6.13 The global statement", "text": "import.html | simple.html | exec.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.13 The global statement\n`global_stmt` | ::= | `\"global\" identifier (\",\" identifier )*`\nDownload entire grammar as text. (grammar.txt)\nThe global statement is a declaration which holds for the\nentire current code block. It means that the listed identifiers are to be\ninterpreted as globals. While using global names is automatic\nif they are not defined in the local scope, assigning to global\nnames would be impossible without global.\nNames listed in a global statement must not be used in the same\ncode block textually preceding that global statement.\nNames listed in a global statement must not be defined as formal\nparameters or in a for loop control target, class\ndefinition, function definition, or import statement.\n(The current implementation does not enforce the latter two\nrestrictions, but programs should not abuse this freedom, as future\nimplementations may enforce them or silently change the meaning of the\nprogram.)\nProgrammer's note:\nthe global is a directive to the parser. It\napplies only to code parsed at the same time as the global\nstatement. In particular, a global statement contained in an\nexec statement does not affect the code block containing\nthe exec statement, and code contained in an exec\nstatement is unaffected by global statements in the code\ncontaining the exec statement. The same applies to the\neval(), execfile() and compile() functions.", "python_version": "2.2", "length": 1479, "url": "https://docs.python.org/2.2/ref/global.html"} {"title": "2.3.2 Reserved classes of identifiers", "text": "keywords.html | identifiers.html | literals.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.3.2 Reserved classes of identifiers\nCertain classes of identifiers (besides keywords) have special\nmeanings. These are:\n(XXX need section references here.)\nNote:\n(1): The special identifier \"_\" is used in the interactive\ninterpreter to store the result of the last evaluation; it is stored\nin the __builtin__ module. When not in interactive mode,\n\"_\" has no special meaning and is not defined.", "python_version": "2.2", "length": 509, "url": "https://docs.python.org/2.2/ref/id-classes.html"} {"title": "2.3 Identifiers and keywords", "text": "other-tokens.html | lexical.html | keywords.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.3 Identifiers and keywords\nIdentifiers (also referred to as names) are described by the following\nlexical definitions:\n`identifier` | ::= | `( letter |\"_\") ( letter | digit | \"_\")*`\n`letter` | ::= | `lowercase | uppercase`\n`lowercase` | ::= | `\"a\"...\"z\"`\n`uppercase` | ::= | `\"A\"...\"Z\"`\n`digit` | ::= | `\"0\"...\"9\"`\nDownload entire grammar as text. (grammar.txt)\nIdentifiers are unlimited in length. Case is significant.", "python_version": "2.2", "length": 534, "url": "https://docs.python.org/2.2/ref/identifiers.html"} {"title": "7.1 The if statement", "text": "compound.html | compound.html | while.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.1 The if statement\nThe if statement is used for conditional execution:\n`if_stmt` | ::= | `\"if\" expression \":\" suite ( \"elif\" expression \":\" suite )*\n[\"else\" \":\" suite ]`\nDownload entire grammar as text. (grammar.txt)\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section 5.10 (lambda.html#Booleans) for\nthe definition of true and false); then that suite is executed (and no\nother part of the if statement is executed or evaluated). If\nall expressions are false, the suite of the else clause, if\npresent, is executed.", "python_version": "2.2", "length": 692, "url": "https://docs.python.org/2.2/ref/if.html"} {"title": "2.4.6 Imaginary literals", "text": "floating.html | literals.html | operators.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.6 Imaginary literals\nImaginary literals are described by the following lexical definitions:\n`imagnumber` | ::= | `( floatnumber | intpart ) (\"j\" | \"J\")`\nDownload entire grammar as text. (grammar.txt)\nAn imaginary literal yields a complex number with a real part of\n0.0. Complex numbers are represented as a pair of floating point\nnumbers and have the same restrictions on their range. To create a\ncomplex number with a nonzero real part, add a floating point number\nto it, e.g., `(3+4j)`. Some examples of imaginary literals:\n```text\n\n3.14j 10.j 10j .001j 1e100j 3.14e-10j\n```", "python_version": "2.2", "length": 692, "url": "https://docs.python.org/2.2/ref/imaginary.html"} {"title": "2.1.5 Implicit line joining", "text": "explicit-joining.html | line-structure.html | blank-lines.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.5 Implicit line joining\nExpressions in parentheses, square brackets or curly braces can be\nsplit over more than one physical line without using backslashes.\nFor example:\n```text\n\nmonth_names = ['Januari', 'Februari', 'Maart', # These are the\n'April', 'Mei', 'Juni', # Dutch names\n'Juli', 'Augustus', 'September', # for the months\n'Oktober', 'November', 'December'] # of the year\n```\nImplicitly continued lines can carry comments. The indentation of the\ncontinuation lines is not important. Blank continuation lines are\nallowed. There is no NEWLINE token between implicit continuation\nlines. Implicitly continued lines can also occur within triple-quoted\nstrings (see below); in that case they cannot carry comments.", "python_version": "2.2", "length": 847, "url": "https://docs.python.org/2.2/ref/implicit-joining.html"} {"title": "6.12 The import statement", "text": "continue.html | simple.html | global.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.12 The import statement\n`import_stmt` | ::= | `\"import\" module [\"as\" name ]\n( \",\" module [\"as\" name ] )*\n| \"from\" module \"import\" identifier [\"as\" name ]\n( \",\" identifier [\"as\" name ] )*\n| \"from\" module \"import\" \"*\"`\n`module` | ::= | `( identifier \".\")* identifier`\nDownload entire grammar as text. (grammar.txt)\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the import statement occurs).\nThe first form (without from) repeats these steps for each\nidentifier in the list. The form with from performs step\n(1) once, and then performs step (2) repeatedly.\nThe system maintains a table of modules that have been initialized,\nindexed by module name. This table is\naccessible as `sys.modules`. When a module name is found in\nthis table, step (1) is finished. If not, a search for a module\ndefinition is started. When a module is found, it is loaded. Details\nof the module searching and loading process are implementation and\nplatform specific. It generally involves searching for a ``built-in''\nmodule with the given name and then searching a list of locations\ngiven as `sys.path`.\nIf a built-in module is found, its built-in initialization code is\nexecuted and step (1) is finished. If no matching file is found,\nImportError is raised. If a file is found, it is parsed,\nyielding an executable code block. If a syntax error occurs,\nSyntaxError is raised. Otherwise, an empty module of the given\nname is created and inserted in the module table, and then the code\nblock is executed in the context of this module. Exceptions during\nthis execution terminate step (1).\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\nThe first form of import statement binds the module name in\nthe local namespace to the module object, and then goes on to import\nthe next identifier, if any. If the module name is followed by\nas, the name following as is used as the local\nname for the module. To avoid confusion, you cannot import modules\nwith dotted names as a different local name. So `import\nmodule as m` is legal, but `import module.submod as s` is not.\nThe latter should be written as `from module import submod as s`;\nsee below.\nThe from form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in step\n(1), and binds the name in the local namespace to the object thus found.\nAs with the first form of import, an alternate local name can be\nsupplied by specifying \"as localname\". If a name is not found,\nImportError is raised. If the list of identifiers is replaced\nby a star (\"*\"), all public names defined in the module are\nbound in the local namespace of the import statement..\nThe public names defined by a module are determined by checking\nthe module's namespace for a variable named `__all__`; if\ndefined, it must be a sequence of strings which are names defined or\nimported by that module. The names given in `__all__` are all\nconsidered public and are required to exist. If `__all__` is not\ndefined, the set of public names includes all names found in the\nmodule's namespace which do not begin with an underscore character\n(\"_\").\nNames bound by import statements may not occur in\nglobal statements in the same scope.\nThe from form with \"*\" may only occur in a module scope.\nHierarchical module names:when the module names contains one or more dots, the module search\npath is carried out differently. The sequence of identifiers up to\nthe last dot is used to find a ``package''; the final\nidentifier is then searched inside the package. A package is\ngenerally a subdirectory of a directory on `sys.path` that has a\nfile __init__.py.[XXX Can't be bothered to spell this out right now; see the URL\nhttp://www.python.org/doc/essays/packages.html for more details, also\nabout how the module search works from inside a package.]\nThe built-in function __import__() is provided to support\napplications that determine which modules need to be loaded\ndynamically; refer to Built-in\nFunctions (../lib/built-in-funcs.html) in the\nPython Library Reference (../lib/lib.html) for additional\ninformation.", "python_version": "2.2", "length": 4296, "url": "https://docs.python.org/2.2/ref/import.html"} {"title": "2.1.7 Indentation", "text": "blank-lines.html | line-structure.html | whitespace.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.7 Indentation\nLeading whitespace (spaces and tabs) at the beginning of a logical\nline is used to compute the indentation level of the line, which in\nturn is used to determine the grouping of statements.\nFirst, tabs are replaced (from left to right) by one to eight spaces\nsuch that the total number of characters up to and including the\nreplacement is a multiple of\neight (this is intended to be the same rule as used by Unix). The\ntotal number of spaces preceding the first non-blank character then\ndetermines the line's indentation. Indentation cannot be split over\nmultiple physical lines using backslashes; the whitespace up to the\nfirst backslash determines the indentation.\nCross-platform compatibility note: because of the nature of\ntext editors on non-UNIX platforms, it is unwise to use a mixture of\nspaces and tabs for the indentation in a single source file.\nA formfeed character may be present at the start of the line; it will\nbe ignored for the indentation calculations above. Formfeed\ncharacters occurring elsewhere in the leading whitespace have an\nundefined effect (for instance, they may reset the space count to\nzero).\nThe indentation levels of consecutive lines are used to generate\nINDENT and DEDENT tokens, using a stack, as follows.\nBefore the first line of the file is read, a single zero is pushed on\nthe stack; this will never be popped off again. The numbers pushed on\nthe stack will always be strictly increasing from bottom to top. At\nthe beginning of each logical line, the line's indentation level is\ncompared to the top of the stack. If it is equal, nothing happens.\nIf it is larger, it is pushed on the stack, and one INDENT token is\ngenerated. If it is smaller, it must be one of the numbers\noccurring on the stack; all numbers on the stack that are larger are\npopped off, and for each number popped off a DEDENT token is\ngenerated. At the end of the file, a DEDENT token is generated for\neach number remaining on the stack that is larger than zero.\nHere is an example of a correctly (though confusingly) indented piece\nof Python code:\n```text\n\ndef perm(l):\n# Compute the list of all permutations of l\nif len(l) <= 1:\nreturn [l]\nr = []\nfor i in range(len(l)):\ns = l[:i] + l[i+1:]\np = perm(s)\nfor x in p:\nr.append(l[i:i+1] + x)\nreturn r\n```\nThe following example shows various indentation errors:\n```text\n\ndef perm(l): # error: first line indented\nfor i in range(len(l)): # error: not indented\ns = l[:i] + l[i+1:]\np = perm(l[:i] + l[i+1:]) # error: unexpected indent\nfor x in p:\nr.append(l[i:i+1] + x)\nreturn r # error: inconsistent dedent\n```\n(Actually, the first three errors are detected by the parser; only the\nlast error is found by the lexical analyzer -- the indentation of\n`return r` does not match a level popped off the stack.)", "python_version": "2.2", "length": 2896, "url": "https://docs.python.org/2.2/ref/indentation.html"} {"title": "Python Reference Manual", "text": "../index.html | front.html | Python Reference Manual | contents.html | genindex.html\n---\n# Python Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 229, "url": "https://docs.python.org/2.2/ref/index.html"} {"title": "2.4.4 Integer and long integer literals", "text": "numbers.html | literals.html | floating.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.4 Integer and long integer literals\nInteger and long integer literals are described by the following\nlexical definitions:\n`longinteger` | ::= | `integer (\"l\" | \"L\")`\n`integer` | ::= | `decimalinteger | octinteger | hexinteger`\n`decimalinteger` | ::= | `nonzerodigit digit * | \"0\"`\n`octinteger` | ::= | `\"0\" octdigit +`\n`hexinteger` | ::= | `\"0\" (\"x\" | \"X\") hexdigit +`\n`nonzerodigit` | ::= | `\"1\"...\"9\"`\n`octdigit` | ::= | `\"0\"...\"7\"`\n`hexdigit` | ::= | `digit | \"a\"...\"f\" | \"A\"...\"F\"`\nDownload entire grammar as text. (grammar.txt)\nAlthough both lower case `l' and upper case `L' are allowed as suffix\nfor long integers, it is strongly recommended to always use `L', since\nthe letter `l' looks too much like the digit `1'.\nPlain integer decimal literals must be at most 2147483647 (i.e., the\nlargest positive integer, using 32-bit arithmetic). Plain octal and\nhexadecimal literals may be as large as 4294967295, but values larger\nthan 2147483647 are converted to a negative value by subtracting\n4294967296. There is no limit for long integer literals apart from\nwhat can be stored in available memory.\nSome examples of plain and long integer literals:\n```text\n\n7 2147483647 0177 0x80000000\n3L 79228162514264337593543950336L 0377L 0x100000000L\n```", "python_version": "2.2", "length": 1361, "url": "https://docs.python.org/2.2/ref/integers.html"} {"title": "8.3 Interactive input", "text": "file-input.html | top-level.html | expression-input.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.3 Interactive input\nInput in interactive mode is parsed using the following grammar:\n`interactive_input` | ::= | `[ stmt_list ] NEWLINE | compound_stmt NEWLINE`\nDownload entire grammar as text. (grammar.txt)\nNote that a (top-level) compound statement must be followed by a blank\nline in interactive mode; this is needed to help the parser detect the\nend of the input.", "python_version": "2.2", "length": 490, "url": "https://docs.python.org/2.2/ref/interactive.html"} {"title": "1. Introduction", "text": "contents.html | ref.html | notation.html | Python Reference Manual | contents.html | genindex.html\n---\n# 1. Introduction\nThis reference manual describes the Python programming language.\nIt is not intended as a tutorial.\nWhile I am trying to be as precise as possible, I chose to use English\nrather than formal specifications for everything except syntax and\nlexical analysis. This should make the document more understandable\nto the average reader, but will leave room for ambiguities.\nConsequently, if you were coming from Mars and tried to re-implement\nPython from this document alone, you might have to guess things and in\nfact you would probably end up implementing quite a different language.\nOn the other hand, if you are using\nPython and wonder what the precise rules about a particular area of\nthe language are, you should definitely be able to find them here.\nIf you would like to see a more formal definition of the language,\nmaybe you could volunteer your time -- or invent a cloning machine\n:-).\nIt is dangerous to add too many implementation details to a language\nreference document -- the implementation may change, and other\nimplementations of the same language may work differently. On the\nother hand, there is currently only one Python implementation in\nwidespread use (although a second one now exists!), and\nits particular quirks are sometimes worth being mentioned, especially\nwhere the implementation imposes additional limitations. Therefore,\nyou'll find short ``implementation notes'' sprinkled throughout the\ntext.\nEvery Python implementation comes with a number of built-in and\nstandard modules. These are not documented here, but in the separate\nPython Library Reference (../lib/lib.html) document. A few\nbuilt-in modules are mentioned when they interact in a significant way\nwith the language definition.", "python_version": "2.2", "length": 1831, "url": "https://docs.python.org/2.2/ref/introduction.html"} {"title": "2.3.1 Keywords", "text": "identifiers.html | identifiers.html | id-classes.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.3.1 Keywords\nThe following identifiers are used as reserved words, or\nkeywords of the language, and cannot be used as ordinary\nidentifiers. They must be spelled exactly as written here:\n```text\n\nand del for is raise\nassert elif from lambda return\nbreak else global not try\nclass except if or while\ncontinue exec import pass yield\ndef finally in print\n```", "python_version": "2.2", "length": 475, "url": "https://docs.python.org/2.2/ref/keywords.html"} {"title": "5.10 Boolean operations", "text": "comparisons.html | expressions.html | exprlists.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.10 Boolean operations\nBoolean operations have the lowest priority of all Python operations:\n`expression` | ::= | `or_test | lambda_form`\n`or_test` | ::= | `and_test | or_test \"or\" and_test`\n`and_test` | ::= | `not_test | and_test \"and\" not_test`\n`not_test` | ::= | `comparison | \"not\" not_test`\n`lambda_form` | ::= | `\"lambda\" [ parameter_list ]: expression`\nDownload entire grammar as text. (grammar.txt)\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: `None`, numeric zero of all types, empty sequences\n(strings, tuples and lists), and empty mappings (dictionaries). All\nother values are interpreted as true.\nThe operator not yields `1` if its argument is false,\n`0` otherwise.\nThe expression `x and y` first evaluates x; if\nx is false, its value is returned; otherwise, y is\nevaluated and the resulting value is returned.\nThe expression `x or y` first evaluates x; if\nx is true, its value is returned; otherwise, y is\nevaluated and the resulting value is returned.\n(Note that neither and nor or restrict the value\nand type they return to `0` and `1`, but rather return the\nlast evaluated argument.\nThis is sometimes useful, e.g., if `s` is a string that should be\nreplaced by a default value if it is empty, the expression\n`s or 'foo'` yields the desired value. Because not has to\ninvent a value anyway, it does not bother to return a value of the\nsame type as its argument, so e.g., `not 'foo'` yields `0`,\nnot `''`.)\nLambda forms (lambda expressions) have the same syntactic position as\nexpressions. They are a shorthand to create anonymous functions; the\nexpression `lambda arguments : expression`\nyields a function object that behaves virtually identical to one\ndefined with\n```text\n\ndef name(arguments):\nreturn expression\n```\nSee section 7.5 (function.html#function) for the syntax of parameter lists. Note\nthat functions created with lambda forms cannot contain statements.\nProgrammer's note: Prior to Python 2.1, a lambda form defined\ninside a function has no access to names defined in the function's\nnamespace. This is because Python had only two scopes: local and\nglobal. A common work-around was to use default argument values to\npass selected variables into the lambda's namespace, e.g.:\n```text\n\ndef make_incrementor(increment):\nreturn lambda x, n=increment: x+n\n```\nAs of Python 2.1, nested scopes were introduced, and this work-around\nhas not been necessary. Python 2.1 supports nested scopes in modules\nwhich include the statement \"from __future__ import\nnested_scopes\", and more recent versions of Python enable nested\nscopes by default. This version works starting with Python 2.1:\n```text\n\nfrom __future__ import nested_scopes\n\ndef make_incrementor(increment):\nreturn lambda x: x+increment\n```", "python_version": "2.2", "length": 2934, "url": "https://docs.python.org/2.2/ref/lambda.html"} {"title": "2. Lexical analysis", "text": "notation.html | ref.html | line-structure.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2. Lexical analysis\nA Python program is read by a parser. Input to the parser is a\nstream of tokens, generated by the lexical analyzer. This\nchapter describes how the lexical analyzer breaks a file into tokens.\nPython uses the 7-bit ASCII character set for program text and string\nliterals. 8-bit characters may be used in string literals and comments\nbut their interpretation is platform dependent; the proper way to\ninsert 8-bit characters in string literals is by using octal or\nhexadecimal escape sequences.\nThe run-time character set depends on the I/O devices connected to the\nprogram but is generally a superset of ASCII.\nFuture compatibility note: It may be tempting to assume that the\ncharacter set for 8-bit characters is ISO Latin-1 (an ASCII\nsuperset that covers most western languages that use the Latin\nalphabet), but it is possible that in the future Unicode text editors\nwill become common. These generally use the UTF-8 encoding, which is\nalso an ASCII superset, but with very different use for the\ncharacters with ordinals 128-255. While there is no consensus on this\nsubject yet, it is unwise to assume either Latin-1 or UTF-8, even\nthough the current implementation appears to favor Latin-1. This\napplies both to the source character set and the run-time character\nset.", "python_version": "2.2", "length": 1400, "url": "https://docs.python.org/2.2/ref/lexical.html"} {"title": "2.1 Line structure", "text": "lexical.html | lexical.html | logical.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.1 Line structure\nA Python program is divided into a number of logical lines.", "python_version": "2.2", "length": 185, "url": "https://docs.python.org/2.2/ref/line-structure.html"} {"title": "5.2.4 List displays", "text": "parenthesized.html | atoms.html | dict.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.4 List displays\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n`list_display` | ::= | `\"[\" [ listmaker ] \"]\"`\n`listmaker` | ::= | `expression ( list_for | ( \",\" expression )* [\",\"] )`\n`list_iter` | ::= | `list_for | list_if`\n`list_for` | ::= | `\"for\" expression_list \"in\" testlist [ list_iter ]`\n`list_if` | ::= | `\"if\" test [ list_iter ]`\nDownload entire grammar as text. (grammar.txt)\nA list display yields a new list object. Its contents are specified\nby providing either a list of expressions or a list comprehension.\nWhen a comma-separated list of expressions is supplied, its elements are\nevaluated from left to right and placed into the list object in that\norder. When a list comprehension is supplied, it consists of a\nsingle expression followed by at least one for clause and zero or\nmore for or if clauses. In this\ncase, the elements of the new list are those that would be produced\nby considering each of the for or if clauses a block,\nnesting from\nleft to right, and evaluating the expression to produce a list element\neach time the innermost block is reached.", "python_version": "2.2", "length": 1224, "url": "https://docs.python.org/2.2/ref/lists.html"} {"title": "2.4 Literals", "text": "id-classes.html | lexical.html | strings.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.4 Literals\nLiterals are notations for constant values of some built-in types.", "python_version": "2.2", "length": 189, "url": "https://docs.python.org/2.2/ref/literals.html"} {"title": "2.1.1 Logical lines", "text": "line-structure.html | line-structure.html | physical.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.1 Logical lines\nThe end of\na logical line is represented by the token NEWLINE. Statements cannot\ncross logical line boundaries except where NEWLINE is allowed by the\nsyntax (e.g., between statements in compound statements).\nA logical line is constructed from one or more physical lines\nby following the explicit or implicit line joining rules.", "python_version": "2.2", "length": 470, "url": "https://docs.python.org/2.2/ref/logical.html"} {"title": "A.2 __future__ -- Future statement definitions", "text": "future-statements.html | futures.html | nested-scopes.html | Python Reference Manual | contents.html | genindex.html\n---\n# A.2 __future__ --\nFuture statement definitions\n__future__ is a real module, and serves three purposes:\n- To avoid confusing existing tools that analyze import statements\nand expect to find the modules they're importing.\n- To ensure that future_statements run under releases prior to 2.1\nat least yield runtime exceptions (the import of\n__future__ will fail, because there was no module of\nthat name prior to 2.1).\n- To document when incompatible changes were introduced, and when they\nwill be -- or were -- made mandatory. This is a form of executable\ndocumentation, and can be inspected programatically via importing\n__future__ and examining its contents.\nEach statment in __future__.py is of the form:\n```text\n\nFeatureName = \"_Feature(\" OptionalRelease \",\" MandatoryRelease \",\"\nCompilerFlag \")\"\n```\nwhere, normally, OptionalRelease is less then MandatoryRelease, and\nboth are 5-tuples of the same form as `sys.version_info`:\n```text\n\n(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int\nPY_MINOR_VERSION, # the 1; an int\nPY_MICRO_VERSION, # the 0; an int\nPY_RELEASE_LEVEL, # \"alpha\", \"beta\", \"candidate\" or \"final\"; string\nPY_RELEASE_SERIAL # the 3; an int\n)\n```\nOptionalRelease records the first release in which the feature was\naccepted.\nIn the case of MandatoryReleases that have not yet occurred,\nMandatoryRelease predicts the release in which the feature will become\npart of the language.\nElse MandatoryRelease records when the feature became part of the\nlanguage; in releases at or after that, modules no longer need a\nfuture statement to use the feature in question, but may continue to\nuse such imports.\nMandatoryRelease may also be `None`, meaning that a planned\nfeature got dropped.\nInstances of class _Feature have two corresponding methods,\ngetOptionalRelease() and getMandatoryRelease().\nCompilerFlag is the (bitfield) flag that should be passed in the\nfourth argument to the builtin function compile() to enable\nthe feature in dynamically compiled code. This flag is stored in the\ncompiler_flag attribute on _Future instances.\nNo feature description will ever be deleted from __future__.", "python_version": "2.2", "length": 2219, "url": "https://docs.python.org/2.2/ref/module-future.html"} {"title": "A.3 Nested scopes", "text": "module-future.html | futures.html | definitions.html | Python Reference Manual | contents.html | genindex.html\n---\n# A.3 Nested scopes\nThis section defines the new scoping semantics that will be introduced\nin Python 2.2. They are available in Python 2.1 by using the future\nstatement \"nested_scopes\". This section begins with a bit of\nterminology.", "python_version": "2.2", "length": 347, "url": "https://docs.python.org/2.2/ref/nested-scopes.html"} {"title": "B.2 Terms and conditions for accessing or otherwise using Python", "text": "node99.html | node98.html | genindex.html | Python Reference Manual | contents.html | genindex.html\n---\n# B.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.2\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.2 software in source or binary\nform and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, PSF\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python\n2.2 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001 Python Software Foundation; All Rights\nReserved'' are retained in Python 2.2 alone or in any\nderivative version prepared by Licensee.\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 2.2 or any part thereof, and wants to\nmake the derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 2.2.\n4. PSF is making Python 2.2 available to Licensee on an ``AS IS''\nbasis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE\nPOSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee. This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n8. By copying, installing or otherwise using Python 2.2, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (``Licensee'') accessing and otherwise\nusing this software in source or binary form and its associated\ndocumentation (``the Software'').\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n3. BeOpen is making the Software available to Licensee on an ``AS IS''\nbasis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions. Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee. This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party. As an exception, the ``BeOpen Python'' logos available\nat http://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (``CNRI''), and the Individual or Organization\n(``Licensee'') accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., ``Copyright\n© 1995-2001 Corporation for National Research Initiatives;\nAll Rights Reserved'' are retained in Python 1.6.1 alone or in any\nderivative version prepared by Licensee. Alternately, in lieu of\nCNRI's License Agreement, Licensee may substitute the following text\n(omitting the quotes): ``Python 1.6.1 is made available subject to the\nterms and conditions in CNRI's License Agreement. This Agreement\ntogether with Python 1.6.1 may be located on the Internet using the\nfollowing unique, persistent identifier (known as a handle):\n1895.22/1013. This Agreement may also be obtained from a proxy server\non the Internet using the following URL:\nhttp://hdl.handle.net/1895.22/1013.''\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''\nbasis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement. Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee. This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n8. By clicking on the ``ACCEPT'' button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\nACCEPT\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\nCopyright © 1991 - 1995, Stichting Mathematisch Centrum\nAmsterdam, The Netherlands. All rights reserved.\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", "python_version": "2.2", "length": 9769, "url": "https://docs.python.org/2.2/ref/node100.html"} {"title": "B. History and License", "text": "dynamic-features.html | ref.html | node99.html | Python Reference Manual | contents.html | genindex.html\n---\n# B. History and License", "python_version": "2.2", "length": 133, "url": "https://docs.python.org/2.2/ref/node98.html"} {"title": "B.1 History of the software", "text": "node98.html | node98.html | node100.html | Python Reference Manual | contents.html | genindex.html\n---\n# B.1 History of the software\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands\nas a successor of a language called ABC. Guido remains Python's\nprincipal author, although it includes many contributions from others.\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)\nin Reston, Virginia where he released several versions of the\nsoftware.\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team. In October of the same\nyear, the PythonLabs team moved to Zope Corporation (then Digital\nCreations; see http://www.zope.com/). In 2001, the Python\nSoftware Foundation (PSF, see http://www.python.org/psf/) was\nformed, a non-profit organization created specifically to own\nPython-related Intellectual Property. Digital Creations is a\nsponsoring member of the PSF.\nAll Python releases are Open Source (see\nhttp://www.opensource.org/ for the Open Source Definition).\nHistorically, most, but not all, Python releases have also been\nGPL-compatible; the table below summarizes the various releases.\nNote:\nGPL-compatible doesn't mean that we're distributing\nPython under the GPL. All Python licenses, unlike the GPL, let you\ndistribute a modified version without making your changes open source.\nThe GPL-compatible licenses make it possible to combine Python with\nother software that is released under the GPL; the others don't.\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.", "python_version": "2.2", "length": 1763, "url": "https://docs.python.org/2.2/ref/node99.html"} {"title": "1.1 Notation", "text": "introduction.html | introduction.html | lexical.html | Python Reference Manual | contents.html | genindex.html\n---\n# 1.1 Notation\nThe descriptions of lexical analysis and syntax use a modified BNF\ngrammar notation. This uses the following style of definition:\n```text\n\nname: lc_letter (lc_letter | \"_\")*\nlc_letter: \"a\"...\"z\"\n```\nThe first line says that a `name` is an `lc_letter` followed by\na sequence of zero or more `lc_letter`s and underscores. An\n`lc_letter` in turn is any of the single characters \"a\"\nthrough \"z\". (This rule is actually adhered to for the\nnames defined in lexical and grammar rules in this document.)\nEach rule begins with a name (which is the name defined by the rule)\nand a colon. A vertical bar (`|`) is used to separate\nalternatives; it is the least binding operator in this notation. A\nstar (`*`) means zero or more repetitions of the preceding item;\nlikewise, a plus (`+`) means one or more repetitions, and a\nphrase enclosed in square brackets (`[ ]`) means zero or one\noccurrences (in other words, the enclosed phrase is optional). The\n`*` and `+` operators bind as tightly as possible;\nparentheses are used for grouping. Literal strings are enclosed in\nquotes. White space is only meaningful to separate tokens.\nRules are normally contained on a single line; rules with many\nalternatives may be formatted alternatively with each line after the\nfirst beginning with a vertical bar.\nIn lexical definitions (as the example above), two more conventions\nare used: Two literal characters separated by three dots mean a choice\nof any single character in the given (inclusive) range of ASCII\ncharacters. A phrase between angular brackets (`<...>`) gives an\ninformal description of the symbol defined; e.g., this could be used\nto describe the notion of `control character' if needed.", "python_version": "2.2", "length": 1808, "url": "https://docs.python.org/2.2/ref/notation.html"} {"title": "2.4.3 Numeric literals", "text": "string-catenation.html | literals.html | integers.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.3 Numeric literals\nThere are four types of numeric literals: plain integers, long\nintegers, floating point numbers, and imaginary numbers. There are no\ncomplex literals (complex numbers can be formed by adding a real\nnumber and an imaginary number).\nNote that numeric literals do not include a sign; a phrase like\n`-1` is actually an expression composed of the unary operator\n``-`' and the literal `1`.", "python_version": "2.2", "length": 526, "url": "https://docs.python.org/2.2/ref/numbers.html"} {"title": "3.3.6 Emulating numeric types", "text": "sequence-methods.html | specialnames.html | execmodel.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.6 Emulating numeric types\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\nCoercion rules: to evaluate x op y, the\nfollowing steps are taken (where __op__() and\n__rop__() are the method names corresponding to\nop, e.g., if op is ``+`', __add__() and\n__radd__() are used). If an exception occurs at any point,\nthe evaluation is abandoned and exception handling takes over.", "python_version": "2.2", "length": 696, "url": "https://docs.python.org/2.2/ref/numeric-types.html"} {"title": "3.1 Objects, values and types", "text": "datamodel.html | datamodel.html | types.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3.1 Objects, values and types\nObjects are Python's abstraction for data. All data in a Python\nprogram is represented by objects or by relations between objects.\n(In a sense, and in conformance to Von Neumann's model of a\n``stored program computer,'' code is also represented by objects.)\nEvery object has an identity, a type and a value. An object's\nidentity never changes once it has been created; you may think\nof it as the object's address in memory. The ``is`' operator\ncompares the identity of two objects; the\nid()function returns an integer\nrepresenting its identity (currently implemented as its address).\nAn object's type is\nalso unchangeable. It determines the operations that an object\nsupports (e.g., ``does it have a length?'') and also defines the\npossible values for objects of that type. The\ntype()function returns an object's type\n(which is an object itself). The value of some\nobjects can change. Objects whose value can change are said to be\nmutable; objects whose value is unchangeable once they are\ncreated are called immutable.\n(The value of an immutable container object that contains a reference\nto a mutable object can change when the latter's value is changed;\nhowever the container is still considered immutable, because the\ncollection of objects it contains cannot be changed. So, immutability\nis not strictly the same as having an unchangeable value, it is more\nsubtle.)\nAn object's mutability is determined by its type; for instance,\nnumbers, strings and tuples are immutable, while dictionaries and\nlists are mutable.\nObjects are never explicitly destroyed; however, when they become\nunreachable they may be garbage-collected. An implementation is\nallowed to postpone garbage collection or omit it altogether -- it is\na matter of implementation quality how garbage collection is\nimplemented, as long as no objects are collected that are still\nreachable. (Implementation note: the current implementation uses a\nreference-counting scheme with (optional) delayed detection of\ncyclicly linked garbage, which collects most objects as soon as they\nbecome unreachable, but is not guaranteed to collect garbage\ncontaining circular references. See the\nPython Library Reference (../lib/module-gc.html) for\ninformation on controlling the collection of cyclic garbage.)\nNote that the use of the implementation's tracing or debugging\nfacilities may keep objects alive that would normally be collectable.\nAlso note that catching an exception with a\n`try...except' statement may keep objects alive.\nSome objects contain references to ``external'' resources such as open\nfiles or windows. It is understood that these resources are freed\nwhen the object is garbage-collected, but since garbage collection is\nnot guaranteed to happen, such objects also provide an explicit way to\nrelease the external resource, usually a close() method.\nPrograms are strongly recommended to explicitly close such\nobjects. The `try...finally' statement provides\na convenient way to do this.\nSome objects contain references to other objects; these are called\ncontainers. Examples of containers are tuples, lists and\ndictionaries. The references are part of a container's value. In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of\nthe immediately contained objects are implied. So, if an immutable\ncontainer (like a tuple)\ncontains a reference to a mutable object, its value changes\nif that mutable object is changed.\nTypes affect almost all aspects of object behavior. Even the importance\nof object identity is affected in some sense: for immutable types,\noperations that compute new values may actually return a reference to\nany existing object with the same type and value, while for mutable\nobjects this is not allowed. E.g., after\n\"a = 1; b = 1\",\n`a` and `b` may or may not refer to the same object with the\nvalue one, depending on the implementation, but after\n\"c = []; d = []\", `c` and `d`\nare guaranteed to refer to two different, unique, newly created empty\nlists.\n(Note that \"c = d = []\" assigns the same object to both\n`c` and `d`.)", "python_version": "2.2", "length": 4301, "url": "https://docs.python.org/2.2/ref/objects.html"} {"title": "2.5 Operators", "text": "imaginary.html | lexical.html | delimiters.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.5 Operators\nThe following tokens are operators:\n```text\n\n+ - * ** / // %\n<< >> & | ^ ~\n< > <= >= == != <>\n```\nThe comparison operators `<>` and `!=` are alternate\nspellings of the same operator. `!=` is the preferred spelling;\n`<>` is obsolescent.", "python_version": "2.2", "length": 361, "url": "https://docs.python.org/2.2/ref/operators.html"} {"title": "2.2 Other tokens", "text": "whitespace.html | lexical.html | identifiers.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.2 Other tokens\nBesides NEWLINE, INDENT and DEDENT, the following categories of tokens\nexist: identifiers, keywords, literals,\noperators, and delimiters.\nWhitespace characters (other than line terminators, discussed earlier)\nare not tokens, but serve to delimit tokens.\nWhere\nambiguity exists, a token comprises the longest possible string that\nforms a legal token, when read from left to right.", "python_version": "2.2", "length": 510, "url": "https://docs.python.org/2.2/ref/other-tokens.html"} {"title": "5.2.3 Parenthesized forms", "text": "atom-literals.html | atoms.html | lists.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.3 Parenthesized forms\nA parenthesized form is an optional expression list enclosed in\nparentheses:\n`parenth_form` | ::= | `\"(\" [ expression_list ] \")\"`\nDownload entire grammar as text. (grammar.txt)\nA parenthesized expression list yields whatever that expression list\nyields: if the list contains at least one comma, it yields a tuple;\notherwise, it yields the single expression that makes up the\nexpression list.\nAn empty pair of parentheses yields an empty tuple object. Since\ntuples are immutable, the rules for literals apply (i.e., two\noccurrences of the empty tuple may or may not yield the same object).\nNote that tuples are not formed by the parentheses, but rather by use\nof the comma operator. The exception is the empty tuple, for which\nparentheses are required -- allowing unparenthesized ``nothing''\nin expressions would cause ambiguities and allow common typos to\npass uncaught.", "python_version": "2.2", "length": 1006, "url": "https://docs.python.org/2.2/ref/parenthesized.html"} {"title": "6.4 The pass statement", "text": "augassign.html | simple.html | del.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.4 The pass statement\n`pass_stmt` | ::= | `\"pass\"`\nDownload entire grammar as text. (grammar.txt)\npass is a null operation -- when it is executed, nothing\nhappens. It is useful as a placeholder when a statement is\nrequired syntactically, but no code needs to be executed, for example:\n```text\n\ndef f(arg): pass # a function that does nothing (yet)\n\nclass C: pass # a class with no methods (yet)\n```", "python_version": "2.2", "length": 503, "url": "https://docs.python.org/2.2/ref/pass.html"} {"title": "2.1.2 Physical lines", "text": "logical.html | line-structure.html | comments.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.2 Physical lines\nA physical line ends in whatever the current platform's convention is\nfor terminating lines. On Unix, this is the ASCII LF (linefeed)\ncharacter. On DOS/Windows, it is the ASCII sequence CR LF (return\nfollowed by linefeed). On Macintosh, it is the ASCII CR (return)\ncharacter.", "python_version": "2.2", "length": 412, "url": "https://docs.python.org/2.2/ref/physical.html"} {"title": "5.4 The power operator", "text": "calls.html | expressions.html | unary.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.4 The power operator\nThe power operator binds more tightly than unary operators on its\nleft; it binds less tightly than unary operators on its right. The\nsyntax is:\n`power` | ::= | `primary [\"**\" u_expr ]`\nDownload entire grammar as text. (grammar.txt)\nThus, in an unparenthesized sequence of power and unary operators, the\noperators are evaluated from right to left (this does not constrain\nthe evaluation order for the operands).\nThe power operator has the same semantics as the built-in\npow() function, when called with two arguments: it yields\nits left argument raised to the power of its right argument. The\nnumeric arguments are first converted to a common type. The result\ntype is that of the arguments after coercion; if the result is not\nexpressible in that type (as in raising an integer to a negative\npower, or a negative floating point number to a broken power), a\nTypeError exception is raised.", "python_version": "2.2", "length": 1016, "url": "https://docs.python.org/2.2/ref/power.html"} {"title": "5.3 Primaries", "text": "string-conversions.html | expressions.html | attribute-references.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.3 Primaries\nPrimaries represent the most tightly bound operations of the language.\nTheir syntax is:\n`primary` | ::= | `atom | attributeref | subscription | slicing | call`\nDownload entire grammar as text. (grammar.txt)", "python_version": "2.2", "length": 355, "url": "https://docs.python.org/2.2/ref/primaries.html"} {"title": "6.6 The print statement", "text": "del.html | simple.html | return.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.6 The print statement\n`print_stmt` | ::= | `\"print\" ( [ expression (\",\" expression )* [ \",\" ] ] | \"> > \" expression [ (\",\" expression )+ [ \",\" ] ] )`\nDownload entire grammar as text. (grammar.txt)\nprint evaluates each expression in turn and writes the\nresulting object to standard output (see below). If an object is not\na string, it is first converted to a string using the rules for string\nconversions. The (resulting or original) string is then written. A\nspace is written before each object is (converted and) written, unless\nthe output system believes it is positioned at the beginning of a\nline. This is the case (1) when no characters have yet been written\nto standard output, (2) when the last character written to standard\noutput is \"\\n\", or (3) when the last write operation on\nstandard output was not a print statement. (In some cases\nit may be functional to write an empty string to standard output for\nthis reason.) Note:\nObjects which act like file objects but which are\nnot the built-in file objects often do not properly emulate this\naspect of the file object's behavior, so it is best not to rely on\nthis.\nA \"\\n\" character is written at the end, unless the\nprint statement ends with a comma. This is the only action\nif the statement contains just the keyword print.\nStandard output is defined as the file object named `stdout`\nin the built-in module sys. If no such object exists, or if\nit does not have a write() method, a RuntimeError\nexception is raised.\nprint also has an extendedform, defined by the second portion of the syntax described above.\nThis form is sometimes referred to as ``print chevron.''\nIn this form, the first expression after the `>``>` must\nevaluate to a ``file-like'' object, specifically an object that has a\nwrite() method as described above. With this extended form,\nthe subsequent expressions are printed to this file object. If the\nfirst expression evaluates to `None`, then `sys.stdout` is\nused as the file for output.", "python_version": "2.2", "length": 2069, "url": "https://docs.python.org/2.2/ref/print.html"} {"title": "8.1 Complete Python programs", "text": "top-level.html | top-level.html | file-input.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.1 Complete Python programs\nWhile a language specification need not prescribe how the language\ninterpreter is invoked, it is useful to have a notion of a complete\nPython program. A complete Python program is executed in a minimally\ninitialized environment: all built-in and standard modules are\navailable, but none have been initialized, except for sys\n(various system services), __builtin__ (built-in functions,\nexceptions and `None`) and __main__. The latter is used\nto provide the local and global namespace for execution of the\ncomplete program.\nThe syntax for a complete Python program is that for file input,\ndescribed in the next section.\nThe interpreter may also be invoked in interactive mode; in this case,\nit does not read and execute a complete program but reads and executes\none statement (possibly compound) at a time. The initial environment\nis identical to that of a complete program; each statement is executed\nin the namespace of __main__.\nUnder Unix, a complete program can be passed to the interpreter in\nthree forms: with the -c string command line option, as a\nfile passed as the first command line argument, or as standard input.\nIf the file or standard input is a tty device, the interpreter enters\ninteractive mode; otherwise, it executes the file as a complete\nprogram.", "python_version": "2.2", "length": 1410, "url": "https://docs.python.org/2.2/ref/programs.html"} {"title": "6.9 The raise statement", "text": "yield.html | simple.html | break.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.9 The raise statement\n`raise_stmt` | ::= | `\"raise\" [ expression [\",\" expression [\",\" expression ]]]`\nDownload entire grammar as text. (grammar.txt)\nIf no expressions are present, raise re-raises the last\nexpression that was raised in the current scope.\nOtherwise, raise evaluates its first expression, which must yield\na string, class, or instance object. If there is a second expression,\nthis is evaluated, else `None` is substituted. If the first\nexpression is a class object, then the second expression may be an\ninstance of that class or one of its derivatives, and then that\ninstance is raised. If the second expression is not such an instance,\nthe given class is instantiated. The argument list for the\ninstantiation is determined as follows: if the second expression is a\ntuple, it is used as the argument list; if it is `None`, the\nargument list is empty; otherwise, the argument list consists of a\nsingle argument which is the second expression. If the first\nexpression is an instance object, the second expression must be\n`None`.\nIf the first object is a string, it then raises the exception\nidentified by the first object, with the second one (or `None`)\nas its parameter. If the first object is a class or instance,\nit raises the exception identified by the class of the instance\ndetermined in the previous step, with the instance as\nits parameter.\nIf a third object is present, and it is not `None`, it should be\na traceback object (see section 3.2 (types.html#traceback)), and it is\nsubstituted instead of the current location as the place where the\nexception occurred. This is useful to re-raise an exception\ntransparently in an except clause.", "python_version": "2.2", "length": 1763, "url": "https://docs.python.org/2.2/ref/raise.html"} {"title": "Python Reference Manual", "text": "../index.html | front.html | Python Reference Manual | contents.html | genindex.html\n---\n# Python Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 229, "url": "https://docs.python.org/2.2/ref/ref.html"} {"title": "6.7 The return statement", "text": "print.html | simple.html | yield.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.7 The return statement\n`return_stmt` | ::= | `\"return\" [ expression_list ]`\nDownload entire grammar as text. (grammar.txt)\nreturn may only occur syntactically nested in a function\ndefinition, not within a nested class definition.\nIf an expression list is present, it is evaluated, else `None`\nis substituted.\nreturn leaves the current function call with the expression\nlist (or `None`) as return value.\nWhen return passes control out of a try statement\nwith a finally clause, that finally clause is executed\nbefore really leaving the function.\nIn a generator function, the return statement is not allowed\nto include an expression_list (exprlists.html#tok-expression_list). In that context, a bare\nreturn indicates that the generator is done and will cause\nStopIteration to be raised.", "python_version": "2.2", "length": 887, "url": "https://docs.python.org/2.2/ref/return.html"} {"title": "3.3.5 Additional methods for emulation of sequence types", "text": "sequence-types.html | specialnames.html | numeric-types.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.5 Additional methods for emulation of sequence types\nThe following methods can be defined to further emulate sequence\nobjects. Immutable sequences methods should only define\n__getslice__(); mutable sequences, should define all three\nthree methods.\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used, and the slice method is available. For slice\noperations involving extended slice notation, or in absence of the\nslice methods, __getitem__(), __setitem__() or\n__delitem__() is called with a slice object as argument.\nThe following example demonstrate how to make your program or module\ncompatible with earlier versions of Python (assuming that methods\n__getitem__(), __setitem__() and __delitem__()\nsupport slice objects as arguments):\n```text\n\nclass MyClass:\n...\ndef __getitem__(self, index):\n...\ndef __setitem__(self, index, value):\n...\ndef __delitem__(self, index):\n...\n\nif sys.version_info < (2, 0):\n# They won't be defined if version is at least 2.0 final\n\ndef __getslice__(self, i, j):\nreturn self[max(0, i):max(0, j):]\ndef __setslice__(self, i, j, seq):\nself[max(0, i):max(0, j):] = seq\ndef __delslice__(self, i, j):\ndel self[max(0, i):max(0, j):]\n...\n```\nNote the calls to max(); these are actually necessary due\nto the handling of negative indices before the\n__*slice__() methods are called. When negative indexes are\nused, the __*item__() methods receive them as provided, but\nthe __*slice__() methods get a ``cooked'' form of the index\nvalues. For each negative index value, the length of the sequence is\nadded to the index before calling the method (which may still result\nin a negative index); this is the customary handling of negative\nindexes by the built-in sequence types, and the __*item__()\nmethods are expected to do this as well. However, since they should\nalready be doing that, negative indexes cannot be passed in; they must\nbe be constrained to the bounds of the sequence before being passed to\nthe __*item__() methods.\nCalling `max(0, i)` conveniently returns the proper value.", "python_version": "2.2", "length": 2172, "url": "https://docs.python.org/2.2/ref/sequence-methods.html"} {"title": "3.3.4 Emulating container types", "text": "callable-types.html | specialnames.html | sequence-methods.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.4 Emulating container types\nThe following methods can be defined to implement container\nobjects. Containers usually are sequences (such as lists or tuples)\nor mappings (like dictionaries), but can represent other containers as\nwell. The first set of methods is used either to emulate a\nsequence or to emulate a mapping; the difference is that for a\nsequence, the allowable keys should be the integers k for which\n`0 <= k < N` where N is the length of the\nsequence, or slice objects, which define a range of items. (For backwards\ncompatibility, the method __getslice__() (see below) can also be\ndefined to handle simple, but not extended slices.) It is also recommended\nthat mappings provide the methods keys(), values(),\nitems(), has_key(), get(), clear(),\ncopy(), and update() behaving similar to those for\nPython's standard dictionary objects; mutable sequences should provide\nmethods append(), count(), index(),\ninsert(), pop(), remove(), reverse()\nand sort(), like Python standard list objects. Finally,\nsequence types should implement addition (meaning concatenation) and\nmultiplication (meaning repetition) by defining the methods\n__add__(), __radd__(), __iadd__(),\n__mul__(), __rmul__() and __imul__() described\nbelow; they should not define __coerce__() or other numerical\noperators. It is recommended that both mappings and sequences\nimplement the __contains__() method to allow efficient use of\nthe `in` operator; for mappings, `in` should be equivalent\nof has_key(); for sequences, it should search through the\nvalues.\nThe membership test operators (in and not in) are\nnormally implemented as an iteration through a sequence. However,\ncontainer objects can supply the following special method with a more\nefficient implementation, which also does not require the object be a\nsequence.", "python_version": "2.2", "length": 1928, "url": "https://docs.python.org/2.2/ref/sequence-types.html"} {"title": "5.7 Shifting operations", "text": "binary.html | expressions.html | bitwise.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.7 Shifting operations\nThe shifting operations have lower priority than the arithmetic\noperations:\n`shift_expr` | ::= | `a_expr | shift_expr ( \"«\" | \"»\" ) a_expr`\nDownload entire grammar as text. (grammar.txt)\nThese operators accept plain or long integers as arguments. The\narguments are converted to a common type. They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\nA right shift by n bits is defined as division by\n`pow(2, n )`. A left shift by n bits is defined as\nmultiplication with `pow(2, n )`; for plain integers there is\nno overflow check so in that case the operation drops bits and flips\nthe sign if the result is not less than `pow(2,31)` in absolute\nvalue. Negative shift counts raise a ValueError\nexception.", "python_version": "2.2", "length": 884, "url": "https://docs.python.org/2.2/ref/shifting.html"} {"title": "6. Simple statements", "text": "summary.html | ref.html | exprstmts.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6. Simple statements\nSimple statements are comprised within a single logical line.\nSeveral simple statements may occur on a single line separated\nby semicolons. The syntax for simple statements is:\n`simple_stmt` | ::= | `expression_stmt | assert_stmt | assignment_stmt | augmented_assignment_stmt | pass_stmt | del_stmt | print_stmt | return_stmt | yield_stmt | raise_stmt | break_stmt | continue_stmt | import_stmt | global_stmt | exec_stmt`\nDownload entire grammar as text. (grammar.txt)", "python_version": "2.2", "length": 594, "url": "https://docs.python.org/2.2/ref/simple.html"} {"title": "5.3.3 Slicings", "text": "subscriptions.html | primaries.html | calls.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.3 Slicings\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list). Slicings may be used as expressions or as\ntargets in assignment or del statements. The syntax for a slicing:\n`slicing` | ::= | `simple_slicing | extended_slicing`\n`simple_slicing` | ::= | `primary \"[\" short_slice \"]\"`\n`extended_slicing` | ::= | `primary \"[\" slice_list \"]\"`\n`slice_list` | ::= | `slice_item (\",\" slice_item )* [\",\"]`\n`slice_item` | ::= | `expression | proper_slice | ellipsis`\n`proper_slice` | ::= | `short_slice | long_slice`\n`short_slice` | ::= | `[ lower_bound ] \":\" [ upper_bound ]`\n`long_slice` | ::= | `short_slice \":\" [ stride ]`\n`lower_bound` | ::= | `expression`\n`upper_bound` | ::= | `expression`\n`stride` | ::= | `expression`\n`ellipsis` | ::= | `\"...\"`\nDownload entire grammar as text. (grammar.txt)\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing. Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice nor ellipses). Similarly, when the slice\nlist has exactly one short slice and no trailing comma, the\ninterpretation as a simple slicing takes priority over that as an\nextended slicing.\nThe semantics for a simple slicing are as follows. The primary must\nevaluate to a sequence object. The lower and upper bound expressions,\nif present, must evaluate to plain integers; defaults are zero and the\n`sys.maxint`, respectively. If either bound is negative, the\nsequence's length is added to it. The slicing now selects all items\nwith index k such that\n`i <= k < j` where i\nand j are the specified lower and upper bounds. This may be an\nempty sequence. It is not an error if i or j lie outside the\nrange of valid indexes (such items don't exist so they aren't\nselected).\nThe semantics for an extended slicing are as follows. The primary\nmust evaluate to a mapping object, and it is indexed with a key that\nis constructed from the slice list, as follows. If the slice list\ncontains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key. The conversion of a slice item that is an\nexpression is that expression. The conversion of an ellipsis slice\nitem is the built-in `Ellipsis` object. The conversion of a\nproper slice is a slice object (see section 3.2 (types.html#types)) whose\nstart, stop and step attributes are the\nvalues of the expressions given as lower bound, upper bound and\nstride, respectively, substituting `None` for missing\nexpressions.", "python_version": "2.2", "length": 2898, "url": "https://docs.python.org/2.2/ref/slicings.html"} {"title": "3.3 Special method names", "text": "types.html | datamodel.html | customization.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3.3 Special method names\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. For instance, if a class defines\na method named __getitem__(), and `x` is an instance of\nthis class, then `x[i]` is equivalent to\n`x.__getitem__(i)`. (The reverse is not true -- if `x` is\na list object, `x.__getitem__(i)` is not equivalent to\n`x[i]`.) Except where mentioned, attempts to execute an\noperation raise an exception when no appropriate method is defined.\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\nNodeList interface in the W3C's Document Object Model.)", "python_version": "2.2", "length": 1067, "url": "https://docs.python.org/2.2/ref/specialnames.html"} {"title": "2.4.2 String literal concatenation", "text": "strings.html | literals.html | numbers.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.2 String literal concatenation\nMultiple adjacent string literals (delimited by whitespace), possibly\nusing different quoting conventions, are allowed, and their meaning is\nthe same as their concatenation. Thus, `\"hello\" 'world'` is\nequivalent to `\"helloworld\"`. This feature can be used to reduce\nthe number of backslashes needed, to split long strings conveniently\nacross long lines, or even to add comments to parts of strings, for\nexample:\n```text\n\nre.compile(\"[A-Za-z_]\" # letter or underscore\n\"[A-Za-z0-9_]*\" # letter, digit or underscore\n)\n```\nNote that this feature is defined at the syntactical level, but\nimplemented at compile time. The `+' operator must be used to\nconcatenate string expressions at run time. Also note that literal\nconcatenation can use different quoting styles for each component\n(even mixing raw strings and triple quoted strings).", "python_version": "2.2", "length": 974, "url": "https://docs.python.org/2.2/ref/string-catenation.html"} {"title": "5.2.6 String conversions", "text": "dict.html | atoms.html | primaries.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.6 String conversions\nA string conversion is an expression list enclosed in reverse (a.k.a.\nbackward) quotes:\n`string_conversion` | ::= | `\"`\" expression_list \"`\"`\nDownload entire grammar as text. (grammar.txt)\nA string conversion evaluates the contained expression list and\nconverts the resulting object into a string according to rules\nspecific to its type.\nIf the object is a string, a number, `None`, or a tuple, list or\ndictionary containing only objects whose type is one of these, the\nresulting string is a valid Python expression which can be passed to\nthe built-in function eval() to yield an expression with the\nsame value (or an approximation, if floating point numbers are\ninvolved).\n(In particular, converting a string adds quotes around it and converts\n``funny'' characters to escape sequences that are safe to print.)\nIt is illegal to attempt to convert recursive objects (e.g., lists or\ndictionaries that contain a reference to themselves, directly or\nindirectly.)\nThe built-in function repr() performs exactly the same\nconversion in its argument as enclosing it in parentheses and reverse\nquotes does. The built-in function str() performs a\nsimilar but more user-friendly conversion.", "python_version": "2.2", "length": 1308, "url": "https://docs.python.org/2.2/ref/string-conversions.html"} {"title": "2.4.1 String literals", "text": "literals.html | literals.html | string-catenation.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.1 String literals\nString literals are described by the following lexical definitions:\n`stringliteral` | ::= | `[ stringprefix ]( shortstring | longstring )`\n`stringprefix` | ::= | `\"r\" | \"u\" | \"ur\" | \"R\" | \"U\" | \"UR\" | \"Ur\" | \"uR\"`\n`shortstring` | ::= | `\"'\" shortstringitem * \"'\"\n| '\"' shortstringitem * '\"'`\n`longstring` | ::= | `\"'''\" longstringitem * \"'''\"\n| '\"\"\"' longstringitem * '\"\"\"'`\n`shortstringitem` | ::= | `shortstringchar | escapeseq`\n`longstringitem` | ::= | `longstringchar | escapeseq`\n`shortstringchar` | ::= | ``\n`longstringchar` | ::= | ``\n`escapeseq` | ::= | `\"\\\" `\nDownload entire grammar as text. (grammar.txt)\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the stringprefix (strings.html#tok-stringprefix) and\nthe rest of the string literal.\nIn plain English: String literals can be enclosed in matching single\nquotes (`'`) or double quotes (`\"`). They can also be\nenclosed in matching groups of three single or double quotes (these\nare generally referred to as triple-quoted strings). The\nbackslash (`\\`) character is used to escape characters that\notherwise have a special meaning, such as newline, backslash itself,\nor the quote character. String literals may optionally be prefixed\nwith a letter `r' or `R'; such strings are called raw\nstringsand use different rules for interpreting\nbackslash escape sequences. A prefix of 'u' or 'U' makes the string\na Unicode string. Unicode strings use the Unicode character set as\ndefined by the Unicode Consortium and ISO 10646. Some additional\nescape sequences, described below, are available in Unicode strings.\nThe two prefix characters may be combined; in this case, `u' must\nappear before `r'.\nIn triple-quoted strings,\nunescaped newlines and quotes are allowed (and are retained), except\nthat three unescaped quotes in a row terminate the string. (A\n``quote'' is the character used to open the string, i.e. either\n`'` or `\"`.)\nUnless an `r' or `R' prefix is present, escape sequences in strings\nare interpreted according to rules similar\nto those used by Standard C. The recognized escape sequences are:\nAs in Standard C, up to three octal digits are accepted. However,\nexactly two hex digits are taken in hex escapes.\nUnlike Standard ,\nall unrecognized escape sequences are left in the string unchanged,\ni.e., the backslash is left in the string. (This behavior is\nuseful when debugging: if an escape sequence is mistyped, the\nresulting output is more easily recognized as broken.) It is also\nimportant to note that the escape sequences marked as ``(Unicode\nonly)'' in the table above fall into the category of unrecognized\nescapes for non-Unicode string literals.\nWhen an `r' or `R' prefix is present, a character following a\nbackslash is included in the string without change, and all\nbackslashes are left in the string. For example, the string literal\n`r\"\\n\"` consists of two characters: a backslash and a lowercase\n`n'. String quotes can be escaped with a backslash, but the backslash\nremains in the string; for example, `r\"\\\"\"` is a valid string\nliteral consisting of two characters: a backslash and a double quote;\n`r\"\\\"` is not a valid string literal (even a raw string cannot\nend in an odd number of backslashes). Specifically, a raw\nstring cannot end in a single backslash (since the backslash would\nescape the following quote character). Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, not as a line continuation.", "python_version": "2.2", "length": 3756, "url": "https://docs.python.org/2.2/ref/strings.html"} {"title": "5.3.2 Subscriptions", "text": "attribute-references.html | primaries.html | slicings.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.2 Subscriptions\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n`subscription` | ::= | `primary \"[\" expression_list \"]\"`\nDownload entire grammar as text. (grammar.txt)\nThe primary must evaluate to an object of a sequence or mapping type.\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey. (The expression list is a tuple except if it has exactly one\nitem.)\nIf the primary is a sequence, the expression (list) must evaluate to a\nplain integer. If this value is negative, the length of the sequence\nis added to it (so that, e.g., `x[-1]` selects the last item of\n`x`.) The resulting value must be a nonnegative integer less\nthan the number of items in the sequence, and the subscription selects\nthe item whose index is that value (counting from zero).\nA string's items are characters. A character is not a separate data\ntype but a string of exactly one character.", "python_version": "2.2", "length": 1198, "url": "https://docs.python.org/2.2/ref/subscriptions.html"} {"title": "5.12 Summary", "text": "exprlists.html | expressions.html | simple.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.12 Summary\nThe following table summarizes the operator\nprecedencesin Python, from lowest\nprecedence (least binding) to highest precedence (most binding).\nOperators in the same box have the same precedence. Unless the syntax\nis explicitly given, operators are binary. Operators in the same box\ngroup left to right (except for comparisons, which chain from left to\nright -- see above, and exponentiation, which groups from right to\nleft).", "python_version": "2.2", "length": 550, "url": "https://docs.python.org/2.2/ref/summary.html"} {"title": "8. Top-level components", "text": "class.html | ref.html | programs.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8. Top-level components\nThe Python interpreter can get its input from a number of sources:\nfrom a script passed to it as standard input or as program argument,\ntyped in interactively, from a module source file, etc. This chapter\ngives the syntax used in these cases.", "python_version": "2.2", "length": 368, "url": "https://docs.python.org/2.2/ref/top-level.html"} {"title": "7.4 The try statement", "text": "for.html | compound.html | function.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.4 The try statement\nThe try statement specifies exception handlers and/or cleanup\ncode for a group of statements:\n`try_stmt` | ::= | `try_exc_stmt | try_fin_stmt`\n`try_exc_stmt` | ::= | `\"try\" \":\" suite (\"except\" [ expression [\",\" target ]] \":\" suite )+\n[\"else\" \":\" suite ]`\n`try_fin_stmt` | ::= | `\"try\" \":\" suite \"finally\" \":\" suite`\nDownload entire grammar as text. (grammar.txt)\nThere are two forms of try statement:\ntry...except and\ntry...finally. These forms cannot be mixed (but\nthey can be nested in each other).\nThe try...except form specifies one or more\nexception handlers\n(the except clauses). When no exception occurs in the\ntry clause, no exception handler is executed. When an\nexception occurs in the try suite, a search for an exception\nhandler is started. This search inspects the except clauses in turn until\none is found that matches the exception. An expression-less except\nclause, if present, must be last; it matches any exception. For an\nexcept clause with an expression, that expression is evaluated, and the\nclause matches the exception if the resulting object is ``compatible''\nwith the exception. An object is compatible with an exception if it\nis either the object that identifies the exception, or (for exceptions\nthat are classes) it is a base class of the exception, or it is a\ntuple containing an item that is compatible with the exception. Note\nthat the object identities must match, i.e. it must be the same\nobject, not just an object with the same value.\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled\nand a search starts for the new exception in the surrounding code and\non the call stack (it is treated as if the entire try statement\nraised the exception).\nWhen a matching except clause is found, the exception's parameter is\nassigned to the target specified in that except clause, if present,\nand the except clause's suite is executed. All except clauses must\nhave an executable block. When the end of this block\nis reached, execution continues normally after the entire try\nstatement. (This means that if two nested handlers exist for the same\nexception, and the exception occurs in the try clause of the inner\nhandler, the outer handler will not handle the exception.)\nBefore an except clause's suite is executed, details about the\nexception are assigned to three variables in the\nsysmodule: `sys.exc_type` receives\nthe object identifying the exception; `sys.exc_value` receives\nthe exception's parameter; `sys.exc_traceback` receives a\ntraceback object(see section 3.2 (types.html#traceback))\nidentifying the point in the program where the exception occurred.\nThese details are also available through the sys.exc_info()\nfunction, which returns a tuple `( exc_type , exc_value , exc_traceback )`. Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program. As of Python 1.5, the variables are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\nThe optional else clause is executed if and when control\nflows off the end of the try clause.7.1 (#foot5195) Exceptions in the else clause are not handled by the\npreceding except clauses.\nThe try...finally form specifies a `cleanup' handler. The\ntry clause is executed. When no exception occurs, the\nfinally clause is executed. When an exception occurs in the\ntry clause, the exception is temporarily saved, the\nfinally clause is executed, and then the saved exception is\nre-raised. If the finally clause raises another exception or\nexecutes a return or break statement, the saved\nexception is lost. A continue statement is illegal in the\nfinally clause. (The reason is a problem with the current\nimplementation - thsi restriction may be lifted in the future). The\nexception information is not available to the program during execution of\nthe finally clause.\nWhen a return, break or continue statement is\nexecuted in the try suite of a try...finally\nstatement, the finally clause is also executed `on the way out.' A\ncontinue statement is illegal in the finally clause.\n(The reason is a problem with the current implementation -- this\nrestriction may be lifted in the future).", "python_version": "2.2", "length": 4522, "url": "https://docs.python.org/2.2/ref/try.html"} {"title": "3.2 The standard type hierarchy", "text": "objects.html | datamodel.html | specialnames.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3.2 The standard type hierarchy\nBelow is a list of the types that are built into Python. Extension\nmodules written in C can define additional types. Future versions of\nPython may add types to the type hierarchy (e.g., rational\nnumbers, efficiently stored arrays of integers, etc.).\nSome of the type descriptions below contain a paragraph listing\n`special attributes.' These are attributes that provide access to the\nimplementation and are not intended for general use. Their definition\nmay change in the future.\nNone: This type has a single value. There is a single object with this value.\nThis object is accessed through the built-in name `None`.\nIt is used to signify the absence of a value in many situations, e.g.,\nit is returned from functions that don't explicitly return anything.\nIts truth value is false.\nNotImplemented: This type has a single value. There is a single object with this value.\nThis object is accessed through the built-in name `NotImplemented`.\nNumeric methods and rich comparison methods may return this value if\nthey do not implement the operation for the operands provided. (The\ninterpreter will then try the reflected operation, or some other\nfallback, depending on the operator.) Its truth value is true.\nEllipsis: This type has a single value. There is a single object with this value.\nThis object is accessed through the built-in name `Ellipsis`.\nIt is used to indicate the presence of the \"...\" syntax in a\nslice. Its truth value is true.\nNumbers: These are created by numeric literals and returned as results by\narithmetic operators and arithmetic built-in functions. Numeric\nobjects are immutable; once created their value never changes. Python\nnumbers are of course strongly related to mathematical numbers, but\nsubject to the limitations of numerical representation in computers.\nPython distinguishes between integers, floating point numbers, and\ncomplex numbers:\nIntegers: These represent elements from the mathematical set of whole numbers.\nThere are two types of integers:\nPlain integers: These represent numbers in the range -2147483648 through 2147483647.\n(The range may be larger on machines with a larger natural word\nsize, but not smaller.)\nWhen the result of an operation would fall outside this range, the\nexception OverflowError is raised.\nFor the purpose of shift and mask operations, integers are assumed to\nhave a binary, 2's complement notation using 32 or more bits, and\nhiding no bits from the user (i.e., all 4294967296 different bit\npatterns correspond to different values).\nLong integers: These represent numbers in an unlimited range, subject to available\n(virtual) memory only. For the purpose of shift and mask operations,\na binary representation is assumed, and negative numbers are\nrepresented in a variant of 2's complement which gives the illusion of\nan infinite string of sign bits extending to the left.\nThe rules for integer representation are intended to give the most\nmeaningful interpretation of shift and mask operations involving\nnegative integers and the least surprises when switching between the\nplain and long integer domains. For any operation except left shift,\nif it yields a result in the plain integer domain without causing\noverflow, it will yield the same result in the long integer domain or\nwhen using mixed operands.\nFloating point numbers: These represent machine-level double precision floating point numbers.\nYou are at the mercy of the underlying machine architecture and\nC implementation for the accepted range and handling of overflow.\nPython does not support single-precision floating point numbers; the\nsavings in processor and memory usage that are usually the reason for using\nthese is dwarfed by the overhead of using objects in Python, so there\nis no reason to complicate the language with two kinds of floating\npoint numbers.\nComplex numbers: These represent complex numbers as a pair of machine-level double\nprecision floating point numbers. The same caveats apply as for\nfloating point numbers. The real and imaginary value of a complex\nnumber `z` can be retrieved through the attributes `z.real`\nand `z.imag`.\nSequences: These represent finite ordered sets indexed by non-negative numbers.\nThe built-in function len()returns the\nnumber of items of a sequence.\nWhen the length of a sequence is n, the\nindex set contains the numbers 0, 1, ..., n-1. Item\ni of sequence a is selected by `a [ i ]`.\nSequences also support slicing: `a [ i : j ]`\nselects all items with index k such that i `<=`\nk `<` j. When used as an expression, a slice is a\nsequence of the same type. This implies that the index set is\nrenumbered so that it starts at 0.\nSequences are distinguished according to their mutability:\nImmutable sequences: An object of an immutable sequence type cannot change once it is\ncreated. (If the object contains references to other objects,\nthese other objects may be mutable and may be changed; however,\nthe collection of objects directly referenced by an immutable object\ncannot change.)\nThe following types are immutable sequences:\nStrings: The items of a string are characters. There is no separate\ncharacter type; a character is represented by a string of one item.\nCharacters represent (at least) 8-bit bytes. The built-in\nfunctions chr()and\nord()convert between characters and\nnonnegative integers representing the byte values. Bytes with the\nvalues 0-127 usually represent the corresponding ASCII values, but\nthe interpretation of values is up to the program. The string\ndata type is also used to represent arrays of bytes, e.g., to hold data\nread from a file.\n(On systems whose native character set is not ASCII, strings may use\nEBCDIC in their internal representation, provided the functions\nchr() and ord() implement a mapping between ASCII and\nEBCDIC, and string comparison preserves the ASCII order.\nOr perhaps someone can propose a better rule?)\nUnicode: The items of a Unicode object are Unicode characters. A Unicode\ncharacter is represented by a Unicode object of one item and can hold\na 16-bit value representing a Unicode ordinal. The built-in functions\nunichr()and\nord()convert between characters and\nnonnegative integers representing the Unicode ordinals as defined in\nthe Unicode Standard 3.0. Conversion from and to other encodings are\npossible through the Unicode method encode and the built-in\nfunction unicode()\nTuples: The items of a tuple are arbitrary Python objects.\nTuples of two or more items are formed by comma-separated lists\nof expressions. A tuple of one item (a `singleton') can be formed\nby affixing a comma to an expression (an expression by itself does\nnot create a tuple, since parentheses must be usable for grouping of\nexpressions). An empty tuple can be formed by an empty pair of\nparentheses.\nMutable sequences: Mutable sequences can be changed after they are created. The\nsubscription and slicing notations can be used as the target of\nassignment and del (delete) statements.\nThere is currently a single mutable sequence type:\nLists: The items of a list are arbitrary Python objects. Lists are formed\nby placing a comma-separated list of expressions in square brackets.\n(Note that there are no special cases needed to form lists of length 0\nor 1.)\nThe extension module arrayprovides an\nadditional example of a mutable sequence type.\nMappings: These represent finite sets of objects indexed by arbitrary index sets.\nThe subscript notation `a[k]` selects the item indexed\nby `k` from the mapping `a`; this can be used in\nexpressions and as the target of assignments or del statements.\nThe built-in function len() returns the number of items\nin a mapping.\nThere is currently a single intrinsic mapping type:\nDictionaries: Theserepresent finite sets of objects indexed by\nnearly arbitrary values. The only types of values not acceptable as\nkeys are values containing lists or dictionaries or other mutable\ntypes that are compared by value rather than by object identity, the\nreason being that the efficient implementation of dictionaries\nrequires a key's hash value to remain constant.\nNumeric types used for keys obey the normal rules for numeric\ncomparison: if two numbers compare equal (e.g., `1` and\n`1.0`) then they can be used interchangeably to index the same\ndictionary entry.\nDictionaries are mutable; they are created by the\n`{...}` notation (see section 5.2.5 (dict.html#dict), ``Dictionary\nDisplays'').\nThe extension modules dbm\ngdbm bsddbprovide additional examples of mapping types.\nCallable types: Theseare the types to which the function call\noperation (see section 5.3.4 (calls.html#calls), ``Calls'') can be applied:\nUser-defined functions: A user-defined function object is created by a function definition\n(see section 7.5 (function.html#function), ``Function definitions''). It should be\ncalled with an argument\nlist containing the same number of items as the function's formal\nparameter list.\nSpecial attributes: func_doc or __doc__ is the\nfunction's documentation string, or None if unavailable;\nfunc_name or __name__ is the function's name;\nfunc_defaults is a tuple containing default argument values for\nthose arguments that have defaults, or `None` if no arguments\nhave a default value; func_code is the code object representing\nthe compiled function body; func_globals is (a reference to)\nthe dictionary that holds the function's global variables -- it\ndefines the global namespace of the module in which the function was\ndefined; func_dict or __dict__ contains the\nnamespace supporting arbitrary function attributes;\nfunc_closure is `None` or a tuple of cells that contain\nbinding for the function's free variables.\nOf these, func_code, func_defaults, func_closure,\nfunc_doc/__doc__, and\nfunc_dict/__dict__ may be writable; the\nothers can never be changed. Additional information about a\nfunction's definition can be retrieved from its code object; see the\ndescription of internal types below.\nIn Python 2.1, the func_closure slot is always `None`\nunless nested scopes are enabled. (See the appendix.)\nUser-defined methods: A user-defined method object combines a class, a class instance (or\n`None`) and any callable object (normally a user-defined\nfunction).\nSpecial read-only attributes: im_self is the class instance\nobject, im_func is the function object;\nim_class is the class of im_self for bound methods,\nor the class that asked for the method for unbound methods);\n__doc__ is the method's documentation (same as\n`im_func.__doc__`); __name__ is the method name (same as\n`im_func.__name__`).\nChanged in version 2.2:\nim_self used to refer to the class that\ndefined the method.\nMethods also support accessing (but not setting) the arbitrary\nfunction attributes on the underlying function object.\nUser-defined method objects are created in two ways: when getting an\nattribute of a class that is a user-defined function object, or when\ngetting an attribute of a class instance that is a user-defined\nfunction object defined by the class of the instance. In the former\ncase (class attribute), the im_self attribute is `None`,\nand the method object is said to be unbound; in the latter case\n(instance attribute), im_self is the instance, and the method\nobject is said to be bound. For\ninstance, when C is a class which has a method\nf(), `C.f` does not yield the function object\n`f`; rather, it yields an unbound method object `m` where\n`m.im_class` is C, `m.im_func` is f(), and\n`m.im_self` is `None`. When `x` is a C\ninstance, `x.f` yields a bound method object `m` where\n`m.im_class` is `C`, `m.im_func` is f(), and\n`m.im_self` is `x`.\nWhen an unbound user-defined method object is called, the underlying\nfunction (im_func) is called, with the restriction that the\nfirst argument must be an instance of the proper class\n(im_class) or of a derived class thereof.\nWhen a bound user-defined method object is called, the underlying\nfunction (im_func) is called, inserting the class instance\n(im_self) in front of the argument list. For instance, when\nC is a class which contains a definition for a function\nf(), and `x` is an instance of C, calling\n`x.f(1)` is equivalent to calling `C.f(x, 1)`.\nNote that the transformation from function object to (unbound or\nbound) method object happens each time the attribute is retrieved from\nthe class or instance. In some cases, a fruitful optimization is to\nassign the attribute to a local variable and call that local variable.\nAlso notice that this transformation only happens for user-defined\nfunctions; other callable objects (and all non-callable objects) are\nretrieved without transformation. It is also important to note that\nuser-defined functions which are attributes of a class instance are\nnot converted to bound methods; this only happens when the\nfunction is an attribute of the class.\nGenerator functions: A function or method which uses the yield statement (see\nsection 6.8 (yield.html#yield), ``The yield statement'') is called a\ngenerator function. Such a function, when called, always\nreturns an iterator object which can be used to execute the body of\nthe function: calling the iterator's next() method will\ncause the function to execute until it provides a value using the\nyield statement. When the function executes a\nreturn statement or falls off the end, a\nStopIteration exception is raised and the iterator will\nhave reached the end of the set of values to be returned.\nBuilt-in functions: A built-in function object is a wrapper around a C function. Examples\nof built-in functions are len() and math.sin()\n(math is a standard built-in module).\nThe number and type of the arguments are\ndetermined by the C function.\nSpecial read-only attributes: __doc__ is the function's\ndocumentation string, or `None` if unavailable; __name__\nis the function's name; __self__ is set to `None` (but see\nthe next item).\nBuilt-in methods: This is really a different disguise of a built-in function, this time\ncontaining an object passed to the C function as an implicit extra\nargument. An example of a built-in method is\n`list .append()`, assuming\nlist is a list object.\nIn this case, the special read-only attribute __self__ is set\nto the object denoted by list.\nClasses: Class objects are described below. When a class object is called,\na new class instance (also described below) is created and\nreturned. This implies a call to the class's __init__() method\nif it has one. Any arguments are passed on to the __init__()\nmethod. If there is no __init__() method, the class must be called\nwithout arguments.\nClass instances: Class instances are described below. Class instances are callable\nonly when the class has a __call__() method; `x(arguments)`\nis a shorthand for `x.__call__(arguments)`.\nModules: Modules are imported by the import statement (see section\n6.12 (import.html#import), ``The import statement'').\nA module object has a namespace implemented by a dictionary object\n(this is the dictionary referenced by the func_globals attribute of\nfunctions defined in the module). Attribute references are translated\nto lookups in this dictionary, e.g., `m.x` is equivalent to\n`m.__dict__[\"x\"]`.\nA module object does not contain the code object used to\ninitialize the module (since it isn't needed once the initialization\nis done).\nAttribute assignment updates the module's namespace dictionary,\ne.g., \"m.x = 1\" is equivalent to \"m.__dict__[\"x\"] = 1\".\nSpecial read-only attribute: __dict__ is the module's\nnamespace as a dictionary object.\nPredefined (writable) attributes: __name__\nis the module's name; __doc__ is the\nmodule's documentation string, or\n`None` if unavailable; __file__ is the pathname of the\nfile from which the module was loaded, if it was loaded from a file.\nThe __file__ attribute is not present for C modules that are\nstatically linked into the interpreter; for extension modules loaded\ndynamically from a shared library, it is the pathname of the shared\nlibrary file.\nClasses: Class objects are created by class definitions (see section\n7.6 (class.html#class), ``Class definitions'').\nA class has a namespace implemented by a dictionary object.\nClass attribute references are translated to\nlookups in this dictionary,\ne.g., \"C.x\" is translated to \"C.__dict__[\"x\"]\".\nWhen the attribute name is not found\nthere, the attribute search continues in the base classes. The search\nis depth-first, left-to-right in the order of occurrence in the\nbase class list.\nWhen a class attribute reference would yield a user-defined function\nobject, it is transformed into an unbound user-defined method object\n(see above). The im_class attribute of this method object is the\nclass for which the attribute reference was initiated.\nClass attribute assignments update the class's dictionary, never the\ndictionary of a base class.\nA class object can be called (see above) to yield a class instance (see\nbelow).\nSpecial attributes: __name__ is the class name;\n__module__ is the module name in which the class was defined;\n__dict__ is the dictionary containing the class's namespace;\n__bases__ is a tuple (possibly empty or a singleton)\ncontaining the base classes, in the order of their occurrence in the\nbase class list; __doc__ is the class's documentation string,\nor None if undefined.\nClass instances: A class instance is created by calling a class object (see above).\nA class instance has a namespace implemented as a dictionary which\nis the first place in which\nattribute references are searched. When an attribute is not found\nthere, and the instance's class has an attribute by that name,\nthe search continues with the class attributes. If a class attribute\nis found that is a user-defined function object (and in no other\ncase), it is transformed into an unbound user-defined method object\n(see above). The im_class attribute of this method object is\nthe\nclass of the instance for which the attribute reference was initiated.\nIf no class attribute is found, and the object's class has a\n__getattr__() method, that is called to satisfy the lookup.\nAttribute assignments and deletions update the instance's dictionary,\nnever a class's dictionary. If the class has a __setattr__() or\n__delattr__() method, this is called instead of updating the\ninstance dictionary directly.\nClass instances can pretend to be numbers, sequences, or mappings if\nthey have methods with certain special names. See\nsection 3.3 (specialnames.html#specialnames), ``Special method names.''\nSpecial attributes: __dict__ is the attribute\ndictionary; __class__ is the instance's class.\nFiles: A fileobject represents an open file. File objects are\ncreated by the open()built-in function,\nand also by\nos.popen(),\nos.fdopen(), and the\nmakefile()method of socket objects (and perhaps by other functions or methods\nprovided by extension modules). The objects\n`sys.stdin`,\n`sys.stdout` and\n`sys.stderr` are initialized to file objects\ncorresponding to the interpreter's standardinput, output\nand error streams. See the Python Library\nReference (../lib/lib.html) for complete documentation of file objects.\nInternal types: A few types used internally by the interpreter are exposed to the user.\nTheir definitions may change with future versions of the interpreter,\nbut they are mentioned here for completeness.\nCode objects: Code objects represent byte-compiled executable Python code, or\nbytecode.\nThe difference between a code\nobject and a function object is that the function object contains an\nexplicit reference to the function's globals (the module in which it\nwas defined), while a code object contains no context;\nalso the default argument values are stored in the function object,\nnot in the code object (because they represent values calculated at\nrun-time). Unlike function objects, code objects are immutable and\ncontain no references (directly or indirectly) to mutable objects.\nSpecial read-only attributes: co_name gives the function\nname; co_argcount is the number of positional arguments\n(including arguments with default values); co_nlocals is the\nnumber of local variables used by the function (including arguments);\nco_varnames is a tuple containing the names of the local\nvariables (starting with the argument names); co_cellvars is\na tuple containing the names of local variables that are referenced by\nnested functions; co_freevars is a tuple containing the names\nof local variables that are neither local nor global; co_code\nis a string representing the sequence of bytecode instructions;\nco_consts is a tuple containing the literals used by the\nbytecode; co_names is a tuple containing the names used by\nthe bytecode; co_filename is the filename from which the code\nwas compiled; co_firstlineno is the first line number of the\nfunction; co_lnotab is a string encoding the mapping from\nbyte code offsets to line numbers (for details see the source code of\nthe interpreter); co_stacksize is the required stack size\n(including local variables); co_flags is an integer encoding\na number of flags for the interpreter.\nThe co_cellvars and co_freevars are present in\nPython 2.1 when nested scopes are not enabled, but the code itself\ndoes not use or create cells.\nThe following flag bits are defined for co_flags: bit\n`0x04` is set if the function uses the \"*arguments\" syntax\nto accept an arbitrary number of positional arguments; bit\n`0x08` is set if the function uses the \"**keywords\" syntax\nto accept arbitrary keyword arguments; other bits are used internally\nor reserved for future use; bit `0x10` is set if the function was\ncompiled with nested scopes enabled. Ifa\ncode object represents a function, the first item in\nco_consts is the documentation string of the function, or\n`None` if undefined.\nFrame objects: Frame objects represent execution frames. They may occur in traceback\nobjects (see below).\nSpecial read-only attributes: f_back is to the previous\nstack frame (towards the caller), or `None` if this is the bottom\nstack frame; f_code is the code object being executed in this\nframe; f_locals is the dictionary used to look up local\nvariables; f_globals is used for global variables;\nf_builtins is used for built-in (intrinsic) names;\nf_restricted is a flag indicating whether the function is\nexecuting in restricted execution mode;\nf_lineno gives the line number and f_lasti gives the\nprecise instruction (this is an index into the bytecode string of\nthe code object).\nSpecial writable attributes: f_trace, if not `None`, is a\nfunction called at the start of each source code line (this is used by\nthe debugger); f_exc_type, f_exc_value,\nf_exc_traceback represent the most recent exception caught in\nthis frame.\nTraceback objects: Traceback objects represent a stack trace of an exception. A\ntraceback object is created when an exception occurs. When the search\nfor an exception handler unwinds the execution stack, at each unwound\nlevel a traceback object is inserted in front of the current\ntraceback. When an exception handler is entered, the stack trace is\nmade available to the program.\n(See section 7.4 (try.html#try), ``The `try` statement.'')\nIt is accessible as `sys.exc_traceback`, and also as the third\nitem of the tuple returned by `sys.exc_info()`. The latter is\nthe preferred interface, since it works correctly when the program is\nusing multiple threads.\nWhen the program contains no suitable handler, the stack trace is written\n(nicely formatted) to the standard error stream; if the interpreter is\ninteractive, it is also made available to the user as\n`sys.last_traceback`.\nSpecial read-only attributes: tb_next is the next level in the\nstack trace (towards the frame where the exception occurred), or\n`None` if there is no next level; tb_frame points to the\nexecution frame of the current level; tb_lineno gives the line\nnumber where the exception occurred; tb_lasti indicates the\nprecise instruction. The line number and last instruction in the\ntraceback may differ from the line number of its frame object if the\nexception occurred in a try statement with no matching\nexcept clause or with a finally clause.\nSlice objects: Slice objects are used to represent slices when extended slice\nsyntax is used. This is a slice using two colons, or multiple slices\nor ellipses separated by commas, e.g., `a[i:j:step]`, `a[i:j,\nk:l]`, or `a[..., i:j])`. They are also created by the built-in\nslice()function.\nSpecial read-only attributes: start is the lower bound;\nstop is the upper bound; step is the step value; each is\n`None` if omitted. These attributes can have any type.", "python_version": "2.2", "length": 24432, "url": "https://docs.python.org/2.2/ref/types.html"} {"title": "5.5 Unary arithmetic operations", "text": "power.html | expressions.html | binary.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.5 Unary arithmetic operations\nAll unary arithmetic (and bit-wise) operations have the same priority:\n`u_expr` | ::= | `power | \"-\" u_expr | \"+\" u_expr | \" \" u_expr`\nDownload entire grammar as text. (grammar.txt)\nThe unary `-` (minus) operator yields the negation of its\nnumeric argument.\nThe unary `+` (plus) operator yields its numeric argument\nunchanged.\nThe unary `~` (invert) operator yields the bit-wise inversion\nof its plain or long integer argument. The bit-wise inversion of\n`x` is defined as `-(x+1)`. It only applies to integral\nnumbers.\nIn all three cases, if the argument does not have the proper type,\na TypeError exception is raised.", "python_version": "2.2", "length": 758, "url": "https://docs.python.org/2.2/ref/unary.html"} {"title": "2.4.3 Unicode literals", "text": "string-catenation.html | literals.html | numbers.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.3 Unicode literals\nXXX explain more here...", "python_version": "2.2", "length": 166, "url": "https://docs.python.org/2.2/ref/unicode.html"} {"title": "7.2 The while statement", "text": "if.html | compound.html | for.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.2 The while statement\nThe while statement is used for repeated execution as long\nas an expression is true:\n`while_stmt` | ::= | `\"while\" expression \":\" suite [\"else\" \":\" suite ]`\nDownload entire grammar as text. (grammar.txt)\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time it\nis tested) the suite of the else clause, if present, is\nexecuted and the loop terminates.\nA break statement executed in the first suite terminates the\nloop without executing the else clause's suite. A\ncontinue statement executed in the first suite skips the rest\nof the suite and goes back to testing the expression.", "python_version": "2.2", "length": 785, "url": "https://docs.python.org/2.2/ref/while.html"} {"title": "2.1.8 Whitespace between tokens", "text": "indentation.html | line-structure.html | other-tokens.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.8 Whitespace between tokens\nExcept at the beginning of a logical line or in string literals, the\nwhitespace characters space, tab and formfeed can be used\ninterchangeably to separate tokens. Whitespace is needed between two\ntokens only if their concatenation could otherwise be interpreted as a\ndifferent token (e.g., ab is one token, but a b is two tokens).", "python_version": "2.2", "length": 486, "url": "https://docs.python.org/2.2/ref/whitespace.html"} {"title": "6.8 The yield statement", "text": "return.html | simple.html | raise.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.8 The yield statement\n`yield_stmt` | ::= | `\"yield\" expression_list`\nDownload entire grammar as text. (grammar.txt)\nThe yield statement is only used when defining a generator\nfunction, and is only used in the body of the generator function.\nUsing a yield statement in a function definition is\nsufficient to cause that definition to create a generator function\ninstead of a normal function.\nWhen a generator function is called, it returns an iterator known as a\ngenerator iterator, or more commonly, a generator. The body of the\ngenerator function is executed by calling the generator's\nnext() method repeatedly until it raises an exception.\nWhen a yield statement is executed, the state of the\ngenerator is frozen and the value of expression_list (exprlists.html#tok-expression_list) is\nreturned to next()'s caller. By ``frozen'' we mean that all\nlocal state is retained, including the current bindings of local\nvariables, the instruction pointer, and the internal evaluation stack:\nenough information is saved so that the next time next() is\ninvoked, the function can proceed exactly as if the yield\nstatement were just another external call.\nThe yield statement is not allowed in the try\nclause of a try ... finally construct. The\ndifficulty is that there's no guarantee the generator will ever be\nresumed, hence no guarantee that the finally block will ever\nget executed.\nNote:\nIn Python 2.2, the yield statement is only allowed\nwhen the `generators` feature has been enabled. It will always\nbe enabled in Python 2.3. This `__future__` import statment can\nbe used to enable the feature:\n```text\n\nfrom __future__ import generators\n```\nSee Also:", "python_version": "2.2", "length": 1751, "url": "https://docs.python.org/2.2/ref/yield.html"} {"title": "About this document ...", "text": "node15.html | tut.html | Python Tutorial | node2.html\n---\n# About this document ...\nPython Tutorial,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nnode15.html | tut.html | Python Tutorial | node2.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1639, "url": "https://docs.python.org/2.2/tut/about.html"} {"title": "Python Tutorial", "text": "../index.html | node1.html | Python Tutorial | node2.html\n---\n# Python Tutorial\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 194, "url": "https://docs.python.org/2.2/tut/index.html"} {"title": "Front Matter", "text": "tut.html | tut.html | node2.html | Python Tutorial | node2.html\n---\n# Front Matter\nCopyright © 2001 Python Software Foundation.\nAll rights reserved.\nCopyright © 2000 BeOpen.com.\nAll rights reserved.\nCopyright © 1995-2000 Corporation for National Research Initiatives.\nAll rights reserved.\nCopyright © 1991-1995 Stichting Mathematisch Centrum.\nAll rights reserved.\nSee the end of this document for complete license and permissions\ninformation.\n### Abstract:\nPython is an easy to learn, powerful programming language. It has\nefficient high-level data structures and a simple but effective\napproach to object-oriented programming. Python's elegant syntax and\ndynamic typing, together with its interpreted nature, make it an ideal\nlanguage for scripting and rapid application development in many areas\non most platforms.\nThe Python interpreter and the extensive standard library are freely\navailable in source or binary form for all major platforms from the\nPython Web site, http://www.python.org/, and can be freely\ndistributed. The same site also contains distributions of and\npointers to many free third party Python modules, programs and tools,\nand additional documentation.\nThe Python interpreter is easily extended with new functions and data\ntypes implemented in C or C++ (or other languages callable from C).\nPython is also suitable as an extension language for customizable\napplications.\nThis tutorial introduces the reader informally to the basic concepts\nand features of the Python language and system. It helps to have a\nPython interpreter handy for hands-on experience, but all examples are\nself-contained, so the tutorial can be read off-line as well.\nFor a description of standard objects and modules, see the\nPython Library Reference (../lib/lib.html) document. The\nPython Reference Manual (../ref/ref.html) gives a more\nformal definition of the language. To write extensions in C or\nC++, read Extending and Embedding the\nPython Interpreter (../ext/ext.html) and Python/C API\nReference (../api/api.html). There are also several books covering Python in depth.\nThis tutorial does not attempt to be comprehensive and cover every\nsingle feature, or even every commonly used feature. Instead, it\nintroduces many of Python's most noteworthy features, and will give\nyou a good idea of the language's flavor and style. After reading it,\nyou will be able to read and write Python modules and programs, and\nyou will be ready to learn more about the various Python library\nmodules described in the Python Library\nReference (../lib/lib.html).", "python_version": "2.2", "length": 2543, "url": "https://docs.python.org/2.2/tut/node1.html"} {"title": "8. Errors and Exceptions", "text": "node9.html | tut.html | node11.html | Python Tutorial | node2.html\n---\n- 8.1 Syntax Errors (#SECTION0010100000000000000000)\n 8.2 Exceptions (#SECTION0010200000000000000000)\n 8.3 Handling Exceptions (#SECTION0010300000000000000000)\n 8.4 Raising Exceptions (#SECTION0010400000000000000000)\n 8.5 User-defined Exceptions (#SECTION0010500000000000000000)\n 8.6 Defining Clean-up Actions (#SECTION0010600000000000000000)\n---\n# 8. Errors and Exceptions\nUntil now error messages haven't been more than mentioned, but if you\nhave tried out the examples you have probably seen some. There are\n(at least) two distinguishable kinds of errors:\nsyntax errors and exceptions.\n# 8.1 Syntax Errors\nSyntax errors, also known as parsing errors, are perhaps the most common\nkind of complaint you get while you are still learning Python:\n```text\n\n>>> while 1 print 'Hello world'\nFile \"\", line 1, in ?\nwhile 1 print 'Hello world'\n^\nSyntaxError: invalid syntax\n```\nThe parser repeats the offending line and displays a little `arrow'\npointing at the earliest point in the line where the error was\ndetected. The error is caused by (or at least detected at) the token\npreceding the arrow: in the example, the error is detected at\nthe keyword print, since a colon (\":\") is missing\nbefore it. File name and line number are printed so you know where to\nlook in case the input came from a script.\n# 8.2 Exceptions\nEven if a statement or expression is syntactically correct, it may\ncause an error when an attempt is made to execute it.\nErrors detected during execution are called exceptions and are\nnot unconditionally fatal: you will soon learn how to handle them in\nPython programs. Most exceptions are not handled by programs,\nhowever, and result in error messages as shown here:\n```text\n\n>>> 10 * (1/0)\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nZeroDivisionError: integer division or modulo\n>>> 4 + spam*3\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nNameError: spam\n>>> '2' + 2\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: illegal argument type for built-in operation\n```\nThe last line of the error message indicates what happened.\nExceptions come in different types, and the type is printed as part of\nthe message: the types in the example are\nZeroDivisionError, NameError and\nTypeError.\nThe string printed as the exception type is the name of the built-in\nname for the exception that occurred. This is true for all built-in\nexceptions, but need not be true for user-defined exceptions (although\nit is a useful convention).\nStandard exception names are built-in identifiers (not reserved\nkeywords).\nThe rest of the line is a detail whose interpretation depends on the\nexception type; its meaning is dependent on the exception type.\nThe preceding part of the error message shows the context where the\nexception happened, in the form of a stack backtrace.\nIn general it contains a stack backtrace listing source lines; however,\nit will not display lines read from standard input.\nThe Python Library\nReference (../lib/module-exceptions.html) lists the built-in exceptions and their meanings.\n# 8.3 Handling Exceptions\nIt is possible to write programs that handle selected exceptions.\nLook at the following example, which asks the user for input until a\nvalid integer has been entered, but allows the user to interrupt the\nprogram (using Control-C or whatever the operating system\nsupports); note that a user-generated interruption is signalled by\nraising the KeyboardInterrupt exception.\n```text\n\n>>> while 1:\n... try:\n... x = int(raw_input(\"Please enter a number: \"))\n... break\n... except ValueError:\n... print \"Oops! That was no valid number. Try again...\"\n...\n```\nThe try statement works as follows.\n- First, the try clause (the statement(s) between the\ntry and except keywords) is executed.\n- If no exception occurs, the except clause is skipped and\nexecution of the try statement is finished.\n- If an exception occurs during execution of the try clause, the rest of\nthe clause is skipped. Then if its type matches the exception named\nafter the except keyword, the rest of the try clause is\nskipped, the except clause is executed, and then execution continues\nafter the try statement.\n- If an exception occurs which does not match the exception named in the\nexcept clause, it is passed on to outer try statements; if\nno handler is found, it is an unhandled exception and execution\nstops with a message as shown above.\nA try statement may have more than one except clause, to\nspecify handlers for different exceptions. At most one handler will\nbe executed. Handlers only handle exceptions that occur in the\ncorresponding try clause, not in other handlers of the same\ntry statement. An except clause may name multiple exceptions\nas a parenthesized list, for example:\n```text\n\n... except (RuntimeError, TypeError, NameError):\n... pass\n```\nThe last except clause may omit the exception name(s), to serve as a\nwildcard. Use this with extreme caution, since it is easy to mask a\nreal programming error in this way! It can also be used to print an\nerror message and then re-raise the exception (allowing a caller to\nhandle the exception as well):\n```text\n\nimport string, sys\n\ntry:\nf = open('myfile.txt')\ns = f.readline()\ni = int(string.strip(s))\nexcept IOError, (errno, strerror):\nprint \"I/O error(%s): %s\" % (errno, strerror)\nexcept ValueError:\nprint \"Could not convert data to an integer.\"\nexcept:\nprint \"Unexpected error:\", sys.exc_info()[0]\nraise\n```\nThe try ... except statement has an optional\nelse clause, which, when present, must follow all except\nclauses. It is useful for code that must be executed if the try\nclause does not raise an exception. For example:\n```text\n\nfor arg in sys.argv[1:]:\ntry:\nf = open(arg, 'r')\nexcept IOError:\nprint 'cannot open', arg\nelse:\nprint arg, 'has', len(f.readlines()), 'lines'\nf.close()\n```\nThe use of the else clause is better than adding additional\ncode to the try clause because it avoids accidentally\ncatching an exception that wasn't raised by the code being protected\nby the try ... except statement.\nWhen an exception occurs, it may have an associated value, also known as\nthe exception's argument.\nThe presence and type of the argument depend on the exception type.\nFor exception types which have an argument, the except clause may\nspecify a variable after the exception name (or list) to receive the\nargument's value, as follows:\n```text\n\n>>> try:\n... spam()\n... except NameError, x:\n... print 'name', x, 'undefined'\n...\nname spam undefined\n```\nIf an exception has an argument, it is printed as the last part\n(`detail') of the message for unhandled exceptions.\nException handlers don't just handle exceptions if they occur\nimmediately in the try clause, but also if they occur inside functions\nthat are called (even indirectly) in the try clause.\nFor example:\n```text\n\n>>> def this_fails():\n... x = 1/0\n...\n>>> try:\n... this_fails()\n... except ZeroDivisionError, detail:\n... print 'Handling run-time error:', detail\n...\nHandling run-time error: integer division or modulo\n```\n# 8.4 Raising Exceptions\nThe raise statement allows the programmer to force a\nspecified exception to occur.\nFor example:\n```text\n\n>>> raise NameError, 'HiThere'\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nNameError: HiThere\n```\nThe first argument to raise names the exception to be\nraised. The optional second argument specifies the exception's\nargument.\nIf you need to determine whether an exception was raised but don't\nintend to handle it, a simpler form of the raise statement\nallows you to re-raise the exception:\n```text\n\n>>> try:\n... raise NameError, 'HiThere'\n... except NameError:\n... print 'An exception flew by!'\n... raise\n...\nAn exception flew by!\nTraceback (most recent call last):\nFile \"\", line 2, in ?\nNameError: HiThere\n```\n# 8.5 User-defined Exceptions\nPrograms may name their own exceptions by creating a new exception\nclass. Exceptions should typically be derived from the\nException class, either directly or indirectly. For\nexample:\n```text\n\n>>> class MyError(Exception):\n... def __init__(self, value):\n... self.value = value\n... def __str__(self):\n... return `self.value`\n...\n>>> try:\n... raise MyError(2*2)\n... except MyError, e:\n... print 'My exception occurred, value:', e.value\n...\nMy exception occurred, value: 4\n>>> raise MyError, 'oops!'\nTraceback (most recent call last):\nFile \"\", line 1, in ?\n__main__.MyError: 'oops!'\n```\nException classes can be defined which do anything any other class can\ndo, but are usually kept simple, often only offering a number of\nattributes that allow information about the error to be extracted by\nhandlers for the exception. When creating a module which can raise\nseveral distinct errors, a common practice is to create a base class\nfor exceptions defined by that module, and subclass that to create\nspecific exception classes for different error conditions:\n```text\n\nclass Error(Exception):\n\"\"\"Base class for exceptions in this module.\"\"\"\npass\n\nclass InputError(Error):\n\"\"\"Exception raised for errors in the input.\n\nAttributes:\nexpression -- input expression in which the error occurred\nmessage -- explanation of the error\n\"\"\"\n\ndef __init__(self, expression, message):\nself.expression = expression\nself.message = message\n\nclass TransitionError(Error):\n\"\"\"Raised when an operation attempts a state transition that's not\nallowed.\n\nAttributes:\nprevious -- state at beginning of transition\nnext -- attempted new state\nmessage -- explanation of why the specific transition is not allowed\n\"\"\"\n\ndef __init__(self, previous, next, message):\nself.previous = previous\nself.next = next\nself.message = message\n```\nMost exceptions are defined with names that end in ``Error,'' similar\nto the naming of the standard exceptions.\nMany standard modules define their own exceptions to report errors\nthat may occur in functions they define. More information on classes\nis presented in chapter 9 (node11.html#classes), ``Classes.''\n# 8.6 Defining Clean-up Actions\nThe try statement has another optional clause which is\nintended to define clean-up actions that must be executed under all\ncircumstances. For example:\n```text\n\n>>> try:\n... raise KeyboardInterrupt\n... finally:\n... print 'Goodbye, world!'\n...\nGoodbye, world!\nTraceback (most recent call last):\nFile \"\", line 2, in ?\nKeyboardInterrupt\n```\nA finally clause is executed whether or not an exception has\noccurred in the try clause. When an exception has occurred, it is\nre-raised after the finally clause is executed. The finally clause is\nalso executed ``on the way out'' when the try statement is\nleft via a break or return statement.\nThe code in the finally clause is useful for releasing external\nresources (such as files or network connections), regardless of\nwhether or not the use of the resource was successful.\nA try statement must either have one or more except clauses\nor one finally clause, but not both.", "python_version": "2.2", "length": 10937, "url": "https://docs.python.org/2.2/tut/node10.html"} {"title": "9. Classes", "text": "node10.html | tut.html | node12.html | Python Tutorial | node2.html\n---\n- 9.1 A Word About Terminology (#SECTION0011100000000000000000)\n 9.2 Python Scopes and Name Spaces (#SECTION0011200000000000000000)\n 9.3 A First Look at Classes (#SECTION0011300000000000000000)\n - 9.3.1 Class Definition Syntax (#SECTION0011310000000000000000)\n 9.3.2 Class Objects (#SECTION0011320000000000000000)\n 9.3.3 Instance Objects (#SECTION0011330000000000000000)\n 9.3.4 Method Objects (#SECTION0011340000000000000000)\n 9.4 Random Remarks (#SECTION0011400000000000000000)\n 9.5 Inheritance (#SECTION0011500000000000000000)\n - 9.5.1 Multiple Inheritance (#SECTION0011510000000000000000)\n 9.6 Private Variables (#SECTION0011600000000000000000)\n 9.7 Odds and Ends (#SECTION0011700000000000000000)\n - 9.7.1 Exceptions Can Be Classes (#SECTION0011710000000000000000)\n---\n# 9. Classes\nPython's class mechanism adds classes to the language with a minimum\nof new syntax and semantics. It is a mixture of the class mechanisms\nfound in C++ and Modula-3. As is true for modules, classes in Python\ndo not put an absolute barrier between definition and user, but rather\nrely on the politeness of the user not to ``break into the\ndefinition.'' The most important features of classes are retained\nwith full power, however: the class inheritance mechanism allows\nmultiple base classes, a derived class can override any methods of its\nbase class or classes, a method can call the method of a base class with the\nsame name. Objects can contain an arbitrary amount of private data.\nIn C++ terminology, all class members (including the data members) are\npublic, and all member functions are virtual. There are\nno special constructors or destructors. As in Modula-3, there are no\nshorthands for referencing the object's members from its methods: the\nmethod function is declared with an explicit first argument\nrepresenting the object, which is provided implicitly by the call. As\nin Smalltalk, classes themselves are objects, albeit in the wider\nsense of the word: in Python, all data types are objects. This\nprovides semantics for importing and renaming. But, just like in\nC++ or Modula-3, built-in types cannot be used as base classes for\nextension by the user. Also, like in C++ but unlike in Modula-3, most\nbuilt-in operators with special syntax (arithmetic operators,\nsubscripting etc.) can be redefined for class instances.\n# 9.1 A Word About Terminology\nLacking universally accepted terminology to talk about classes, I will\nmake occasional use of Smalltalk and C++ terms. (I would use Modula-3\nterms, since its object-oriented semantics are closer to those of\nPython than C++, but I expect that few readers have heard of it.)\nI also have to warn you that there's a terminological pitfall for\nobject-oriented readers: the word ``object'' in Python does not\nnecessarily mean a class instance. Like C++ and Modula-3, and\nunlike Smalltalk, not all types in Python are classes: the basic\nbuilt-in types like integers and lists are not, and even somewhat more\nexotic types like files aren't. However, all Python types\nshare a little bit of common semantics that is best described by using\nthe word object.\nObjects have individuality, and multiple names (in multiple scopes)\ncan be bound to the same object. This is known as aliasing in other\nlanguages. This is usually not appreciated on a first glance at\nPython, and can be safely ignored when dealing with immutable basic\ntypes (numbers, strings, tuples). However, aliasing has an\n(intended!) effect on the semantics of Python code involving mutable\nobjects such as lists, dictionaries, and most types representing\nentities outside the program (files, windows, etc.). This is usually\nused to the benefit of the program, since aliases behave like pointers\nin some respects. For example, passing an object is cheap since only\na pointer is passed by the implementation; and if a function modifies\nan object passed as an argument, the caller will see the change -- this\nobviates the need for two different argument passing mechanisms as in\nPascal.\n# 9.2 Python Scopes and Name Spaces\nBefore introducing classes, I first have to tell you something about\nPython's scope rules. Class definitions play some neat tricks with\nnamespaces, and you need to know how scopes and namespaces work to\nfully understand what's going on. Incidentally, knowledge about this\nsubject is useful for any advanced Python programmer.\nLet's begin with some definitions.\nA namespace is a mapping from names to objects. Most\nnamespaces are currently implemented as Python dictionaries, but\nthat's normally not noticeable in any way (except for performance),\nand it may change in the future. Examples of namespaces are: the set\nof built-in names (functions such as abs(), and built-in\nexception names); the global names in a module; and the local names in\na function invocation. In a sense the set of attributes of an object\nalso form a namespace. The important thing to know about namespaces\nis that there is absolutely no relation between names in different\nnamespaces; for instance, two different modules may both define a\nfunction ``maximize'' without confusion -- users of the modules must\nprefix it with the module name.\nBy the way, I use the word attribute for any name following a\ndot -- for example, in the expression `z.real`, `real` is\nan attribute of the object `z`. Strictly speaking, references to\nnames in modules are attribute references: in the expression\n`modname.funcname`, `modname` is a module object and\n`funcname` is an attribute of it. In this case there happens to\nbe a straightforward mapping between the module's attributes and the\nglobal names defined in the module: they share the same namespace!\n9.1 (#foot1407)\nAttributes may be read-only or writable. In the latter case,\nassignment to attributes is possible. Module attributes are writable:\nyou can write \"modname.the_answer = 42\". Writable attributes may\nalso be deleted with the del statement. For example,\n\"del modname.the_answer\" will remove the attribute\nthe_answer from the object named by `modname`.\nName spaces are created at different moments and have different\nlifetimes. The namespace containing the built-in names is created\nwhen the Python interpreter starts up, and is never deleted. The\nglobal namespace for a module is created when the module definition\nis read in; normally, module namespaces also last until the\ninterpreter quits. The statements executed by the top-level\ninvocation of the interpreter, either read from a script file or\ninteractively, are considered part of a module called\n__main__, so they have their own global namespace. (The\nbuilt-in names actually also live in a module; this is called\n__builtin__.)\nThe local namespace for a function is created when the function is\ncalled, and deleted when the function returns or raises an exception\nthat is not handled within the function. (Actually, forgetting would\nbe a better way to describe what actually happens.) Of course,\nrecursive invocations each have their own local namespace.\nA scope is a textual region of a Python program where a\nnamespace is directly accessible. ``Directly accessible'' here means\nthat an unqualified reference to a name attempts to find the name in\nthe namespace.\nAlthough scopes are determined statically, they are used dynamically.\nAt any time during execution, exactly three nested scopes are in use\n(exactly three namespaces are directly accessible): the\ninnermost scope, which is searched first, contains the local names,\nthe middle scope, searched next, contains the current module's global\nnames, and the outermost scope (searched last) is the namespace\ncontaining built-in names.\nUsually, the local scope references the local names of the (textually)\ncurrent function. Outside of functions, the local scope references\nthe same namespace as the global scope: the module's namespace.\nClass definitions place yet another namespace in the local scope.\nIt is important to realize that scopes are determined textually: the\nglobal scope of a function defined in a module is that module's\nnamespace, no matter from where or by what alias the function is\ncalled. On the other hand, the actual search for names is done\ndynamically, at run time -- however, the language definition is\nevolving towards static name resolution, at ``compile'' time, so don't\nrely on dynamic name resolution! (In fact, local variables are\nalready determined statically.)\nA special quirk of Python is that assignments always go into the\ninnermost scope. Assignments do not copy data -- they just\nbind names to objects. The same is true for deletions: the statement\n\"del x\" removes the binding of `x` from the namespace\nreferenced by the local scope. In fact, all operations that introduce\nnew names use the local scope: in particular, import statements and\nfunction definitions bind the module or function name in the local\nscope. (The global statement can be used to indicate that\nparticular variables live in the global scope.)\n# 9.3 A First Look at Classes\nClasses introduce a little bit of new syntax, three new object types,\nand some new semantics.\n## 9.3.1 Class Definition Syntax\nThe simplest form of class definition looks like this:\n```text\n\nclass ClassName:\n\n.\n.\n.\n\n```\nClass definitions, like function definitions\n(def statements) must be executed before they have any\neffect. (You could conceivably place a class definition in a branch\nof an if statement, or inside a function.)\nIn practice, the statements inside a class definition will usually be\nfunction definitions, but other statements are allowed, and sometimes\nuseful -- we'll come back to this later. The function definitions\ninside a class normally have a peculiar form of argument list,\ndictated by the calling conventions for methods -- again, this is\nexplained later.\nWhen a class definition is entered, a new namespace is created, and\nused as the local scope -- thus, all assignments to local variables\ngo into this new namespace. In particular, function definitions bind\nthe name of the new function here.\nWhen a class definition is left normally (via the end), a class\nobject is created. This is basically a wrapper around the contents\nof the namespace created by the class definition; we'll learn more\nabout class objects in the next section. The original local scope\n(the one in effect just before the class definitions was entered) is\nreinstated, and the class object is bound here to the class name given\nin the class definition header (ClassName in the example).\n## 9.3.2 Class Objects\nClass objects support two kinds of operations: attribute references\nand instantiation.\nAttribute references use the standard syntax used for all\nattribute references in Python: `obj.name`. Valid attribute\nnames are all the names that were in the class's namespace when the\nclass object was created. So, if the class definition looked like\nthis:\n```text\n\nclass MyClass:\n\"A simple example class\"\ni = 12345\ndef f(self):\nreturn 'hello world'\n```\nthen `MyClass.i` and `MyClass.f` are valid attribute\nreferences, returning an integer and a method object, respectively.\nClass attributes can also be assigned to, so you can change the value\nof `MyClass.i` by assignment. __doc__ is also a valid\nattribute, returning the docstring belonging to the class: `\"A\nsimple example class\"`).\nClass instantiation uses function notation. Just pretend that\nthe class object is a parameterless function that returns a new\ninstance of the class. For example (assuming the above class):\n```text\n\nx = MyClass()\n```\ncreates a new instance of the class and assigns this object to\nthe local variable `x`.\nThe instantiation operation (``calling'' a class object) creates an\nempty object. Many classes like to create objects in a known initial\nstate. Therefore a class may define a special method named\n__init__(), like this:\n```text\n\ndef __init__(self):\nself.data = []\n```\nWhen a class defines an __init__() method, class\ninstantiation automatically invokes __init__() for the\nnewly-created class instance. So in this example, a new, initialized\ninstance can be obtained by:\n```text\n\nx = MyClass()\n```\nOf course, the __init__() method may have arguments for\ngreater flexibility. In that case, arguments given to the class\ninstantiation operator are passed on to __init__(). For\nexample,\n```text\n\n>>> class Complex:\n... def __init__(self, realpart, imagpart):\n... self.r = realpart\n... self.i = imagpart\n...\n>>> x = Complex(3.0, -4.5)\n>>> x.r, x.i\n(3.0, -4.5)\n```\n## 9.3.3 Instance Objects\nNow what can we do with instance objects? The only operations\nunderstood by instance objects are attribute references. There are\ntwo kinds of valid attribute names.\nThe first I'll call data attributes. These correspond to\n``instance variables'' in Smalltalk, and to ``data members'' in\nC++. Data attributes need not be declared; like local variables,\nthey spring into existence when they are first assigned to. For\nexample, if `x` is the instance of MyClass created above,\nthe following piece of code will print the value `16`, without\nleaving a trace:\n```text\n\nx.counter = 1\nwhile x.counter < 10:\nx.counter = x.counter * 2\nprint x.counter\ndel x.counter\n```\nThe second kind of attribute references understood by instance objects\nare methods. A method is a function that ``belongs to'' an\nobject. (In Python, the term method is not unique to class instances:\nother object types can have methods as well. For example, list objects have\nmethods called append, insert, remove, sort, and so on. However,\nbelow, we'll use the term method exclusively to mean methods of class\ninstance objects, unless explicitly stated otherwise.)\nValid method names of an instance object depend on its class. By\ndefinition, all attributes of a class that are (user-defined) function\nobjects define corresponding methods of its instances. So in our\nexample, `x.f` is a valid method reference, since\n`MyClass.f` is a function, but `x.i` is not, since\n`MyClass.i` is not. But `x.f` is not the same thing as\n`MyClass.f` -- it is a method object, not\na function object.\n## 9.3.4 Method Objects\nUsually, a method is called immediately:\n```text\n\nx.f()\n```\nIn our example, this will return the string `'hello world'`.\nHowever, it is not necessary to call a method right away:\n`x.f` is a method object, and can be stored away and called at a\nlater time. For example:\n```text\n\nxf = x.f\nwhile 1:\nprint xf()\n```\nwill continue to print \"hello world\" until the end of time.\nWhat exactly happens when a method is called? You may have noticed\nthat `x.f()` was called without an argument above, even though\nthe function definition for f specified an argument. What\nhappened to the argument? Surely Python raises an exception when a\nfunction that requires an argument is called without any -- even if\nthe argument isn't actually used...\nActually, you may have guessed the answer: the special thing about\nmethods is that the object is passed as the first argument of the\nfunction. In our example, the call `x.f()` is exactly equivalent\nto `MyClass.f(x)`. In general, calling a method with a list of\nn arguments is equivalent to calling the corresponding function\nwith an argument list that is created by inserting the method's object\nbefore the first argument.\nIf you still don't understand how methods work, a look at the\nimplementation can perhaps clarify matters. When an instance\nattribute is referenced that isn't a data attribute, its class is\nsearched. If the name denotes a valid class attribute that is a\nfunction object, a method object is created by packing (pointers to)\nthe instance object and the function object just found together in an\nabstract object: this is the method object. When the method object is\ncalled with an argument list, it is unpacked again, a new argument\nlist is constructed from the instance object and the original argument\nlist, and the function object is called with this new argument list.\n# 9.4 Random Remarks\n[These should perhaps be placed more carefully...]\nData attributes override method attributes with the same name; to\navoid accidental name conflicts, which may cause hard-to-find bugs in\nlarge programs, it is wise to use some kind of convention that\nminimizes the chance of conflicts. Possible conventions include\ncapitalizing method names, prefixing data attribute names with a small\nunique string (perhaps just an underscore), or using verbs for methods\nand nouns for data attributes.\nData attributes may be referenced by methods as well as by ordinary\nusers (``clients'') of an object. In other words, classes are not\nusable to implement pure abstract data types. In fact, nothing in\nPython makes it possible to enforce data hiding -- it is all based\nupon convention. (On the other hand, the Python implementation,\nwritten in C, can completely hide implementation details and control\naccess to an object if necessary; this can be used by extensions to\nPython written in C.)\nClients should use data attributes with care -- clients may mess up\ninvariants maintained by the methods by stamping on their data\nattributes. Note that clients may add data attributes of their own to\nan instance object without affecting the validity of the methods, as\nlong as name conflicts are avoided -- again, a naming convention can\nsave a lot of headaches here.\nThere is no shorthand for referencing data attributes (or other\nmethods!) from within methods. I find that this actually increases\nthe readability of methods: there is no chance of confusing local\nvariables and instance variables when glancing through a method.\nConventionally, the first argument of methods is often called\n`self`. This is nothing more than a convention: the name\n`self` has absolutely no special meaning to Python. (Note,\nhowever, that by not following the convention your code may be less\nreadable by other Python programmers, and it is also conceivable that\na class browser program be written which relies upon such a\nconvention.)\nAny function object that is a class attribute defines a method for\ninstances of that class. It is not necessary that the function\ndefinition is textually enclosed in the class definition: assigning a\nfunction object to a local variable in the class is also ok. For\nexample:\n```text\n\n# Function defined outside the class\ndef f1(self, x, y):\nreturn min(x, x+y)\n\nclass C:\nf = f1\ndef g(self):\nreturn 'hello world'\nh = g\n```\nNow `f`, `g` and `h` are all attributes of class\nC that refer to function objects, and consequently they are all\nmethods of instances of C -- `h` being exactly equivalent\nto `g`. Note that this practice usually only serves to confuse\nthe reader of a program.\nMethods may call other methods by using method attributes of the\n`self` argument:\n```text\n\nclass Bag:\ndef __init__(self):\nself.data = []\ndef add(self, x):\nself.data.append(x)\ndef addtwice(self, x):\nself.add(x)\nself.add(x)\n```\nMethods may reference global names in the same way as ordinary\nfunctions. The global scope associated with a method is the module\ncontaining the class definition. (The class itself is never used as a\nglobal scope!) While one rarely encounters a good reason for using\nglobal data in a method, there are many legitimate uses of the global\nscope: for one thing, functions and modules imported into the global\nscope can be used by methods, as well as functions and classes defined\nin it. Usually, the class containing the method is itself defined in\nthis global scope, and in the next section we'll find some good\nreasons why a method would want to reference its own class!\n# 9.5 Inheritance\nOf course, a language feature would not be worthy of the name ``class''\nwithout supporting inheritance. The syntax for a derived class\ndefinition looks as follows:\n```text\n\nclass DerivedClassName(BaseClassName):\n\n.\n.\n.\n\n```\nThe name BaseClassName must be defined in a scope containing\nthe derived class definition. Instead of a base class name, an\nexpression is also allowed. This is useful when the base class is\ndefined in another module,\n```text\n\nclass DerivedClassName(modname.BaseClassName):\n```\nExecution of a derived class definition proceeds the same as for a\nbase class. When the class object is constructed, the base class is\nremembered. This is used for resolving attribute references: if a\nrequested attribute is not found in the class, it is searched in the\nbase class. This rule is applied recursively if the base class itself\nis derived from some other class.\nThere's nothing special about instantiation of derived classes:\n`DerivedClassName()` creates a new instance of the class. Method\nreferences are resolved as follows: the corresponding class attribute\nis searched, descending down the chain of base classes if necessary,\nand the method reference is valid if this yields a function object.\nDerived classes may override methods of their base classes. Because\nmethods have no special privileges when calling other methods of the\nsame object, a method of a base class that calls another method\ndefined in the same base class, may in fact end up calling a method of\na derived class that overrides it. (For C++ programmers: all methods\nin Python are effectively virtual.)\nAn overriding method in a derived class may in fact want to extend\nrather than simply replace the base class method of the same name.\nThere is a simple way to call the base class method directly: just\ncall \"BaseClassName.methodname(self, arguments)\". This is\noccasionally useful to clients as well. (Note that this only works if\nthe base class is defined or imported directly in the global scope.)\n## 9.5.1 Multiple Inheritance\nPython supports a limited form of multiple inheritance as well. A\nclass definition with multiple base classes looks as follows:\n```text\n\nclass DerivedClassName(Base1, Base2, Base3):\n\n.\n.\n.\n\n```\nThe only rule necessary to explain the semantics is the resolution\nrule used for class attribute references. This is depth-first,\nleft-to-right. Thus, if an attribute is not found in\nDerivedClassName, it is searched in Base1, then\n(recursively) in the base classes of Base1, and only if it is\nnot found there, it is searched in Base2, and so on.\n(To some people breadth first -- searching Base2 and\nBase3 before the base classes of Base1 -- looks more\nnatural. However, this would require you to know whether a particular\nattribute of Base1 is actually defined in Base1 or in\none of its base classes before you can figure out the consequences of\na name conflict with an attribute of Base2. The depth-first\nrule makes no differences between direct and inherited attributes of\nBase1.)\nIt is clear that indiscriminate use of multiple inheritance is a\nmaintenance nightmare, given the reliance in Python on conventions to\navoid accidental name conflicts. A well-known problem with multiple\ninheritance is a class derived from two classes that happen to have a\ncommon base class. While it is easy enough to figure out what happens\nin this case (the instance will have a single copy of ``instance\nvariables'' or data attributes used by the common base class), it is\nnot clear that these semantics are in any way useful.\n# 9.6 Private Variables\nThere is limited support for class-private\nidentifiers. Any identifier of the form `__spam` (at least two\nleading underscores, at most one trailing underscore) is now textually\nreplaced with `_classname__spam`, where `classname` is the\ncurrent class name with leading underscore(s) stripped. This mangling\nis done without regard of the syntactic position of the identifier, so\nit can be used to define class-private instance and class variables,\nmethods, as well as globals, and even to store instance variables\nprivate to this class on instances of other classes. Truncation\nmay occur when the mangled name would be longer than 255 characters.\nOutside classes, or when the class name consists of only underscores,\nno mangling occurs.\nName mangling is intended to give classes an easy way to define\n``private'' instance variables and methods, without having to worry\nabout instance variables defined by derived classes, or mucking with\ninstance variables by code outside the class. Note that the mangling\nrules are designed mostly to avoid accidents; it still is possible for\na determined soul to access or modify a variable that is considered\nprivate. This can even be useful in special circumstances, such as in\nthe debugger, and that's one reason why this loophole is not closed.\n(Buglet: derivation of a class with the same name as the base class\nmakes use of private variables of the base class possible.)\nNotice that code passed to `exec`, `eval()` or\n`evalfile()` does not consider the classname of the invoking\nclass to be the current class; this is similar to the effect of the\n`global` statement, the effect of which is likewise restricted to\ncode that is byte-compiled together. The same restriction applies to\n`getattr()`, `setattr()` and `delattr()`, as well as\nwhen referencing `__dict__` directly.\nHere's an example of a class that implements its own\n__getattr__() and __setattr__() methods and stores\nall attributes in a private variable, in a way that works in all\nversions of Python, including those available before this feature was\nadded:\n```text\n\nclass VirtualAttributes:\n__vdict = None\n__vdict_name = locals().keys()[0]\n\ndef __init__(self):\nself.__dict__[self.__vdict_name] = {}\n\ndef __getattr__(self, name):\nreturn self.__vdict[name]\n\ndef __setattr__(self, name, value):\nself.__vdict[name] = value\n```\n# 9.7 Odds and Ends\nSometimes it is useful to have a data type similar to the Pascal\n``record'' or C ``struct'', bundling together a couple of named data\nitems. An empty class definition will do nicely:\n```text\n\nclass Employee:\npass\n\njohn = Employee() # Create an empty employee record\n\n# Fill the fields of the record\njohn.name = 'John Doe'\njohn.dept = 'computer lab'\njohn.salary = 1000\n```\nA piece of Python code that expects a particular abstract data type\ncan often be passed a class that emulates the methods of that data\ntype instead. For instance, if you have a function that formats some\ndata from a file object, you can define a class with methods\nread() and readline() that gets the data from a string\nbuffer instead, and pass it as an argument.\nInstance method objects have attributes, too: `m.im_self` is the\nobject of which the method is an instance, and `m.im_func` is the\nfunction object corresponding to the method.\n## 9.7.1 Exceptions Can Be Classes\nUser-defined exceptions are no longer limited to being string objects\n-- they can be identified by classes as well. Using this mechanism it\nis possible to create extensible hierarchies of exceptions.\nThere are two new valid (semantic) forms for the raise statement:\n```text\n\nraise Class, instance\n\nraise instance\n```\nIn the first form, `instance` must be an instance of\nClass or of a class derived from it. The second form is a\nshorthand for:\n```text\n\nraise instance.__class__, instance\n```\nAn except clause may list classes as well as string objects. A class\nin an except clause is compatible with an exception if it is the same\nclass or a base class thereof (but not the other way around -- an\nexcept clause listing a derived class is not compatible with a base\nclass). For example, the following code will print B, C, D in that\norder:\n```text\n\nclass B:\npass\nclass C(B):\npass\nclass D(C):\npass\n\nfor c in [B, C, D]:\ntry:\nraise c()\nexcept D:\nprint \"D\"\nexcept C:\nprint \"C\"\nexcept B:\nprint \"B\"\n```\nNote that if the except clauses were reversed (with\n\"except B\" first), it would have printed B, B, B -- the first\nmatching except clause is triggered.\nWhen an error message is printed for an unhandled exception which is a\nclass, the class name is printed, then a colon and a space, and\nfinally the instance converted to a string using the built-in function\nstr().", "python_version": "2.2", "length": 27766, "url": "https://docs.python.org/2.2/tut/node11.html"} {"title": "10. What Now?", "text": "node11.html | tut.html | node13.html | Python Tutorial | node2.html\n---\n# 10. What Now?\nReading this tutorial has probably reinforced your interest in using\nPython -- you should be eager to apply Python to solve your\nreal-world problems. Now what should you do?\nYou should read, or at least page through, the\nPython Library Reference (../lib/lib.html),\nwhich gives complete (though terse) reference material about types,\nfunctions, and modules that can save you a lot of time when writing\nPython programs. The standard Python distribution includes a\nlot of code in both C and Python; there are modules to read\nUnix mailboxes, retrieve documents via HTTP, generate random\nnumbers, parse command-line options, write CGI programs, compress\ndata, and a lot more; skimming through the Library Reference will give\nyou an idea of what's available.\nThe major Python Web site is http://www.python.org/; it contains\ncode, documentation, and pointers to Python-related pages around the\nWeb. This Web site is mirrored in various places around the\nworld, such as Europe, Japan, and Australia; a mirror may be faster\nthan the main site, depending on your geographical location. A more\ninformal site is http://starship.python.net/, which contains a\nbunch of Python-related personal home pages; many people have\ndownloadable software there.\nFor Python-related questions and problem reports, you can post to the\nnewsgroup comp.lang.python (news:comp.lang.python), or send them to the mailing\nlist at python-list@python.org. The newsgroup and mailing list\nare gatewayed, so messages posted to one will automatically be\nforwarded to the other. There are around 120 postings a day,\nasking (and answering) questions, suggesting new features, and\nannouncing new modules. Before posting, be sure to check the list of\nFrequently Asked Questions (also called the FAQ), at\nhttp://www.python.org/doc/FAQ.html, or look for it in the\nMisc/ directory of the Python source distribution. Mailing\nlist archives are available at http://www.python.org/pipermail/.\nThe FAQ answers many of the questions that come up again and again,\nand may already contain the solution for your problem.", "python_version": "2.2", "length": 2151, "url": "https://docs.python.org/2.2/tut/node12.html"} {"title": "A. Interactive Input Editing and History Substitution", "text": "node12.html | tut.html | node14.html | Python Tutorial | node2.html\n---\n- A.1 Line Editing (#SECTION0013100000000000000000)\n A.2 History Substitution (#SECTION0013200000000000000000)\n A.3 Key Bindings (#SECTION0013300000000000000000)\n A.4 Commentary (#SECTION0013400000000000000000)\n---\n# A. Interactive Input Editing and History Substitution\nSome versions of the Python interpreter support editing of the current\ninput line and history substitution, similar to facilities found in\nthe Korn shell and the GNU Bash shell. This is implemented using the\nGNU Readline library, which supports Emacs-style and vi-style\nediting. This library has its own documentation which I won't\nduplicate here; however, the basics are easily explained. The\ninteractive editing and history described here are optionally\navailable in the Unix and CygWin versions of the interpreter.\nThis chapter does not document the editing facilities of Mark\nHammond's PythonWin package or the Tk-based environment, IDLE,\ndistributed with Python. The command line history recall which\noperates within DOS boxes on NT and some other DOS and Windows flavors\nis yet another beast.\n# A.1 Line Editing\nIf supported, input line editing is active whenever the interpreter\nprints a primary or secondary prompt. The current line can be edited\nusing the conventional Emacs control characters. The most important\nof these are: C-A (Control-A) moves the cursor to the beginning\nof the line, C-E to the end, C-B moves it one position to\nthe left, C-F to the right. Backspace erases the character to\nthe left of the cursor, C-D the character to its right.\nC-K kills (erases) the rest of the line to the right of the\ncursor, C-Y yanks back the last killed string.\nC-underscore undoes the last change you made; it can be repeated\nfor cumulative effect.\n# A.2 History Substitution\nHistory substitution works as follows. All non-empty input lines\nissued are saved in a history buffer, and when a new prompt is given\nyou are positioned on a new line at the bottom of this buffer.\nC-P moves one line up (back) in the history buffer,\nC-N moves one down. Any line in the history buffer can be\nedited; an asterisk appears in front of the prompt to mark a line as\nmodified. Pressing the Return key passes the current line to\nthe interpreter. C-R starts an incremental reverse search;\nC-S starts a forward search.\n# A.3 Key Bindings\nThe key bindings and some other parameters of the Readline library can\nbe customized by placing commands in an initialization file called\n~/.inputrc. Key bindings have the form\n```text\n\nkey-name: function-name\n```\nor\n```text\n\n\"string\": function-name\n```\nand options can be set with\n```text\n\nset option-name value\n```\nFor example:\n```text\n\n# I prefer vi-style editing:\nset editing-mode vi\n\n# Edit using a single line:\nset horizontal-scroll-mode On\n\n# Rebind some keys:\nMeta-h: backward-kill-word\n\"\\C-u\": universal-argument\n\"\\C-x\\C-r\": re-read-init-file\n```\nNote that the default binding for Tab in Python is to insert a\nTab character instead of Readline's default filename completion\nfunction. If you insist, you can override this by putting\n```text\n\nTab: complete\n```\nin your ~/.inputrc. (Of course, this makes it harder to\ntype indented continuation lines.)\nAutomatic completion of variable and module names is optionally\navailable. To enable it in the interpreter's interactive mode, add\nthe following to your startup file:A.1 (#foot1426)\n```text\n\nimport rlcompleter, readline\nreadline.parse_and_bind('tab: complete')\n```\nThis binds the Tab key to the completion function, so hitting\nthe Tab key twice suggests completions; it looks at Python\nstatement names, the current local variables, and the available module\nnames. For dotted expressions such as `string.a`, it will\nevaluate the the expression up to the final \".\" and then\nsuggest completions from the attributes of the resulting object. Note\nthat this may execute application-defined code if an object with a\n__getattr__() method is part of the expression.\nA more capable startup file might look like this example. Note that\nthis deletes the names it creates once they are no longer needed; this\nis done since the startup file is executed in the same namespace as\nthe interactive commands, and removing the names avoids creating side\neffects in the interactive environments. You may find it convenient\nto keep some of the imported modules, such as os, which turn\nout to be needed in most sessions with the interpreter.\n```text\n\n# Add auto-completion and a stored history file of commands to your Python\n# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is\n# bound to the Esc key by default (you can change it - see readline docs).\n#\n# Store the file in ~/.pystartup, and set an environment variable to point\n# to it, e.g. \"export PYTHONSTARTUP=/max/home/itamar/.pystartup\" in bash.\n#\n# Note that PYTHONSTARTUP does *not* expand \"~\", so you have to put in the\n# full path to your home directory.\n\nimport atexit\nimport os\nimport readline\nimport rlcompleter\n\nhistoryPath = os.path.expanduser(\"~/.pyhistory\")\n\ndef save_history(historyPath=historyPath):\nimport readline\nreadline.write_history_file(historyPath)\n\nif os.path.exists(historyPath):\nreadline.read_history_file(historyPath)\n\natexit.register(save_history)\ndel os, atexit, readline, rlcompleter, save_history, historyPath\n```\n# A.4 Commentary\nThis facility is an enormous step forward compared to earlier versions\nof the interpreter; however, some wishes are left: It would be nice if\nthe proper indentation were suggested on continuation lines (the\nparser knows if an indent token is required next). The completion\nmechanism might use the interpreter's symbol table. A command to\ncheck (or even suggest) matching parentheses, quotes, etc., would also\nbe useful.", "python_version": "2.2", "length": 5771, "url": "https://docs.python.org/2.2/tut/node13.html"} {"title": "B. Floating Point Arithmetic: Issues and Limitations", "text": "node13.html | tut.html | node15.html | Python Tutorial | node2.html\n---\n- B.1 Representation Error (#SECTION0014100000000000000000)\n---\n# B. Floating Point Arithmetic: Issues and Limitations\nFloating-point numbers are represented in computer hardware as\nbase 2 (binary) fractions. For example, the decimal fraction\n```text\n\n0.125\n```\nhas value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction\n```text\n\n0.001\n```\nhas value 0/2 + 0/4 + 1/8. These two fractions have identical values,\nthe only real difference being that the first is written in base 10\nfractional notation, and the second in base 2.\nUnfortunately, most decimal fractions cannot be represented exactly as\nbinary fractions. A consequence is that, in general, the decimal\nfloating-point numbers you enter are only approximated by the binary\nfloating-point numbers actually stored in the machine.\nThe problem is easier to understand at first in base 10. Consider the\nfraction 1/3. You can approximate that as a base 10 fraction:\n```text\n\n0.3\n```\nor, better,\n```text\n\n0.33\n```\nor, better,\n```text\n\n0.333\n```\nand so on. No matter how many digits you're willing to write down, the\nresult will never be exactly 1/3, but will be an increasingly better\napproximation to 1/3.\nIn the same way, no matter how many base 2 digits you're willing to\nuse, the decimal value 0.1 cannot be represented exactly as a base 2\nfraction. In base 2, 1/10 is the infinitely repeating fraction\n```text\n\n0.0001100110011001100110011001100110011001100110011...\n```\nStop at any finite number of bits, and you get an approximation. This\nis why you see things like:\n```text\n\n>>> 0.1\n0.10000000000000001\n```\nOn most machines today, that is what you'll see if you enter 0.1 at\na Python prompt. You may not, though, because the number of bits\nused by the hardware to store floating-point values can vary across\nmachines, and Python only prints a decimal approximation to the true\ndecimal value of the binary approximation stored by the machine. On\nmost machines, if Python were to print the true decimal value of\nthe binary approximation stored for 0.1, it would have to display\n```text\n\n>>> 0.1\n0.1000000000000000055511151231257827021181583404541015625\n```\ninstead! The Python prompt (implicitly) uses the builtin\nrepr() function to obtain a string version of everything it\ndisplays. For floats, `repr( float )` rounds the true\ndecimal value to 17 significant digits, giving\n```text\n\n0.10000000000000001\n```\n`repr( float )` produces 17 significant digits because it\nturns out that's enough (on most machines) so that\n`eval(repr( x )) == x` exactly for all finite floats\nx, but rounding to 16 digits is not enough to make that true.\nNote that this is in the very nature of binary floating-point: this is\nnot a bug in Python, it is not a bug in your code either, and you'll\nsee the same kind of thing in all languages that support your\nhardware's floating-point arithmetic (although some languages may\nnot display the difference by default, or in all output modes).\nPython's builtin str() function produces only 12\nsignificant digits, and you may wish to use that instead. It's\nunusual for `eval(str( x ))` to reproduce x, but the\noutput may be more pleasant to look at:\n```text\n\n>>> print str(0.1)\n0.1\n```\nIt's important to realize that this is, in a real sense, an illusion:\nthe value in the machine is not exactly 1/10, you're simply rounding\nthe display of the true machine value.\nOther surprises follow from this one. For example, after seeing\n```text\n\n>>> 0.1\n0.10000000000000001\n```\nyou may be tempted to use the round() function to chop it\nback to the single digit you expect. But that makes no difference:\n```text\n\n>>> round(0.1, 1)\n0.10000000000000001\n```\nThe problem is that the binary floating-point value stored for \"0.1\"\nwas already the best possible binary approximation to 1/10, so trying\nto round it again can't make it better: it was already as good as it\ngets.\nAnother consequence is that since 0.1 is not exactly 1/10, adding 0.1\nto itself 10 times may not yield exactly 1.0, either:\n```text\n\n>>> sum = 0.0\n>>> for i in range(10):\n... sum += 0.1\n...\n>>> sum\n0.99999999999999989\n```\nBinary floating-point arithmetic holds many surprises like this. The\nproblem with \"0.1\" is explained in precise detail below, in the\n\"Representation Error\" section. See\nThe Perils of Floating\nPoint (http://www.lahey.com/float.htm) for a more complete account of other common surprises.\nAs that says near the end, ``there are no easy answers.'' Still,\ndon't be unduly wary of floating-point! The errors in Python float\noperations are inherited from the floating-point hardware, and on most\nmachines are on the order of no more than 1 part in 2**53 per\noperation. That's more than adequate for most tasks, but you do need\nto keep in mind that it's not decimal arithmetic, and that every float\noperation can suffer a new rounding error.\nWhile pathological cases do exist, for most casual use of\nfloating-point arithmetic you'll see the result you expect in the end\nif you simply round the display of your final results to the number of\ndecimal digits you expect. str() usually suffices, and for\nfiner control see the discussion of Pythons's `%` format\noperator: the `%g`, `%f` and `%e` format codes\nsupply flexible and easy ways to round float results for display.\n# B.1 Representation Error\nThis section explains the ``0.1'' example in detail, and shows how\nyou can perform an exact analysis of cases like this yourself. Basic\nfamiliarity with binary floating-point representation is assumed.\nRepresentation error refers to that some (most, actually)\ndecimal fractions cannot be represented exactly as binary (base 2)\nfractions. This is the chief reason why Python (or Perl, C, C++,\nJava, Fortran, and many others) often won't display the exact decimal\nnumber you expect:\n```text\n\n>>> 0.1\n0.10000000000000001\n```\nWhy is that? 1/10 is not exactly representable as a binary fraction.\nAlmost all machines today (November 2000) use IEEE-754 floating point\narithmetic, and almost all platforms map Python floats to IEEE-754\n\"double precision\". 754 doubles contain 53 bits of precision, so on\ninput the computer strives to convert 0.1 to the closest fraction it can\nof the form J/2**N where J is an integer containing\nexactly 53 bits. Rewriting\n```text\n\n1 / 10 ~= J / (2**N)\n```\nas\n```text\n\nJ ~= 2**N / 10\n```\nand recalling that J has exactly 53 bits (is `>= 2**52` but\n`< 2**53`), the best value for N is 56:\n```text\n\n>>> 2L**52\n4503599627370496L\n>>> 2L**53\n9007199254740992L\n>>> 2L**56/10\n7205759403792793L\n```\nThat is, 56 is the only value for N that leaves J with\nexactly 53 bits. The best possible value for J is then that\nquotient rounded:\n```text\n\n>>> q, r = divmod(2L**56, 10)\n>>> r\n6L\n```\nSince the remainder is more than half of 10, the best approximation is\nobtained by rounding up:\n```text\n\n>>> q+1\n7205759403792794L\n```\nTherefore the best possible approximation to 1/10 in 754 double\nprecision is that over 2**56, or\n```text\n\n7205759403792794 / 72057594037927936\n```\nNote that since we rounded up, this is actually a little bit larger than\n1/10; if we had not rounded up, the quotient would have been a little\nbit smaller than 1/10. But in no case can it be exactly 1/10!\nSo the computer never ``sees'' 1/10: what it sees is the exact\nfraction given above, the best 754 double approximation it can get:\n```text\n\n>>> .1 * 2L**56\n7205759403792794.0\n```\nIf we multiply that fraction by 10**30, we can see the (truncated)\nvalue of its 30 most significant decimal digits:\n```text\n\n>>> 7205759403792794L * 10L**30 / 2L**56\n100000000000000005551115123125L\n```\nmeaning that the exact number stored in the computer is approximately\nequal to the decimal value 0.100000000000000005551115123125. Rounding\nthat to 17 significant digits gives the 0.10000000000000001 that Python\ndisplays (well, will display on any 754-conforming platform that does\nbest-possible input and output conversions in its C library -- yours may\nnot!).", "python_version": "2.2", "length": 7960, "url": "https://docs.python.org/2.2/tut/node14.html"} {"title": "C. History and License", "text": "node14.html | tut.html | node16.html | Python Tutorial | node2.html\n---\n- C.1 History of the software (#SECTION0015100000000000000000)\n C.2 Terms and conditions for accessing or otherwise using Python (#SECTION0015200000000000000000)\n---\n# C. History and License\n# C.1 History of the software\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl/) in the Netherlands\nas a successor of a language called ABC. Guido remains Python's\nprincipal author, although it includes many contributions from others.\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us/)\nin Reston, Virginia where he released several versions of the\nsoftware.\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team. In October of the same\nyear, the PythonLabs team moved to Zope Corporation (then Digital\nCreations; see http://www.zope.com/). In 2001, the Python\nSoftware Foundation (PSF, see http://www.python.org/psf/) was\nformed, a non-profit organization created specifically to own\nPython-related Intellectual Property. Digital Creations is a\nsponsoring member of the PSF.\nAll Python releases are Open Source (see\nhttp://www.opensource.org/ for the Open Source Definition).\nHistorically, most, but not all, Python releases have also been\nGPL-compatible; the table below summarizes the various releases.\nNote:\nGPL-compatible doesn't mean that we're distributing\nPython under the GPL. All Python licenses, unlike the GPL, let you\ndistribute a modified version without making your changes open source.\nThe GPL-compatible licenses make it possible to combine Python with\nother software that is released under the GPL; the others don't.\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.\n# C.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.2\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.2 software in source or binary\nform and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, PSF\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python\n2.2 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001 Python Software Foundation; All Rights\nReserved'' are retained in Python 2.2 alone or in any\nderivative version prepared by Licensee.\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 2.2 or any part thereof, and wants to\nmake the derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 2.2.\n4. PSF is making Python 2.2 available to Licensee on an ``AS IS''\nbasis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.2 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE\nPOSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee. This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n8. By copying, installing or otherwise using Python 2.2, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n1. This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (``Licensee'') accessing and otherwise\nusing this software in source or binary form and its associated\ndocumentation (``the Software'').\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n3. BeOpen is making the Software available to Licensee on an ``AS IS''\nbasis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions. Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee. This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party. As an exception, the ``BeOpen Python'' logos available\nat http://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (``CNRI''), and the Individual or Organization\n(``Licensee'') accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., ``Copyright\n© 1995-2001 Corporation for National Research Initiatives;\nAll Rights Reserved'' are retained in Python 1.6.1 alone or in any\nderivative version prepared by Licensee. Alternately, in lieu of\nCNRI's License Agreement, Licensee may substitute the following text\n(omitting the quotes): ``Python 1.6.1 is made available subject to the\nterms and conditions in CNRI's License Agreement. This Agreement\ntogether with Python 1.6.1 may be located on the Internet using the\nfollowing unique, persistent identifier (known as a handle):\n1895.22/1013. This Agreement may also be obtained from a proxy server\non the Internet using the following URL:\nhttp://hdl.handle.net/1895.22/1013.''\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n4. CNRI is making Python 1.6.1 available to Licensee on an ``AS IS''\nbasis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement. Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee. This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n8. By clicking on the ``ACCEPT'' button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\nACCEPT\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\nCopyright © 1991 - 1995, Stichting Mathematisch Centrum\nAmsterdam, The Netherlands. All rights reserved.\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.", "python_version": "2.2", "length": 11590, "url": "https://docs.python.org/2.2/tut/node15.html"} {"title": "About this document ...", "text": "node15.html | tut.html | Python Tutorial | node2.html\n---\n# About this document ...\nPython Tutorial,\nDecember 21, 2001, Release 2.2\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nnode15.html | tut.html | Python Tutorial | node2.html\n---\nRelease 2.2, documentation updated on December 21, 2001.", "python_version": "2.2", "length": 1639, "url": "https://docs.python.org/2.2/tut/node16.html"} {"title": "Contents", "text": "node1.html | tut.html | node3.html | Python Tutorial\n---\n## Contents\nTable of Contents\n- Front Matter (node1.html)\n 1. Whetting Your Appetite (node3.html)\n - 1.1 Where From Here (node3.html#SECTION003100000000000000000)\n 2. Using the Python Interpreter (node4.html)\n - 2.1 Invoking the Interpreter (node4.html#SECTION004100000000000000000)\n - 2.1.1 Argument Passing (node4.html#SECTION004110000000000000000)\n 2.1.2 Interactive Mode (node4.html#SECTION004120000000000000000)\n 2.2 The Interpreter and Its Environment (node4.html#SECTION004200000000000000000)\n - 2.2.1 Error Handling (node4.html#SECTION004210000000000000000)\n 2.2.2 Executable Python Scripts (node4.html#SECTION004220000000000000000)\n 2.2.3 The Interactive Startup File (node4.html#SECTION004230000000000000000)\n 3. An Informal Introduction to Python (node5.html)\n - 3.1 Using Python as a Calculator (node5.html#SECTION005100000000000000000)\n - 3.1.1 Numbers (node5.html#SECTION005110000000000000000)\n 3.1.2 Strings (node5.html#SECTION005120000000000000000)\n 3.1.3 Unicode Strings (node5.html#SECTION005130000000000000000)\n 3.1.4 Lists (node5.html#SECTION005140000000000000000)\n 3.2 First Steps Towards Programming (node5.html#SECTION005200000000000000000)\n 4. More Control Flow Tools (node6.html)\n - 4.1 if Statements (node6.html#SECTION006100000000000000000)\n 4.2 for Statements (node6.html#SECTION006200000000000000000)\n 4.3 The range() Function (node6.html#SECTION006300000000000000000)\n 4.4 break and continue Statements, and else Clauses on Loops (node6.html#SECTION006400000000000000000)\n 4.5 pass Statements (node6.html#SECTION006500000000000000000)\n 4.6 Defining Functions (node6.html#SECTION006600000000000000000)\n 4.7 More on Defining Functions (node6.html#SECTION006700000000000000000)\n - 4.7.1 Default Argument Values (node6.html#SECTION006710000000000000000)\n 4.7.2 Keyword Arguments (node6.html#SECTION006720000000000000000)\n 4.7.3 Arbitrary Argument Lists (node6.html#SECTION006730000000000000000)\n 4.7.4 Lambda Forms (node6.html#SECTION006740000000000000000)\n 4.7.5 Documentation Strings (node6.html#SECTION006750000000000000000)\n 5. Data Structures (node7.html)\n - 5.1 More on Lists (node7.html#SECTION007100000000000000000)\n - 5.1.1 Using Lists as Stacks (node7.html#SECTION007110000000000000000)\n 5.1.2 Using Lists as Queues (node7.html#SECTION007120000000000000000)\n 5.1.3 Functional Programming Tools (node7.html#SECTION007130000000000000000)\n 5.1.4 List Comprehensions (node7.html#SECTION007140000000000000000)\n 5.2 The del statement (node7.html#SECTION007200000000000000000)\n 5.3 Tuples and Sequences (node7.html#SECTION007300000000000000000)\n 5.4 Dictionaries (node7.html#SECTION007400000000000000000)\n 5.5 More on Conditions (node7.html#SECTION007500000000000000000)\n 5.6 Comparing Sequences and Other Types (node7.html#SECTION007600000000000000000)\n 6. Modules (node8.html)\n - 6.1 More on Modules (node8.html#SECTION008100000000000000000)\n - 6.1.1 The Module Search Path (node8.html#SECTION008110000000000000000)\n 6.1.2 ``Compiled'' Python files (node8.html#SECTION008120000000000000000)\n 6.2 Standard Modules (node8.html#SECTION008200000000000000000)\n 6.3 The dir() Function (node8.html#SECTION008300000000000000000)\n 6.4 Packages (node8.html#SECTION008400000000000000000)\n - 6.4.1 Importing * From a Package (node8.html#SECTION008410000000000000000)\n 6.4.2 Intra-package References (node8.html#SECTION008420000000000000000)\n 7. Input and Output (node9.html)\n - 7.1 Fancier Output Formatting (node9.html#SECTION009100000000000000000)\n 7.2 Reading and Writing Files (node9.html#SECTION009200000000000000000)\n - 7.2.1 Methods of File Objects (node9.html#SECTION009210000000000000000)\n 7.2.2 The pickle Module (node9.html#SECTION009220000000000000000)\n 8. Errors and Exceptions (node10.html)\n - 8.1 Syntax Errors (node10.html#SECTION0010100000000000000000)\n 8.2 Exceptions (node10.html#SECTION0010200000000000000000)\n 8.3 Handling Exceptions (node10.html#SECTION0010300000000000000000)\n 8.4 Raising Exceptions (node10.html#SECTION0010400000000000000000)\n 8.5 User-defined Exceptions (node10.html#SECTION0010500000000000000000)\n 8.6 Defining Clean-up Actions (node10.html#SECTION0010600000000000000000)\n 9. Classes (node11.html)\n - 9.1 A Word About Terminology (node11.html#SECTION0011100000000000000000)\n 9.2 Python Scopes and Name Spaces (node11.html#SECTION0011200000000000000000)\n 9.3 A First Look at Classes (node11.html#SECTION0011300000000000000000)\n - 9.3.1 Class Definition Syntax (node11.html#SECTION0011310000000000000000)\n 9.3.2 Class Objects (node11.html#SECTION0011320000000000000000)\n 9.3.3 Instance Objects (node11.html#SECTION0011330000000000000000)\n 9.3.4 Method Objects (node11.html#SECTION0011340000000000000000)\n 9.4 Random Remarks (node11.html#SECTION0011400000000000000000)\n 9.5 Inheritance (node11.html#SECTION0011500000000000000000)\n - 9.5.1 Multiple Inheritance (node11.html#SECTION0011510000000000000000)\n 9.6 Private Variables (node11.html#SECTION0011600000000000000000)\n 9.7 Odds and Ends (node11.html#SECTION0011700000000000000000)\n - 9.7.1 Exceptions Can Be Classes (node11.html#SECTION0011710000000000000000)\n 10. What Now? (node12.html)\n A. Interactive Input Editing and History Substitution (node13.html)\n - A.1 Line Editing (node13.html#SECTION0013100000000000000000)\n A.2 History Substitution (node13.html#SECTION0013200000000000000000)\n A.3 Key Bindings (node13.html#SECTION0013300000000000000000)\n A.4 Commentary (node13.html#SECTION0013400000000000000000)\n B. Floating Point Arithmetic: Issues and Limitations (node14.html)\n - B.1 Representation Error (node14.html#SECTION0014100000000000000000)\n C. History and License (node15.html)\n - C.1 History of the software (node15.html#SECTION0015100000000000000000)\n C.2 Terms and conditions for accessing or otherwise using Python (node15.html#SECTION0015200000000000000000)\n About this document ... (node16.html)\nEnd of Table of Contents", "python_version": "2.2", "length": 5997, "url": "https://docs.python.org/2.2/tut/node2.html"} {"title": "1. Whetting Your Appetite", "text": "node2.html | tut.html | node4.html | Python Tutorial | node2.html\n---\n- 1.1 Where From Here (#SECTION003100000000000000000)\n---\n# 1. Whetting Your Appetite\nIf you ever wrote a large shell script, you probably know this\nfeeling: you'd love to add yet another feature, but it's already so\nslow, and so big, and so complicated; or the feature involves a system\ncall or other function that is only accessible from C ...Usually\nthe problem at hand isn't serious enough to warrant rewriting the\nscript in C; perhaps the problem requires variable-length strings or\nother data types (like sorted lists of file names) that are easy in\nthe shell but lots of work to implement in C, or perhaps you're not\nsufficiently familiar with C.\nAnother situation: perhaps you have to work with several C libraries,\nand the usual C write/compile/test/re-compile cycle is too slow. You\nneed to develop software more quickly. Possibly perhaps you've\nwritten a program that could use an extension language, and you don't\nwant to design a language, write and debug an interpreter for it, then\ntie it into your application.\nIn such cases, Python may be just the language for you. Python is\nsimple to use, but it is a real programming language, offering much\nmore structure and support for large programs than the shell has. On\nthe other hand, it also offers much more error checking than C, and,\nbeing a very-high-level language, it has high-level data types\nbuilt in, such as flexible arrays and dictionaries that would cost you\ndays to implement efficiently in C. Because of its more general data\ntypes Python is applicable to a much larger problem domain than\nAwk or even Perl, yet many things are at least as easy\nin Python as in those languages.\nPython allows you to split up your program in modules that can be\nreused in other Python programs. It comes with a large collection of\nstandard modules that you can use as the basis of your programs -- or\nas examples to start learning to program in Python. There are also\nbuilt-in modules that provide things like file I/O, system calls,\nsockets, and even interfaces to graphical user interface toolkits like Tk.\nPython is an interpreted language, which can save you considerable time\nduring program development because no compilation and linking is\nnecessary. The interpreter can be used interactively, which makes it\neasy to experiment with features of the language, to write throw-away\nprograms, or to test functions during bottom-up program development.\nIt is also a handy desk calculator.\nPython allows writing very compact and readable programs. Programs\nwritten in Python are typically much shorter than equivalent C or\nC++ programs, for several reasons:\n- the high-level data types allow you to express complex operations in a\nsingle statement;\n- statement grouping is done by indentation instead of begin/end\nbrackets;\n- no variable or argument declarations are necessary.\nPython is extensible: if you know how to program in C it is easy\nto add a new built-in function or module to the interpreter, either to\nperform critical operations at maximum speed, or to link Python\nprograms to libraries that may only be available in binary form (such\nas a vendor-specific graphics library). Once you are really hooked,\nyou can link the Python interpreter into an application written in C\nand use it as an extension or command language for that application.\nBy the way, the language is named after the BBC show ``Monty Python's\nFlying Circus'' and has nothing to do with nasty reptiles. Making\nreferences to Monty Python skits in documentation is not only allowed,\nit is encouraged!\n# 1.1 Where From Here\nNow that you are all excited about Python, you'll want to examine it\nin some more detail. Since the best way to learn a language is\nusing it, you are invited here to do so.\nIn the next chapter, the mechanics of using the interpreter are\nexplained. This is rather mundane information, but essential for\ntrying out the examples shown later.\nThe rest of the tutorial introduces various features of the Python\nlanguage and system through examples, beginning with simple\nexpressions, statements and data types, through functions and modules,\nand finally touching upon advanced concepts like exceptions\nand user-defined classes.", "python_version": "2.2", "length": 4251, "url": "https://docs.python.org/2.2/tut/node3.html"} {"title": "2. Using the Python Interpreter", "text": "node3.html | tut.html | node5.html | Python Tutorial | node2.html\n---\n- 2.1 Invoking the Interpreter (#SECTION004100000000000000000)\n - 2.1.1 Argument Passing (#SECTION004110000000000000000)\n 2.1.2 Interactive Mode (#SECTION004120000000000000000)\n 2.2 The Interpreter and Its Environment (#SECTION004200000000000000000)\n - 2.2.1 Error Handling (#SECTION004210000000000000000)\n 2.2.2 Executable Python Scripts (#SECTION004220000000000000000)\n 2.2.3 The Interactive Startup File (#SECTION004230000000000000000)\n---\n# 2. Using the Python Interpreter\n# 2.1 Invoking the Interpreter\nThe Python interpreter is usually installed as\n/usr/local/bin/python on those machines where it is available;\nputting /usr/local/bin in your Unix shell's search path\nmakes it possible to start it by typing the command\n```text\n\npython\n```\nto the shell. Since the choice of the directory where the interpreter\nlives is an installation option, other places are possible; check with\nyour local Python guru or system administrator. (E.g.,\n/usr/local/python is a popular alternative location.)\nTyping an end-of-file character (Control-D on Unix,\nControl-Z on DOS or Windows) at the primary prompt causes the\ninterpreter to exit with a zero exit status. If that doesn't work,\nyou can exit the interpreter by typing the following commands:\n\"import sys; sys.exit()\".\nThe interpreter's line-editing features usually aren't very\nsophisticated. On Unix, whoever installed the interpreter may have\nenabled support for the GNU readline library, which adds more\nelaborate interactive editing and history features. Perhaps the\nquickest check to see whether command line editing is supported is\ntyping Control-P to the first Python prompt you get. If it beeps, you\nhave command line editing; see Appendix A (node13.html#interacting) for an\nintroduction to the keys. If nothing appears to happen, or if\n`P` is echoed, command line editing isn't available; you'll\nonly be able to use backspace to remove characters from the current\nline.\nThe interpreter operates somewhat like the Unix shell: when called\nwith standard input connected to a tty device, it reads and executes\ncommands interactively; when called with a file name argument or with\na file as standard input, it reads and executes a script from\nthat file.\nA third way of starting the interpreter is\n\"python -c command [arg] ...\", which\nexecutes the statement(s) in command, analogous to the shell's\n-c option. Since Python statements often contain spaces\nor other characters that are special to the shell, it is best to quote\ncommand in its entirety with double quotes.\nNote that there is a difference between \"python file\" and\n\"python `>`> \"); for continuation lines it prompts with the\nsecondary prompt, by default three dots (\"... \").\nThe interpreter prints a welcome message stating its version number\nand a copyright notice before printing the first prompt:\n```text\n\npython\nPython 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5\nCopyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam\n>>>\n```\nContinuation lines are needed when entering a multi-line construct.\nAs an example, take a look at this if statement:\n```text\n\n>>> the_world_is_flat = 1\n>>> if the_world_is_flat:\n... print \"Be careful not to fall off!\"\n...\nBe careful not to fall off!\n```\n# 2.2 The Interpreter and Its Environment\n## 2.2.1 Error Handling\nWhen an error occurs, the interpreter prints an error\nmessage and a stack trace. In interactive mode, it then returns to\nthe primary prompt; when input came from a file, it exits with a\nnonzero exit status after printing\nthe stack trace. (Exceptions handled by an `except` clause in a\n`try` statement are not errors in this context.) Some errors are\nunconditionally fatal and cause an exit with a nonzero exit; this\napplies to internal inconsistencies and some cases of running out of\nmemory. All error messages are written to the standard error stream;\nnormal output from the executed commands is written to standard\noutput.\nTyping the interrupt character (usually Control-C or DEL) to the\nprimary or secondary prompt cancels the input and returns to the\nprimary prompt.2.1 (#foot108)Typing an interrupt while a command is executing raises the\n`KeyboardInterrupt` exception, which may be handled by a\n`try` statement.\n## 2.2.2 Executable Python Scripts\nOn BSD'ish Unix systems, Python scripts can be made directly\nexecutable, like shell scripts, by putting the line\n```text\n\n#! /usr/bin/env python\n```\n(assuming that the interpreter is on the user's PATH) at the\nbeginning of the script and giving the file an executable mode. The\n\"#!\" must be the first two characters of the file. Note that\nthe hash, or pound, character, \"#\", is used to start a\ncomment in Python.\n## 2.2.3 The Interactive Startup File\nWhen you use Python interactively, it is frequently handy to have some\nstandard commands executed every time the interpreter is started. You\ncan do this by setting an environment variable named\nPYTHONSTARTUP to the name of a file containing your start-up\ncommands. This is similar to the .profile feature of the\nUnix shells.\nThis file is only read in interactive sessions, not when Python reads\ncommands from a script, and not when /dev/tty is given as the\nexplicit source of commands (which otherwise behaves like an\ninteractive session). It is executed in the same namespace where\ninteractive commands are executed, so that objects that it defines or\nimports can be used without qualification in the interactive session.\nYou can also change the prompts `sys.ps1` and `sys.ps2` in\nthis file.\nIf you want to read an additional start-up file from the current\ndirectory, you can program this in the global start-up file using code\nlike \"if os.path.isfile('.pythonrc.py'):\nexecfile('.pythonrc.py')\". If you want to use the startup file in a\nscript, you must do this explicitly in the script:\n```text\n\nimport os\nfilename = os.environ.get('PYTHONSTARTUP')\nif filename and os.path.isfile(filename):\nexecfile(filename)\n```", "python_version": "2.2", "length": 7528, "url": "https://docs.python.org/2.2/tut/node4.html"} {"title": "3. An Informal Introduction to Python", "text": "node4.html | tut.html | node6.html | Python Tutorial | node2.html\n---\n- 3.1 Using Python as a Calculator (#SECTION005100000000000000000)\n - 3.1.1 Numbers (#SECTION005110000000000000000)\n 3.1.2 Strings (#SECTION005120000000000000000)\n 3.1.3 Unicode Strings (#SECTION005130000000000000000)\n 3.1.4 Lists (#SECTION005140000000000000000)\n 3.2 First Steps Towards Programming (#SECTION005200000000000000000)\n---\n# 3. An Informal Introduction to Python\nIn the following examples, input and output are distinguished by the\npresence or absence of prompts (\">`>`> \" and \"... \"): to repeat\nthe example, you must type everything after the prompt, when the\nprompt appears; lines that do not begin with a prompt are output from\nthe interpreter. Note that a secondary prompt on a line by itself in an example means\nyou must type a blank line; this is used to end a multi-line command.\nMany of the examples in this manual, even those entered at the\ninteractive prompt, include comments. Comments in Python start with\nthe hash character, \"#\", and extend to the end of the\nphysical line. A comment may appear at the start of a line or\nfollowing whitespace or code, but not within a string literal. A hash\ncharacter within a string literal is just a hash character.\nSome examples:\n```text\n\n# this is the first comment\nSPAM = 1 # and this is the second comment\n# ... and now a third!\nSTRING = \"# This is not a comment.\"\n```\n# 3.1 Using Python as a Calculator\nLet's try some simple Python commands. Start the interpreter and wait\nfor the primary prompt, \">`>`> \". (It shouldn't take long.)\n## 3.1.1 Numbers\nThe interpreter acts as a simple calculator: you can type an\nexpression at it and it will write the value. Expression syntax is\nstraightforward: the operators `+`, `-`, `*` and\n`/` work just like in most other languages (for example, Pascal\nor C); parentheses can be used for grouping. For example:\n```text\n\n>>> 2+2\n4\n>>> # This is a comment\n... 2+2\n4\n>>> 2+2 # and a comment on the same line as code\n4\n>>> (50-5*6)/4\n5\n>>> # Integer division returns the floor:\n... 7/3\n2\n>>> 7/-3\n-3\n```\nLike in C, the equal sign (\"=\") is used to assign a value to a\nvariable. The value of an assignment is not written:\n```text\n\n>>> width = 20\n>>> height = 5*9\n>>> width * height\n900\n```\nA value can be assigned to several variables simultaneously:\n```text\n\n>>> x = y = z = 0 # Zero x, y and z\n>>> x\n0\n>>> y\n0\n>>> z\n0\n```\nThere is full support for floating point; operators with mixed type\noperands convert the integer operand to floating point:\n```text\n\n>>> 3 * 3.75 / 1.5\n7.5\n>>> 7.0 / 2\n3.5\n```\nComplex numbers are also supported; imaginary numbers are written with\na suffix of \"j\" or \"J\". Complex numbers with a nonzero\nreal component are written as \"(real+imagj)\", or can\nbe created with the \"complex(real, imag)\" function.\n```text\n\n>>> 1j * 1J\n(-1+0j)\n>>> 1j * complex(0,1)\n(-1+0j)\n>>> 3+1j*3\n(3+3j)\n>>> (3+1j)*3\n(9+3j)\n>>> (1+2j)/(1+1j)\n(1.5+0.5j)\n```\nComplex numbers are always represented as two floating point numbers,\nthe real and imaginary part. To extract these parts from a complex\nnumber z, use `z .real` and `z .imag`.\n```text\n\n>>> a=1.5+0.5j\n>>> a.real\n1.5\n>>> a.imag\n0.5\n```\nThe conversion functions to floating point and integer\n(float(), int() and long()) don't\nwork for complex numbers -- there is no one correct way to convert a\ncomplex number to a real number. Use `abs( z )` to get its\nmagnitude (as a float) or `z.real` to get its real part.\n```text\n\n>>> a=3.0+4.0j\n>>> float(a)\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: can't convert complex to float; use e.g. abs(z)\n>>> a.real\n3.0\n>>> a.imag\n4.0\n>>> abs(a) # sqrt(a.real**2 + a.imag**2)\n5.0\n>>>\n```\nIn interactive mode, the last printed expression is assigned to the\nvariable `_`. This means that when you are using Python as a\ndesk calculator, it is somewhat easier to continue calculations, for\nexample:\n```text\n\n>>> tax = 12.5 / 100\n>>> price = 100.50\n>>> price * tax\n12.5625\n>>> price + _\n113.0625\n>>> round(_, 2)\n113.06\n>>>\n```\nThis variable should be treated as read-only by the user. Don't\nexplicitly assign a value to it -- you would create an independent\nlocal variable with the same name masking the built-in variable with\nits magic behavior.\n## 3.1.2 Strings\nBesides numbers, Python can also manipulate strings, which can be\nexpressed in several ways. They can be enclosed in single quotes or\ndouble quotes:\n```text\n\n>>> 'spam eggs'\n'spam eggs'\n>>> 'doesn\\'t'\n\"doesn't\"\n>>> \"doesn't\"\n\"doesn't\"\n>>> '\"Yes,\" he said.'\n'\"Yes,\" he said.'\n>>> \"\\\"Yes,\\\" he said.\"\n'\"Yes,\" he said.'\n>>> '\"Isn\\'t,\" she said.'\n'\"Isn\\'t,\" she said.'\n```\nString literals can span multiple lines in several ways. Continuation\nlines can be used, with a backslash as the last character on the line\nindicating that the next line is a logical continuation of the line:\n```text\n\nhello = \"This is a rather long string containing\\n\\\nseveral lines of text just as you would do in C.\\n\\\nNote that whitespace at the beginning of the line is\\\nsignificant.\"\n\nprint hello\n```\nNote that newlines would still need to be embedded in the string using\n`\\n`; the newline following the trailing backslash is\ndiscarded. This example would print the following:\n```text\n\nThis is a rather long string containing\nseveral lines of text just as you would do in C.\nNote that whitespace at the beginning of the line is significant.\n```\nIf we make the string literal a ``raw'' string, however, the\n`\\n` sequences are not converted to newlines, but the backslash\nat the end of the line, and the newline character in the source, are\nboth included in the string as data. Thus, the example:\n```text\n\nhello = r\"This is a rather long string containing\\n\\\nseveral lines of text much as you would do in C.\"\n\nprint hello\n```\nwould print:\n```text\n\nThis is a rather long string containing\\n\\\nseveral lines of text much as you would do in C.\n```\nOr, strings can be surrounded in a pair of matching triple-quotes:\n`\"\"\"` or `' ' '`. End of lines do not need to be escaped\nwhen using triple-quotes, but they will be included in the string.\n```text\n\nprint \"\"\"\nUsage: thingy [OPTIONS]\n-h Display this usage message\n-H hostname Hostname to connect to\n\"\"\"\n```\nproduces the following output:\n```text\n\nUsage: thingy [OPTIONS]\n-h Display this usage message\n-H hostname Hostname to connect to\n```\nThe interpreter prints the result of string operations in the same way\nas they are typed for input: inside quotes, and with quotes and other\nfunny characters escaped by backslashes, to show the precise\nvalue. The string is enclosed in double quotes if the string contains\na single quote and no double quotes, else it's enclosed in single\nquotes. (The print statement, described later, can be used\nto write strings without quotes or escapes.)\nStrings can be concatenated (glued together) with the\n`+` operator, and repeated with `*`:\n```text\n\n>>> word = 'Help' + 'A'\n>>> word\n'HelpA'\n>>> '<' + word*5 + '>'\n''\n```\nTwo string literals next to each other are automatically concatenated;\nthe first line above could also have been written \"word = 'Help'\n'A'\"; this only works with two literals, not with arbitrary string\nexpressions:\n```text\n\n>>> import string\n>>> 'str' 'ing' # <- This is ok\n'string'\n>>> string.strip('str') + 'ing' # <- This is ok\n'string'\n>>> string.strip('str') 'ing' # <- This is invalid\nFile \"\", line 1, in ?\nstring.strip('str') 'ing'\n^\nSyntaxError: invalid syntax\n```\nStrings can be subscripted (indexed); like in C, the first character\nof a string has subscript (index) 0. There is no separate character\ntype; a character is simply a string of size one. Like in Icon,\nsubstrings can be specified with the slice notation: two indices\nseparated by a colon.\n```text\n\n>>> word[4]\n'A'\n>>> word[0:2]\n'He'\n>>> word[2:4]\n'lp'\n```\nUnlike a C string, Python strings cannot be changed. Assigning to an\nindexed position in the string results in an error:\n```text\n\n>>> word[0] = 'x'\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: object doesn't support item assignment\n>>> word[:1] = 'Splat'\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: object doesn't support slice assignment\n```\nHowever, creating a new string with the combined content is easy and\nefficient:\n```text\n\n>>> 'x' + word[1:]\n'xelpA'\n>>> 'Splat' + word[4]\n'SplatA'\n```\nSlice indices have useful defaults; an omitted first index defaults to\nzero, an omitted second index defaults to the size of the string being\nsliced.\n```text\n\n>>> word[:2] # The first two characters\n'He'\n>>> word[2:] # All but the first two characters\n'lpA'\n```\nHere's a useful invariant of slice operations:\n`s[:i] + s[i:]` equals `s`.\n```text\n\n>>> word[:2] + word[2:]\n'HelpA'\n>>> word[:3] + word[3:]\n'HelpA'\n```\nDegenerate slice indices are handled gracefully: an index that is too\nlarge is replaced by the string size, an upper bound smaller than the\nlower bound returns an empty string.\n```text\n\n>>> word[1:100]\n'elpA'\n>>> word[10:]\n''\n>>> word[2:1]\n''\n```\nIndices may be negative numbers, to start counting from the right.\nFor example:\n```text\n\n>>> word[-1] # The last character\n'A'\n>>> word[-2] # The last-but-one character\n'p'\n>>> word[-2:] # The last two characters\n'pA'\n>>> word[:-2] # All but the last two characters\n'Hel'\n```\nBut note that -0 is really the same as 0, so it does not count from\nthe right!\n```text\n\n>>> word[-0] # (since -0 equals 0)\n'H'\n```\nOut-of-range negative slice indices are truncated, but don't try this\nfor single-element (non-slice) indices:\n```text\n\n>>> word[-100:]\n'HelpA'\n>>> word[-10] # error\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nIndexError: string index out of range\n```\nThe best way to remember how slices work is to think of the indices as\npointing between characters, with the left edge of the first\ncharacter numbered 0. Then the right edge of the last character of a\nstring of n characters has index n, for example:\n```text\n\n+---+---+---+---+---+\n| H | e | l | p | A |\n+---+---+---+---+---+\n0 1 2 3 4 5\n-5 -4 -3 -2 -1\n```\nThe first row of numbers gives the position of the indices 0...5 in\nthe string; the second row gives the corresponding negative indices.\nThe slice from i to j consists of all characters between\nthe edges labeled i and j, respectively.\nFor non-negative indices, the length of a slice is the difference of\nthe indices, if both are within bounds. For example, the length of\n`word[1:3]` is 2.\nThe built-in function len() returns the length of a string:\n```text\n\n>>> s = 'supercalifragilisticexpialidocious'\n>>> len(s)\n34\n```\n## 3.1.3 Unicode Strings\nStarting with Python 2.0 a new data type for storing text data is\navailable to the programmer: the Unicode object. It can be used to\nstore and manipulate Unicode data (see http://www.unicode.org/)\nand integrates well with the existing string objects providing\nauto-conversions where necessary.\nUnicode has the advantage of providing one ordinal for every character\nin every script used in modern and ancient texts. Previously, there\nwere only 256 possible ordinals for script characters and texts were\ntypically bound to a code page which mapped the ordinals to script\ncharacters. This lead to very much confusion especially with respect\nto internationalization (usually written as \"i18n\" --\n\"i\" + 18 characters + \"n\") of software. Unicode\nsolves these problems by defining one code page for all scripts.\nCreating Unicode strings in Python is just as simple as creating\nnormal strings:\n```text\n\n>>> u'Hello World !'\nu'Hello World !'\n```\nThe small \"u\" in front of the quote indicates that an\nUnicode string is supposed to be created. If you want to include\nspecial characters in the string, you can do so by using the Python\nUnicode-Escape encoding. The following example shows how:\n```text\n\n>>> u'Hello\\u0020World !'\nu'Hello World !'\n```\nThe escape sequence `\\u0020` indicates to insert the Unicode\ncharacter with the ordinal value 0x0020 (the space character) at the\ngiven position.\nOther characters are interpreted by using their respective ordinal\nvalues directly as Unicode ordinals. If you have literal strings\nin the standard Latin-1 encoding that is used in many Western countries,\nyou will find it convenient that the lower 256 characters\nof Unicode are the same as the 256 characters of Latin-1.\nFor experts, there is also a raw mode just like the one for normal\nstrings. You have to prefix the opening quote with 'ur' to have\nPython use the Raw-Unicode-Escape encoding. It will only apply\nthe above `\\uXXXX` conversion if there is an uneven number of\nbackslashes in front of the small 'u'.\n```text\n\n>>> ur'Hello\\u0020World !'\nu'Hello World !'\n>>> ur'Hello\\\\u0020World !'\nu'Hello\\\\\\\\u0020World !'\n```\nThe raw mode is most useful when you have to enter lots of\nbackslashes, as can be necessary in regular expressions.\nApart from these standard encodings, Python provides a whole set of\nother ways of creating Unicode strings on the basis of a known\nencoding.\nThe built-in function unicode()provides\naccess to all registered Unicode codecs (COders and DECoders). Some of\nthe more well known encodings which these codecs can convert are\nLatin-1, ASCII, UTF-8, and UTF-16.\nThe latter two are variable-length encodings that store each Unicode\ncharacter in one or more bytes. The default encoding is\nnormally set to ASCII, which passes through characters in the range\n0 to 127 and rejects any other characters with an error.\nWhen a Unicode string is printed, written to a file, or converted\nwith str(), conversion takes place using this default encoding.\n```text\n\n>>> u\"abc\"\nu'abc'\n>>> str(u\"abc\")\n'abc'\n>>> u\"\"\nu'\\xe4\\xf6\\xfc'\n>>> str(u\"\")\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nUnicodeError: ASCII encoding error: ordinal not in range(128)\n```\nTo convert a Unicode string into an 8-bit string using a specific\nencoding, Unicode objects provide an encode() method\nthat takes one argument, the name of the encoding. Lowercase names\nfor encodings are preferred.\n```text\n\n>>> u\"\".encode('utf-8')\n'\\xc3\\xa4\\xc3\\xb6\\xc3\\xbc'\n```\nIf you have data in a specific encoding and want to produce a\ncorresponding Unicode string from it, you can use the\nunicode() function with the encoding name as the second\nargument.\n```text\n\n>>> unicode('\\xc3\\xa4\\xc3\\xb6\\xc3\\xbc', 'utf-8')\nu'\\xe4\\xf6\\xfc'\n```\n## 3.1.4 Lists\nPython knows a number of compound data types, used to group\ntogether other values. The most versatile is the list, which\ncan be written as a list of comma-separated values (items) between\nsquare brackets. List items need not all have the same type.\n```text\n\n>>> a = ['spam', 'eggs', 100, 1234]\n>>> a\n['spam', 'eggs', 100, 1234]\n```\nLike string indices, list indices start at 0, and lists can be sliced,\nconcatenated and so on:\n```text\n\n>>> a[0]\n'spam'\n>>> a[3]\n1234\n>>> a[-2]\n100\n>>> a[1:-1]\n['eggs', 100]\n>>> a[:2] + ['bacon', 2*2]\n['spam', 'eggs', 'bacon', 4]\n>>> 3*a[:3] + ['Boe!']\n['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']\n```\nUnlike strings, which are immutable, it is possible to change\nindividual elements of a list:\n```text\n\n>>> a\n['spam', 'eggs', 100, 1234]\n>>> a[2] = a[2] + 23\n>>> a\n['spam', 'eggs', 123, 1234]\n```\nAssignment to slices is also possible, and this can even change the size\nof the list:\n```text\n\n>>> # Replace some items:\n... a[0:2] = [1, 12]\n>>> a\n[1, 12, 123, 1234]\n>>> # Remove some:\n... a[0:2] = []\n>>> a\n[123, 1234]\n>>> # Insert some:\n... a[1:1] = ['bletch', 'xyzzy']\n>>> a\n[123, 'bletch', 'xyzzy', 1234]\n>>> a[:0] = a # Insert (a copy of) itself at the beginning\n>>> a\n[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]\n```\nThe built-in function len() also applies to lists:\n```text\n\n>>> len(a)\n8\n```\nIt is possible to nest lists (create lists containing other lists),\nfor example:\n```text\n\n>>> q = [2, 3]\n>>> p = [1, q, 4]\n>>> len(p)\n3\n>>> p[1]\n[2, 3]\n>>> p[1][0]\n2\n>>> p[1].append('xtra') # See section 5.1\n>>> p\n[1, [2, 3, 'xtra'], 4]\n>>> q\n[2, 3, 'xtra']\n```\nNote that in the last example, `p[1]` and `q` really refer to\nthe same object! We'll come back to object semantics later.\n# 3.2 First Steps Towards Programming\nOf course, we can use Python for more complicated tasks than adding\ntwo and two together. For instance, we can write an initial\nsub-sequence of the Fibonacci series as follows:\n```text\n\n>>> # Fibonacci series:\n... # the sum of two elements defines the next\n... a, b = 0, 1\n>>> while b < 10:\n... print b\n... a, b = b, a+b\n...\n1\n1\n2\n3\n5\n8\n```\nThis example introduces several new features.\n- The first line contains a multiple assignment: the variables\n`a` and `b` simultaneously get the new values 0 and 1. On the\nlast line this is used again, demonstrating that the expressions on\nthe right-hand side are all evaluated first before any of the\nassignments take place. The right-hand side expressions are evaluated\nfrom the left to the right.\n- The while loop executes as long as the condition (here:\n`b < 10`) remains true. In Python, like in C, any non-zero\ninteger value is true; zero is false. The condition may also be a\nstring or list value, in fact any sequence; anything with a non-zero\nlength is true, empty sequences are false. The test used in the\nexample is a simple comparison. The standard comparison operators are\nwritten the same as in C: `<` (less than), `>` (greater than),\n`==` (equal to), `<=` (less than or equal to),\n`>=` (greater than or equal to) and `!=` (not equal to).\n- The body of the loop is indented: indentation is Python's\nway of grouping statements. Python does not (yet!) provide an\nintelligent input line editing facility, so you have to type a tab or\nspace(s) for each indented line. In practice you will prepare more\ncomplicated input for Python with a text editor; most text editors have\nan auto-indent facility. When a compound statement is entered\ninteractively, it must be followed by a blank line to indicate\ncompletion (since the parser cannot guess when you have typed the last\nline). Note that each line within a basic block must be indented by\nthe same amount.\n- The print statement writes the value of the expression(s) it is\ngiven. It differs from just writing the expression you want to write\n(as we did earlier in the calculator examples) in the way it handles\nmultiple expressions and strings. Strings are printed without quotes,\nand a space is inserted between items, so you can format things nicely,\nlike this:\n```text\n\n>>> i = 256*256\n>>> print 'The value of i is', i\nThe value of i is 65536\n```\nA trailing comma avoids the newline after the output:\n```text\n\n>>> a, b = 0, 1\n>>> while b < 1000:\n... print b,\n... a, b = b, a+b\n...\n1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987\n```\nNote that the interpreter inserts a newline before it prints the next\nprompt if the last line was not completed.", "python_version": "2.2", "length": 18752, "url": "https://docs.python.org/2.2/tut/node5.html"} {"title": "4. More Control Flow Tools", "text": "node5.html | tut.html | node7.html | Python Tutorial | node2.html\n---\n- 4.1 if Statements (#SECTION006100000000000000000)\n 4.2 for Statements (#SECTION006200000000000000000)\n 4.3 The range() Function (#SECTION006300000000000000000)\n 4.4 break and continue Statements, and\n else Clauses on Loops (#SECTION006400000000000000000)\n 4.5 pass Statements (#SECTION006500000000000000000)\n 4.6 Defining Functions (#SECTION006600000000000000000)\n 4.7 More on Defining Functions (#SECTION006700000000000000000)\n - 4.7.1 Default Argument Values (#SECTION006710000000000000000)\n 4.7.2 Keyword Arguments (#SECTION006720000000000000000)\n 4.7.3 Arbitrary Argument Lists (#SECTION006730000000000000000)\n 4.7.4 Lambda Forms (#SECTION006740000000000000000)\n 4.7.5 Documentation Strings (#SECTION006750000000000000000)\n---\n# 4. More Control Flow Tools\nBesides the while statement just introduced, Python knows\nthe usual control flow statements known from other languages, with\nsome twists.\n# 4.1 if Statements\nPerhaps the most well-known statement type is the\nif statement. For example:\n```text\n\n>>> x = int(raw_input(\"Please enter an integer: \"))\n>>> if x < 0:\n... x = 0\n... print 'Negative changed to zero'\n... elif x == 0:\n... print 'Zero'\n... elif x == 1:\n... print 'Single'\n... else:\n... print 'More'\n...\n```\nThere can be zero or more elif parts, and the\nelse part is optional. The keyword `elif' is\nshort for `else if', and is useful to avoid excessive indentation. An\nif ... elif ... elif ... sequence\nis a substitute for the switch or\ncase statements found in other languages.\n# 4.2 for Statements\nThe forstatement in Python differs a bit from\nwhat you may be used to in C or Pascal. Rather than always\niterating over an arithmetic progression of numbers (like in Pascal),\nor giving the user the ability to define both the iteration step and\nhalting condition (as C), Python's\nforstatement iterates over the items of any\nsequence (a list or a string), in the order that they appear in\nthe sequence. For example (no pun intended):\n```text\n\n>>> # Measure some strings:\n... a = ['cat', 'window', 'defenestrate']\n>>> for x in a:\n... print x, len(x)\n...\ncat 3\nwindow 6\ndefenestrate 12\n```\nIt is not safe to modify the sequence being iterated over in the loop\n(this can only happen for mutable sequence types, such as lists). If\nyou need to modify the list you are iterating over (for example, to\nduplicate selected items) you must iterate over a copy. The slice\nnotation makes this particularly convenient:\n```text\n\n>>> for x in a[:]: # make a slice copy of the entire list\n... if len(x) > 6: a.insert(0, x)\n...\n>>> a\n['defenestrate', 'cat', 'window', 'defenestrate']\n```\n# 4.3 The range() Function\nIf you do need to iterate over a sequence of numbers, the built-in\nfunction range() comes in handy. It generates lists\ncontaining arithmetic progressions:\n```text\n\n>>> range(10)\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\nThe given end point is never part of the generated list;\n`range(10)` generates a list of 10 values, exactly the legal\nindices for items of a sequence of length 10. It is possible to let\nthe range start at another number, or to specify a different increment\n(even negative; sometimes this is called the `step'):\n```text\n\n>>> range(5, 10)\n[5, 6, 7, 8, 9]\n>>> range(0, 10, 3)\n[0, 3, 6, 9]\n>>> range(-10, -100, -30)\n[-10, -40, -70]\n```\nTo iterate over the indices of a sequence, combine\nrange() and len() as follows:\n```text\n\n>>> a = ['Mary', 'had', 'a', 'little', 'lamb']\n>>> for i in range(len(a)):\n... print i, a[i]\n...\n0 Mary\n1 had\n2 a\n3 little\n4 lamb\n```\n# 4.4 break and continue Statements, and\nelse Clauses on Loops\nThe break statement, like in C, breaks out of the smallest\nenclosing for or while loop.\nThe continue statement, also borrowed from C, continues\nwith the next iteration of the loop.\nLoop statements may have an `else` clause; it is executed when\nthe loop terminates through exhaustion of the list (with\nfor) or when the condition becomes false (with\nwhile), but not when the loop is terminated by a\nbreak statement. This is exemplified by the following loop,\nwhich searches for prime numbers:\n```text\n\n>>> for n in range(2, 10):\n... for x in range(2, n):\n... if n % x == 0:\n... print n, 'equals', x, '*', n/x\n... break\n... else:\n... # loop fell through without finding a factor\n... print n, 'is a prime number'\n...\n2 is a prime number\n3 is a prime number\n4 equals 2 * 2\n5 is a prime number\n6 equals 2 * 3\n7 is a prime number\n8 equals 2 * 4\n9 equals 3 * 3\n```\n# 4.5 pass Statements\nThe pass statement does nothing.\nIt can be used when a statement is required syntactically but the\nprogram requires no action.\nFor example:\n```text\n\n>>> while 1:\n... pass # Busy-wait for keyboard interrupt\n...\n```\n# 4.6 Defining Functions\nWe can create a function that writes the Fibonacci series to an\narbitrary boundary:\n```text\n\n>>> def fib(n): # write Fibonacci series up to n\n... \"\"\"Print a Fibonacci series up to n.\"\"\"\n... a, b = 0, 1\n... while b < n:\n... print b,\n... a, b = b, a+b\n...\n>>> # Now call the function we just defined:\n... fib(2000)\n1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597\n```\nThe keyword def introduces a function definition. It\nmust be followed by the function name and the parenthesized list of\nformal parameters. The statements that form the body of the function\nstart at the next line, and must be indented. The first statement of\nthe function body can optionally be a string literal; this string\nliteral is the function's documentation\nstring, or docstring.\nThere are tools which use docstrings to automatically produce online\nor printed documentation, or to let the user interactively browse\nthrough code; it's good practice to include docstrings in code that\nyou write, so try to make a habit of it.\nThe execution of a function introduces a new symbol table used\nfor the local variables of the function. More precisely, all variable\nassignments in a function store the value in the local symbol table;\nwhereas variable references first look in the local symbol table, then\nin the global symbol table, and then in the table of built-in names.\nThus, global variables cannot be directly assigned a value within a\nfunction (unless named in a global statement), although\nthey may be referenced.\nThe actual parameters (arguments) to a function call are introduced in\nthe local symbol table of the called function when it is called; thus,\narguments are passed using call by value (where the\nvalue is always an object reference, not the value of\nthe object).4.1 (#foot1349) When a function calls another function, a new local symbol table is\ncreated for that call.\nA function definition introduces the function name in the current\nsymbol table. The value of the function name\nhas a type that is recognized by the interpreter as a user-defined\nfunction. This value can be assigned to another name which can then\nalso be used as a function. This serves as a general renaming\nmechanism:\n```text\n\n>>> fib\n\n>>> f = fib\n>>> f(100)\n1 1 2 3 5 8 13 21 34 55 89\n```\nYou might object that `fib` is not a function but a procedure. In\nPython, like in C, procedures are just functions that don't return a\nvalue. In fact, technically speaking, procedures do return a value,\nalbeit a rather boring one. This value is called `None` (it's a\nbuilt-in name). Writing the value `None` is normally suppressed by\nthe interpreter if it would be the only value written. You can see it\nif you really want to:\n```text\n\n>>> print fib(0)\nNone\n```\nIt is simple to write a function that returns a list of the numbers of\nthe Fibonacci series, instead of printing it:\n```text\n\n>>> def fib2(n): # return Fibonacci series up to n\n... \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n... result = []\n... a, b = 0, 1\n... while b < n:\n... result.append(b) # see below\n... a, b = b, a+b\n... return result\n...\n>>> f100 = fib2(100) # call it\n>>> f100 # write the result\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n```\nThis example, as usual, demonstrates some new Python features:\n- The return statement returns with a value from a function.\nreturn without an expression argument returns `None`.\nFalling off the end of a procedure also returns `None`.\n- The statement `result.append(b)` calls a method of the list\nobject `result`. A method is a function that `belongs' to an\nobject and is named `obj.methodname`, where `obj` is some\nobject (this may be an expression), and `methodname` is the name\nof a method that is defined by the object's type. Different types\ndefine different methods. Methods of different types may have the\nsame name without causing ambiguity. (It is possible to define your\nown object types and methods, using classes, as discussed later\nin this tutorial.)\nThe method append() shown in the example, is defined for\nlist objects; it adds a new element at the end of the list. In this\nexample it is equivalent to \"result = result + [b]\", but more\nefficient.\n# 4.7 More on Defining Functions\nIt is also possible to define functions with a variable number of\narguments. There are three forms, which can be combined.\n## 4.7.1 Default Argument Values\nThe most useful form is to specify a default value for one or more\narguments. This creates a function that can be called with fewer\narguments than it is defined\n```text\n\ndef ask_ok(prompt, retries=4, complaint='Yes or no, please!'):\nwhile 1:\nok = raw_input(prompt)\nif ok in ('y', 'ye', 'yes'): return 1\nif ok in ('n', 'no', 'nop', 'nope'): return 0\nretries = retries - 1\nif retries < 0: raise IOError, 'refusenik user'\nprint complaint\n```\nThis function can be called either like this:\n`ask_ok('Do you really want to quit?')` or like this:\n`ask_ok('OK to overwrite the file?', 2)`.\nThe default values are evaluated at the point of function definition\nin the defining scope, so that\n```text\n\ni = 5\n\ndef f(arg=i):\nprint arg\n\ni = 6\nf()\n```\nwill print `5`.\nImportant warning: The default value is evaluated only once.\nThis makes a difference when the default is a mutable object such as a\nlist or dictionary. For example, the following function accumulates\nthe arguments passed to it on subsequent calls:\n```text\n\ndef f(a, L=[]):\nL.append(a)\nreturn L\n\nprint f(1)\nprint f(2)\nprint f(3)\n```\nThis will print\n```text\n\n[1]\n[1, 2]\n[1, 2, 3]\n```\nIf you don't want the default to be shared between subsequent calls,\nyou can write the function like this instead:\n```text\n\ndef f(a, L=None):\nif L is None:\nL = []\nL.append(a)\nreturn L\n```\n## 4.7.2 Keyword Arguments\nFunctions can also be called using\nkeyword arguments of the form \"keyword = value\". For\ninstance, the following function:\n```text\n\ndef parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):\nprint \"-- This parrot wouldn't\", action,\nprint \"if you put\", voltage, \"Volts through it.\"\nprint \"-- Lovely plumage, the\", type\nprint \"-- It's\", state, \"!\"\n```\ncould be called in any of the following ways:\n```text\n\nparrot(1000)\nparrot(action = 'VOOOOOM', voltage = 1000000)\nparrot('a thousand', state = 'pushing up the daisies')\nparrot('a million', 'bereft of life', 'jump')\n```\nbut the following calls would all be invalid:\n```text\n\nparrot() # required argument missing\nparrot(voltage=5.0, 'dead') # non-keyword argument following keyword\nparrot(110, voltage=220) # duplicate value for argument\nparrot(actor='John Cleese') # unknown keyword\n```\nIn general, an argument list must have any positional arguments\nfollowed by any keyword arguments, where the keywords must be chosen\nfrom the formal parameter names. It's not important whether a formal\nparameter has a default value or not. No argument may receive a\nvalue more than once -- formal parameter names corresponding to\npositional arguments cannot be used as keywords in the same calls.\nHere's an example that fails due to this restriction:\n```text\n\n>>> def function(a):\n... pass\n...\n>>> function(0, a=0)\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: keyword parameter redefined\n```\nWhen a final formal parameter of the form `** name` is\npresent, it receives a dictionary containing all keyword arguments\nwhose keyword doesn't correspond to a formal parameter. This may be\ncombined with a formal parameter of the form\n`* name` (described in the next subsection) which receives a\ntuple containing the positional arguments beyond the formal parameter\nlist. (`* name` must occur before `** name`.)\nFor example, if we define a function like this:\n```text\n\ndef cheeseshop(kind, *arguments, **keywords):\nprint \"-- Do you have any\", kind, '?'\nprint \"-- I'm sorry, we're all out of\", kind\nfor arg in arguments: print arg\nprint '-'*40\nfor kw in keywords.keys(): print kw, ':', keywords[kw]\n```\nIt could be called like this:\n```text\n\ncheeseshop('Limburger', \"It's very runny, sir.\",\n\"It's really very, VERY runny, sir.\",\nclient='John Cleese',\nshopkeeper='Michael Palin',\nsketch='Cheese Shop Sketch')\n```\nand of course it would print:\n```text\n\n-- Do you have any Limburger ?\n-- I'm sorry, we're all out of Limburger\nIt's very runny, sir.\nIt's really very, VERY runny, sir.\n----------------------------------------\nclient : John Cleese\nshopkeeper : Michael Palin\nsketch : Cheese Shop Sketch\n```\n## 4.7.3 Arbitrary Argument Lists\nFinally, the least frequently used option is to specify that a\nfunction can be called with an arbitrary number of arguments. These\narguments will be wrapped up in a tuple. Before the variable number\nof arguments, zero or more normal arguments may occur.\n```text\n\ndef fprintf(file, format, *args):\nfile.write(format % args)\n```\n## 4.7.4 Lambda Forms\nBy popular demand, a few features commonly found in functional\nprogramming languages and Lisp have been added to Python. With the\nlambda keyword, small anonymous functions can be created.\nHere's a function that returns the sum of its two arguments:\n\"lambda a, b: a+b\". Lambda forms can be used wherever function\nobjects are required. They are syntactically restricted to a single\nexpression. Semantically, they are just syntactic sugar for a normal\nfunction definition. Like nested function definitions, lambda forms\ncan reference variables from the containing scope:\n```text\n\n>>> def make_incrementor(n):\n... return lambda x: x + n\n...\n>>> f = make_incrementor(42)\n>>> f(0)\n42\n>>> f(1)\n43\n```\n## 4.7.5 Documentation Strings\nThere are emerging conventions about the content and formatting of\ndocumentation strings.\nThe first line should always be a short, concise summary of the\nobject's purpose. For brevity, it should not explicitly state the\nobject's name or type, since these are available by other means\n(except if the name happens to be a verb describing a function's\noperation). This line should begin with a capital letter and end with\na period.\nIf there are more lines in the documentation string, the second line\nshould be blank, visually separating the summary from the rest of the\ndescription. The following lines should be one or more paragraphs\ndescribing the object's calling conventions, its side effects, etc.\nThe Python parser does not strip indentation from multi-line string\nliterals in Python, so tools that process documentation have to strip\nindentation if desired. This is done using the following convention.\nThe first non-blank line after the first line of the string\ndetermines the amount of indentation for the entire documentation\nstring. (We can't use the first line since it is generally adjacent\nto the string's opening quotes so its indentation is not apparent in\nthe string literal.) Whitespace ``equivalent'' to this indentation is\nthen stripped from the start of all lines of the string. Lines that\nare indented less should not occur, but if they occur all their\nleading whitespace should be stripped. Equivalence of whitespace\nshould be tested after expansion of tabs (to 8 spaces, normally).\nHere is an example of a multi-line docstring:\n```text\n\n>>> def my_function():\n... \"\"\"Do nothing, but document it.\n...\n... No, really, it doesn't do anything.\n... \"\"\"\n... pass\n...\n>>> print my_function.__doc__\nDo nothing, but document it.\n\nNo, really, it doesn't do anything.\n```", "python_version": "2.2", "length": 16013, "url": "https://docs.python.org/2.2/tut/node6.html"} {"title": "5. Data Structures", "text": "node6.html | tut.html | node8.html | Python Tutorial | node2.html\n---\n- 5.1 More on Lists (#SECTION007100000000000000000)\n - 5.1.1 Using Lists as Stacks (#SECTION007110000000000000000)\n 5.1.2 Using Lists as Queues (#SECTION007120000000000000000)\n 5.1.3 Functional Programming Tools (#SECTION007130000000000000000)\n 5.1.4 List Comprehensions (#SECTION007140000000000000000)\n 5.2 The del statement (#SECTION007200000000000000000)\n 5.3 Tuples and Sequences (#SECTION007300000000000000000)\n 5.4 Dictionaries (#SECTION007400000000000000000)\n 5.5 More on Conditions (#SECTION007500000000000000000)\n 5.6 Comparing Sequences and Other Types (#SECTION007600000000000000000)\n---\n# 5. Data Structures\nThis chapter describes some things you've learned about already in\nmore detail, and adds some new things as well.\n# 5.1 More on Lists\nThe list data type has some more methods. Here are all of the methods\nof list objects:\n`append(x)`: Add an item to the end of the list;\nequivalent to `a[len(a):] = [x]`.\n`extend(L)`: Extend the list by appending all the items in the given list;\nequivalent to `a[len(a):] = L`.\n`insert(i, x)`: Insert an item at a given position. The first argument is the index of\nthe element before which to insert, so `a.insert(0, x)` inserts at\nthe front of the list, and `a.insert(len(a), x)` is equivalent to\n`a.append(x)`.\n`remove(x)`: Remove the first item from the list whose value is `x`.\nIt is an error if there is no such item.\n`pop( [ i ] )`: Remove the item at the given position in the list, and return it. If\nno index is specified, `a.pop()` returns the last item in the\nlist. The item is also removed from the list.\n`index(x)`: Return the index in the list of the first item whose value is `x`.\nIt is an error if there is no such item.\n`count(x)`: Return the number of times `x` appears in the list.\n`sort()`: Sort the items of the list, in place.\n`reverse()`: Reverse the elements of the list, in place.\nAn example that uses most of the list methods:\n```text\n\n>>> a = [66.6, 333, 333, 1, 1234.5]\n>>> print a.count(333), a.count(66.6), a.count('x')\n2 1 0\n>>> a.insert(2, -1)\n>>> a.append(333)\n>>> a\n[66.6, 333, -1, 333, 1, 1234.5, 333]\n>>> a.index(333)\n1\n>>> a.remove(333)\n>>> a\n[66.6, -1, 333, 1, 1234.5, 333]\n>>> a.reverse()\n>>> a\n[333, 1234.5, 1, 333, -1, 66.6]\n>>> a.sort()\n>>> a\n[-1, 1, 66.6, 333, 333, 1234.5]\n```\n## 5.1.1 Using Lists as Stacks\nThe list methods make it very easy to use a list as a stack, where the\nlast element added is the first element retrieved (``last-in,\nfirst-out''). To add an item to the top of the stack, use\nappend(). To retrieve an item from the top of the stack, use\npop() without an explicit index. For example:\n```text\n\n>>> stack = [3, 4, 5]\n>>> stack.append(6)\n>>> stack.append(7)\n>>> stack\n[3, 4, 5, 6, 7]\n>>> stack.pop()\n7\n>>> stack\n[3, 4, 5, 6]\n>>> stack.pop()\n6\n>>> stack.pop()\n5\n>>> stack\n[3, 4]\n```\n## 5.1.2 Using Lists as Queues\nYou can also use a list conveniently as a queue, where the first\nelement added is the first element retrieved (``first-in,\nfirst-out''). To add an item to the back of the queue, use\nappend(). To retrieve an item from the front of the queue,\nuse pop() with `0` as the index. For example:\n```text\n\n>>> queue = [\"Eric\", \"John\", \"Michael\"]\n>>> queue.append(\"Terry\") # Terry arrives\n>>> queue.append(\"Graham\") # Graham arrives\n>>> queue.pop(0)\n'Eric'\n>>> queue.pop(0)\n'John'\n>>> queue\n['Michael', 'Terry', 'Graham']\n```\n## 5.1.3 Functional Programming Tools\nThere are three built-in functions that are very useful when used with\nlists: filter(), map(), and reduce().\n\"filter(function, sequence)\" returns a sequence (of\nthe same type, if possible) consisting of those items from the\nsequence for which `function ( item )` is true. For\nexample, to compute some primes:\n```text\n\n>>> def f(x): return x % 2 != 0 and x % 3 != 0\n...\n>>> filter(f, range(2, 25))\n[5, 7, 11, 13, 17, 19, 23]\n```\n\"map(function, sequence)\" calls\n`function ( item )` for each of the sequence's items and\nreturns a list of the return values. For example, to compute some\ncubes:\n```text\n\n>>> def cube(x): return x*x*x\n...\n>>> map(cube, range(1, 11))\n[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]\n```\nMore than one sequence may be passed; the function must then have as\nmany arguments as there are sequences and is called with the\ncorresponding item from each sequence (or `None` if some sequence\nis shorter than another). If `None` is passed for the function,\na function returning its argument(s) is substituted.\nCombining these two special cases, we see that\n\"map(None, list1, list2)\" is a convenient way of\nturning a pair of lists into a list of pairs. For example:\n```text\n\n>>> seq = range(8)\n>>> def square(x): return x*x\n...\n>>> map(None, seq, map(square, seq))\n[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]\n```\n\"reduce(func, sequence)\" returns a single value\nconstructed by calling the binary function func on the first two\nitems of the sequence, then on the result and the next item, and so\non. For example, to compute the sum of the numbers 1 through 10:\n```text\n\n>>> def add(x,y): return x+y\n...\n>>> reduce(add, range(1, 11))\n55\n```\nIf there's only one item in the sequence, its value is returned; if\nthe sequence is empty, an exception is raised.\nA third argument can be passed to indicate the starting value. In this\ncase the starting value is returned for an empty sequence, and the\nfunction is first applied to the starting value and the first sequence\nitem, then to the result and the next item, and so on. For example,\n```text\n\n>>> def sum(seq):\n... def add(x,y): return x+y\n... return reduce(add, seq, 0)\n...\n>>> sum(range(1, 11))\n55\n>>> sum([])\n0\n```\n## 5.1.4 List Comprehensions\nList comprehensions provide a concise way to create lists without resorting\nto use of map(), filter() and/or lambda.\nThe resulting list definition tends often to be clearer than lists built\nusing those constructs. Each list comprehension consists of an expression\nfollowing by a for clause, then zero or more for or\nif clauses. The result will be a list resulting from evaluating\nthe expression in the context of the for and if clauses\nwhich follow it. If the expression would evaluate to a tuple, it must be\nparenthesized.\n```text\n\n>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']\n>>> [weapon.strip() for weapon in freshfruit]\n['banana', 'loganberry', 'passion fruit']\n>>> vec = [2, 4, 6]\n>>> [3*x for x in vec]\n[6, 12, 18]\n>>> [3*x for x in vec if x > 3]\n[12, 18]\n>>> [3*x for x in vec if x < 2]\n[]\n>>> [{x: x**2} for x in vec]\n[{2: 4}, {4: 16}, {6: 36}]\n>>> [[x,x**2] for x in vec]\n[[2, 4], [4, 16], [6, 36]]\n>>> [x, x**2 for x in vec] # error - parens required for tuples\nFile \"\", line 1, in ?\n[x, x**2 for x in vec]\n^\nSyntaxError: invalid syntax\n>>> [(x, x**2) for x in vec]\n[(2, 4), (4, 16), (6, 36)]\n>>> vec1 = [2, 4, 6]\n>>> vec2 = [4, 3, -9]\n>>> [x*y for x in vec1 for y in vec2]\n[8, 6, -18, 16, 12, -36, 24, 18, -54]\n>>> [x+y for x in vec1 for y in vec2]\n[6, 5, -7, 8, 7, -5, 10, 9, -3]\n>>> [vec1[i]*vec2[i] for i in range(len(vec1))]\n[8, 12, -54]\n```\n# 5.2 The del statement\nThere is a way to remove an item from a list given its index instead\nof its value: the del statement. This can also be used to\nremove slices from a list (which we did earlier by assignment of an\nempty list to the slice). For example:\n```text\n\n>>> a\n[-1, 1, 66.6, 333, 333, 1234.5]\n>>> del a[0]\n>>> a\n[1, 66.6, 333, 333, 1234.5]\n>>> del a[2:4]\n>>> a\n[1, 66.6, 1234.5]\n```\ndel can also be used to delete entire variables:\n```text\n\n>>> del a\n```\nReferencing the name `a` hereafter is an error (at least until\nanother value is assigned to it). We'll find other uses for\ndel later.\n# 5.3 Tuples and Sequences\nWe saw that lists and strings have many common properties, such as\nindexing and slicing operations. They are two examples of\nsequence data types. Since Python is an evolving language,\nother sequence data types may be added. There is also another\nstandard sequence data type: the tuple.\nA tuple consists of a number of values separated by commas, for\ninstance:\n```text\n\n>>> t = 12345, 54321, 'hello!'\n>>> t[0]\n12345\n>>> t\n(12345, 54321, 'hello!')\n>>> # Tuples may be nested:\n... u = t, (1, 2, 3, 4, 5)\n>>> u\n((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))\n```\nAs you see, on output tuples are alway enclosed in parentheses, so\nthat nested tuples are interpreted correctly; they may be input with\nor without surrounding parentheses, although often parentheses are\nnecessary anyway (if the tuple is part of a larger expression).\nTuples have many uses. For example: (x, y) coordinate pairs, employee\nrecords from a database, etc. Tuples, like strings, are immutable: it\nis not possible to assign to the individual items of a tuple (you can\nsimulate much of the same effect with slicing and concatenation,\nthough). It is also possible to create tuples which contain mutable\nobjects, such as lists.\nA special problem is the construction of tuples containing 0 or 1\nitems: the syntax has some extra quirks to accommodate these. Empty\ntuples are constructed by an empty pair of parentheses; a tuple with\none item is constructed by following a value with a comma\n(it is not sufficient to enclose a single value in parentheses).\nUgly, but effective. For example:\n```text\n\n>>> empty = ()\n>>> singleton = 'hello', # <-- note trailing comma\n>>> len(empty)\n0\n>>> len(singleton)\n1\n>>> singleton\n('hello',)\n```\nThe statement `t = 12345, 54321, 'hello!'` is an example of\ntuple packing: the values `12345`, `54321` and\n`'hello!'` are packed together in a tuple. The reverse operation\nis also possible:\n```text\n\n>>> x, y, z = t\n```\nThis is called, appropriately enough, sequence unpacking.\nSequence unpacking requires that the list of variables on the left\nhave the same number of elements as the length of the sequence. Note\nthat multiple assignment is really just a combination of tuple packing\nand sequence unpacking!\nThere is a small bit of asymmetry here: packing multiple values\nalways creates a tuple, and unpacking works for any sequence.\n# 5.4 Dictionaries\nAnother useful data type built into Python is the dictionary.\nDictionaries are sometimes found in other languages as ``associative\nmemories'' or ``associative arrays''. Unlike sequences, which are\nindexed by a range of numbers, dictionaries are indexed by keys,\nwhich can be any immutable type; strings and numbers can always be\nkeys. Tuples can be used as keys if they contain only strings,\nnumbers, or tuples; if a tuple contains any mutable object either\ndirectly or indirectly, it cannot be used as a key. You can't use\nlists as keys, since lists can be modified in place using their\nappend() and extend() methods, as well as slice and\nindexed assignments.\nIt is best to think of a dictionary as an unordered set of\nkey: value pairs, with the requirement that the keys are unique\n(within one dictionary).\nA pair of braces creates an empty dictionary: `{}`.\nPlacing a comma-separated list of key:value pairs within the\nbraces adds initial key:value pairs to the dictionary; this is also the\nway dictionaries are written on output.\nThe main operations on a dictionary are storing a value with some key\nand extracting the value given the key. It is also possible to delete\na key:value pair\nwith `del`.\nIf you store using a key that is already in use, the old value\nassociated with that key is forgotten. It is an error to extract a\nvalue using a non-existent key.\nThe `keys()` method of a dictionary object returns a list of all\nthe keys used in the dictionary, in random order (if you want it\nsorted, just apply the `sort()` method to the list of keys). To\ncheck whether a single key is in the dictionary, use the\n`has_key()` method of the dictionary.\nHere is a small example using a dictionary:\n```text\n\n>>> tel = {'jack': 4098, 'sape': 4139}\n>>> tel['guido'] = 4127\n>>> tel\n{'sape': 4139, 'guido': 4127, 'jack': 4098}\n>>> tel['jack']\n4098\n>>> del tel['sape']\n>>> tel['irv'] = 4127\n>>> tel\n{'guido': 4127, 'irv': 4127, 'jack': 4098}\n>>> tel.keys()\n['guido', 'irv', 'jack']\n>>> tel.has_key('guido')\n1\n```\n# 5.5 More on Conditions\nThe conditions used in `while` and `if` statements above can\ncontain other operators besides comparisons.\nThe comparison operators `in` and `not in` check whether a value\noccurs (does not occur) in a sequence. The operators `is` and\n`is not` compare whether two objects are really the same object; this\nonly matters for mutable objects like lists. All comparison operators\nhave the same priority, which is lower than that of all numerical\noperators.\nComparisons can be chained. For example, `a < b == c` tests\nwhether `a` is less than `b` and moreover `b` equals\n`c`.\nComparisons may be combined by the Boolean operators `and` and\n`or`, and the outcome of a comparison (or of any other Boolean\nexpression) may be negated with `not`. These all have lower\npriorities than comparison operators again; between them, `not` has\nthe highest priority, and `or` the lowest, so that\n`A and not B or C` is equivalent to `(A and (not B)) or C`. Of\ncourse, parentheses can be used to express the desired composition.\nThe Boolean operators `and` and `or` are so-called\nshortcut operators: their arguments are evaluated from left to\nright, and evaluation stops as soon as the outcome is determined.\nE.g., if `A` and `C` are true but `B` is false, `A\nand B and C` does not evaluate the expression C. In general, the\nreturn value of a shortcut operator, when used as a general value and\nnot as a Boolean, is the last evaluated argument.\nIt is possible to assign the result of a comparison or other Boolean\nexpression to a variable. For example,\n```text\n\n>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n>>> non_null = string1 or string2 or string3\n>>> non_null\n'Trondheim'\n```\nNote that in Python, unlike C, assignment cannot occur inside expressions.\nC programmers may grumble about this, but it avoids a common class of\nproblems encountered in C programs: typing `=` in an expression when\n`==` was intended.\n# 5.6 Comparing Sequences and Other Types\nSequence objects may be compared to other objects with the same\nsequence type. The comparison uses lexicographical ordering:\nfirst the first two items are compared, and if they differ this\ndetermines the outcome of the comparison; if they are equal, the next\ntwo items are compared, and so on, until either sequence is exhausted.\nIf two items to be compared are themselves sequences of the same type,\nthe lexicographical comparison is carried out recursively. If all\nitems of two sequences compare equal, the sequences are considered\nequal. If one sequence is an initial sub-sequence of the other, the\nshorter sequence is the smaller (lesser) one. Lexicographical\nordering for strings uses the ASCII ordering for individual\ncharacters. Some examples of comparisons between sequences with the\nsame types:\n```text\n\n(1, 2, 3) < (1, 2, 4)\n[1, 2, 3] < [1, 2, 4]\n'ABC' < 'C' < 'Pascal' < 'Python'\n(1, 2, 3, 4) < (1, 2, 4)\n(1, 2) < (1, 2, -1)\n(1, 2, 3) == (1.0, 2.0, 3.0)\n(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)\n```\nNote that comparing objects of different types is legal. The outcome\nis deterministic but arbitrary: the types are ordered by their name.\nThus, a list is always smaller than a string, a string is always\nsmaller than a tuple, etc. Mixed numeric types are compared according\nto their numeric value, so 0 equals 0.0, etc.5.1 (#foot611)", "python_version": "2.2", "length": 15375, "url": "https://docs.python.org/2.2/tut/node7.html"} {"title": "6. Modules", "text": "node7.html | tut.html | node9.html | Python Tutorial | node2.html\n---\n- 6.1 More on Modules (#SECTION008100000000000000000)\n - 6.1.1 The Module Search Path (#SECTION008110000000000000000)\n 6.1.2 ``Compiled'' Python files (#SECTION008120000000000000000)\n 6.2 Standard Modules (#SECTION008200000000000000000)\n 6.3 The dir() Function (#SECTION008300000000000000000)\n 6.4 Packages (#SECTION008400000000000000000)\n - 6.4.1 Importing * From a Package (#SECTION008410000000000000000)\n 6.4.2 Intra-package References (#SECTION008420000000000000000)\n---\n# 6. Modules\nIf you quit from the Python interpreter and enter it again, the\ndefinitions you have made (functions and variables) are lost.\nTherefore, if you want to write a somewhat longer program, you are\nbetter off using a text editor to prepare the input for the interpreter\nand running it with that file as input instead. This is known as creating a\nscript. As your program gets longer, you may want to split it\ninto several files for easier maintenance. You may also want to use a\nhandy function that you've written in several programs without copying\nits definition into each program.\nTo support this, Python has a way to put definitions in a file and use\nthem in a script or in an interactive instance of the interpreter.\nSuch a file is called a module; definitions from a module can be\nimported into other modules or into the main module (the\ncollection of variables that you have access to in a script\nexecuted at the top level\nand in calculator mode).\nA module is a file containing Python definitions and statements. The\nfile name is the module name with the suffix .py appended. Within\na module, the module's name (as a string) is available as the value of\nthe global variable `__name__`. For instance, use your favorite text\neditor to create a file called fibo.py in the current directory\nwith the following contents:\n```text\n\n# Fibonacci numbers module\n\ndef fib(n): # write Fibonacci series up to n\na, b = 0, 1\nwhile b < n:\nprint b,\na, b = b, a+b\n\ndef fib2(n): # return Fibonacci series up to n\nresult = []\na, b = 0, 1\nwhile b < n:\nresult.append(b)\na, b = b, a+b\nreturn result\n```\nNow enter the Python interpreter and import this module with the\nfollowing command:\n```text\n\n>>> import fibo\n```\nThis does not enter the names of the functions defined in `fibo`\ndirectly in the current symbol table; it only enters the module name\n`fibo` there.\nUsing the module name you can access the functions:\n```text\n\n>>> fibo.fib(1000)\n1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987\n>>> fibo.fib2(100)\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n>>> fibo.__name__\n'fibo'\n```\nIf you intend to use a function often you can assign it to a local name:\n```text\n\n>>> fib = fibo.fib\n>>> fib(500)\n1 1 2 3 5 8 13 21 34 55 89 144 233 377\n```\n# 6.1 More on Modules\nA module can contain executable statements as well as function\ndefinitions.\nThese statements are intended to initialize the module.\nThey are executed only the\nfirst time the module is imported somewhere.6.1 (#foot632)\nEach module has its own private symbol table, which is used as the\nglobal symbol table by all functions defined in the module.\nThus, the author of a module can use global variables in the module\nwithout worrying about accidental clashes with a user's global\nvariables.\nOn the other hand, if you know what you are doing you can touch a\nmodule's global variables with the same notation used to refer to its\nfunctions,\n`modname.itemname`.\nModules can import other modules. It is customary but not required to\nplace all import statements at the beginning of a module (or\nscript, for that matter). The imported module names are placed in the\nimporting module's global symbol table.\nThere is a variant of the import statement that imports\nnames from a module directly into the importing module's symbol\ntable. For example:\n```text\n\n>>> from fibo import fib, fib2\n>>> fib(500)\n1 1 2 3 5 8 13 21 34 55 89 144 233 377\n```\nThis does not introduce the module name from which the imports are taken\nin the local symbol table (so in the example, `fibo` is not\ndefined).\nThere is even a variant to import all names that a module defines:\n```text\n\n>>> from fibo import *\n>>> fib(500)\n1 1 2 3 5 8 13 21 34 55 89 144 233 377\n```\nThis imports all names except those beginning with an underscore\n(`_`).\n## 6.1.1 The Module Search Path\nWhen a module named spam is imported, the interpreter searches\nfor a file named spam.py in the current directory,\nand then in the list of directories specified by\nthe environment variable PYTHONPATH. This has the same syntax as\nthe shell variable PATH, that is, a list of\ndirectory names. When PYTHONPATH is not set, or when the file\nis not found there, the search continues in an installation-dependent\ndefault path; on Unix, this is usually .:/usr/local/lib/python.\nActually, modules are searched in the list of directories given by the\nvariable `sys.path` which is initialized from the directory\ncontaining the input script (or the current directory),\nPYTHONPATH and the installation-dependent default. This allows\nPython programs that know what they're doing to modify or replace the\nmodule search path. Note that because the directory containing the\nscript being run is on the search path, it is important that the\nscript not have the same name as a standard module, or Python will\nattempt to load the script as a module when that module is imported.\nThis will generally be an error. See section 6.2 (node8.html#standardModules),\n``Standard Modules.'' for more information.\n## 6.1.2 ``Compiled'' Python files\nAs an important speed-up of the start-up time for short programs that\nuse a lot of standard modules, if a file called spam.pyc exists\nin the directory where spam.py is found, this is assumed to\ncontain an already-``byte-compiled'' version of the module spam.\nThe modification time of the version of spam.py used to create\nspam.pyc is recorded in spam.pyc, and the\n.pyc file is ignored if these don't match.\nNormally, you don't need to do anything to create the\nspam.pyc file. Whenever spam.py is successfully\ncompiled, an attempt is made to write the compiled version to\nspam.pyc. It is not an error if this attempt fails; if for any\nreason the file is not written completely, the resulting\nspam.pyc file will be recognized as invalid and thus ignored\nlater. The contents of the spam.pyc file are platform\nindependent, so a Python module directory can be shared by machines of\ndifferent architectures.\nSome tips for experts:\n- When the Python interpreter is invoked with the -O flag,\noptimized code is generated and stored in .pyo files.\nThe optimizer currently doesn't help much; it only removes\nassert statements and `SET_LINENO` instructions.\nWhen -O is used, all bytecode is optimized;\n`.pyc` files are ignored and `.py` files are compiled to\noptimized bytecode.\n- Passing two -O flags to the Python interpreter\n(-OO) will cause the bytecode compiler to perform\noptimizations that could in some rare cases result in malfunctioning\nprograms. Currently only `__doc__` strings are removed from the\nbytecode, resulting in more compact .pyo files. Since some\nprograms may rely on having these available, you should only use this\noption if you know what you're doing.\n- A program doesn't run any faster when it is read from a .pyc or\n.pyo file than when it is read from a .py file; the only\nthing that's faster about .pyc or .pyo files is the\nspeed with which they are loaded.\n- When a script is run by giving its name on the command line, the\nbytecode for the script is never written to a .pyc or\n.pyo file. Thus, the startup time of a script may be reduced\nby moving most of its code to a module and having a small bootstrap\nscript that imports that module. It is also possible to name a\n.pyc or .pyo file directly on the command line.\n- It is possible to have a file called spam.pyc (or\nspam.pyo when -O is used) without a file\nspam.py for the same module. This can be used to distribute a\nlibrary of Python code in a form that is moderately hard to reverse\nengineer.\n- The module compileallcan create\n.pyc files (or .pyo files when -O is used) for\nall modules in a directory.\n# 6.2 Standard Modules\nPython comes with a library of standard modules, described in a separate\ndocument, the Python Library Reference (../lib/lib.html)\n(``Library Reference'' hereafter). Some modules are built into the\ninterpreter; these provide access to operations that are not part of\nthe core of the language but are nevertheless built in, either for\nefficiency or to provide access to operating system primitives such as\nsystem calls. The set of such modules is a configuration option which\nalso dependson the underlying platform For example,\nthe amoeba module is only provided on systems that somehow\nsupport Amoeba primitives. One particular module deserves some\nattention: sys, which is built into every\nPython interpreter. The variables `sys.ps1` and\n`sys.ps2` define the strings used as primary and secondary\nprompts:\n```text\n\n>>> import sys\n>>> sys.ps1\n'>>> '\n>>> sys.ps2\n'... '\n>>> sys.ps1 = 'C> '\nC> print 'Yuck!'\nYuck!\nC>\n```\nThese two variables are only defined if the interpreter is in\ninteractive mode.\nThe variable `sys.path` is a list of strings that determine the\ninterpreter's search path for modules. It is initialized to a default\npath taken from the environment variable PYTHONPATH, or from\na built-in default if PYTHONPATH is not set. You can modify\nit using standard list operations:\n```text\n\n>>> import sys\n>>> sys.path.append('/ufs/guido/lib/python')\n```\n# 6.3 The dir() Function\nThe built-in function dir() is used to find out which names\na module defines. It returns a sorted list of strings:\n```text\n\n>>> import fibo, sys\n>>> dir(fibo)\n['__name__', 'fib', 'fib2']\n>>> dir(sys)\n['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',\n'__stdin__', '__stdout__', '_getframe', 'argv', 'builtin_module_names',\n'byteorder', 'copyright', 'displayhook', 'exc_info', 'exc_type',\n'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding',\n'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion',\n'maxint', 'maxunicode', 'modules', 'path', 'platform', 'prefix', 'ps1',\n'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile',\n'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version',\n'version_info', 'warnoptions']\n```\nWithout arguments, dir() lists the names you have defined\ncurrently:\n```text\n\n>>> a = [1, 2, 3, 4, 5]\n>>> import fibo, sys\n>>> fib = fibo.fib\n>>> dir()\n['__name__', 'a', 'fib', 'fibo', 'sys']\n```\nNote that it lists all types of names: variables, modules, functions, etc.\ndir() does not list the names of built-in functions and\nvariables. If you want a list of those, they are defined in the\nstandard module __builtin__:\n```text\n\n>>> import __builtin__\n>>> dir(__builtin__)\n['ArithmeticError', 'AssertionError', 'AttributeError',\n'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',\n'Exception', 'FloatingPointError', 'IOError', 'ImportError',\n'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',\n'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',\n'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',\n'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError',\n'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',\n'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError',\n'UnicodeError', 'UserWarning', 'ValueError', 'Warning',\n'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',\n'__name__', 'abs', 'apply', 'buffer', 'callable', 'chr', 'classmethod',\n'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr',\n'dict', 'dir', 'divmod', 'eval', 'execfile', 'exit', 'file', 'filter',\n'float', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',\n'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len',\n'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object',\n'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input',\n'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod',\n'str', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange',\n'zip']\n```\n# 6.4 Packages\nPackages are a way of structuring Python's module namespace\nby using ``dotted module names''. For example, the module name\nA.B designates a submodule named \"B\" in a package named\n\"A\". Just like the use of modules saves the authors of different\nmodules from having to worry about each other's global variable names,\nthe use of dotted module names saves the authors of multi-module\npackages like NumPy or the Python Imaging Library from having to worry\nabout each other's module names.\nSuppose you want to design a collection of modules (a ``package'') for\nthe uniform handling of sound files and sound data. There are many\ndifferent sound file formats (usually recognized by their extension,\nfor example: .wav, .aiff, .au), so you may need\nto create and maintain a growing collection of modules for the\nconversion between the various file formats. There are also many\ndifferent operations you might want to perform on sound data (such as\nmixing, adding echo, applying an equalizer function, creating an\nartificial stereo effect), so in addition you will be writing a\nnever-ending stream of modules to perform these operations. Here's a\npossible structure for your package (expressed in terms of a\nhierarchical filesystem):\n```text\n\nSound/ Top-level package\n__init__.py Initialize the sound package\nFormats/ Subpackage for file format conversions\n__init__.py\nwavread.py\nwavwrite.py\naiffread.py\naiffwrite.py\nauread.py\nauwrite.py\n...\nEffects/ Subpackage for sound effects\n__init__.py\necho.py\nsurround.py\nreverse.py\n...\nFilters/ Subpackage for filters\n__init__.py\nequalizer.py\nvocoder.py\nkaraoke.py\n...\n```\nThe __init__.py files are required to make Python treat the\ndirectories as containing packages; this is done to prevent\ndirectories with a common name, such as \"string\", from\nunintentionally hiding valid modules that occur later on the module\nsearch path. In the simplest case, __init__.py can just be an\nempty file, but it can also execute initialization code for the\npackage or set the `__all__` variable, described later.\nUsers of the package can import individual modules from the\npackage, for example:\n```text\n\nimport Sound.Effects.echo\n```\nThis loads the submodule Sound.Effects.echo. It must be referenced\nwith its full name.\n```text\n\nSound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)\n```\nAn alternative way of importing the submodule is:\n```text\n\nfrom Sound.Effects import echo\n```\nThis also loads the submodule echo, and makes it available without\nits package prefix, so it can be used as follows:\n```text\n\necho.echofilter(input, output, delay=0.7, atten=4)\n```\nYet another variation is to import the desired function or variable directly:\n```text\n\nfrom Sound.Effects.echo import echofilter\n```\nAgain, this loads the submodule echo, but this makes its function\nechofilter() directly available:\n```text\n\nechofilter(input, output, delay=0.7, atten=4)\n```\nNote that when using `from package import item`, the\nitem can be either a submodule (or subpackage) of the package, or some\nother name defined in the package, like a function, class or\nvariable. The `import` statement first tests whether the item is\ndefined in the package; if not, it assumes it is a module and attempts\nto load it. If it fails to find it, an\nImportError exception is raised.\nContrarily, when using syntax like `import item.subitem.subsubitem`, each item except for the last must be\na package; the last item can be a module or a package but can't be a\nclass or function or variable defined in the previous item.\n## 6.4.1 Importing * From a Package\nNow what happens when the user writes `from Sound.Effects import\n*`? Ideally, one would hope that this somehow goes out to the\nfilesystem, finds which submodules are present in the package, and\nimports them all. Unfortunately, this operation does not work very\nwell on Mac and Windows platforms, where the filesystem does not\nalways have accurate information about the case of a filename! On\nthese platforms, there is no guaranteed way to know whether a file\nECHO.PY should be imported as a module echo,\nEcho or ECHO. (For example, Windows 95 has the\nannoying practice of showing all file names with a capitalized first\nletter.) The DOS 8+3 filename restriction adds another interesting\nproblem for long module names.\nThe only solution is for the package author to provide an explicit\nindex of the package. The import statement uses the following\nconvention: if a package's __init__.py code defines a list\nnamed `__all__`, it is taken to be the list of module names that\nshould be imported when `from package import *` is\nencountered. It is up to the package author to keep this list\nup-to-date when a new version of the package is released. Package\nauthors may also decide not to support it, if they don't see a use for\nimporting * from their package. For example, the file\nSounds/Effects/__init__.py could contain the following code:\n```text\n\n__all__ = [\"echo\", \"surround\", \"reverse\"]\n```\nThis would mean that `from Sound.Effects import *` would\nimport the three named submodules of the Sound package.\nIf `__all__` is not defined, the statement `from Sound.Effects\nimport *` does not import all submodules from the package\nSound.Effects into the current namespace; it only ensures that the\npackage Sound.Effects has been imported (possibly running its\ninitialization code, __init__.py) and then imports whatever names are\ndefined in the package. This includes any names defined (and\nsubmodules explicitly loaded) by __init__.py. It also includes any\nsubmodules of the package that were explicitly loaded by previous\nimport statements. Consider this code:\n```text\n\nimport Sound.Effects.echo\nimport Sound.Effects.surround\nfrom Sound.Effects import *\n```\nIn this example, the echo and surround modules are imported in the\ncurrent namespace because they are defined in the\nSound.Effects package when the `from...import` statement\nis executed. (This also works when `__all__` is defined.)\nNote that in general the practicing of importing * from a module or\npackage is frowned upon, since it often causes poorly readable code.\nHowever, it is okay to use it to save typing in interactive sessions,\nand certain modules are designed to export only names that follow\ncertain patterns.\nRemember, there is nothing wrong with using `from Package\nimport specific_submodule`! In fact, this is the\nrecommended notation unless the importing module needs to use\nsubmodules with the same name from different packages.\n## 6.4.2 Intra-package References\nThe submodules often need to refer to each other. For example, the\nsurround module might use the echo module. In fact, such references\nare so common that the `import` statement first looks in the\ncontaining package before looking in the standard module search path.\nThus, the surround module can simply use `import echo` or\n`from echo import echofilter`. If the imported module is not\nfound in the current package (the package of which the current module\nis a submodule), the `import` statement looks for a top-level module\nwith the given name.\nWhen packages are structured into subpackages (as with the\nSound package in the example), there's no shortcut to refer\nto submodules of sibling packages - the full name of the subpackage\nmust be used. For example, if the module\nSound.Filters.vocoder needs to use the echo module\nin the Sound.Effects package, it can use `from\nSound.Effects import echo`.", "python_version": "2.2", "length": 19545, "url": "https://docs.python.org/2.2/tut/node8.html"} {"title": "7. Input and Output", "text": "node8.html | tut.html | node10.html | Python Tutorial | node2.html\n---\n- 7.1 Fancier Output Formatting (#SECTION009100000000000000000)\n 7.2 Reading and Writing Files (#SECTION009200000000000000000)\n - 7.2.1 Methods of File Objects (#SECTION009210000000000000000)\n 7.2.2 The pickle Module (#SECTION009220000000000000000)\n---\n# 7. Input and Output\nThere are several ways to present the output of a program; data can be\nprinted in a human-readable form, or written to a file for future use.\nThis chapter will discuss some of the possibilities.\n# 7.1 Fancier Output Formatting\nSo far we've encountered two ways of writing values: expression\nstatements and the print statement. (A third way is using\nthe write() method of file objects; the standard output file\ncan be referenced as `sys.stdout`. See the Library Reference for\nmore information on this.)\nOften you'll want more control over the formatting of your output than\nsimply printing space-separated values. There are two ways to format\nyour output; the first way is to do all the string handling yourself;\nusing string slicing and concatenation operations you can create any\nlay-out you can imagine. The standard module\nstringcontains some useful operations\nfor padding strings to a given column width; these will be discussed\nshortly. The second way is to use the `%` operator with a\nstring as the left argument. The `%` operator interprets the\nleft argument much like a sprintf()-style format\nstring to be applied to the right argument, and returns the string\nresulting from this formatting operation.\nOne question remains, of course: how do you convert values to strings?\nLuckily, Python has ways to convert any value to a string: pass it to\nthe repr() or str() functions, or just write\nthe value between reverse quotes (````, equivalent to\nrepr()).\nThe str() function is meant to return representations of\nvalues which are fairly human-readable, while repr() is\nmeant to generate representations which can be read by the interpreter\n(or will force a SyntaxError if there is not equivalent\nsyntax). For objects which don't have a particular representation for\nhuman consumption, str() will return the same value as\nrepr(). Many values, such as numbers or structures like\nlists and dictionaries, have the same representation using either\nfunction. Strings and floating point numbers, in particular, have two\ndistinct representations.\nSome examples:\n```text\n\n>>> s = 'Hello, world.'\n>>> str(s)\n'Hello, world.'\n>>> `s`\n\"'Hello, world.'\"\n>>> str(0.1)\n'0.1'\n>>> `0.1`\n'0.10000000000000001'\n>>> x = 10 * 3.25\n>>> y = 200 * 200\n>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'\n>>> print s\nThe value of x is 32.5, and y is 40000...\n>>> # Reverse quotes work on other types besides numbers:\n... p = [x, y]\n>>> ps = repr(p)\n>>> ps\n'[32.5, 40000]'\n>>> # Converting a string adds string quotes and backslashes:\n... hello = 'hello, world\\n'\n>>> hellos = `hello`\n>>> print hellos\n'hello, world\\n'\n>>> # The argument of reverse quotes may be a tuple:\n... `x, y, ('spam', 'eggs')`\n\"(32.5, 40000, ('spam', 'eggs'))\"\n```\nHere are two ways to write a table of squares and cubes:\n```text\n\n>>> import string\n>>> for x in range(1, 11):\n... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),\n... # Note trailing comma on previous line\n... print string.rjust(`x*x*x`, 4)\n...\n1 1 1\n2 4 8\n3 9 27\n4 16 64\n5 25 125\n6 36 216\n7 49 343\n8 64 512\n9 81 729\n10 100 1000\n>>> for x in range(1,11):\n... print '%2d %3d %4d' % (x, x*x, x*x*x)\n...\n1 1 1\n2 4 8\n3 9 27\n4 16 64\n5 25 125\n6 36 216\n7 49 343\n8 64 512\n9 81 729\n10 100 1000\n```\n(Note that one space between each column was added by the way\nprint works: it always adds spaces between its arguments.)\nThis example demonstrates the function string.rjust(),\nwhich right-justifies a string in a field of a given width by padding\nit with spaces on the left. There are similar functions\nstring.ljust() and string.center(). These\nfunctions do not write anything, they just return a new string. If\nthe input string is too long, they don't truncate it, but return it\nunchanged; this will mess up your column lay-out but that's usually\nbetter than the alternative, which would be lying about a value. (If\nyou really want truncation you can always add a slice operation, as in\n\"string.ljust(x, n)[0:n]\".)\nThere is another function, string.zfill(), which pads a\nnumeric string on the left with zeros. It understands about plus and\nminus signs:\n```text\n\n>>> import string\n>>> string.zfill('12', 5)\n'00012'\n>>> string.zfill('-3.14', 7)\n'-003.14'\n>>> string.zfill('3.14159265359', 5)\n'3.14159265359'\n```\nUsing the `%` operator looks like this:\n```text\n\n>>> import math\n>>> print 'The value of PI is approximately %5.3f.' % math.pi\nThe value of PI is approximately 3.142.\n```\nIf there is more than one format in the string, you need to pass a\ntuple as right operand, as in this example:\n```text\n\n>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}\n>>> for name, phone in table.items():\n... print '%-10s ==> %10d' % (name, phone)\n...\nJack ==> 4098\nDcab ==> 7678\nSjoerd ==> 4127\n```\nMost formats work exactly as in C and require that you pass the proper\ntype; however, if you don't you get an exception, not a core dump.\nThe `%s` format is more relaxed: if the corresponding argument is\nnot a string object, it is converted to string using the\nstr() built-in function. Using `*` to pass the width\nor precision in as a separate (integer) argument is supported. The\nC formats `%n` and `%p` are not supported.\nIf you have a really long format string that you don't want to split\nup, it would be nice if you could reference the variables to be\nformatted by name instead of by position. This can be done by using\nform `%(name)format`, as shown here:\n```text\n\n>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}\n>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table\nJack: 4098; Sjoerd: 4127; Dcab: 8637678\n```\nThis is particularly useful in combination with the new built-in\nvars() function, which returns a dictionary containing all\nlocal variables.\n# 7.2 Reading and Writing Files\nopen()returns a file\nobject, and is most commonly used with two arguments:\n\"open(filename, mode)\".\n```text\n\n>>> f=open('/tmp/workfile', 'w')\n>>> print f\n\n```\nThe first argument is a string containing the filename. The second\nargument is another string containing a few characters describing the\nway in which the file will be used. mode can be `'r'` when\nthe file will only be read, `'w'` for only writing (an existing\nfile with the same name will be erased), and `'a'` opens the file\nfor appending; any data written to the file is automatically added to\nthe end. `'r+'` opens the file for both reading and writing.\nThe mode argument is optional; `'r'` will be assumed if\nit's omitted.\nOn Windows and the Macintosh, `'b'` appended to the\nmode opens the file in binary mode, so there are also modes like\n`'rb'`, `'wb'`, and `'r+b'`. Windows makes a\ndistinction between text and binary files; the end-of-line characters\nin text files are automatically altered slightly when data is read or\nwritten. This behind-the-scenes modification to file data is fine for\nASCII text files, but it'll corrupt binary data like that in JPEGs or\n.EXE files. Be very careful to use binary mode when reading and\nwriting such files. (Note that the precise semantics of text mode on\nthe Macintosh depends on the underlying C library being used.)\n## 7.2.1 Methods of File Objects\nThe rest of the examples in this section will assume that a file\nobject called `f` has already been created.\nTo read a file's contents, call `f.read( size )`, which reads\nsome quantity of data and returns it as a string. size is an\noptional numeric argument. When size is omitted or negative,\nthe entire contents of the file will be read and returned; it's your\nproblem if the file is twice as large as your machine's memory.\nOtherwise, at most size bytes are read and returned. If the end\nof the file has been reached, `f.read()` will return an empty\nstring (`\"\"`).\n```text\n\n>>> f.read()\n'This is the entire file.\\n'\n>>> f.read()\n''\n```\n`f.readline()` reads a single line from the file; a newline\ncharacter (`\\n`) is left at the end of the string, and is only\nomitted on the last line of the file if the file doesn't end in a\nnewline. This makes the return value unambiguous; if\n`f.readline()` returns an empty string, the end of the file has\nbeen reached, while a blank line is represented by `'\\n'`, a\nstring containing only a single newline.\n```text\n\n>>> f.readline()\n'This is the first line of the file.\\n'\n>>> f.readline()\n'Second line of the file\\n'\n>>> f.readline()\n''\n```\n`f.readlines()` returns a list containing all the lines of data\nin the file. If given an optional parameter sizehint, it reads\nthat many bytes from the file and enough more to complete a line, and\nreturns the lines from that. This is often used to allow efficient\nreading of a large file by lines, but without having to load the\nentire file in memory. Only complete lines will be returned.\n```text\n\n>>> f.readlines()\n['This is the first line of the file.\\n', 'Second line of the file\\n']\n```\n`f.write( string )` writes the contents of string to\nthe file, returning `None`.\n```text\n\n>>> f.write('This is a test\\n')\n```\n`f.tell()` returns an integer giving the file object's current\nposition in the file, measured in bytes from the beginning of the\nfile. To change the file object's position, use\n\"f.seek(offset, from_what)\". The position is\ncomputed from adding offset to a reference point; the reference\npoint is selected by the from_what argument. A\nfrom_what value of 0 measures from the beginning of the file, 1\nuses the current file position, and 2 uses the end of the file as the\nreference point. from_what can be omitted and defaults to 0,\nusing the beginning of the file as the reference point.\n```text\n\n>>> f=open('/tmp/workfile', 'r+')\n>>> f.write('0123456789abcdef')\n>>> f.seek(5) # Go to the 6th byte in the file\n>>> f.read(1)\n'5'\n>>> f.seek(-3, 2) # Go to the 3rd byte before the end\n>>> f.read(1)\n'd'\n```\nWhen you're done with a file, call `f.close()` to close it and\nfree up any system resources taken up by the open file. After calling\n`f.close()`, attempts to use the file object will automatically fail.\n```text\n\n>>> f.close()\n>>> f.read()\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nValueError: I/O operation on closed file\n```\nFile objects have some additional methods, such as\nisatty() and truncate() which are less frequently\nused; consult the Library Reference for a complete guide to file\nobjects.\n## 7.2.2 The pickle Module\nStrings can easily be written to and read from a file. Numbers take a\nbit more effort, since the read() method only returns\nstrings, which will have to be passed to a function like\nstring.atoi(), which takes a string like `'123'` and\nreturns its numeric value 123. However, when you want to save more\ncomplex data types like lists, dictionaries, or class instances,\nthings get a lot more complicated.\nRather than have users be constantly writing and debugging code to\nsave complicated data types, Python provides a standard module called\npickle. This is an amazing module that can take almost\nany Python object (even some forms of Python code!), and convert it to\na string representation; this process is called pickling.\nReconstructing the object from the string representation is called\nunpickling. Between pickling and unpickling, the string\nrepresenting the object may have been stored in a file or data, or\nsent over a network connection to some distant machine.\nIf you have an object `x`, and a file object `f` that's been\nopened for writing, the simplest way to pickle the object takes only\none line of code:\n```text\n\npickle.dump(x, f)\n```\nTo unpickle the object again, if `f` is a file object which has\nbeen opened for reading:\n```text\n\nx = pickle.load(f)\n```\n(There are other variants of this, used when pickling many objects or\nwhen you don't want to write the pickled data to a file; consult the\ncomplete documentation for pickle in the Library Reference.)\npickle is the standard way to make Python objects which can\nbe stored and reused by other programs or by a future invocation of\nthe same program; the technical term for this is a\npersistent object. Because pickle is so widely used,\nmany authors who write Python extensions take care to ensure that new\ndata types such as matrices can be properly pickled and unpickled.", "python_version": "2.2", "length": 12469, "url": "https://docs.python.org/2.2/tut/node9.html"} {"title": "Python Tutorial", "text": "../index.html | node1.html | Python Tutorial | node2.html\n---\n# Python Tutorial\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.2\nDecember 21, 2001", "python_version": "2.2", "length": 194, "url": "https://docs.python.org/2.2/tut/tut.html"}