{"title": "About the Python Documentation", "text": "index.html | About the Python Documentation\nUp:\nPython Documentation Index (index.html)\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.3", "length": 1217, "url": "https://docs.python.org/2.3/Python-Docs-2.3/about.html"} {"title": "Acknowledgements", "text": "index.html | 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 | Ben Gertzfield | Detlef Lannert | Donald Wallace Rouse II\nMichael Abbott | Nadim Ghaznavi | Piers Lauder | Nick Russo\nSteve Alexander | Jonathan Giddy | Glyph Lefkowitz | Chris Ryland\nJim Ahlstrom | Shelley Gooch | Marc-Andr Lemburg | Constantina S.\nFred Allen | Nathaniel Gray | Ulf A. Lindgren | Hugh Sasse\nA. Amoroso | Grant Griffin | Everett Lipman | Bob Savage\nPehr Anderson | Thomas Guettler | Mirko Liss | Scott Schram\nOliver Andrich | Anders Hammarquist | Martin von Lwis | Neil Schemenauer\nJess Cea Avin | Mark Hammond | Fredrik Lundh | Barry Scott\nDaniel Barclay | Harald Hanche-Olsen | Jeff MacDonald | Joakim Sernbrant\nChris Barker | Manus Hand | John Machin | Justin Sheehy\nDon Bashford | Gerhard Hring | Andrew MacIntyre | Michael Simcich\nAnthony Baxter | Travis B. Hartwell | Vladimir Marangozov | Ionel Simionescu\nBennett Benson | Janko Hauser | Vincent Marchetti | Roy Smith\nJonathan Black | Bernhard Herzog | Laura Matson | Clay Spence\nRobin Boerdijk | Magnus L. Hetland | Daniel May | Nicholas Spies\nMichal Bozon | Konrad Hinsen | Doug Mennella | Tage Stabell-Kulo\nAaron Brancotti | Stefan Hoffmeister | Paolo Milani | Frank Stajano\nKeith Briggs | Albert Hofkamp | Skip Montanaro | Anthony Starks\nLee Busby | Gregor Hoffleit | Paul Moore | Greg Stein\nLorenzo M. Catucci | Steve Holden | Ross Moore | Peter Stoehr\nMauro Cicognini | Thomas Holenstein | Sjoerd Mullender | Mark Summerfield\nGilles Civario | Gerrit Holl | Dale Nagata | Reuben Sumner\nMike Clarkson | Rob Hooft | Ng Pheng Siong | Kalle Svensson\nSteve Clift | Brian Hooper | Koray Oner | Jim Tittsler\nDave Cole | Randall Hopper | Tomas Oppelstrup | Ville Vainio\nMatthew Cowles | Michael Hudson | Denis S. Otkidach | Martijn Vries\nJeremy Craven | Eric Huss | Zooko O'Whielacronx | Charles G. Waldman\nAndrew Dalke | Jeremy Hylton | William Park | Greg Ward\nBen Darnell | Roger Irwin | Joonas Paalasmaa | Barry Warsaw\nL. Peter Deutsch | 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\nHernn Martnez 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\n---\nindex.html | Acknowledgements", "python_version": "2.3", "length": 3359, "url": "https://docs.python.org/2.3/Python-Docs-2.3/acks.html"} {"title": "About this document ...", "text": "genindex.html | api.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\nUp:\nPython/C API Reference Manual (api.html)\n---\n# About this document ...\nPython/C API Reference Manual,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1663, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/about.html"} {"title": "6.6 Buffer Protocol", "text": "iterator.html | abstract.html | concrete.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n6.5 Iterator Protocol (iterator.html)\nUp:\n6. Abstract Objects Layer (abstract.html)\nNext:\n7. Concrete Objects Layer (concrete.html)\n---\n# 6.6 Buffer Protocol", "python_version": "2.3", "length": 277, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/abstract-buffer.html"} {"title": "6. Abstract Objects Layer", "text": "arg-parsing.html | api.html | object.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n5.5 Parsing arguments and (arg-parsing.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n6.1 Object Protocol (object.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.3", "length": 541, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.2 Profiling and Tracing (profiling.html)\nUp:\n8. Initialization, Finalization, and (initialization.html)\nNext:\n9. Memory Management (memory.html)\n---\n# 8.3 Advanced Debugger Support\nThese functions are only intended to be used by advanced debugging\ntools.", "python_version": "2.3", "length": 381, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n10. Object Implementation Support (newTypes.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.2 Common Object Structures (common-structs.html)\n---\n# 10.1 Allocating Objects on the Heap\nDL_IMPORT", "python_version": "2.3", "length": 339, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/allocating-objects.html"} {"title": "Python/C API Reference Manual", "text": "../index.html | front.html | Python/C API Reference Manual | contents.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 316, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.4 Data marshalling support (marshalling-utils.html)\nUp:\n5. Utilities (utilities.html)\nNext:\n6. Abstract Objects Layer (abstract.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).\nThe first three of these functions described,\nPyArg_ParseTuple(),\nPyArg_ParseTupleAndKeywords(), and\nPyArg_Parse(), all use format strings which are\nused to tell the function about the expected arguments. The format\nstrings use the same syntax for each of these functions.\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 these functions. In the following\ndescription, the quoted form is the format unit; the entry in (round)\nparentheses is the Python object type that matches the format unit;\nand the entry in [square] brackets is the type of the C variable(s)\nwhose address should be passed.\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\nNUL-terminated. The Python string must not contain embedded NUL\nbytes; if it does, a TypeError exception is raised.\nUnicode objects are converted to C strings using the default\nencoding. If this conversion fails, a 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\na pointer 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\nthe object 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\nwhich case the C pointer is set to NULL.\n\"z#\" (string or `None` or any read buffer\ncompatible object) [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 NUL-terminated\nbuffer of 16-bit Unicode (UTF-16) data. As with \"s\", there is\nno need to provide storage for the Unicode data buffer; a pointer to\nthe existing Unicode data is stored into the Py_UNICODE\npointer variable whose address 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.\nNon-Unicode objects are handled by interpreting their read-buffer\npointer as pointer to a Py_UNICODE array.\n\"es\" (string, Unicode object or character buffer\ncompatible object) [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 NUL bytes.\nThis format requires two arguments. The first is only used as\ninput, and must be a char* which points to the name of an\nencoding as a NUL-terminated string, or NULL, in which case the\ndefault encoding is used. An exception is raised if the named\nencoding is not known to Python. The second argument must be a\nchar**; the value of the pointer it references will be set\nto a buffer with the contents of the argument text. The text will\nbe encoded in the encoding specified by the first argument.\nPyArg_ParseTuple() will allocate a buffer of the needed\nsize, copy the encoded data into this buffer and adjust\n*buffer to reference the newly allocated storage. The caller\nis responsible for calling PyMem_Free() to free the\nallocated buffer after use.\n\"et\" (string, Unicode object or character buffer\ncompatible object) [const char *encoding, char **buffer]: Same as \"es\" except that 8-bit string objects are passed\nthrough without recoding them. Instead, the implementation assumes\nthat the string object 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. Unlike the\n\"es\" format, this variant allows input data which contains NUL\ncharacters.\nIt requires three arguments. The first is only used as input, and\nmust be a char* which points to the name of an encoding as a\nNUL-terminated string, or NULL, in which case the default encoding\nis used. An exception is raised if the named encoding is not known\nto Python. The second argument must be a char**; the value\nof the pointer it references will be set to a buffer with the\ncontents of the argument text. The text will be encoded in the\nencoding specified by the first argument. The third argument must\nbe a pointer to an integer; the referenced integer will be set to\nthe number of bytes in the output buffer.\nThere are two modes of operation:\nIf *buffer points a NULL pointer, the function will\nallocate a buffer of the needed size, copy the encoded data into\nthis buffer and set *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\nallocated buffer), PyArg_ParseTuple() will use this\nlocation as the buffer and interpret the initial value of\n*buffer_length as the buffer size. It will then copy the\nencoded data into the buffer and NUL-terminate it. If the buffer\nis not large enough, a ValueError will be set.\nIn both cases, *buffer_length is set to the length of the\nencoded data without the trailing NUL 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\nwithout recoding them. Instead, the implementation assumes that the\nstring object 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\"B\" (integer) [unsigned char]: Convert a Python integer to a tiny int without overflow checking,\nstored in a C unsigned char.\nNew in version 2.3.\n\"h\" (integer) [short int]: Convert a Python integer to a C short int.\n\"H\" (integer) [unsigned short int]: Convert a Python integer to a C unsigned short int, without\noverflow checking.\nNew in version 2.3.\n\"i\" (integer) [int]: Convert a Python integer to a plain C int.\n\"I\" (integer) [unsigned int]: Convert a Python integer to a C unsigned int, without\noverflow checking.\nNew in version 2.3.\n\"l\" (integer) [long int]: Convert a Python integer to a C long int.\n\"k\" (integer) [unsigned long]: Convert a Python integer to a C unsigned long without\noverflow checking.\nNew in version 2.3.\n\"L\" (integer) [PY_LONG_LONG]: Convert a Python integer to a C long long. This format is\nonly available on platforms that support long long (or\n_int64 on Windows).\n\"K\" (integer) [unsigned PY_LONG_LONG]: Convert a Python integer to a C unsigned long long\nwithout overflow checking. This format is only available on\nplatforms that support unsigned long long (or\nunsigned _int64 on Windows).\nNew in version 2.3.\n\"c\" (string of length 1) [char]: Convert a Python character, represented as a string of length 1, to\na C 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\npointer. The C program thus receives the actual object that was\npassed. The object's reference count is not increased. The pointer\nstored is not NULL.\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. If\nthe 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\nas follows:\nstatus`=`converter`(`object,\naddress`);`\nwhere object is the Python object to be converted and\naddress is the void* argument that was passed to the\nPyArg_Parse*() function. The returned status\nshould be `1` for a successful conversion and `0` if the\nconversion has failed. When the conversion fails, the\nconverter function should raise an exception.\n\"S\" (string) [PyStringObject *]: Like \"O\" but requires that the Python object is a string\nobject. Raises TypeError if the object is not a string\nobject. The C variable may also be declared as PyObject*.\n\"U\" (Unicode string) [PyUnicodeObject *]: Like \"O\" but requires that the Python object is a Unicode\nobject. Raises TypeError if the object is not a Unicode\nobject. The 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\nread-only 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\"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\nof the 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 only\naccepted 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\nare optional. The C variables corresponding to optional arguments\nshould be initialized to their default value -- when an optional\nargument is not specified, PyArg_ParseTuple() does not\ntouch the contents of the corresponding C variable(s).\n\":\": The list of format units ends here; the string after the colon is\nused as the function name in error messages (the ``associated\nvalue'' of the exception that PyArg_ParseTuple()\nraises).\n\";\": The list of format units ends here; the string after the semicolon\nis used as the error message instead of the default error\nmessage. Clearly, \":\" and \";\" mutually exclude each\nother.\nNote that any Python object references which are provided to the\ncaller are borrowed references; do not decrement their\nreference count!\nAdditional arguments passed to these functions must be addresses of\nvariables whose type is determined by the format string; these are\nused to store values from the input tuple. There are a few cases, as\ndescribed in the list of format units above, where these parameters\nare used as input values; they should match what is specified for the\ncorresponding format unit in that case.\nFor the conversion to succeed, the arg object must match the\nformat and the format must be exhausted. On success, the\nPyArg_Parse*() functions return true, otherwise they\nreturn false and raise an appropriate exception.", "python_version": "2.3", "length": 13143, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/arg-parsing.html"} {"title": "10.7 Buffer Object Structures", "text": "sequence-structs.html | newTypes.html | supporting-iteration.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.6 Sequence Object Structures (sequence-structs.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.8 Supporting the Iterator (supporting-iteration.html)\n---\n# 10.7 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.3", "length": 1190, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3.2.2 Methods and Slot (unicodeMethodsAndSlots.html)\nUp:\n7.3 Sequence Objects (sequenceObjects.html)\nNext:\n7.3.4 Tuple Objects (tupleObjects.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.7 (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.3", "length": 2368, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3.2 Unicode Objects (unicodeObjects.html)\nUp:\n7.3.2 Unicode Objects (unicodeObjects.html)\nNext:\n7.3.2.2 Methods and Slot (unicodeMethodsAndSlots.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.3", "length": 3184, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.9 CObjects (cObjects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n8. Initialization, Finalization, and (initialization.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.3", "length": 889, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.8 Weak Reference Objects (weakref-objects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.10 Cell Objects (cell-objects.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.3", "length": 459, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/cObjects.html"} {"title": "10.2 Common Object Structures", "text": "allocating-objects.html | newTypes.html | type-structs.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.1 Allocating Objects on (allocating-objects.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.3 Type Objects (type-structs.html)\n---\n# 10.2 Common Object Structures\nThere are a large number of structures which are used in the\ndefinition of object types for Python. This section describes these\nstructures and how they are used.\nAll Python objects ultimately share a small number of fields at the\nbeginning of the object's representation in memory. These are\nrepresented by the PyObject and PyVarObject types,\nwhich are defined, in turn, by the expansions of some macros also\nused, whether directly or indirectly, in the definition of all other\nPython objects.\nThese macros are used in the definition of PyObject and\nPyVarObject:\nPyObject_HEAD_INIT\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 ml_flags field is a bitfield which can include the\nfollowing flags. The individual flags indicate either a calling\nconvention or a binding convention. Of the calling convention flags,\nonly METH_VARARGS and METH_KEYWORDS can be\ncombined (but note that METH_KEYWORDS alone is equivalent\nto `METH_VARARGS | METH_KEYWORDS`).\nAny of the calling convention flags can be combined with a\nbinding flag.\nThese two constants are not used to indicate the calling convention\nbut the binding when use with methods of classes. These may not be\nused for functions defined for modules. At most one of these flags\nmay be set for any given method.", "python_version": "2.3", "length": 1902, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/common-structs.html"} {"title": "7.2.4 Complex Number Objects", "text": "floatObjects.html | numericObjects.html | node38.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.2.3 Floating Point Objects (floatObjects.html)\nUp:\n7.2 Numeric Objects (numericObjects.html)\nNext:\n7.2.4.1 Complex Numbers as (node38.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.3", "length": 587, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/complexObjects.html"} {"title": "7. Concrete Objects Layer", "text": "abstract-buffer.html | api.html | fundamental.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n6.6 Buffer Protocol (abstract-buffer.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n7.1 Fundamental Objects (fundamental.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.3", "length": 1013, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/concrete.html"} {"title": "Contents", "text": "front.html | api.html | intro.html | Python/C API Reference Manual | genindex.html\nPrevious:\nFront Matter (front.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n1. Introduction (intro.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 6.6 Buffer Protocol (abstract-buffer.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. Object Implementation Support (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 Type Objects (type-structs.html)\n 10.4 Mapping Object Structures (mapping-structs.html)\n 10.5 Number Object Structures (number-structs.html)\n 10.6 Sequence Object Structures (sequence-structs.html)\n 10.7 Buffer Object Structures (buffer-structs.html)\n 10.8 Supporting the Iterator Protocol (supporting-iteration.html)\n 10.9 Supporting Cyclic Garbarge Collection (supporting-cycle-detection.html)\n A. Reporting Bugs (reporting-bugs.html)\n B. History and License (node80.html)\n - B.1 History of the software (node81.html)\n B.2 Terms and conditions for accessing or otherwise using Python (node82.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.3", "length": 3859, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/contents.html"} {"title": "3. Reference Counting", "text": "veryhigh.html | api.html | exceptionHandling.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n2. The Very High (veryhigh.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n4. Exception Handling (exceptionHandling.html)\n---\n# 3. Reference Counting\nThe macros in this section are used for managing reference counts\nof Python objects.", "python_version": "2.3", "length": 367, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.5 Iterator Objects (iterator-objects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.7 Slice Objects (slice-objects.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.3", "length": 425, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.4 Mapping Objects (mapObjects.html)\nUp:\n7.4 Mapping Objects (mapObjects.html)\nNext:\n7.5 Other Objects (otherObjects.html)\n---\n## 7.4.1 Dictionary Objects", "python_version": "2.3", "length": 283, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/dictObjects.html"} {"title": "1.4 Embedding Python", "text": "exceptions.html | intro.html | veryhigh.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n1.3 Exceptions (exceptions.html)\nUp:\n1. Introduction (intro.html)\nNext:\n2. The Very High (veryhigh.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.3 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.3. (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.3", "length": 2451, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/embedding.html"} {"title": "4. Exception Handling", "text": "countingRefs.html | api.html | standardExceptions.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n3. Reference Counting (countingRefs.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n4.1 Standard Exceptions (standardExceptions.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 propagated, 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.3", "length": 1846, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/exceptionHandling.html"} {"title": "1.3 Exceptions", "text": "types.html | intro.html | embedding.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n1.2.2 Types (types.html)\nUp:\n1. Introduction (intro.html)\nNext:\n1.4 Embedding Python (embedding.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.3", "length": 5607, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5 Other Objects (otherObjects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.2 Instance Objects (instanceObjects.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.3", "length": 476, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.2.2 Long Integer Objects (longObjects.html)\nUp:\n7.2 Numeric Objects (numericObjects.html)\nNext:\n7.2.4 Complex Number Objects (complexObjects.html)\n---\n## 7.2.3 Floating Point Objects", "python_version": "2.3", "length": 319, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/floatObjects.html"} {"title": "Front Matter", "text": "api.html | api.html | contents.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\nPython/C API Reference Manual (api.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n---\n# Front Matter\nCopyright © 2001, 2002, 2003 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.3", "length": 1138, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/front.html"} {"title": "7.1 Fundamental Objects", "text": "concrete.html | concrete.html | typeObjects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7. Concrete Objects Layer (concrete.html)\nUp:\n7. Concrete Objects Layer (concrete.html)\nNext:\n7.1.1 Type Objects (typeObjects.html)\n---\n# 7.1 Fundamental Objects\nThis section describes Python type objects and the singleton object\n`None`.", "python_version": "2.3", "length": 360, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/fundamental.html"} {"title": "Index", "text": "node82.html | api.html | about.html | Python/C API Reference Manual | contents.html\nPrevious:\nB.2 Terms and conditions (node82.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\nAbout this document ... (about.html)\n---\n## Index\n---\nSymbols (#letter-Symbols) |\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## Symbols\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.3", "length": 816, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.2 Process Control (processControl.html)\nUp:\n5. Utilities (utilities.html)\nNext:\n5.4 Data marshalling support (marshalling-utils.html)\n---\n# 5.3 Importing Modules", "python_version": "2.3", "length": 299, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/importing.html"} {"title": "1.1 Include Files", "text": "intro.html | intro.html | objects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n1. Introduction (intro.html)\nUp:\n1. Introduction (intro.html)\nNext:\n1.2 Objects, Types and (objects.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.3", "length": 2286, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/includes.html"} {"title": "Python/C API Reference Manual", "text": "../index.html | front.html | Python/C API Reference Manual | contents.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 316, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.10 Cell Objects (cell-objects.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n8.1 Thread State and (threads.html)\n---\n# 8. Initialization, Finalization, and Threads", "python_version": "2.3", "length": 295, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.1 File Objects (fileObjects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.3 Method Objects (method-objects.html)\n---\n## 7.5.2 Instance Objects\nThere are very few functions specific to instance objects.", "python_version": "2.3", "length": 350, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.2 Numeric Objects (numericObjects.html)\nUp:\n7.2 Numeric Objects (numericObjects.html)\nNext:\n7.2.2 Long Integer Objects (longObjects.html)\n---\n## 7.2.1 Plain Integer Objects", "python_version": "2.3", "length": 309, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/intObjects.html"} {"title": "1. Introduction", "text": "contents.html | api.html | includes.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n1.1 Include Files (includes.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.3", "length": 1508, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.4 Module Objects (moduleObjects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.6 Descriptor Objects (descriptor-objects.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.3", "length": 641, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/iterator-objects.html"} {"title": "6.5 Iterator Protocol", "text": "mapping.html | abstract.html | abstract-buffer.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n6.4 Mapping Protocol (mapping.html)\nUp:\n6. Abstract Objects Layer (abstract.html)\nNext:\n6.6 Buffer Protocol (abstract-buffer.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:\n```text\n\nPyObject *iterator = PyObject_GetIter(obj);\nPyObject *item;\n\nif (iterator == NULL) {\n/* propagate error */\n}\n\nwhile (item = PyIter_Next(iterator)) {\n/* do something with item */\n...\n/* release reference when done */\nPy_DECREF(item);\n}\n\nPy_DECREF(iterator);\n\nif (PyErr_Occurred()) {\n/* propagate error */\n}\nelse {\n/* continue doing useful work */\n}\n```", "python_version": "2.3", "length": 836, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3.4 Tuple Objects (tupleObjects.html)\nUp:\n7.3 Sequence Objects (sequenceObjects.html)\nNext:\n7.4 Mapping Objects (mapObjects.html)\n---\n## 7.3.5 List Objects", "python_version": "2.3", "length": 290, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.2.1 Plain Integer Objects (intObjects.html)\nUp:\n7.2 Numeric Objects (numericObjects.html)\nNext:\n7.2.3 Floating Point Objects (floatObjects.html)\n---\n## 7.2.2 Long Integer Objects", "python_version": "2.3", "length": 312, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/longObjects.html"} {"title": "7.4 Mapping Objects", "text": "listObjects.html | concrete.html | dictObjects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.3.5 List Objects (listObjects.html)\nUp:\n7. Concrete Objects Layer (concrete.html)\nNext:\n7.4.1 Dictionary Objects (dictObjects.html)\n---\n# 7.4 Mapping Objects", "python_version": "2.3", "length": 285, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/mapObjects.html"} {"title": "10.4 Mapping Object Structures", "text": "type-structs.html | newTypes.html | number-structs.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.3 Type Objects (type-structs.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.5 Number Object Structures (number-structs.html)\n---\n# 10.4 Mapping Object Structures", "python_version": "2.3", "length": 316, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.3 Sequence Protocol (sequence.html)\nUp:\n6. Abstract Objects Layer (abstract.html)\nNext:\n6.5 Iterator Protocol (iterator.html)\n---\n# 6.4 Mapping Protocol", "python_version": "2.3", "length": 274, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.3 Importing Modules (importing.html)\nUp:\n5. Utilities (utilities.html)\nNext:\n5.5 Parsing arguments and (arg-parsing.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.3", "length": 1060, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.3 Advanced Debugger Support (advanced-debugging.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n9.1 Overview (memoryOverview.html)\n---\n# 9. Memory Management", "python_version": "2.3", "length": 299, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/memory.html"} {"title": "9.3 Examples", "text": "memoryInterface.html | memory.html | newTypes.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n9.2 Memory Interface (memoryInterface.html)\nUp:\n9. Memory Management (memory.html)\nNext:\n10. Object Implementation Support (newTypes.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.3", "length": 2034, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/memoryExamples.html"} {"title": "9.2 Memory Interface", "text": "memoryOverview.html | memory.html | memoryExamples.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n9.1 Overview (memoryOverview.html)\nUp:\n9. Memory Management (memory.html)\nNext:\n9.3 Examples (memoryExamples.html)\n---\n# 9.2 Memory Interface\nThe following function sets, modeled after the ANSI C standard,\nbut specifying behavior when requesting zero bytes,\nare available 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.3", "length": 945, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/memoryInterface.html"} {"title": "9.1 Overview", "text": "memory.html | memory.html | memoryInterface.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n9. Memory Management (memory.html)\nUp:\n9. Memory Management (memory.html)\nNext:\n9.2 Memory Interface (memoryInterface.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 over 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.3", "length": 3735, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.2 Instance Objects (instanceObjects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.4 Module Objects (moduleObjects.html)\n---\n## 7.5.3 Method Objects\nThere are some useful functions that are useful for working with\nmethod objects.", "python_version": "2.3", "length": 380, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.3 Method Objects (method-objects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.5 Iterator Objects (iterator-objects.html)\n---\n## 7.5.4 Module Objects\nThere are only a few functions special to module objects.", "python_version": "2.3", "length": 361, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/moduleObjects.html"} {"title": "10. Object Implementation Support", "text": "memoryExamples.html | api.html | allocating-objects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n9.3 Examples (memoryExamples.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n10.1 Allocating Objects on (allocating-objects.html)\n---\n# 10. Object Implementation Support\nThis chapter describes the functions, types, and macros used when\ndefining new object types.", "python_version": "2.3", "length": 402, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.1 Standard Exceptions (standardExceptions.html)\nUp:\n4. Exception Handling (exceptionHandling.html)\nNext:\n5. Utilities (utilities.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.3", "length": 416, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/node15.html"} {"title": "7.2.4.1 Complex Numbers as C Structures", "text": "complexObjects.html | complexObjects.html | node39.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.2.4 Complex Number Objects (complexObjects.html)\nUp:\n7.2.4 Complex Number Objects (complexObjects.html)\nNext:\n7.2.4.2 Complex Numbers as (node39.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.3", "length": 528, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/node38.html"} {"title": "7.2.4.2 Complex Numbers as Python Objects", "text": "node38.html | complexObjects.html | sequenceObjects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.2.4.1 Complex Numbers as (node38.html)\nUp:\n7.2.4 Complex Number Objects (complexObjects.html)\nNext:\n7.3 Sequence Objects (sequenceObjects.html)\n---\n### 7.2.4.2 Complex Numbers as Python Objects", "python_version": "2.3", "length": 326, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/node39.html"} {"title": "B. History and License", "text": "reporting-bugs.html | api.html | node81.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\nA. Reporting Bugs (reporting-bugs.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\nB.1 History of the (node81.html)\n---\n# B. History and License", "python_version": "2.3", "length": 271, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/node80.html"} {"title": "B.1 History of the software", "text": "node80.html | node80.html | node82.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\nB. History and License (node80.html)\nUp:\nB. History and License (node80.html)\nNext:\nB.2 Terms and conditions (node82.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 Digital Creations (now Zope\nCorporation; 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. Zope Corporation 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.3", "length": 1899, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/node81.html"} {"title": "B.2 Terms and conditions for accessing or otherwise using Python", "text": "node81.html | node80.html | genindex.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\nB.1 History of the (node81.html)\nUp:\nB. History and License (node80.html)\nNext:\n---\n# B.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.3\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.3 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.3 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001-2003 Python Software Foundation; All\nRights Reserved'' are retained in Python 2.3 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.3 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.3.\n4. PSF is making Python 2.3 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.3 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.3, 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.3, 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.3", "length": 9870, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/node82.html"} {"title": "7.1.2 The None Object", "text": "typeObjects.html | fundamental.html | numericObjects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.1.1 Type Objects (typeObjects.html)\nUp:\n7.1 Fundamental Objects (fundamental.html)\nNext:\n7.2 Numeric Objects (numericObjects.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.3", "length": 523, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/noneObject.html"} {"title": "10.5 Number Object Structures", "text": "mapping-structs.html | newTypes.html | sequence-structs.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.4 Mapping Object Structures (mapping-structs.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.6 Sequence Object Structures (sequence-structs.html)\n---\n# 10.5 Number Object Structures", "python_version": "2.3", "length": 340, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1 Object Protocol (object.html)\nUp:\n6. Abstract Objects Layer (abstract.html)\nNext:\n6.3 Sequence Protocol (sequence.html)\n---\n# 6.2 Number Protocol", "python_version": "2.3", "length": 267, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/number.html"} {"title": "7.2 Numeric Objects", "text": "noneObject.html | concrete.html | intObjects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.1.2 The None Object (noneObject.html)\nUp:\n7. Concrete Objects Layer (concrete.html)\nNext:\n7.2.1 Plain Integer Objects (intObjects.html)\n---\n# 7.2 Numeric Objects", "python_version": "2.3", "length": 287, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/numericObjects.html"} {"title": "6.1 Object Protocol", "text": "abstract.html | abstract.html | number.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n6. Abstract Objects Layer (abstract.html)\nUp:\n6. Abstract Objects Layer (abstract.html)\nNext:\n6.2 Number Protocol (number.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.3", "length": 939, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.1 Include Files (includes.html)\nUp:\n1. Introduction (intro.html)\nNext:\n1.2.1 Reference Counts (refcounts.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.3", "length": 1451, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5. Utilities (utilities.html)\nUp:\n5. Utilities (utilities.html)\nNext:\n5.2 Process Control (processControl.html)\n---\n# 5.1 Operating System Utilities", "python_version": "2.3", "length": 276, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/os.html"} {"title": "7.5 Other Objects", "text": "dictObjects.html | concrete.html | fileObjects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.4.1 Dictionary Objects (dictObjects.html)\nUp:\n7. Concrete Objects Layer (concrete.html)\nNext:\n7.5.1 File Objects (fileObjects.html)\n---\n# 7.5 Other Objects", "python_version": "2.3", "length": 283, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/otherObjects.html"} {"title": "5.2 Process Control", "text": "os.html | utilities.html | importing.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n5.1 Operating System Utilities (os.html)\nUp:\n5. Utilities (utilities.html)\nNext:\n5.3 Importing Modules (importing.html)\n---\n# 5.2 Process Control", "python_version": "2.3", "length": 261, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.1 Thread State and (threads.html)\nUp:\n8. Initialization, Finalization, and (initialization.html)\nNext:\n8.3 Advanced Debugger Support (advanced-debugging.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.3", "length": 1069, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.2.1 Reference Counts (refcounts.html)\nUp:\n1.2.1 Reference Counts (refcounts.html)\nNext:\n1.2.2 Types (types.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.3", "length": 5740, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.2 Objects, Types and (objects.html)\nUp:\n1.2 Objects, Types and (objects.html)\nNext:\n1.2.1.1 Reference Count Details (refcountDetails.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.3", "length": 3777, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/refcounts.html"} {"title": "A. Reporting Bugs", "text": "supporting-cycle-detection.html | api.html | node80.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.9 Supporting Cyclic Garbarge (supporting-cycle-detection.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\nB. History and License (node80.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.\nBefore submitting a report, you will be required to log into SourceForge;\nthis will make it possible for the developers to contact you\nfor additional information if needed. It is not possible to submit a\nbug report anonymously.\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.\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. You will\nreceive an update each time action is taken on the bug.\nSee Also:", "python_version": "2.3", "length": 2593, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/reporting-bugs.html"} {"title": "10.6 Sequence Object Structures", "text": "number-structs.html | newTypes.html | buffer-structs.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.5 Number Object Structures (number-structs.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.7 Buffer Object Structures (buffer-structs.html)\n---\n# 10.6 Sequence Object Structures", "python_version": "2.3", "length": 333, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.2 Number Protocol (number.html)\nUp:\n6. Abstract Objects Layer (abstract.html)\nNext:\n6.4 Mapping Protocol (mapping.html)\n---\n# 6.3 Sequence Protocol", "python_version": "2.3", "length": 266, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/sequence.html"} {"title": "7.3 Sequence Objects", "text": "node39.html | concrete.html | stringObjects.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.2.4.2 Complex Numbers as (node39.html)\nUp:\n7. Concrete Objects Layer (concrete.html)\nNext:\n7.3.1 String Objects (stringObjects.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.3", "length": 469, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.6 Descriptor Objects (descriptor-objects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.8 Weak Reference Objects (weakref-objects.html)\n---\n## 7.5.7 Slice Objects", "python_version": "2.3", "length": 318, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4. Exception Handling (exceptionHandling.html)\nUp:\n4. Exception Handling (exceptionHandling.html)\nNext:\n4.2 Deprecation of String (node15.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.3", "length": 778, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3 Sequence Objects (sequenceObjects.html)\nUp:\n7.3 Sequence Objects (sequenceObjects.html)\nNext:\n7.3.2 Unicode Objects (unicodeObjects.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.3", "length": 419, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/stringObjects.html"} {"title": "10.9 Supporting Cyclic Garbarge Collection", "text": "supporting-iteration.html | newTypes.html | reporting-bugs.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.8 Supporting the Iterator (supporting-iteration.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\nA. Reporting Bugs (reporting-bugs.html)\n---\n# 10.9 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.\nAn example showing the use of these interfaces can be found in\n``Supporting the Cycle\nCollector (../ext/example-cycle-support.html)'' in\nExtending and Embedding the Python\nInterpreter (../ext/ext.html).\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.3", "length": 1930, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/supporting-cycle-detection.html"} {"title": "10.8 Supporting the Iterator Protocol", "text": "buffer-structs.html | newTypes.html | supporting-cycle-detection.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.7 Buffer Object Structures (buffer-structs.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.9 Supporting Cyclic Garbarge (supporting-cycle-detection.html)\n---\n# 10.8 Supporting the Iterator Protocol", "python_version": "2.3", "length": 365, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8. Initialization, Finalization, and (initialization.html)\nUp:\n8. Initialization, Finalization, and (initialization.html)\nNext:\n8.2 Profiling and Tracing (profiling.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 100 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\nPy_BEGIN_ALLOW_THREADSmacro opens a new block and declares a hidden local variable; the\nPy_END_ALLOW_THREADSmacro closes the block. Another advantage of using these two macros\nis that when Python is compiled without thread support, they are\ndefined empty, thus 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).\nAssuming you have access to an interpreter object, the typical idiom\nfor calling into Python from a C thread is\n```text\n\nPyThreadState *tstate;\nPyObject *result;\n\n/* interp is your reference to an interpreter object. */\ntstate = PyThreadState_New(interp);\nPyEval_AcquireThread(tstate);\n\n/* Perform Python actions here. */\nresult = CallSomeFunction();\n/* evaluate result */\n\n/* Release the thread. No Python API allowed beyond this point. */\nPyEval_ReleaseThread(tstate);\n\n/* You can either delete the thread state, or save it\nuntil you need it the next time. */\nPyThreadState_Delete(tstate);\n```\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.3", "length": 6530, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3.3 Buffer Objects (bufferObjects.html)\nUp:\n7.3 Sequence Objects (sequenceObjects.html)\nNext:\n7.3.5 List Objects (listObjects.html)\n---\n## 7.3.4 Tuple Objects", "python_version": "2.3", "length": 295, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/tupleObjects.html"} {"title": "10.3 Type Objects", "text": "common-structs.html | newTypes.html | mapping-structs.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n10.2 Common Object Structures (common-structs.html)\nUp:\n10. Object Implementation Support (newTypes.html)\nNext:\n10.4 Mapping Object Structures (mapping-structs.html)\n---\n# 10.3 Type Objects\nPerhaps one of the most important structures of the Python object\nsystem is the structure that defines a new type: the\nPyTypeObject structure. Type objects can be handled using any\nof the PyObject_*() or PyType_*() functions,\nbut do not offer much that's interesting to most Python applications.\nThese objects are fundamental to how objects behave, so they are very\nimportant to the interpreter itself and to any extension module that\nimplements new types.\nType objects are fairly large compared to most of the standard types.\nThe reason for the size is that each type object stores a large number\nof values, mostly C function pointers, each of which implements a\nsmall part of the type's functionality. The fields of the type object\nare examined in detail in this section. The fields will be described\nin the order in which they occur in the structure.\nTypedefs:\nunaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,\nintintargfunc, intobjargproc, intintobjargproc, objobjargproc,\ndestructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc,\nsetattrofunc, cmpfunc, reprfunc, hashfunc\nThe structure definition for PyTypeObject can be found in\nInclude/object.h. For convenience of reference, this repeats\nthe definition found there:\n```text\ntypedef struct _typeobject {\nPyObject_VAR_HEAD\nchar *tp_name; /* For printing, in format \".\" */\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 PyMemberDef *tp_members;\nstruct PyGetSetDef *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;\nfreefunc tp_free; /* Low-level free-memory routine */\ninquiry tp_is_gc; /* For PyObject_IS_GC */\nPyObject *tp_bases;\nPyObject *tp_mro; /* method resolution order */\nPyObject *tp_cache;\nPyObject *tp_subclasses;\nPyObject *tp_weaklist;\n\n} PyTypeObject;\n```\nDownload as text (original file name: typestruct.h). (typestruct.txt)\nThe type object structure extends the PyVarObject structure.\nThe ob_size field is used for dynamic types (created\nby type_new(), usually called from a class statement).\nNote that PyType_Type (the metatype) initializes\ntp_itemsize, which means that its instances (i.e. type\nobjects) must have the ob_size field.\nPyNumberMethods *tp_as_number;\nXXX\nPySequenceMethods *tp_as_sequence;\nXXX\nPyMappingMethods *tp_as_mapping;\nXXX\nThe following three fields only exist if the\nPy_TPFLAGS_HAVE_RICHCOMPARE flag bit is set.\nThe next field only exists if the Py_TPFLAGS_HAVE_WEAKREFS\nflag bit is set.\nThe next two fields only exist if the\nPy_TPFLAGS_HAVE_CLASS flag bit is set.\nThe next fields, up to and including tp_weaklist, only exist\nif the Py_TPFLAGS_HAVE_CLASS flag bit is set.\nThe remaining fields are only defined if the feature test macro\nCOUNT_ALLOCS is defined, and are for internal use only.\nThey are documented here for completeness. None of these fields are\ninherited by subtypes.", "python_version": "2.3", "length": 4485, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/type-structs.html"} {"title": "7.1.1 Type Objects", "text": "fundamental.html | fundamental.html | noneObject.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n7.1 Fundamental Objects (fundamental.html)\nUp:\n7.1 Fundamental Objects (fundamental.html)\nNext:\n7.1.2 The None Object (noneObject.html)\n---\n## 7.1.1 Type Objects", "python_version": "2.3", "length": 289, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/typeObjects.html"} {"title": "1.2.2 Types", "text": "refcountDetails.html | objects.html | exceptions.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n1.2.1.1 Reference Count Details (refcountDetails.html)\nUp:\n1.2 Objects, Types and (objects.html)\nNext:\n1.3 Exceptions (exceptions.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.3", "length": 704, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3.2.1 Built-in Codecs (builtinCodecs.html)\nUp:\n7.3.2 Unicode Objects (unicodeObjects.html)\nNext:\n7.3.3 Buffer Objects (bufferObjects.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.3", "length": 557, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3.1 String Objects (stringObjects.html)\nUp:\n7.3 Sequence Objects (sequenceObjects.html)\nNext:\n7.3.2.1 Built-in Codecs (builtinCodecs.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.3", "length": 1094, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/unicodeObjects.html"} {"title": "5. Utilities", "text": "node15.html | api.html | os.html | Python/C API Reference Manual | contents.html | genindex.html\nPrevious:\n4.2 Deprecation of String (node15.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n5.1 Operating System Utilities (os.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.3", "length": 487, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.4 Embedding Python (embedding.html)\nUp:\nPython/C API Reference Manual (api.html)\nNext:\n3. Reference Counting (countingRefs.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.3", "length": 1202, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.7 Slice Objects (slice-objects.html)\nUp:\n7.5 Other Objects (otherObjects.html)\nNext:\n7.5.9 CObjects (cObjects.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.3", "length": 532, "url": "https://docs.python.org/2.3/Python-Docs-2.3/api/weakref-objects.html"} {"title": "About this document ...", "text": "module-distutils.sysconfig.html | dist.html | Distributing Python Modules\nPrevious:\n10 distutils.sysconfig (module-distutils.sysconfig.html)\nUp:\nDistributing Python Modules (dist.html)\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, either in the content or the presentation, please\nreport 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\nPrevious:\n10 distutils.sysconfig (module-distutils.sysconfig.html)\nUp:\nDistributing Python Modules (dist.html)\n---", "python_version": "2.3", "length": 1867, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/about.html"} {"title": "Distributing Python Modules", "text": "../index.html | intro.html | Distributing Python Modules\nUp:\nPython Documentation Index (../index.html)\nNext:\n1 Introduction (intro.html)\n---\n# Distributing Python Modules\nGreg Ward\nEmail: distutils-sig@python.org\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.3", "length": 518, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/dist.html"} {"title": "Distributing Python Modules", "text": "../index.html | intro.html | Distributing Python Modules\nUp:\nPython Documentation Index (../index.html)\nNext:\n1 Introduction (intro.html)\n---\n# Distributing Python Modules\nGreg Ward\nEmail: distutils-sig@python.org\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.3", "length": 518, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/index.html"} {"title": "1 Introduction", "text": "dist.html | dist.html | simple-example.html | Distributing Python Modules\nPrevious:\nDistributing Python Modules (dist.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n2 Concepts & Terminology (simple-example.html)\n---\n# 1 Introduction\nThis document covers using the Distutils to distribute your Python\nmodules, concentrating 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.3", "length": 511, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/intro.html"} {"title": "10 distutils.sysconfig -- System configuration information", "text": "sdist-cmd.html | dist.html | about.html | Distributing Python Modules\nPrevious:\n9 Reference (sdist-cmd.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\nAbout this document ... (about.html)\n---\n# 10 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.3", "length": 1102, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/module-distutils.sysconfig.html"} {"title": "7 Registering with the Package Index", "text": "postinstallation-script.html | dist.html | single-ext.html | Distributing Python Modules\nPrevious:\n6 Creating Built Distributions (postinstallation-script.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n8 Examples (single-ext.html)\n---\n# 7 Registering with the Package Index\nThe Python Package Index (PyPI) holds meta-data describing distributions\npackaged with distutils. The distutils command `register` is\nused to submit your distribution's meta-data to the index. It is invoked\nas follows:\n```text\n\npython setup.py register\n```\nDistutils will respond with the following prompt:\n```text\n\nrunning register\nWe need to know who you are, so please choose either:\n1. use your existing login,\n2. register as a new user,\n3. have the server generate a new password for you (and email it to you), or\n4. quit\nYour selection [default 1]:\n```\nNote: if your username and password are saved locally, you will\nnot see this menu.\nIf you have not registered with PyPI, then you will need to do so now. You\nshould choose option 2, and enter your details as required. Soon after\nsubmitting your details, you will receive an email which will be used to\nconfirm your registration.\nOnce you are registered, you may choose option 1 from the menu. You will\nbe prompted for your PyPI username and password, and `register`\nwill then submit your meta-data to the index.\nYou may submit any number of versions of your distribution to the index. If\nyou alter the meta-data for a particular version, you may submit it again\nand the index will be updated.\nPyPI holds a record for each (name, version) combination submitted. The\nfirst user to submit information for a given name is designated the Owner\nof that name. They may submit changes through the `register`\ncommand or through the web interface. They may also designate other users\nas Owners or Maintainers. Maintainers may edit the package information, but\nnot designate other Owners or Maintainers.\nBy default PyPI will list all versions of a given package. To hide certain\nversions, the Hidden property should be set to yes. This must be edited\nthrough the web interface.", "python_version": "2.3", "length": 2108, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/package-index.html"} {"title": "6 Creating Built Distributions", "text": "source-dist.html | dist.html | package-index.html | Distributing Python Modules\nPrevious:\n5 Creating a Source (source-dist.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n7 Registering with the (package-index.html)\n---\n- 6.1 Creating dumb built distributions (postinstallation-script.html#SECTION000610000000000000000)\n 6.2 Creating RPM packages (postinstallation-script.html#SECTION000620000000000000000)\n 6.3 Creating Windows Installers (postinstallation-script.html#SECTION000630000000000000000)\n - 6.3.1 The Postinstallation script (postinstallation-script.html#SECTION000631000000000000000)\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 called packagers 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 who they are, 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 a 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-1.0.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 any simpler than\njust running `python setup.py install`--but for non-pure\ndistributions, which include extensions that would need to be\ncompiled, it can mean the difference between someone being able to use\nyour extensions or not. And creating ``smart'' built distributions,\nsuch as an RPM package or an executable installer for Windows, is far\nmore convenient for users even if your distribution doesn't include\nany 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-1.0.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 (part of the standard Python library since\nPython 1.6)\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 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.)\n## 6.3 Creating Windows Installers\nExecutable installers are the natural format for binary distributions\non Windows. They display a nice graphical user interface, display\nsome information about the module distribution to be installed taken\nfrom the metadata in the setup script, let the user select a few\noptions, and start or cancel the installation.\nSince the metadata is taken from the setup script, creating Windows\ninstallers is usually as easy as running:\n```text\n\npython setup.py bdist_wininst\n```\nor the `bdist` command with the --formats option:\n```text\n\npython setup.py bdist --formats=wininst\n```\nIf you have a pure module distribution (only containing pure Python\nmodules and packages), the resulting installer will be version\nindependent and have a name like foo-1.0.win32.exe. These\ninstallers 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 dependent.\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. If\nyou don't want this to happen for some reason, you can run the\n`bdist_wininst` command with the\n--no-target-compile and/or the\n--no-target-optimize option.\nBy default the installer will display the cool ``Python Powered'' logo\nwhen it is run, but you can also supply your own bitmap which must be\na Windows .bmp file with the --bitmap option.\nThe installer will also display a large title on the desktop\nbackground window when it is run, which is constructed from the name\nof your distribution and the version number. This can be changed to\nanother text by using the --title option.\nThe installer file will be written to the ``distribution directory''\n-- normally dist/, but customizable with the\n--dist-dir option.\n### 6.3.1 The Postinstallation script\nStarting with Python 2.3, a postinstallation script can be specified\nwhich the --install-script option. The basename of the\nscript must be specified, and the script filename must also be listed\nin the scripts argument to the setup function.\nThis script will be run at installation time on the target system\nafter all the files have been copied, with argv[1] set to '-install',\nand again at uninstallation time before the files are removed with argv[1]\nset to '-remove'.\nThe installation script runs embedded in the windows installer, every\noutput (sys.stdout, sys.stderr) is redirected into a buffer and will\nbe displayed in the GUI after the script has finished.\nSome functions especially useful in this context are available in the\ninstallation script.\n```text\n\ndir_created(pathname)\nfile_created(pathname)\n```\nThese functions should be called when a directory or file is created\nby the postinstall script at installation time. It will register the\npathname with the uninstaller, so that it will be removed when the\ndistribution is uninstalled. To be safe, directories are only removed\nif they are empty.\n```text\n\nget_special_folder_path(csidl_string)\n```\nThis function can be used to retrieve special folder locations on\nWindows like the Start Menu or the Desktop. It returns the full path\nto the folder. 'csidl_string' must be on of the following strings:\n```text\n\n\"CSIDL_APPDATA\"\n\n\"CSIDL_COMMON_STARTMENU\"\n\"CSIDL_STARTMENU\"\n\n\"CSIDL_COMMON_DESKTOPDIRECTORY\"\n\"CSIDL_DESKTOPDIRECTORY\"\n\n\"CSIDL_COMMON_STARTUP\"\n\"CSIDL_STARTUP\"\n\n\"CSIDL_COMMON_PROGRAMS\"\n\"CSIDL_PROGRAMS\"\n\n\"CSIDL_FONTS\"\n```\nIf the folder cannot be retrieved, OSError is raised.\nWhich folders are available depends on the exact Windows version, and probably\nalso the configuration. For details refer to Microsoft's documentation of the\n`SHGetSpecialFolderPath` function.\n```text\n\ncreate_shortcut(target, description, filename[, arguments[,\nworkdir[, iconpath[, iconindex]]]])\n```\nThis function creates a shortcut.\ntarget is the path to the program to be started by the shortcut.\ndescription is the description of the sortcut.\nfilename is the title of the shortcut that the user will see.\narguments specifies the command line arguments, if any.\nworkdir is the working directory for the program.\niconpath is the file containing the icon for the shortcut,\nand iconindex is the index of the icon in the file\niconpath. Again, for details consult the Microsoft\ndocumentation for the `IShellLink` interface.", "python_version": "2.3", "length": 13290, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/postinstallation-script.html"} {"title": "9 Reference", "text": "single-ext.html | dist.html | module-distutils.sysconfig.html | Distributing Python Modules\nPrevious:\n8 Examples (single-ext.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n10 distutils.sysconfig (module-distutils.sysconfig.html)\n---\n- 9.1 Installing modules: the `install` command family (sdist-cmd.html#SECTION000910000000000000000)\n - 9.1.1 `install_data` (sdist-cmd.html#SECTION000911000000000000000)\n 9.1.2 `install_scripts` (sdist-cmd.html#SECTION000912000000000000000)\n 9.2 Creating a source distribution: the\n `sdist` command (sdist-cmd.html#SECTION000920000000000000000)\n---\n# 9 Reference\n## 9.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### 9.1.1 `install_data`\nThis command installs all data files provided with the distribution.\n### 9.1.2 `install_scripts`\nThis command installs all (Python) scripts in the distribution.\n## 9.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.3", "length": 1633, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/sdist-cmd.html"} {"title": "4 Writing the Setup Configuration File", "text": "setup-script.html | dist.html | source-dist.html | Distributing Python Modules\nPrevious:\n3 Writing the Setup (setup-script.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n5 Creating a Source (source-dist.html)\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.\nThe setup configuration file is a useful middle-ground between the setup\nscript--which, ideally, would be opaque to installers1 (#foot345)--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\nthe options that command supports. Any number of options can be\nsupplied for each command, and any number of command sections can be\nincluded in the file. Blank lines are ignored, as are comments, which\nrun from a \"#\" character until the end of the line. Long\noption values can be split across multiple lines simply by indenting\nthe 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```\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.3", "length": 4900, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/setup-config.html"} {"title": "3 Writing the Setup Script", "text": "simple-example.html | dist.html | setup-config.html | Distributing Python Modules\nPrevious:\n2 Concepts & Terminology (simple-example.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n4 Writing the Setup (setup-config.html)\n---\n- 3.1 Listing whole packages (setup-script.html#SECTION000310000000000000000)\n 3.2 Listing individual modules (setup-script.html#SECTION000320000000000000000)\n 3.3 Describing extension modules (setup-script.html#SECTION000330000000000000000)\n - 3.3.1 Extension names and packages (setup-script.html#SECTION000331000000000000000)\n 3.3.2 Extension source files (setup-script.html#SECTION000332000000000000000)\n 3.3.3 Preprocessor options (setup-script.html#SECTION000333000000000000000)\n 3.3.4 Library options (setup-script.html#SECTION000334000000000000000)\n 3.3.5 Other options (setup-script.html#SECTION000335000000000000000)\n 3.4 Installing Scripts (setup-script.html#SECTION000340000000000000000)\n 3.5 Installing Additional Files (setup-script.html#SECTION000350000000000000000)\n 3.6 Additional meta-data (setup-script.html#SECTION000360000000000000000)\n 3.7 Debugging the setup script (setup-script.html#SECTION000370000000000000000)\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\nmetadata, 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. For more information on the additional meta-data, see\nsection 3.7 (setup-script.html#meta-data).\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\nfunctions. If you, for example, use standard Python functions such as\nglob.glob() or os.listdir() to specify files, you\nshould be careful to write portable code instead of hardcoding path\nseparators:\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 still 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 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\nuExtension(\"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++, and\nObjective-C extensions, these are normally C/C++/Objective-C source\nfiles. (Be sure to use appropriate extensions to distinguish C++ source files: .cc and .cpp seem to be recognized by both\nUnix 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 for 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 C code like\n```text\n\n#include \n```\nIf you need to include header files from some other Python extension,\nyou can take advantage of the fact that header files are installed in a\nconsistent way by the Distutils `install_header` command. For\nexample, the Numerical Python header files are installed (on a standard\nUnix installation) to /usr/local/include/python1.5/Numerical.\n(The exact location will differ according to your platform and Python\ninstallation.) Since the Python include\ndirectory--/usr/local/include/python1.5 in this case--is always\nincluded in the search path when building Python extensions, the best\napproach is to write C code like\n```text\n\n#include \n```\nIf you must put the Numerical include directory right into your\nheader search path, though, you can find that directory using the\nDistutils sysconfig 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 respective compiler and\nlinker command lines.\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: Distutils\nwill automatically add `initmodule`\nto the list of exported symbols.\n## 3.4 Installing 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, intended to be\nstarted from the command line. Scripts don't require Distutils to do\nanything very complicated. The only clever feature is that if the\nfirst line of the script starts with `#!` and contains the word\n``python'', the Distutils will adjust the first line to refer to the\ncurrent interpreter location.\nThe scripts option simply is a list of files to be handled\nin this way. From the PyXML setup script:\n```text\n\nsetup (...\nscripts = ['scripts/xmlproc_parse', 'scripts/xmlproc_val']\n)\n```\n## 3.5 Installing Additional Files\nThe data_files option can be used to specify additional\nfiles needed by the module distribution: configuration files, message\ncatalogs, data files, anything which doesn't fit in the previous\ncategories.\ndata_files specifies a sequence of (directory,\nfiles) pairs in the following way:\n```text\n\nsetup(...\ndata_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),\n('config', ['cfg/data.cfg']),\n('/etc/init.d', ['init-script'])]\n)\n```\nNote that you can specify the directory names where the data files\nwill be installed, but you cannot rename the data files themselves.\nEach (directory, files) pair in the sequence specifies the\ninstallation directory and the files to install there. If\ndirectory is a relative path, it is interpreted relative to the\ninstallation prefix (Python's `sys.prefix` for pure-Python\npackages, `sys.exec_prefix` for packages that contain extension\nmodules). Each file name in files is interpreted relative to\nthe setup.py script at the top of the package source\ndistribution. No directory information from files is used to\ndetermine the final location of the installed file; only the name of\nthe file is used.\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.\n## 3.6 Additional meta-data\nThe setup script may include additional meta-data beyond the name and\nversion. This information includes:\nNotes:\n(1): These fields are required.\n(2): It is recommended that versions take the form\nmajor.minor[.patch[.sub]].\n(3): Either the author or the maintainer must be identified.\n(4): These fields should not be used if your package is to be\ncompatible with Python versions prior to 2.2.3 or 2.3. The list is\navailable from the PyPI website (http://www.python.org/pypi).\n\"short string\": A single line of text, not more than 200 characters.\n\"long string\": Multiple lines of plain text in ReStructuredText\nformat (see http://docutils.sf.net/).\n\"list of strings\": See below.\nNone of the string values may be Unicode.\nEncoding the version information is an art in itself. Python packages\ngenerally adhere to the version format\nmajor.minor[.patch][sub]. The major number is\n0 for\ninitial, experimental releases of software. It is incremented for\nreleases that represent major milestones in a package. The minor\nnumber is incremented when important new features are added to the\npackage. The patch number increments when bug-fix releases are\nmade. Additional trailing version information is sometimes used to\nindicate sub-releases. These are \"a1,a2,...,aN\" (for alpha releases,\nwhere functionality and API may change), \"b1,b2,...,bN\" (for beta\nreleases, which only fix bugs) and \"pr1,pr2,...,prN\" (for final\npre-release release testing). Some examples:\n0.1.0: the first, experimental release of a package\n1.0.1a2: the second alpha release of the first patch version of 1.0\nclassifiers are specified in a python list:\n```text\n\nsetup(...\nclassifiers = [\n'Development Status :: 4 - Beta',\n'Environment :: Console',\n'Environment :: Web Environment',\n'Intended Audience :: End Users/Desktop',\n'Intended Audience :: Developers',\n'Intended Audience :: System Administrators',\n'License :: OSI Approved :: Python Software Foundation License',\n'Operating System :: MacOS :: MacOS X',\n'Operating System :: Microsoft :: Windows',\n'Operating System :: POSIX',\n'Programming Language :: Python',\n'Topic :: Communications :: Email',\n'Topic :: Office/Business',\n'Topic :: Software Development :: Bug Tracking',\n],\n)\n```\nIf you wish to include classifiers in your setup.py file and also\nwish to remain backwards-compatible with Python releases prior to 2.2.3,\nthen you can include the following code fragment in your setup.py\nbefore the `setup()` call.\n```text\n\n# patch distutils if it can't cope with the \"classifiers\" or\n# \"download_url\" keywords\nif sys.version < '2.2.3':\nfrom distutils.dist import DistributionMetadata\nDistributionMetadata.classifiers = None\nDistributionMetadata.download_url = None\n```\n## 3.7 Debugging the setup script\nSometimes things go wrong, and the setup script doesn't do what the\ndeveloper wants.\nDistutils catches any exceptions when running the setup script, and\nprint a simple error message before the script is terminated. The\nmotivation for this behaviour is to not confuse administrators who\ndon't know much about Python and are trying to install a package. If\nthey get a big long traceback from deep inside the guts of Distutils,\nthey may think the package or the Python installation is broken\nbecause they don't read all the way down to the bottom and see that\nit's a permission problem.\nOn the other hand, this doesn't help the developer to find the cause\nof the failure. For this purpose, the DISTUTILS_DEBUG environment\nvariable can be set to anything except an empty string, and distutils\nwill now print detailed information what it is doing, and prints the\nfull traceback in case an exception occurrs.", "python_version": "2.3", "length": 20795, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/setup-script.html"} {"title": "2 Concepts & Terminology", "text": "intro.html | dist.html | setup-script.html | Distributing Python Modules\nPrevious:\n1 Introduction (intro.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n3 Writing the Setup (setup-script.html)\n---\n- 2.1 A Simple Example (simple-example.html#SECTION000210000000000000000)\n 2.2 General Python terminology (simple-example.html#SECTION000220000000000000000)\n 2.3 Distutils-specific terminology (simple-example.html#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\nin Python, there are no arbitrary limits to what you can do with it,\nthough you should be careful about putting arbitrarily expensive\noperations in your setup script. Unlike, say, Autoconf-style configure\nscripts, the setup script may be run multiple times in the course of\nbuilding and installing your module distribution.\nIf all you want to do is distribute a module called foo,\ncontained in a file foo.py, then your setup script can be as\nsimple as this:\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\nmetadata (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 metadata, 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.\nOther useful built distribution formats are RPM, implemented by the\n`bdist_rpm` command, Solaris pkgtool\n(`bdist_pkgtool`), and HP-UX swinstall\n(`bdist_sdux`). For example, the following command will\ncreate an RPM file called foo-1.0.noarch.rpm:\n```text\n\npython setup.py bdist_rpm\n```\n(The `bdist_rpm` command uses the `rpm` executable,\ntherefore this has to be run on an RPM-based system such as Red Hat\nLinux, 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 Jython.\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 Jython 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`\ncontributes 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\nmxBase. (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. Generally\nsetup.py will be run from this directory.", "python_version": "2.3", "length": 7893, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/simple-example.html"} {"title": "8 Examples", "text": "package-index.html | dist.html | sdist-cmd.html | Distributing Python Modules\nPrevious:\n7 Registering with the (package-index.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n9 Reference (sdist-cmd.html)\n---\n- 8.1 Pure Python distribution (by module) (single-ext.html#SECTION000810000000000000000)\n 8.2 Pure Python distribution (by package) (single-ext.html#SECTION000820000000000000000)\n 8.3 Single extension module (single-ext.html#SECTION000830000000000000000)\n---\n# 8 Examples\n## 8.1 Pure Python distribution (by module)\nIf you're just distributing a couple of modules, especially if they\ndon't live in a particular package, you can specify them individually\nusing the py_modules option in the setup script.\nIn the simplest case, you'll have two files to worry about: a setup\nscript and the single module you're distributing, foo.py in this\nexample:\n```text\n\n/\nsetup.py\nfoo.py\n```\n(In all diagrams in this section, `` will refer to the\ndistribution root directory.) A minimal setup script to describe this\nsituation would be:\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foo\", version = \"1.0\",\npy_modules = [\"foo\"])\n```\nNote that the name of the distribution is specified independently with\nthe name option, and there's no rule that says it has to be the\nsame as the name of the sole module in the distribution (although that's\nprobably a good convention to follow). However, the distribution name\nis used to generate filenames, so you should stick to letters, digits,\nunderscores, and hyphens.\nSince py_modules is a list, you can of course specify multiple\nmodules, eg. if you're distributing modules foo and\nbar, your setup might look like this:\n```text\n\n/\nsetup.py\nfoo.py\nbar.py\n```\nand the setup script might be\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\npy_modules = [\"foo\", \"bar\"])\n```\nYou can put module source files into another directory, but if you have\nenough modules to do that, it's probably easier to specify modules by\npackage rather than listing them individually.\n## 8.2 Pure Python distribution (by package)\nIf you have more than a couple of modules to distribute, especially if\nthey are in multiple packages, it's probably easier to specify whole\npackages rather than individual modules. This works even if your\nmodules are not in a package; you can just tell the Distutils to process\nmodules from the root package, and that works the same as any other\npackage (except that you don't have to have an __init__.py\nfile).\nThe setup script from the last example could also be written as\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\npackages = [\"\"])\n```\n(The empty string stands for the root package.)\nIf those two files are moved into a subdirectory, but remain in the root\npackage, e.g.:\n```text\n\n/\nsetup.py\nsrc/ foo.py\nbar.py\n```\nthen you would still specify the root package, but you have to tell the\nDistutils where source files in the root package live:\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\npackage_dir = {\"\": \"src\"},\npackages = [\"\"])\n```\nMore typically, though, you will want to distribute multiple modules in\nthe same package (or in sub-packages). For example, if the foo\nand bar modules belong in package foobar, one way to\nlayout your source tree is\n```text\n\n/\nsetup.py\nfoobar/\n__init__.py\nfoo.py\nbar.py\n```\nThis is in fact the default layout expected by the Distutils, and the\none that requires the least work to describe in your setup script:\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\npackages = [\"foobar\"])\n```\nIf you want to put modules in directories not named for their package,\nthen you need to use the package_dir option again. For\nexample, if the src directory holds modules in the\nfoobar package:\n```text\n\n/\nsetup.py\nsrc/\n__init__.py\nfoo.py\nbar.py\n```\nan appropriate setup script would be\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\npackage_dir = {\"foobar\" : \"src\"},\npackages = [\"foobar\"])\n```\nOr, you might put modules from your main package right in the\ndistribution root:\n```text\n\n/\nsetup.py\n__init__.py\nfoo.py\nbar.py\n```\nin which case your setup script would be\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\npackage_dir = {\"foobar\" : \"\"},\npackages = [\"foobar\"])\n```\n(The empty string also stands for the current directory.)\nIf you have sub-packages, they must be explicitly listed in\npackages, but any entries in package_dir\nautomatically extend to sub-packages. (In other words, the Distutils\ndoes not scan your source tree, trying to figure out which\ndirectories correspond to Python packages by looking for\n__init__.py files.) Thus, if the default layout grows a\nsub-package:\n```text\n\n/\nsetup.py\nfoobar/\n__init__.py\nfoo.py\nbar.py\nsubfoo/\n__init__.py\nblah.py\n```\nthen the corresponding setup script would be\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\npackages = [\"foobar\", \"foobar.subfoo\"])\n```\n(Again, the empty string in package_dir stands for the current\ndirectory.)\n## 8.3 Single extension module\nExtension modules are specified using the ext_modules option.\npackage_dir has no effect on where extension source files are\nfound; it only affects the source for pure Python modules. The simplest\ncase, a single extension module in a single C source file, is:\n```text\n\n/\nsetup.py\nfoo.c\n```\nIf the foo extension belongs in the root package, the setup\nscript for this could be\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\next_modules = [Extension(\"foo\", [\"foo.c\"])])\n```\nIf the extension actually belongs in a package, say foopkg,\nthen\nWith exactly the same source tree layout, this extension can be put in\nthe foopkg package simply by changing the name of the\nextension:\n```text\n\nfrom distutils.core import setup\nsetup(name = \"foobar\", version = \"1.0\",\next_modules = [Extension(\"foopkg.foo\", [\"foo.c\"])])\n```", "python_version": "2.3", "length": 6036, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/single-ext.html"} {"title": "5 Creating a Source Distribution", "text": "setup-config.html | dist.html | postinstallation-script.html | Distributing Python Modules\nPrevious:\n4 Writing the Setup (setup-config.html)\nUp:\nDistributing Python Modules (dist.html)\nNext:\n6 Creating Built Distributions (postinstallation-script.html)\n---\n- 5.1 Specifying the files to distribute (source-dist.html#SECTION000510000000000000000)\n 5.2 Manifest-related options (source-dist.html#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 a 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 (part of the standard Python library since\nPython 1.6)\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 9.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 set\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.\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.3", "length": 7115, "url": "https://docs.python.org/2.3/Python-Docs-2.3/dist/source-dist.html"} {"title": "About this document ...", "text": "discussion.html | doc.html | Documenting Python | contents.html\nPrevious:\n8.2 Discussion Forums (discussion.html)\nUp:\nDocumenting Python (doc.html)\n---\n# About this document ...\nDocumenting Python,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1656, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/about.html"} {"title": "5 Document Classes", "text": "latex-structure.html | doc.html | special-constructs.html | Documenting Python | contents.html\nPrevious:\n4.2 Hierarchical Structure (latex-structure.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n6 Special Markup Constructs (special-constructs.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.3", "length": 1733, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/classes.html"} {"title": "Contents", "text": "doc.html | doc.html | intro.html | Documenting Python\nPrevious:\nDocumenting Python (doc.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n1 Introduction (intro.html)\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 (latex-syntax.html)\n 4.2 Hierarchical Structure (latex-structure.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 6.13 Graphical Interface Components (gui-markup.html)\n 7 Processing Tools (tools.html)\n - 7.1 External Tools (tools-external.html)\n 7.2 Internal Tools (tools-internal.html)\n 7.3 Working on Cygwin (cygwin.html)\n 8 Future Directions (futures.html)\n - 8.1 Structured Documentation (structured.html)\n 8.2 Discussion Forums (discussion.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.3", "length": 1511, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/contents.html"} {"title": "7.3 Working on Cygwin", "text": "tools-internal.html | tools.html | futures.html | Documenting Python | contents.html\nPrevious:\n7.2 Internal Tools (tools-internal.html)\nUp:\n7 Processing Tools (tools.html)\nNext:\n8 Future Directions (futures.html)\n---\n## 7.3 Working on Cygwin\nInstalling the required tools under Cygwin under Cygwin can be a\nlittle tedious, if only because many packages are more difficult\nto install under Cygwin.\nUsing the Cygwin installer, make sure your Cygwin installation\nincludes Perl, Python, and the TEX packages. Perl and Python\nare located under Interpreters in the installer.\nThe TEX packages are located in the Text\nsection; installing the `tetex-beta`, `texmf`,\n`texmf-base`, and `texmf-extra` ensures that all the\nrequired packages are available. (There may be a more minimal\nset, but I've not spent time trying to minimize the installation.)\nThe netpbm package is used by LATEX2HTML, and must be\ninstalled before LATEX2HTML can be successfully installed, even\nthough they will never be used for most Python documentation.\nReferences to download locations are located in the netpbm\nREADME (http://netpbm.sourceforge.net/README). Install according\nto the instructions.\nLATEX2HTML can be installed from the source archive, but only\nafter munging one of the files in the distribution. Edit the file\nL2hos.pm in the top level of the unpacked distribution;\nnear the bottom of the file, change the text\n`$^O` with the text `'unix'`. Proceed\nusing this command to build and install the software:\n```text\n\n% configure && make install\n```\nYou should now be able to build at least the HTML, PDF, and\nPostScript versions of the formatted documentation.", "python_version": "2.3", "length": 1638, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/cygwin.html"} {"title": "2 Directory Structure", "text": "intro.html | doc.html | style-guide.html | Documenting Python | contents.html\nPrevious:\n1 Introduction (intro.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n3 Style Guide (style-guide.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.3", "length": 990, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/directories.html"} {"title": "8.2 Discussion Forums", "text": "structured.html | futures.html | about.html | Documenting Python | contents.html\nPrevious:\n8.1 Structured Documentation (structured.html)\nUp:\n8 Future Directions (futures.html)\nNext:\nAbout this document ... (about.html)\n---\n## 8.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.3", "length": 860, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/discussion.html"} {"title": "Documenting Python", "text": "../index.html | contents.html | Documenting Python | contents.html\nUp:\nPython Documentation Index (../index.html)\nNext:\n---\n# Documenting Python\nFred L. Drake, Jr.\nPythonLabs\nEmail: fdrake@acm.org\nRelease 2.3\nJuly 29, 2003\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.3", "length": 886, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/doc.html"} {"title": "8 Future Directions", "text": "cygwin.html | doc.html | structured.html | Documenting Python | contents.html\nPrevious:\n7.3 Working on Cygwin (cygwin.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n8.1 Structured Documentation (structured.html)\n---\n# 8 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.3", "length": 606, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/futures.html"} {"title": "6.12 Grammar Production Displays", "text": "indexing.html | special-constructs.html | gui-markup.html | Documenting Python | contents.html\nPrevious:\n6.11 Index-generating Markup (indexing.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.13 Graphical Interface Components (gui-markup.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.3", "length": 1311, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/grammar-displays.html"} {"title": "6.13 Graphical Interface Components", "text": "grammar-displays.html | special-constructs.html | tools.html | Documenting Python | contents.html\nPrevious:\n6.12 Grammar Production Displays (grammar-displays.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n7 Processing Tools (tools.html)\n---\n## 6.13 Graphical Interface Components\nThe components of graphical interfaces will be assigned markup, but\nmost of the specifics have not been determined.", "python_version": "2.3", "length": 419, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/gui-markup.html"} {"title": "Documenting Python", "text": "../index.html | contents.html | Documenting Python | contents.html\nUp:\nPython Documentation Index (../index.html)\nNext:\n---\n# Documenting Python\nFred L. Drake, Jr.\nPythonLabs\nEmail: fdrake@acm.org\nRelease 2.3\nJuly 29, 2003\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.3", "length": 886, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/index.html"} {"title": "6.11 Index-generating Markup", "text": "references.html | special-constructs.html | grammar-displays.html | Documenting Python | contents.html\nPrevious:\n6.10 Reference List Markup (references.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.12 Grammar Production Displays (grammar-displays.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.3", "length": 1895, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/indexing.html"} {"title": "6.3 Information Units", "text": "meta-info.html | special-constructs.html | showing-examples.html | Documenting Python | contents.html\nPrevious:\n6.2 Meta-information Markup (meta-info.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.4 Showing Code Examples (showing-examples.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.3", "length": 1851, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/info-units.html"} {"title": "6.5 Inline Markup", "text": "showing-examples.html | special-constructs.html | misc-text-markup.html | Documenting Python | contents.html\nPrevious:\n6.4 Showing Code Examples (showing-examples.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.6 Miscellaneous Text Markup (misc-text-markup.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.3", "length": 540, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/inline-markup.html"} {"title": "1 Introduction", "text": "contents.html | doc.html | directories.html | Documenting Python | contents.html\nPrevious:\nUp:\nDocumenting Python (doc.html)\nNext:\n2 Directory Structure (directories.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.3", "length": 1872, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/intro.html"} {"title": "4 LATEX Primer", "text": "style-guide.html | doc.html | latex-syntax.html | Documenting Python | contents.html\nPrevious:\n3 Style Guide (style-guide.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n4.1 Syntax (latex-syntax.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.3", "length": 2344, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/latex-primer.html"} {"title": "4.2 Hierarchical Structure", "text": "latex-syntax.html | latex-primer.html | classes.html | Documenting Python | contents.html\nPrevious:\n4.1 Syntax (latex-syntax.html)\nUp:\n4 LATEX Primer (latex-primer.html)\nNext:\n5 Document Classes (classes.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 (#foot181) 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.3", "length": 902, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/latex-structure.html"} {"title": "4.1 Syntax", "text": "latex-primer.html | latex-primer.html | latex-structure.html | Documenting Python | contents.html\nPrevious:\n4 LATEX Primer (latex-primer.html)\nUp:\n4 LATEX Primer (latex-primer.html)\nNext:\n4.2 Hierarchical Structure (latex-structure.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 characters which are not found in ASCII or which a\nconsidered special, or active in TEX or LATEX. Given\nthat these are often used adjacent to other characters, the markup\nrequired to produce the proper character may need to be followed\nby a space or an empty group, or the markup can be enclosed in a\ngroup. Some which are found in Python documentation are:", "python_version": "2.3", "length": 5729, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/latex-syntax.html"} {"title": "6.8 Library-level Markup", "text": "module-markup.html | special-constructs.html | table-markup.html | Documenting Python | contents.html\nPrevious:\n6.7 Module-specific Markup (module-markup.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.9 Table Markup (table-markup.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.3", "length": 591, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/library-markup.html"} {"title": "6.2 Meta-information Markup", "text": "preamble-info.html | special-constructs.html | info-units.html | Documenting Python | contents.html\nPrevious:\n6.1 Markup for the (preamble-info.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.3 Information Units (info-units.html)\n---\n## 6.2 Meta-information Markup", "python_version": "2.3", "length": 288, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/meta-info.html"} {"title": "6.6 Miscellaneous Text Markup", "text": "inline-markup.html | special-constructs.html | module-markup.html | Documenting Python | contents.html\nPrevious:\n6.5 Inline Markup (inline-markup.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.7 Module-specific Markup (module-markup.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.3", "length": 610, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.6 Miscellaneous Text Markup (misc-text-markup.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.8 Library-level Markup (library-markup.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.3", "length": 1444, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/module-markup.html"} {"title": "6.1 Markup for the Preamble", "text": "special-constructs.html | special-constructs.html | meta-info.html | Documenting Python | contents.html\nPrevious:\n6 Special Markup Constructs (special-constructs.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.2 Meta-information Markup (meta-info.html)\n---\n## 6.1 Markup for the Preamble", "python_version": "2.3", "length": 311, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/preamble-info.html"} {"title": "6.10 Reference List Markup", "text": "table-markup.html | special-constructs.html | indexing.html | Documenting Python | contents.html\nPrevious:\n6.9 Table Markup (table-markup.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.11 Index-generating Markup (indexing.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.3", "length": 1389, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/references.html"} {"title": "6.4 Showing Code Examples", "text": "info-units.html | special-constructs.html | inline-markup.html | Documenting Python | contents.html\nPrevious:\n6.3 Information Units (info-units.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.5 Inline Markup (inline-markup.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.3", "length": 2018, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/showing-examples.html"} {"title": "6 Special Markup Constructs", "text": "classes.html | doc.html | preamble-info.html | Documenting Python | contents.html\nPrevious:\n5 Document Classes (classes.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n6.1 Markup for the (preamble-info.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.3", "length": 379, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/special-constructs.html"} {"title": "8.1 Structured Documentation", "text": "futures.html | futures.html | discussion.html | Documenting Python | contents.html\nPrevious:\n8 Future Directions (futures.html)\nUp:\n8 Future Directions (futures.html)\nNext:\n8.2 Discussion Forums (discussion.html)\n---\n## 8.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.3", "length": 3589, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/structured.html"} {"title": "3 Style Guide", "text": "directories.html | doc.html | latex-primer.html | Documenting Python | contents.html\nPrevious:\n2 Directory Structure (directories.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n4 LATEX Primer (latex-primer.html)\n---\n# 3 Style Guide\nThe Python documentation should follow the Apple Publications Style Guide (http://developer.apple.com/documentation/UserExperience/Conceptual/APStyleGuide/AppleStyleGuide2003.pdf) wherever possible. This particular\nstyle guide was selected mostly because it seems reasonable and is\neasy to get online.\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\nname.", "python_version": "2.3", "length": 2061, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/style-guide.html"} {"title": "6.9 Table Markup", "text": "library-markup.html | special-constructs.html | references.html | Documenting Python | contents.html\nPrevious:\n6.8 Library-level Markup (library-markup.html)\nUp:\n6 Special Markup Constructs (special-constructs.html)\nNext:\n6.10 Reference List Markup (references.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\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.\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\\lineii{FutureWarning}\n{Base category for warnings about constructs that will change\nsemantically in the future.}\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.3", "length": 4084, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/table-markup.html"} {"title": "7.1 External Tools", "text": "tools.html | tools.html | tools-internal.html | Documenting Python | contents.html\nPrevious:\n7 Processing Tools (tools.html)\nUp:\n7 Processing Tools (tools.html)\nNext:\n7.2 Internal Tools (tools-internal.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: 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.3", "length": 3023, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/tools-external.html"} {"title": "7.2 Internal Tools", "text": "tools-external.html | tools.html | cygwin.html | Documenting Python | contents.html\nPrevious:\n7.1 External Tools (tools-external.html)\nUp:\n7 Processing Tools (tools.html)\nNext:\n7.3 Working on Cygwin (cygwin.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. It is usually a good idea to\nalways use the latest version of this tool rather than a\nversion from an older source release of Python.\nXXX Need more here.", "python_version": "2.3", "length": 1137, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/tools-internal.html"} {"title": "7 Processing Tools", "text": "gui-markup.html | doc.html | tools-external.html | Documenting Python | contents.html\nPrevious:\n6.13 Graphical Interface Components (gui-markup.html)\nUp:\nDocumenting Python (doc.html)\nNext:\n7.1 External Tools (tools-external.html)\n---\n# 7 Processing Tools", "python_version": "2.3", "length": 255, "url": "https://docs.python.org/2.3/Python-Docs-2.3/doc/tools.html"} {"title": "About this document ...", "text": "node50.html | ext.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\nB.2 Terms and conditions (node50.html)\nUp:\nExtending and Embedding the (ext.html)\n---\n# About this document ...\nExtending and Embedding the Python Interpreter,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1716, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.2 Intermezzo: Errors and (errors.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.4 The Module's Method (methodTable.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.3", "length": 1916, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/backToExample.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\nPrevious:\n3.1 Distributing your extension (distributing.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\n4.1 A Cookbook Approach (win-cookbook.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.\nModule authors are encouraged to use the distutils approach for\nbuilding extension modules, instead of the one described in this\nsection. You will still need the C compiler that was used to build\nPython; typically Microsoft Visual C++.\nNote:\nThis chapter mentions a number of filenames that include an encoded\nPython version number. These filenames are represented with the\nversion number shown as \"XY\"; in practive, \"X\" will\nbe the major version number and \"Y\" will be the minor\nversion number of the Python release you're working with. For\nexample, if you are using Python 2.2.1, \"XY\" will actually be\n\"22\".", "python_version": "2.3", "length": 1327, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/building-on-windows.html"} {"title": "3. Building C and C++ Extensions with distutils", "text": "node33.html | ext.html | distributing.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.6 More Suggestions (node33.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\n3.1 Distributing your extension (distributing.html)\n---\n# 3. Building C and C++ Extensions with distutils\nStarting in Python 1.4, Python provides, on Unix, a special make\nfile for building make files for building dynamically-linked\nextensions and custom interpreters. Starting with Python 2.0, this\nmechanism (known as related to Makefile.pre.in, and Setup files) is no\nlonger supported. Building custom interpreters was rarely used, and\nextension modules can be built using distutils.\nBuilding an extension module using distutils requires that distutils\nis installed on the build machine, which is included in Python 2.x and\navailable separately for Python 1.5. Since distutils also supports\ncreation of binary packages, users don't necessarily need a compiler\nand distutils to install the extension.\nA distutils package contains a driver script, setup.py. This is\na plain Python file, which, in the most simple case, could look like\nthis:\n```text\n\nfrom distutils.core import setup, Extension\n\nmodule1 = Extension('demo',\nsources = ['demo.c'])\n\nsetup (name = 'PackageName',\nversion = '1.0',\ndescription = 'This is a demo package',\next_modules = [module1])\n```\nWith this setup.py, and a file demo.c, running\n```text\n\npython setup.py build\n```\nwill compile demo.c, and produce an extension module named\n\"demo\" in the build directory. Depending on the system,\nthe module file will end up in a subdirectory build/lib.system,\nand may have a name like demo.so or demo.pyd.\nIn the setup.py, all execution is performed by calling the\n\"setup\" function. This takes a variable number of keyword\narguments, of which the example above uses only a\nsubset. Specifically, the example specifies meta-information to build\npackages, and it specifies the contents of the package. Normally, a\npackage will contain of addition modules, like Python source modules,\ndocumentation, subpackages, etc. Please refer to the distutils\ndocumentation in Distributing Python\nModules (../dist/dist.html) to learn more about the features of distutils; this section\nexplains building extension modules only.\nIt is common to pre-compute arguments to setup, to better\nstructure the driver script. In the example above,\nthe\"ext_modules\" argument to setup is a list of\nextension modules, each of which is an instance of the\nExtension. In the example, the instance defines an extension\nnamed \"demo\" which is build by compiling a single source file,\ndemo.c.\nIn many cases, building an extension is more complex, since additional\npreprocessor defines and libraries may be needed. This is demonstrated\nin the example below.\n```text\n\nfrom distutils.core import setup, Extension\n\nmodule1 = Extension('demo',\ndefine_macros = [('MAJOR_VERSION', '1'),\n('MINOR_VERSION', '0')],\ninclude_dirs = ['/usr/local/include'],\nlibraries = ['tcl83'],\nlibrary_dirs = ['/usr/local/lib'],\nsources = ['demo.c'])\n\nsetup (name = 'PackageName',\nversion = '1.0',\ndescription = 'This is a demo package',\nauthor = 'Martin v. Loewis',\nauthor_email = 'martin@v.loewis.de',\nurl = 'http://www.python.org/doc/current/ext/building.html',\nlong_description = '''\nThis is really just a demo package.\n''',\next_modules = [module1])\n```\nIn this example, setup is called with additional\nmeta-information, which is recommended when distribution packages have\nto be built. For the extension itself, it specifies preprocessor\ndefines, include directories, library directories, and libraries.\nDepending on the compiler, distutils passes this information in\ndifferent ways to the compiler. For example, on Unix, this may\nresult in the compilation commands\n```text\n\ngcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o\n\ngcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so\n```\nThese lines are for demonstration purposes only; distutils users\nshould trust that distutils gets the invocations right.", "python_version": "2.3", "length": 4198, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/building.html"} {"title": "1.9 Building Arbitrary Values", "text": "parseTupleAndKeywords.html | intro.html | refcounts.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n1.8 Keyword Parameters for (parseTupleAndKeywords.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.10 Reference Counts (refcounts.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.\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.3", "length": 1926, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.5 Compilation and Linkage (compilation.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.7 Extracting Parameters in (parseTuple.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(PyObject *dummy, PyObject *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.3", "length": 5805, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/callingPython.html"} {"title": "1.5 Compilation and Linkage", "text": "methodTable.html | intro.html | callingPython.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n1.4 The Module's Method (methodTable.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.6 Calling Python Functions (callingPython.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 may depend on the style of dynamic loading your\nsystem uses; see the chapters about building extension modules\n(chapter 3 (building.html#building)) and additional information that pertains only\nto building on Windows (chapter 4 (building-on-windows.html#building-on-windows)) for more\ninformation 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 on Unix: just place your file (spammodule.c for\nexample) in the Modules/ directory of an unpacked source\ndistribution, add a line to the file Modules/Setup.local\ndescribing 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.3", "length": 1635, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/compilation.html"} {"title": "Contents", "text": "front.html | ext.html | intro.html | Extending and Embedding the Python Interpreter\nPrevious:\nFront Matter (front.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\n1. Extending Python with (intro.html)\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.1.1 Adding data and methods to the Basic example (node22.html)\n 2.1.2 Providing finer control over data attributes (node23.html)\n 2.1.3 Supporting cyclic garbage collection (node24.html)\n 2.2 Type Methods (dnt-type-methods.html)\n - 2.2.1 Finalization and De-allocation (node26.html)\n 2.2.2 Object Presentation (node27.html)\n 2.2.3 Attribute Management (node28.html)\n 2.2.4 Object Comparison (node31.html)\n 2.2.5 Abstract Protocol Support (node32.html)\n 2.2.6 More Suggestions (node33.html)\n 3. Building C and C++ Extensions with distutils (building.html)\n - 3.1 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 (node48.html)\n - B.1 History of the software (node49.html)\n B.2 Terms and conditions for accessing or otherwise using Python (node50.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.3", "length": 2838, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.10.4 NULL Pointers (nullPointers.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.12 Providing a C (using-cobjects.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.3", "length": 923, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/cplusplus.html"} {"title": "2. Defining New Types", "text": "using-cobjects.html | ext.html | dnt-basics.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n1.12 Providing a C (using-cobjects.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\n2.1 The Basics (dnt-basics.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.\nNote:\nThe way new types are defined changed dramatically (and for the\nbetter) in Python 2.2. This document documents how to define new\ntypes for Python 2.2 and later. If you need to support older\nversions of Python, you will need to refer to older versions of this\ndocumentation.", "python_version": "2.3", "length": 895, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/defining-new-types.html"} {"title": "3.1 Distributing your extension modules", "text": "building.html | building.html | building-on-windows.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n3. Building C and (building.html)\nUp:\n3. Building C and (building.html)\nNext:\n4. Building C and (building-on-windows.html)\n---\n# 3.1 Distributing your extension modules\nWhen an extension has been successfully build, there are three ways to\nuse it.\nEnd-users will typically want to install the module, they do so by\nrunning\n```text\n\npython setup.py install\n```\nModule maintainers should produce source packages; to do so, they run\n```text\n\npython setup.py sdist\n```\nIn some cases, additional files need to be included in a source\ndistribution; this is done through a MANIFEST.in file; see the\ndistutils documentation for details.\nIf the source distribution has been build successfully, maintainers\ncan also create binary distributions. Depending on the platform, one\nof the following commands can be used to do so.", "python_version": "2.3", "length": 945, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/distributing.html"} {"title": "2.1 The Basics", "text": "defining-new-types.html | defining-new-types.html | node22.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2. Defining New Types (defining-new-types.html)\nUp:\n2. Defining New Types (defining-new-types.html)\nNext:\n2.1.1 Adding data and (node22.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. These C functions are called ``type methods'' to distinguish\nthem from things like `[].append` (which we call ``object\nmethods'').\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#include \n\ntypedef struct {\nPyObject_HEAD\n/* Type-specific fields go here. */\n} noddy_NoddyObject;\n\nstatic PyTypeObject noddy_NoddyType = {\nPyObject_HEAD_INIT(NULL)\n0, /*ob_size*/\n\"noddy.Noddy\", /*tp_name*/\nsizeof(noddy_NoddyObject), /*tp_basicsize*/\n0, /*tp_itemsize*/\n0, /*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, /*tp_flags*/\n\"Noddy objects\", /* tp_doc */\n};\n\nstatic PyMethodDef noddy_methods[] = {\n{NULL} /* Sentinel */\n};\n\n#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */\n#define PyMODINIT_FUNC void\n#endif\nPyMODINIT_FUNC\ninitnoddy(void)\n{\nPyObject* m;\n\nnoddy_NoddyType.tp_new = PyType_GenericNew;\nif (PyType_Ready(&noddy_NoddyType) < 0)\nreturn;\n\nm = Py_InitModule3(\"noddy\", noddy_methods,\n\"Example module that creates an extension type.\");\n\nPy_INCREF(&noddy_NoddyType);\nPyModule_AddObject(m, \"Noddy\", (PyObject *)&noddy_NoddyType);\n}\n```\nDownload as text (original file name: noddy.c). (noddy.txt)\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\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, namely 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 in debug builds. Note that there is\nno semicolon after the `PyObject_HEAD` macro; one is included in\nthe macro definition. Be wary of adding one by accident; it's easy to\ndo from habit, and your compiler might not complain, but someone\nelse's probably will! (On Windows, MSVC is known to call this an\nerror and refuse to compile the code.)\nFor contrast, let's take a look at the corresponding definition for\nstandard Python integers:\n```text\n\ntypedef struct {\nPyObject_HEAD\nlong ob_ival;\n} PyIntObject;\n```\nMoving on, we come to the crunch -- the type object.\n```text\n\nstatic PyTypeObject noddy_NoddyType = {\nPyObject_HEAD_INIT(NULL)\n0, /*ob_size*/\n\"noddy.Noddy\", /*tp_name*/\nsizeof(noddy_NoddyObject), /*tp_basicsize*/\n0, /*tp_itemsize*/\n0, /*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, /*tp_flags*/\n\"Noddy objects\", /* tp_doc */\n};\n```\nNow if you go and look up the definition of PyTypeObject in\nobject.h you'll see that it has 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 we're 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. Fortunately, this member\nwill be filled in for us by PyType_Ready().\n```text\n\n0, /* ob_size */\n```\nThe ob_size field of the header is not used; its presence in\nthe type structure is a historical artifact that is maintained for\nbinary compatibility with extension modules compiled for older\nversions of Python. Always set this field to zero.\n```text\n\n\"noddy.Noddy\", /* tp_name */\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.Noddy\" to string\n```\nNote that the name is a dotted name that includes both the module name\nand the name of the type within the module. The module in this case is\nnoddy and the type is Noddy, so we set the type name\nto noddy.Noddy.\n```text\n\nsizeof(noddy_NoddyObject), /* tp_basicsize */\n```\nThis is so that Python knows how much memory to allocate when you call\nPyObject_New().\n```text\n\n0, /* tp_itemsize */\n```\nThis has to do with variable length objects like lists and strings.\nIgnore this for now.\nSkipping a number of type methods that we don't provide, we set the\nclass flags to Py_TPFLAGS_DEFAULT.\n```text\n\nPy_TPFLAGS_DEFAULT, /*tp_flags*/\n```\nAll types should include this constant in their flags. It enables all\nof the members defined by the current version of Python.\nWe provide a doc string for the type in tp_doc.\n```text\n\n\"Noddy objects\", /* tp_doc */\n```\nNow we get into the type methods, the things that make your objects\ndifferent from the others. We aren't going to implement any of these\nin this version of the module. We'll expand this example later to\nhave more interesting behavior.\nFor now, all we want to be able to do is to create new Noddy\nobjects. To enable object creation, we have to provide a\ntp_new implementation. In this case, we can just use the\ndefault implementation provided by the API function\nPyType_GenericNew(). We'd like to just assign this to the\ntp_new slot, but we can't, for portability sake, On some\nplatforms or compilers, we can't statically initialize a structure\nmember with a function defined in another C module, so, instead, we'll\nassign the tp_new slot in the module initialization function\njust before calling PyType_Ready():\n```text\n\nnoddy_NoddyType.tp_new = PyType_GenericNew;\nif (PyType_Ready(&noddy_NoddyType) < 0)\nreturn;\n```\nAll the other type methods are NULL, so we'll go over them later\n-- that's for a later section!\nEverything else in the file should be familiar, except for some code\nin initnoddy():\n```text\n\nif (PyType_Ready(&noddy_NoddyType) < 0)\nreturn;\n```\nThis initializes the Noddy type, filing in a number of\nmembers, including ob_type that we initially set to NULL.\n```text\n\nPyModule_AddObject(m, \"Noddy\", (PyObject *)&noddy_NoddyType);\n```\nThis adds the type to the module dictionary. This allows us to create\nNoddy instances by calling the Noddy class:\n```text\n\nimport noddy\nmynoddy = noddy.Noddy()\n```\nThat's it! All that remains is to build it; put the above code in a\nfile called noddy.c and\n```text\n\nfrom distutils.core import setup, Extension\nsetup(name=\"noddy\", version=\"1.0\",\next_modules=[Extension(\"noddy\", [\"noddy.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?\nOf course, the current Noddy type is pretty uninteresting. It has no\ndata and doesn't do anything. It can't even be subclassed.", "python_version": "2.3", "length": 8070, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/dnt-basics.html"} {"title": "2.2 Type Methods", "text": "node24.html | defining-new-types.html | node26.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.1.3 Supporting cyclic garbage (node24.html)\nUp:\n2. Defining New Types (defining-new-types.html)\nNext:\n2.2.1 Finalization and De-allocation (node26.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\ntypedef struct _typeobject {\nPyObject_VAR_HEAD\nchar *tp_name; /* For printing, in format \".\" */\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 PyMemberDef *tp_members;\nstruct PyGetSetDef *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;\nfreefunc tp_free; /* Low-level free-memory routine */\ninquiry tp_is_gc; /* For PyObject_IS_GC */\nPyObject *tp_bases;\nPyObject *tp_mro; /* method resolution order */\nPyObject *tp_cache;\nPyObject *tp_subclasses;\nPyObject *tp_weaklist;\n\n} PyTypeObject;\n```\nDownload as text (original file name: typestruct.h). (typestruct.txt)\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 type 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.3", "length": 3920, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.1 A Cookbook Approach (win-cookbook.html)\nUp:\n4. Building C and (building-on-windows.html)\nNext:\n4.3 Using DLLs in (win-dlls.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.3", "length": 3019, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.3 Using DLLs in (win-dlls.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\n5.1 Very High Level (high-level-embedding.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.3", "length": 2210, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.4 Extending Embedded Python (extending-with-embedding.html)\nUp:\n5. Embedding Python in (embedding.html)\nNext:\n5.6 Linking Requirements (link-reqs.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.3", "length": 631, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.1 A Simple Example (simpleExample.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.3 Back to the (backToExample.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\nPyMODINIT_FUNC\ninitspam(void)\n{\nPyObject *m;\n\nm = Py_InitModule(\"spam\", SpamMethods);\n\nSpamError = PyErr_NewException(\"spam.error\", NULL, NULL);\nPy_INCREF(SpamError);\nPyModule_AddObject(m, \"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.\nWe discuss the use of PyMODINIT_FUNC later in this sample.", "python_version": "2.3", "length": 6182, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/errors.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "../index.html | front.html | Extending and Embedding the Python Interpreter | contents.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.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.3\nJuly 29, 2003", "python_version": "2.3", "length": 334, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.3 Pure Embedding (pure-embedding.html)\nUp:\n5. Embedding Python in (embedding.html)\nNext:\n5.5 Embedding Python in (embeddingInCplusplus.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.3", "length": 1852, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/extending-with-embedding.html"} {"title": "Front Matter", "text": "ext.html | ext.html | contents.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\nExtending and Embedding the (ext.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\n---\n# Front Matter\nCopyright © 2001, 2002, 2003 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.3", "length": 1724, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5. Embedding Python in (embedding.html)\nUp:\n5. Embedding Python in (embedding.html)\nNext:\n5.2 Beyond Very High (lower-level-embedding.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.3", "length": 1352, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.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.3\nJuly 29, 2003", "python_version": "2.3", "length": 334, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\nUp:\nExtending and Embedding the (ext.html)\nNext:\n1.1 A Simple Example (simpleExample.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.3", "length": 937, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/intro.html"} {"title": "5.6 Linking Requirements", "text": "embeddingInCplusplus.html | embedding.html | reporting-bugs.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n5.5 Embedding Python in (embeddingInCplusplus.html)\nUp:\n5. Embedding Python in (embedding.html)\nNext:\nA. Reporting Bugs (reporting-bugs.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.3", "length": 1744, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.1 Very High Level (high-level-embedding.html)\nUp:\n5. Embedding Python in (embedding.html)\nNext:\n5.3 Pure Embedding (pure-embedding.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.3", "length": 1902, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.3 Back to the (backToExample.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.5 Compilation and Linkage (compilation.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\nPyMODINIT_FUNC\ninitspam(void)\n{\n(void) Py_InitModule(\"spam\", SpamMethods);\n}\n```\nNote that PyMODINIT_FUNC declares the function as `void` return type,\ndeclares any special linkage declarations required by the platform, and for\nC++declares the function as `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\nmain(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.3", "length": 4344, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/methodTable.html"} {"title": "2.1.1 Adding data and methods to the Basic example", "text": "dnt-basics.html | dnt-basics.html | node23.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.1 The Basics (dnt-basics.html)\nUp:\n2.1 The Basics (dnt-basics.html)\nNext:\n2.1.2 Providing finer control (node23.html)\n---\n## 2.1.1 Adding data and methods to the Basic example\nLet's expend the basic example to add some data and methods. Let's\nalso make the type usable as a base class. We'll create\na new module, noddy2 that adds these capabilities:\n```text\n#include \n#include \"structmember.h\"\n\ntypedef struct {\nPyObject_HEAD\nPyObject *first;\nPyObject *last;\nint number;\n} Noddy;\n\nstatic void\nNoddy_dealloc(Noddy* self)\n{\nPy_XDECREF(self->first);\nPy_XDECREF(self->last);\nself->ob_type->tp_free((PyObject*)self);\n}\n\nstatic PyObject *\nNoddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\nNoddy *self;\n\nself = (Noddy *)type->tp_alloc(type, 0);\nif (self != NULL) {\nself->first = PyString_FromString(\"\");\nif (self->first == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->last = PyString_FromString(\"\");\nif (self->last == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->number = 0;\n}\n\nreturn (PyObject *)self;\n}\n\nstatic int\nNoddy_init(Noddy *self, PyObject *args, PyObject *kwds)\n{\nPyObject *first=NULL, *last=NULL;\n\nstatic char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n\nif (! PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n&first, &last,\n&self->number))\nreturn -1;\n\nif (first) {\nPy_XDECREF(self->first);\nPy_INCREF(first);\nself->first = first;\n}\n\nif (last) {\nPy_XDECREF(self->last);\nPy_INCREF(last);\nself->last = last;\n}\n\nreturn 0;\n}\n\nstatic PyMemberDef Noddy_members[] = {\n{\"first\", T_OBJECT_EX, offsetof(Noddy, first), 0,\n\"first name\"},\n{\"last\", T_OBJECT_EX, offsetof(Noddy, last), 0,\n\"last name\"},\n{\"number\", T_INT, offsetof(Noddy, number), 0,\n\"noddy number\"},\n{NULL} /* Sentinel */\n};\n\nstatic PyObject *\nNoddy_name(Noddy* self)\n{\nstatic PyObject *format = NULL;\nPyObject *args, *result;\n\nif (format == NULL) {\nformat = PyString_FromString(\"%s %s\");\nif (format == NULL)\nreturn NULL;\n}\n\nif (self->first == NULL) {\nPyErr_SetString(PyExc_AttributeError, \"first\");\nreturn NULL;\n}\n\nif (self->last == NULL) {\nPyErr_SetString(PyExc_AttributeError, \"last\");\nreturn NULL;\n}\n\nargs = Py_BuildValue(\"OO\", self->first, self->last);\nif (args == NULL)\nreturn NULL;\n\nresult = PyString_Format(format, args);\nPy_DECREF(args);\n\nreturn result;\n}\n\nstatic PyMethodDef Noddy_methods[] = {\n{\"name\", (PyCFunction)Noddy_name, METH_NOARGS,\n\"Return the name, combining the first and last name\"\n},\n{NULL} /* Sentinel */\n};\n\nstatic PyTypeObject NoddyType = {\nPyObject_HEAD_INIT(NULL)\n0, /*ob_size*/\n\"noddy.Noddy\", /*tp_name*/\nsizeof(Noddy), /*tp_basicsize*/\n0, /*tp_itemsize*/\n(destructor)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 */\n0, /*tp_call*/\n0, /*tp_str*/\n0, /*tp_getattro*/\n0, /*tp_setattro*/\n0, /*tp_as_buffer*/\nPy_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n\"Noddy objects\", /* tp_doc */\n0, /* tp_traverse */\n0, /* tp_clear */\n0, /* tp_richcompare */\n0, /* tp_weaklistoffset */\n0, /* tp_iter */\n0, /* tp_iternext */\nNoddy_methods, /* tp_methods */\nNoddy_members, /* tp_members */\n0, /* tp_getset */\n0, /* tp_base */\n0, /* tp_dict */\n0, /* tp_descr_get */\n0, /* tp_descr_set */\n0, /* tp_dictoffset */\n(initproc)Noddy_init, /* tp_init */\n0, /* tp_alloc */\nNoddy_new, /* tp_new */\n};\n\nstatic PyMethodDef module_methods[] = {\n{NULL} /* Sentinel */\n};\n\n#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */\n#define PyMODINIT_FUNC void\n#endif\nPyMODINIT_FUNC\ninitnoddy2(void)\n{\nPyObject* m;\n\nif (PyType_Ready(&NoddyType) < 0)\nreturn;\n\nm = Py_InitModule3(\"noddy2\", module_methods,\n\"Example module that creates an extension type.\");\n\nif (m == NULL)\nreturn;\n\nPy_INCREF(&NoddyType);\nPyModule_AddObject(m, \"Noddy\", (PyObject *)&NoddyType);\n}\n```\nDownload as text (original file name: noddy2.c). (noddy2.txt)\nThis version of the module has a number of changes.\nWe've added an extra include:\n```text\n\n#include \"structmember.h\"\n```\nThis include provides declarations that we use to handle attributes,\nas described a bit later.\nThe name of the Noddy object structure has been shortened to\nNoddy. The type object name has been shortened to\nNoddyType.\nThe Noddy type now has three data attributes, first,\nlast, and number. The first and last\nvariables are Python strings containing first and last names. The\nnumber attribute is an integer.\nThe object structure is updated accordingly:\n```text\n\ntypedef struct {\nPyObject_HEAD\nPyObject *first;\nPyObject *last;\nint number;\n} Noddy;\n```\nBecause we now have data to manage, we have to be more careful about\nobject allocation and deallocation. At a minimum, we need a\ndeallocation method:\n```text\n\nstatic void\nNoddy_dealloc(Noddy* self)\n{\nPy_XDECREF(self->first);\nPy_XDECREF(self->last);\nself->ob_type->tp_free((PyObject*)self);\n}\n```\nwhich is assigned to the tp_dealloc member:\n```text\n\n(destructor)Noddy_dealloc, /*tp_dealloc*/\n```\nThis method decrements the reference counts of the two Python\nattributes. We use Py_XDECREF() here because the\nfirst and last members could be NULL. It then\ncalls the tp_free member of the object's type to free the\nobject's memory. Note that the object's type might not be\nNoddyType, because the object may be an instance of a\nsubclass.\nWe want to make sure that the first and last names are initialized to\nempty strings, so we provide a new method:\n```text\n\nstatic PyObject *\nNoddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\nNoddy *self;\n\nself = (Noddy *)type->tp_alloc(type, 0);\nif (self != NULL) {\nself->first = PyString_FromString(\"\");\nif (self->first == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->last = PyString_FromString(\"\");\nif (self->last == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->number = 0;\n}\n\nreturn (PyObject *)self;\n}\n```\nand install it in the tp_new member:\n```text\n\nNoddy_new, /* tp_new */\n```\nThe new member is responsible for creating (as opposed to\ninitializing) objects of the type. It is exposed in Python as the\n__new__() method. See the paper titled ``Unifying types and\nclasses in Python'' for a detailed discussion of the __new__()\nmethod. One reason to implement a new method is to assure the initial\nvalues of instance variables. In this case, we use the new method to\nmake sure that the initial values of the members first and\nlast are not NULL. If we didn't care whether the initial\nvalues were NULL, we could have used PyType_GenericNew() as\nour new method, as we did before. PyType_GenericNew()\ninitializes all of the instance variable members to NULLs.\nThe new method is a static method that is passed the type being\ninstantiated and any arguments passed when the type was called,\nand that returns the new object created. New methods always accept\npositional and keyword arguments, but they often ignore the arguments,\nleaving the argument handling to initializer methods. Note that if the\ntype supports subclassing, the type passed may not be the type being\ndefined. The new method calls the tp_alloc slot to allocate memory.\nWe don't fill the tp_alloc slot ourselves. Rather\nPyType_Ready() fills it for us by inheriting it from our\nbase class, which is object by default. Most types use the\ndefault allocation.\nWe provide an initialization function:\n```text\n\nstatic int\nNoddy_init(Noddy *self, PyObject *args, PyObject *kwds)\n{\nPyObject *first=NULL, *last=NULL;\n\nstatic char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n\nif (! PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n&first, &last,\n&self->number))\nreturn -1;\n\nif (first) {\nPy_XDECREF(self->first);\nPy_INCREF(first);\nself->first = first;\n}\n\nif (last) {\nPy_XDECREF(self->last);\nPy_INCREF(last);\nself->last = last;\n}\n\nreturn 0;\n}\n```\nby filling the tp_init slot.\n```text\n\n(initproc)Noddy_init, /* tp_init */\n```\nThe tp_init slot is exposed in Python as the\n__init__() method. It is used to initialize an object after\nit's created. Unlike the new method, we can't guarantee that the\ninitializer is called. The initializer isn't called when unpickling\nobjects and it can be overridden. Our initializer accepts arguments\nto provide initial values for our instance. Initializers always accept\npositional and keyword arguments.\nWe want to want to expose our instance variables as attributes. There\nare a number of ways to do that. The simplest way is to define member\ndefinitions:\n```text\n\nstatic PyMemberDef Noddy_members[] = {\n{\"first\", T_OBJECT_EX, offsetof(Noddy, first), 0,\n\"first name\"},\n{\"last\", T_OBJECT_EX, offsetof(Noddy, last), 0,\n\"last name\"},\n{\"number\", T_INT, offsetof(Noddy, number), 0,\n\"noddy number\"},\n{NULL} /* Sentinel */\n};\n```\nand put the definitions in the tp_members slot:\n```text\n\nNoddy_members, /* tp_members */\n```\nEach member definition has a member name, type, offset, access flags\nand documentation string. See the ``Generic Attribute Management''\nsection below for details.\nA disadvantage of this approach is that it doesn't provide a way to\nrestrict the types of objects that can be assigned to the Python\nattributes. We expect the first and last names to be strings, but any\nPython objects can be assigned. Further, the attributes can be\ndeleted, setting the C pointers to NULL. Even though we can make\nsure the members are initialized to non-NULLvalues, the members can\nbe set to NULLif the attributes are deleted.\nWe define a single method, name, that outputs the objects\nname as the concatenation of the first and last names.\n```text\n\nstatic PyObject *\nNoddy_name(Noddy* self)\n{\nstatic PyObject *format = NULL;\nPyObject *args, *result;\n\nif (format == NULL) {\nformat = PyString_FromString(\"%s %s\");\nif (format == NULL)\nreturn NULL;\n}\n\nif (self->first == NULL) {\nPyErr_SetString(PyExc_AttributeError, \"first\");\nreturn NULL;\n}\n\nif (self->last == NULL) {\nPyErr_SetString(PyExc_AttributeError, \"last\");\nreturn NULL;\n}\n\nargs = Py_BuildValue(\"OO\", self->first, self->last);\nif (args == NULL)\nreturn NULL;\n\nresult = PyString_Format(format, args);\nPy_DECREF(args);\n\nreturn result;\n}\n```\nThe method is implemented as a C function that takes a Noddy (or\nNoddy subclass) instance as the first argument. Methods\nalways take an instance as the first argument. Methods often take\npositional and keyword arguments as well, but in this cased we don't\ntake any and don't need to accept a positional argument tuple or\nkeyword argument dictionary. This method is equivalent to the Python\nmethod:\n```text\n\ndef name(self):\nreturn \"%s %s\" % (self.first, self.last)\n```\nNote that we have to check for the possibility that our first\nand last members are NULL. This is because they can be\ndeleted, in which case they are set to NULL. It would be better to\nprevent deletion of these attributes and to restrict the attribute\nvalues to be strings. We'll see how to do that in the next section.\nNow that we've defined the method, we need to create an array of\nmethod definitions:\n```text\n\nstatic PyMethodDef Noddy_methods[] = {\n{\"name\", (PyCFunction)Noddy_name, METH_NOARGS,\n\"Return the name, combining the first and last name\"\n},\n{NULL} /* Sentinel */\n};\n```\nand assign them to the tp_methods slot:\n```text\n\nNoddy_methods, /* tp_methods */\n```\nNote that used the METH_NOARGS flag to indicate that the\nmethod is passed no arguments.\nFinally, we'll make our type usable as a base class. We've written\nour methods carefully so far so that they don't make any assumptions\nabout the type of the object being created or used, so all we need to\ndo is to add the Py_TPFLAGS_BASETYPE to our class flag\ndefinition:\n```text\n\nPy_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n```\nWe rename initnoddy() to initnoddy2()\nand update the module name passed to Py_InitModule3().\nFinally, we update our setup.py file to build the new module:\n```text\n\nfrom distutils.core import setup, Extension\nsetup(name=\"noddy\", version=\"1.0\",\next_modules=[\nExtension(\"noddy\", [\"noddy.c\"]),\nExtension(\"noddy2\", [\"noddy2.c\"]),\n])\n```", "python_version": "2.3", "length": 11996, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node22.html"} {"title": "2.1.2 Providing finer control over data attributes", "text": "node22.html | dnt-basics.html | node24.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.1.1 Adding data and (node22.html)\nUp:\n2.1 The Basics (dnt-basics.html)\nNext:\n2.1.3 Supporting cyclic garbage (node24.html)\n---\n## 2.1.2 Providing finer control over data attributes\nIn this section, we'll provide finer control over how the\nfirst and last attributes are set in the\nNoddy example. In the previous version of our module, the\ninstance variables first and last could be set to\nnon-string values or even deleted. We want to make sure that these\nattributes always contain strings.\n```text\n#include \n#include \"structmember.h\"\n\ntypedef struct {\nPyObject_HEAD\nPyObject *first;\nPyObject *last;\nint number;\n} Noddy;\n\nstatic void\nNoddy_dealloc(Noddy* self)\n{\nPy_XDECREF(self->first);\nPy_XDECREF(self->last);\nself->ob_type->tp_free((PyObject*)self);\n}\n\nstatic PyObject *\nNoddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\nNoddy *self;\n\nself = (Noddy *)type->tp_alloc(type, 0);\nif (self != NULL) {\nself->first = PyString_FromString(\"\");\nif (self->first == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->last = PyString_FromString(\"\");\nif (self->last == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->number = 0;\n}\n\nreturn (PyObject *)self;\n}\n\nstatic int\nNoddy_init(Noddy *self, PyObject *args, PyObject *kwds)\n{\nPyObject *first=NULL, *last=NULL;\n\nstatic char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n\nif (! PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n&first, &last,\n&self->number))\nreturn -1;\n\nif (first) {\nPy_DECREF(self->first);\nPy_INCREF(first);\nself->first = first;\n}\n\nif (last) {\nPy_DECREF(self->last);\nPy_INCREF(last);\nself->last = last;\n}\n\nreturn 0;\n}\n\nstatic PyMemberDef Noddy_members[] = {\n{\"number\", T_INT, offsetof(Noddy, number), 0,\n\"noddy number\"},\n{NULL} /* Sentinel */\n};\n\nstatic PyObject *\nNoddy_getfirst(Noddy *self, void *closure)\n{\nPy_INCREF(self->first);\nreturn self->first;\n}\n\nstatic int\nNoddy_setfirst(Noddy *self, PyObject *value, void *closure)\n{\nif (value == NULL) {\nPyErr_SetString(PyExc_TypeError, \"Cannot delete the first attribute\");\nreturn -1;\n}\n\nif (! PyString_Check(value)) {\nPyErr_SetString(PyExc_TypeError,\n\"The first attribute value must be a string\");\nreturn -1;\n}\n\nPy_DECREF(self->first);\nPy_INCREF(value);\nself->first = value;\n\nreturn 0;\n}\n\nstatic PyObject *\nNoddy_getlast(Noddy *self, void *closure)\n{\nPy_INCREF(self->last);\nreturn self->last;\n}\n\nstatic int\nNoddy_setlast(Noddy *self, PyObject *value, void *closure)\n{\nif (value == NULL) {\nPyErr_SetString(PyExc_TypeError, \"Cannot delete the last attribute\");\nreturn -1;\n}\n\nif (! PyString_Check(value)) {\nPyErr_SetString(PyExc_TypeError,\n\"The last attribute value must be a string\");\nreturn -1;\n}\n\nPy_DECREF(self->last);\nPy_INCREF(value);\nself->last = value;\n\nreturn 0;\n}\n\nstatic PyGetSetDef Noddy_getseters[] = {\n{\"first\",\n(getter)Noddy_getfirst, (setter)Noddy_setfirst,\n\"first name\",\nNULL},\n{\"last\",\n(getter)Noddy_getlast, (setter)Noddy_setlast,\n\"last name\",\nNULL},\n{NULL} /* Sentinel */\n};\n\nstatic PyObject *\nNoddy_name(Noddy* self)\n{\nstatic PyObject *format = NULL;\nPyObject *args, *result;\n\nif (format == NULL) {\nformat = PyString_FromString(\"%s %s\");\nif (format == NULL)\nreturn NULL;\n}\n\nargs = Py_BuildValue(\"OO\", self->first, self->last);\nif (args == NULL)\nreturn NULL;\n\nresult = PyString_Format(format, args);\nPy_DECREF(args);\n\nreturn result;\n}\n\nstatic PyMethodDef Noddy_methods[] = {\n{\"name\", (PyCFunction)Noddy_name, METH_NOARGS,\n\"Return the name, combining the first and last name\"\n},\n{NULL} /* Sentinel */\n};\n\nstatic PyTypeObject NoddyType = {\nPyObject_HEAD_INIT(NULL)\n0, /*ob_size*/\n\"noddy.Noddy\", /*tp_name*/\nsizeof(Noddy), /*tp_basicsize*/\n0, /*tp_itemsize*/\n(destructor)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 */\n0, /*tp_call*/\n0, /*tp_str*/\n0, /*tp_getattro*/\n0, /*tp_setattro*/\n0, /*tp_as_buffer*/\nPy_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/\n\"Noddy objects\", /* tp_doc */\n0, /* tp_traverse */\n0, /* tp_clear */\n0, /* tp_richcompare */\n0, /* tp_weaklistoffset */\n0, /* tp_iter */\n0, /* tp_iternext */\nNoddy_methods, /* tp_methods */\nNoddy_members, /* tp_members */\nNoddy_getseters, /* tp_getset */\n0, /* tp_base */\n0, /* tp_dict */\n0, /* tp_descr_get */\n0, /* tp_descr_set */\n0, /* tp_dictoffset */\n(initproc)Noddy_init, /* tp_init */\n0, /* tp_alloc */\nNoddy_new, /* tp_new */\n};\n\nstatic PyMethodDef module_methods[] = {\n{NULL} /* Sentinel */\n};\n\n#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */\n#define PyMODINIT_FUNC void\n#endif\nPyMODINIT_FUNC\ninitnoddy3(void)\n{\nPyObject* m;\n\nif (PyType_Ready(&NoddyType) < 0)\nreturn;\n\nm = Py_InitModule3(\"noddy3\", module_methods,\n\"Example module that creates an extension type.\");\n\nif (m == NULL)\nreturn;\n\nPy_INCREF(&NoddyType);\nPyModule_AddObject(m, \"Noddy\", (PyObject *)&NoddyType);\n}\n```\nDownload as text (original file name: noddy3.c). (noddy3.txt)\nTo provide greater control, over the first and last\nattributes, we'll use custom getter and setter functions. Here are\nthe functions for getting and setting the first attribute:\n```text\n\nNoddy_getfirst(Noddy *self, void *closure)\n{\nPy_INCREF(self->first);\nreturn self->first;\n}\n\nstatic int\nNoddy_setfirst(Noddy *self, PyObject *value, void *closure)\n{\nif (value == NULL) {\nPyErr_SetString(PyExc_TypeError, \"Cannot delete the first attribute\");\nreturn -1;\n}\n\nif (! PyString_Check(value)) {\nPyErr_SetString(PyExc_TypeError,\n\"The first attribute value must be a string\");\nreturn -1;\n}\n\nPy_DECREF(self->first);\nPy_INCREF(value);\nself->first = value;\n\nreturn 0;\n}\n```\nThe getter function is passed a Noddy object and a\n``closure'', which is void pointer. In this case, the closure is\nignored. (The closure supports an advanced usage in which definition\ndata is passed to the getter and setter. This could, for example, be\nused to allow a single set of getter and setter functions that decide\nthe attribute to get or set based on data in the closure.)\nThe setter function is passed the Noddy object, the new value,\nand the closure. The new value may be NULL, in which case the\nattribute is being deleted. In our setter, we raise an error if the\nattribute is deleted or if the attribute value is not a string.\nWe create an array of PyGetSetDef structures:\n```text\n\nstatic PyGetSetDef Noddy_getseters[] = {\n{\"first\",\n(getter)Noddy_getfirst, (setter)Noddy_setfirst,\n\"first name\",\nNULL},\n{\"last\",\n(getter)Noddy_getlast, (setter)Noddy_setlast,\n\"last name\",\nNULL},\n{NULL} /* Sentinel */\n};\n```\nand register it in the tp_getset slot:\n```text\n\nNoddy_getseters, /* tp_getset */\n```\nto register out attribute getters and setters.\nThe last item in a PyGetSetDef structure is the closure\nmentioned above. In this case, we aren't using the closure, so we just\npass NULL.\nWe also remove the member definitions for these attributes:\n```text\n\nstatic PyMemberDef Noddy_members[] = {\n{\"number\", T_INT, offsetof(Noddy, number), 0,\n\"noddy number\"},\n{NULL} /* Sentinel */\n};\n```\nWith these changes, we can assure that the first and\nlast members are never NULL so we can remove checks for NULL\nvalues in almost all cases. This means that most of the\nPy_XDECREF() calls can be converted to Py_DECREF()\ncalls. The only place we can't change these calls is in the\ndeallocator, where there is the possibility that the initialization of\nthese members failed in the constructor.\nWe also rename the module initialization function and module name in\nthe initialization function, as we did before, and we add an extra\ndefinition to the setup.py file.", "python_version": "2.3", "length": 7649, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node23.html"} {"title": "2.1.3 Supporting cyclic garbage collection", "text": "node23.html | dnt-basics.html | dnt-type-methods.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.1.2 Providing finer control (node23.html)\nUp:\n2.1 The Basics (dnt-basics.html)\nNext:\n2.2 Type Methods (dnt-type-methods.html)\n---\n## 2.1.3 Supporting cyclic garbage collection\nPython has a cyclic-garbage collector that can identify unneeded\nobjects even when their reference counts are not zero. This can happen\nwhen objects are involved in cycles. For example, consider:\n```text\n\n>>> l = []\n>>> l.append(l)\n>>> del l\n```\nIn this example, we create a list that contains itself. When we delete\nit, it still has a reference from itself. It's reference count doesn't\ndrop to zero. Fortunately, Python's cyclic-garbage collector will\neventually figure out that that the list is garbage and free it.\nIn the second version of the Noddy example, we allowed any\nkind of object to be stored in the first or last\nattributes. This means that Noddy objects can participate in\ncycles:\n```text\n\n>>> import noddy2\n>>> n = noddy2.Noddy()\n>>> l = [n]\n>>> n.first = l\n```\nThis is pretty silly, but it gives us an excuse to add support for the\ncyclic-garbage collector to the Noddy example. To support\ncyclic garbage collection, types need to fill two slots and set a\nclass flag that enables these slots:\n```text\n#include \n#include \"structmember.h\"\n\ntypedef struct {\nPyObject_HEAD\nPyObject *first;\nPyObject *last;\nint number;\n} Noddy;\n\nstatic int\nNoddy_traverse(Noddy *self, visitproc visit, void *arg)\n{\nif (self->first && visit(self->first, arg) < 0)\nreturn -1;\nif (self->last && visit(self->last, arg) < 0)\nreturn -1;\n\nreturn 0;\n}\n\nstatic int\nNoddy_clear(Noddy *self)\n{\nPy_XDECREF(self->first);\nself->first = NULL;\nPy_XDECREF(self->last);\nself->last = NULL;\n\nreturn 0;\n}\n\nstatic void\nNoddy_dealloc(Noddy* self)\n{\nNoddy_clear(self);\nself->ob_type->tp_free((PyObject*)self);\n}\n\nstatic PyObject *\nNoddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\nNoddy *self;\n\nself = (Noddy *)type->tp_alloc(type, 0);\nif (self != NULL) {\nself->first = PyString_FromString(\"\");\nif (self->first == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->last = PyString_FromString(\"\");\nif (self->last == NULL)\n{\nPy_DECREF(self);\nreturn NULL;\n}\n\nself->number = 0;\n}\n\nreturn (PyObject *)self;\n}\n\nstatic int\nNoddy_init(Noddy *self, PyObject *args, PyObject *kwds)\n{\nPyObject *first=NULL, *last=NULL;\n\nstatic char *kwlist[] = {\"first\", \"last\", \"number\", NULL};\n\nif (! PyArg_ParseTupleAndKeywords(args, kwds, \"|OOi\", kwlist,\n&first, &last,\n&self->number))\nreturn -1;\n\nif (first) {\nPy_XDECREF(self->first);\nPy_INCREF(first);\nself->first = first;\n}\n\nif (last) {\nPy_XDECREF(self->last);\nPy_INCREF(last);\nself->last = last;\n}\n\nreturn 0;\n}\n\nstatic PyMemberDef Noddy_members[] = {\n{\"first\", T_OBJECT_EX, offsetof(Noddy, first), 0,\n\"first name\"},\n{\"last\", T_OBJECT_EX, offsetof(Noddy, last), 0,\n\"last name\"},\n{\"number\", T_INT, offsetof(Noddy, number), 0,\n\"noddy number\"},\n{NULL} /* Sentinel */\n};\n\nstatic PyObject *\nNoddy_name(Noddy* self)\n{\nstatic PyObject *format = NULL;\nPyObject *args, *result;\n\nif (format == NULL) {\nformat = PyString_FromString(\"%s %s\");\nif (format == NULL)\nreturn NULL;\n}\n\nif (self->first == NULL) {\nPyErr_SetString(PyExc_AttributeError, \"first\");\nreturn NULL;\n}\n\nif (self->last == NULL) {\nPyErr_SetString(PyExc_AttributeError, \"last\");\nreturn NULL;\n}\n\nargs = Py_BuildValue(\"OO\", self->first, self->last);\nif (args == NULL)\nreturn NULL;\n\nresult = PyString_Format(format, args);\nPy_DECREF(args);\n\nreturn result;\n}\n\nstatic PyMethodDef Noddy_methods[] = {\n{\"name\", (PyCFunction)Noddy_name, METH_NOARGS,\n\"Return the name, combining the first and last name\"\n},\n{NULL} /* Sentinel */\n};\n\nstatic PyTypeObject NoddyType = {\nPyObject_HEAD_INIT(NULL)\n0, /*ob_size*/\n\"noddy.Noddy\", /*tp_name*/\nsizeof(Noddy), /*tp_basicsize*/\n0, /*tp_itemsize*/\n(destructor)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 */\n0, /*tp_call*/\n0, /*tp_str*/\n0, /*tp_getattro*/\n0, /*tp_setattro*/\n0, /*tp_as_buffer*/\nPy_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/\n\"Noddy objects\", /* tp_doc */\n(traverseproc)Noddy_traverse, /* tp_traverse */\n(inquiry)Noddy_clear, /* tp_clear */\n0, /* tp_richcompare */\n0, /* tp_weaklistoffset */\n0, /* tp_iter */\n0, /* tp_iternext */\nNoddy_methods, /* tp_methods */\nNoddy_members, /* tp_members */\n0, /* tp_getset */\n0, /* tp_base */\n0, /* tp_dict */\n0, /* tp_descr_get */\n0, /* tp_descr_set */\n0, /* tp_dictoffset */\n(initproc)Noddy_init, /* tp_init */\n0, /* tp_alloc */\nNoddy_new, /* tp_new */\n};\n\nstatic PyMethodDef module_methods[] = {\n{NULL} /* Sentinel */\n};\n\n#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */\n#define PyMODINIT_FUNC void\n#endif\nPyMODINIT_FUNC\ninitnoddy4(void)\n{\nPyObject* m;\n\nif (PyType_Ready(&NoddyType) < 0)\nreturn;\n\nm = Py_InitModule3(\"noddy4\", module_methods,\n\"Example module that creates an extension type.\");\n\nif (m == NULL)\nreturn;\n\nPy_INCREF(&NoddyType);\nPyModule_AddObject(m, \"Noddy\", (PyObject *)&NoddyType);\n}\n```\nDownload as text (original file name: noddy4.c). (noddy4.txt)\nThe traversal method provides access to subobjects that\ncould participate in cycles:\n```text\n\nstatic int\nNoddy_traverse(Noddy *self, visitproc visit, void *arg)\n{\nif (self->first && visit(self->first, arg) < 0)\nreturn -1;\nif (self->last && visit(self->last, arg) < 0)\nreturn -1;\n\nreturn 0;\n}\n```\nFor each subobject that can participate in cycles, we need to call the\nvisit() function, which is passed to the traversal method.\nThe visit() function takes as arguments the subobject and\nthe extra argument arg passed to the traversal method.\nWe also need to provide a method for clearing any subobjects that can\nparticipate in cycles. We implement the method and reimplement the\ndeallocator to use it:\n```text\n\nstatic int\nNoddy_clear(Noddy *self)\n{\nPy_XDECREF(self->first);\nself->first = NULL;\nPy_XDECREF(self->last);\nself->last = NULL;\n\nreturn 0;\n}\n\nstatic void\nNoddy_dealloc(Noddy* self)\n{\nNoddy_clear(self);\nself->ob_type->tp_free((PyObject*)self);\n}\n```\nFinally, we add the Py_TPFLAGS_HAVE_GC flag to the class\nflags:\n```text\n\nPy_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/\n```\nThat's pretty much it. If we had written custom tp_alloc or\ntp_free slots, we'd need to modify them for cyclic-garbage\ncollection. Most extensions will use the versions automatically\nprovided.", "python_version": "2.3", "length": 6518, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node24.html"} {"title": "2.2.1 Finalization and De-allocation", "text": "dnt-type-methods.html | dnt-type-methods.html | node27.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2 Type Methods (dnt-type-methods.html)\nUp:\n2.2 Type Methods (dnt-type-methods.html)\nNext:\n2.2.2 Object Presentation (node27.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);\nobj->ob_type->tp_free(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}\nobj->ob_type->tp_free((PyObject*)self);\n}\n```", "python_version": "2.3", "length": 2147, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node26.html"} {"title": "2.2.2 Object Presentation", "text": "node26.html | dnt-type-methods.html | node28.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.1 Finalization and De-allocation (node26.html)\nUp:\n2.2 Type Methods (dnt-type-methods.html)\nNext:\n2.2.3 Attribute Management (node28.html)\n---\n## 2.2.2 Object Presentation\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. Its implementation is very similar to the\ntp_repr function, but the resulting string is intended for\nhuman consumption. If 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```\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.3", "length": 2862, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node27.html"} {"title": "2.2.3 Attribute Management", "text": "node27.html | dnt-type-methods.html | node29.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.2 Object Presentation (node27.html)\nUp:\n2.2 Type Methods (dnt-type-methods.html)\nNext:\n2.2.3.1 Generic Attribute Management (node29.html)\n---\n## 2.2.3 Attribute Management\nFor every object which can support attributes, the corresponding type\nmust provide the functions that control how the attributes are\nresolved. There needs to be a function which can retrieve attributes\n(if any are defined), and another to set attributes (if setting\nattributes is allowed). Removing an attribute is a special case, for\nwhich the new value passed to the handler is NULL.\nPython supports two pairs of attribute handlers; a type that supports\nattributes only needs to implement the functions for one pair. The\ndifference is that one pair takes the name of the attribute as a\nchar*, while the other accepts a PyObject*. Each type\ncan use whichever pair makes more sense for the implementation's\nconvenience.\n```text\n\ngetattrfunc tp_getattr; /* char * version */\nsetattrfunc tp_setattr;\n/* ... */\ngetattrofunc tp_getattrofunc; /* PyObject * version */\nsetattrofunc tp_setattrofunc;\n```\nIf accessing attributes of an object is always a simple operation\n(this will be explained shortly), there are generic implementations\nwhich can be used to provide the PyObject* version of the\nattribute management functions. The actual need for type-specific\nattribute handlers almost completely disappeared starting with Python\n2.2, though there are many examples which have not been updated to use\nsome of the new generic mechanism that is available.", "python_version": "2.3", "length": 1649, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node28.html"} {"title": "2.2.3.1 Generic Attribute Management", "text": "node28.html | node28.html | node30.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.3 Attribute Management (node28.html)\nUp:\n2.2.3 Attribute Management (node28.html)\nNext:\n2.2.3.2 Type-specific Attribute Management (node30.html)\n---\n### 2.2.3.1 Generic Attribute Management\nNew in version 2.2.\nMost extension types only use simple attributes. So, what\nmakes the attributes simple? There are only a couple of conditions\nthat must be met:\n1. The name of the attributes must be known when\nPyType_Ready() is called.\n2. No special processing is needed to record that an attribute\nwas looked up or set, nor do actions need to be taken based\non the value.\nNote that this list does not place any restrictions on the values of\nthe attributes, when the values are computed, or how relevant data is\nstored.\nWhen PyType_Ready() is called, it uses three tables\nreferenced by the type object to create descriptors which are\nplaced in the dictionary of the type object. Each descriptor controls\naccess to one attribute of the instance object. Each of the tables is\noptional; if all three are NULL, instances of the type will only have\nattributes that are inherited from their base type, and should leave\nthe tp_getattro and tp_setattro fields NULL as\nwell, allowing the base type to handle attributes.\nThe tables are declared as three fields of the type object:\n```text\n\nstruct PyMethodDef *tp_methods;\nstruct PyMemberDef *tp_members;\nstruct PyGetSetDef *tp_getset;\n```\nIf tp_methods is not NULL, it must refer to an array of\nPyMethodDef structures. Each entry in the table is an\ninstance of this structure:\n```text\n\ntypedef struct PyMethodDef {\nchar *ml_name; /* method name */\nPyCFunction ml_meth; /* implementation function */\nint ml_flags; /* flags */\nchar *ml_doc; /* docstring */\n} PyMethodDef;\n```\nOne entry should be defined for each method provided by the type; no\nentries are needed for methods inherited from a base type. One\nadditional entry is needed at the end; it is a sentinel that marks the\nend of the array. The ml_name field of the sentinel must be\nNULL.\nXXX Need to refer to some unified discussion of the structure fields,\nshared with the next section.\nThe second table is used to define attributes which map directly to\ndata stored in the instance. A variety of primitive C types are\nsupported, and access may be read-only or read-write. The structures\nin the table are defined as:\n```text\n\ntypedef struct PyMemberDef {\nchar *name;\nint type;\nint offset;\nint flags;\nchar *doc;\n} PyMemberDef;\n```\nFor each entry in the table, a descriptor will be constructed and\nadded to the type which will be able to extract a value from the\ninstance structure. The type field should contain one of the\ntype codes defined in the structmember.h header; the value will\nbe used to determine how to convert Python values to and from C\nvalues. The flags field is used to store flags which control\nhow the attribute can be accessed.\nXXX Need to move some of this to a shared section!\nThe following flag constants are defined in structmember.h;\nthey may be combined using bitwise-OR.\nAn interesting advantage of using the tp_members table to\nbuild descriptors that are used at runtime is that any attribute\ndefined this way can have an associated docstring simply by providing\nthe text in the table. An application can use the introspection API\nto retrieve the descriptor from the class object, and get the\ndocstring using its __doc__ attribute.\nAs with the tp_methods table, a sentinel entry with a\nname value of NULL is required.", "python_version": "2.3", "length": 3550, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node29.html"} {"title": "2.2.3.2 Type-specific Attribute Management", "text": "node29.html | node28.html | node31.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.3.1 Generic Attribute Management (node29.html)\nUp:\n2.2.3 Attribute Management (node28.html)\nNext:\n2.2.4 Object Comparison (node31.html)\n---\n### 2.2.3.2 Type-specific Attribute Management\nFor simplicity, only the char* version will be demonstrated\nhere; the type of the name parameter is the only difference between\nthe char* and PyObject* flavors of the interface.\nThis example effectively does the same thing as the generic example\nabove, but does not use the generic support added in Python 2.2. The\nvalue in showing this is two-fold: it demonstrates how basic attribute\nmanagement can be done in a way that is portable to older versions of\nPython, and explains how the handler functions are called, so that if\nyou do need to extend their functionality, you'll understand what\nneeds to be done.\nThe tp_getattr handler 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. The\nmethod table uses the same structure as the tp_methods field\nof the type object.\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.3", "length": 2394, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node30.html"} {"title": "2.2.4 Object Comparison", "text": "node30.html | dnt-type-methods.html | node32.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.3.2 Type-specific Attribute Management (node30.html)\nUp:\n2.2 Type Methods (dnt-type-methods.html)\nNext:\n2.2.5 Abstract Protocol Support (node32.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\nand 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.3", "length": 1590, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node31.html"} {"title": "2.2.5 Abstract Protocol Support", "text": "node31.html | dnt-type-methods.html | node33.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.4 Object Comparison (node31.html)\nUp:\n2.2 Type Methods (dnt-type-methods.html)\nNext:\n2.2.6 More Suggestions (node33.html)\n---\n## 2.2.5 Abstract Protocol Support\nPython supports a variety of abstract `protocols;' the specific\ninterfaces provided to use these interfaces are documented in the\nPython/C API Reference Manual (../api/api.html) in the\nchapter ``Abstract Objects Layer (../api/abstract.html).''\nA number of these abstract interfaces were defined early in the\ndevelopment of the Python implementation. In particular, the number,\nmapping, and sequence protocols have been part of Python since the\nbeginning. Other protocols have been added over time. For protocols\nwhich depend on several handler routines from the type implementation,\nthe older protocols have been defined as optional blocks of handlers\nreferenced by the type object. For newer protocols there are\nadditional slots in the main type object, with a flag bit being set to\nindicate that the slots are present and should be checked by the\ninterpreter. (The flag bit does not indicate that the slot values are\nnon-NULL. The flag may be set to indicate the presense of a slot,\nbut a slot may still be unfilled.)\n```text\n\nPyNumberMethods tp_as_number;\nPySequenceMethods tp_as_sequence;\nPyMappingMethods tp_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 the 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```\nXXX some fields need to be added here...\n```text\n\n/* Added in release 2.2 */\n/* Iterators */\ngetiterfunc tp_iter;\niternextfunc tp_iternext;\n```\nThese functions provide support for the iterator protocol. Any object\nwhich wishes to support iteration over its contents (which may be\ngenerated during iteration) must implement the `tp_iter`\nhandler. Objects which are returned by a `tp_iter` handler must\nimplement both the `tp_iter` and `tp_iternext` handlers.\nBoth handlers take exactly one parameter, the instance for which they\nare being called, and return a new reference. In the case of an\nerror, they should set an exception and return NULL.\nFor an object which represents an iterable collection, the\n`tp_iter` handler must return an iterator object. The iterator\nobject is responsible for maintaining the state of the iteration. For\ncollections which can support multiple iterators which do not\ninterfere with each other (as lists and tuples do), a new iterator\nshould be created and returned. Objects which can only be iterated\nover once (usually due to side effects of iteration) should implement\nthis handler by returning a new reference to themselves, and should\nalso implement the `tp_iternext` handler. File objects are an\nexample of such an iterator.\nIterator objects should implement both handlers. The `tp_iter`\nhandler should return a new reference to the iterator (this is the\nsame as the `tp_iter` handler for objects which can only be\niterated over destructively). The `tp_iternext` handler should\nreturn a new reference to the next object in the iteration if there is\none. If the iteration has reached the end, it may return NULL\nwithout setting an exception or it may set StopIteration;\navoiding the exception can yield slightly better performance. If an\nactual error occurs, it should set an exception and return NULL.", "python_version": "2.3", "length": 5542, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node32.html"} {"title": "2.2.6 More Suggestions", "text": "node32.html | dnt-type-methods.html | building.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n2.2.5 Abstract Protocol Support (node32.html)\nUp:\n2.2 Type Methods (dnt-type-methods.html)\nNext:\n3. Building C and (building.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. There are type definitions for each of\nthe functions you must provide. They are in object.h in the\nPython include directory that comes with the source distribution of\nPython.\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 an object is an instance of the type\nyou are implementing, use the PyObject_TypeCheck function.\nA sample of its use might be something like the following:", "python_version": "2.3", "length": 1091, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node33.html"} {"title": "B. History and License", "text": "reporting-bugs.html | ext.html | node49.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\nA. Reporting Bugs (reporting-bugs.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\nB.1 History of the (node49.html)\n---\n# B. History and License", "python_version": "2.3", "length": 270, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node48.html"} {"title": "B.1 History of the software", "text": "node48.html | node48.html | node50.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\nB. History and License (node48.html)\nUp:\nB. History and License (node48.html)\nNext:\nB.2 Terms and conditions (node50.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 Digital Creations (now Zope\nCorporation; 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. Zope Corporation 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.3", "length": 1900, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node49.html"} {"title": "B.2 Terms and conditions for accessing or otherwise using Python", "text": "node49.html | node48.html | about.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\nB.1 History of the (node49.html)\nUp:\nB. History and License (node48.html)\nNext:\nAbout this document ... (about.html)\n---\n# B.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.3\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.3 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.3 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001-2003 Python Software Foundation; All\nRights Reserved'' are retained in Python 2.3 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.3 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.3.\n4. PSF is making Python 2.3 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.3 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.3, 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.3, 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.3", "length": 9905, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/node50.html"} {"title": "1.10.4 NULL Pointers", "text": "thinIce.html | refcounts.html | cplusplus.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n1.10.3 Thin Ice (thinIce.html)\nUp:\n1.10 Reference Counts (refcounts.html)\nNext:\n1.11 Writing Extensions in (cplusplus.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 (#foot456)\nIt is a severe error to ever let a NULL pointer ``escape'' to\nthe Python user.", "python_version": "2.3", "length": 1681, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/nullPointers.html"} {"title": "1.10.2 Ownership Rules", "text": "refcountsInPython.html | refcounts.html | thinIce.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n1.10.1 Reference Counting in (refcountsInPython.html)\nUp:\n1.10 Reference Counts (refcounts.html)\nNext:\n1.10.3 Thin Ice (thinIce.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.3", "length": 2504, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.6 Calling Python Functions (callingPython.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.8 Keyword Parameters for (parseTupleAndKeywords.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 in\n``Parsing arguments and building\nvalues (../api/arg-parsing.html)'' in the\nPython/C API Reference Manual (../api/api.html). The\nremaining arguments must be addresses of variables whose type is\ndetermined by the format string.\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!\nNote that any Python object references which are provided to the\ncaller are borrowed references; do not decrement their\nreference count!\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.3", "length": 2560, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.7 Extracting Parameters in (parseTuple.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.9 Building Arbitrary Values (buildValue.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(PyObject *self, PyObject *args, PyObject *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```\n```text\n\nvoid\ninitkeywdarg(void)\n{\n/* Create the module and add the functions */\nPy_InitModule(\"keywdarg\", keywdarg_methods);\n}\n```", "python_version": "2.3", "length": 2322, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.2 Beyond Very High (lower-level-embedding.html)\nUp:\n5. Embedding Python in (embedding.html)\nNext:\n5.4 Extending Embedded Python (extending-with-embedding.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;\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);\nPy_DECREF(pName);\n\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) {\nPy_DECREF(pArgs);\nPy_DECREF(pModule);\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);\nPy_DECREF(pArgs);\nif (pValue != NULL) {\nprintf(\"Result of call: %ld\\n\", PyInt_AsLong(pValue));\nPy_DECREF(pValue);\n}\nelse {\nPy_DECREF(pModule);\nPyErr_Print();\nfprintf(stderr,\"Call failed\\n\");\nreturn 1;\n}\n/* pDict and pFunc are borrowed and must not be Py_DECREF-ed */\n}\nelse {\nif (PyErr_Occurred())\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_Finalize();\nreturn 0;\n}\n```\nDownload as text (original file name: run-func.c). (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 \"Will compute\", 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 multiply 3 2\nWill compute 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\npFunc = PyObject_GetAttrString(pModule, argv[2]);\n/* pFunc is a new reference */\n\nif (pFunc && PyCallable_Check(pFunc)) {\n...\n}\nPy_XDECREF(pFunc);\n```\nOnce the script is loaded, the name we're looking for is retrieved\nusing PyObject_GetAttrString(). If the name exists, and\nthe object returned is callable, you can safely assume that it is a\nfunction. The program then proceeds by constructing a tuple of\narguments as normal. The call to the Python function is then made\nwith:\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.3", "length": 3932, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/pure-embedding.html"} {"title": "1.10 Reference Counts", "text": "buildValue.html | intro.html | refcountsInPython.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n1.9 Building Arbitrary Values (buildValue.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.10.1 Reference Counting in (refcountsInPython.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 and\nwe'll restrict the following discussion to the latter.\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.3", "length": 5086, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.10 Reference Counts (refcounts.html)\nUp:\n1.10 Reference Counts (refcounts.html)\nNext:\n1.10.2 Ownership Rules (ownershipRules.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 (#foot395) 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 (#foot527)\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.3", "length": 2470, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/refcountsInPython.html"} {"title": "A. Reporting Bugs", "text": "link-reqs.html | ext.html | node48.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n5.6 Linking Requirements (link-reqs.html)\nUp:\nExtending and Embedding the (ext.html)\nNext:\nB. History and License (node48.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.\nBefore submitting a report, you will be required to log into SourceForge;\nthis will make it possible for the developers to contact you\nfor additional information if needed. It is not possible to submit a\nbug report anonymously.\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.\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. You will\nreceive an update each time action is taken on the bug.\nSee Also:", "python_version": "2.3", "length": 2551, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1. Extending Python with (intro.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n1.2 Intermezzo: Errors and (errors.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 (#foot511)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(PyObject *self, PyObject *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.3", "length": 3601, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/simpleExample.html"} {"title": "1.10.3 Thin Ice", "text": "ownershipRules.html | refcounts.html | nullPointers.html | Extending and Embedding the Python Interpreter | contents.html\nPrevious:\n1.10.2 Ownership Rules (ownershipRules.html)\nUp:\n1.10 Reference Counts (refcounts.html)\nNext:\n1.10.4 NULL Pointers (nullPointers.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\nvoid\nbug(PyObject *list)\n{\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\nvoid\nno_bug(PyObject *list)\n{\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\nPy_BEGIN_ALLOW_THREADS, and to re-acquire it using\nPy_END_ALLOW_THREADS. This is common around blocking\nI/O calls, to let other threads use the processor while waiting for\nthe I/O to complete. Obviously, the following function has the same\nproblem as the previous one:\n```text\n\nvoid\nbug(PyObject *list)\n{\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.3", "length": 3211, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n1.11 Writing Extensions in (cplusplus.html)\nUp:\n1. Extending Python with (intro.html)\nNext:\n2. Defining New Types (defining-new-types.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(char *command)\n{\nreturn system(command);\n}\n```\nThe function spam_system() is modified in a trivial way:\n```text\n\nstatic PyObject *\nspam_system(PyObject *self, PyObject *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\nPyMODINIT_FUNC\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)\nPyModule_AddObject(m, \"_C_API\", c_api_object);\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/* Return -1 and set exception on error, 0 on success. */\nstatic int\nimport_spam(void)\n{\nPyObject *module = PyImport_ImportModule(\"spam\");\n\nif (module != NULL) {\nPyObject *c_api_object = PyObject_GetAttrString(module, \"_C_API\");\nif (c_api_object == NULL)\nreturn -1;\nif (PyCObject_Check(c_api_object))\nPySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object);\nPy_DECREF(c_api_object);\n}\nreturn 0;\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\nPyMODINIT_FUNC\ninitclient(void)\n{\nPyObject *m;\n\nPy_InitModule(\"client\", ClientMethods);\nif (import_spam() < 0)\nreturn;\n/* additional initialization can happen here */\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.3", "length": 7169, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4. Building C and (building-on-windows.html)\nUp:\n4. Building C and (building-on-windows.html)\nNext:\n4.2 Differences Between Unix (dynamic-linking.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. Creating 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`pythonXY.lib` to the list in the ``Object/library modules''\nbox.\nSelect ``Win32 Debug'' in the ``Settings for'' dropdown list, and\nappend `pythonXY_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.3", "length": 6917, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.2 Differences Between Unix (dynamic-linking.html)\nUp:\n4. Building C and (building-on-windows.html)\nNext:\n5. Embedding Python in (embedding.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 pythonXY.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/pythonXY.lib\ncl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.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 pythonXY.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.3", "length": 1436, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ext/win-dlls.html"} {"title": "Python 2.3 Documentation - July 29, 2003", "text": "Python Documentation | modindex.html\n---\n# Python Documentation\nRelease 2.3\nJuly 29, 2003\n---\nSee About the Python Documentation (about.html)\nfor information on suggesting changes.", "python_version": "2.3", "length": 180, "url": "https://docs.python.org/2.3/Python-Docs-2.3/index.html"} {"title": "About this document ...", "text": "tweak-flags.html | inst.html | Installing Python Modules\nPrevious:\n6 Building Extensions: Tips (tweak-flags.html)\nUp:\nInstalling Python Modules (inst.html)\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, either in the content or the presentation, please\nreport 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---\ntweak-flags.html | inst.html | Installing Python Modules\nPrevious:\n6 Building Extensions: Tips (tweak-flags.html)\nUp:\nInstalling Python Modules (inst.html)\n---", "python_version": "2.3", "length": 1807, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/about.html"} {"title": "3 Alternate Installation", "text": "standard-install.html | inst.html | search-path.html | Installing Python Modules\nPrevious:\n2 Standard Build and (standard-install.html)\nUp:\nInstalling Python Modules (inst.html)\nNext:\n4 Custom Installation (search-path.html)\n---\n- 3.1 Alternate installation: Unix (the home scheme) (alt-install-windows.html#SECTION000310000000000000000)\n 3.2 Alternate installation: Unix (the prefix scheme) (alt-install-windows.html#SECTION000320000000000000000)\n 3.3 Alternate installation: Windows (alt-install-windows.html#SECTION000330000000000000000)\n 3.4 Alternate installation: Mac OS 9 (alt-install-windows.html#SECTION000340000000000000000)\n---\n# 3 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## 3.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## 3.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/python2.X rather than\n/usr/lib/python2.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/python2.X,\nbut those modules would have to be installed to, say,\n/mnt/@server/export/lib/python2.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 compatible 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## 3.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\n\\Temp\\Python directory on the\ncurrent drive.\nThe installation base is defined by the --prefix option;\nthe --exec-prefix option is not supported under Windows.\nFiles are installed as follows:\n## 3.4 Alternate installation: Mac OS 9\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.3", "length": 6804, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/alt-install-windows.html"} {"title": "5 Distutils Configuration Files", "text": "search-path.html | inst.html | tweak-flags.html | Installing Python Modules\nPrevious:\n4 Custom Installation (search-path.html)\nUp:\nInstalling Python Modules (inst.html)\nNext:\n6 Building Extensions: Tips (tweak-flags.html)\n---\n- 5.1 Location and names of config files (config-syntax.html#SECTION000510000000000000000)\n 5.2 Syntax of config files (config-syntax.html#SECTION000520000000000000000)\n---\n# 5 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## 5.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\npwd (../lib/module-pwd.html) 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.\n## 5.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\nas `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.3", "length": 4586, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/config-syntax.html"} {"title": "Installing Python Modules", "text": "../index.html | trivial-install.html | Installing Python Modules\nUp:\nPython Documentation Index (../index.html)\nNext:\n1 Introduction (trivial-install.html)\n---\n# Installing Python Modules\nGreg Ward\nEmail: distutils-sig@python.org\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.3", "length": 498, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/index.html"} {"title": "Installing Python Modules", "text": "../index.html | trivial-install.html | Installing Python Modules\nUp:\nPython Documentation Index (../index.html)\nNext:\n1 Introduction (trivial-install.html)\n---\n# Installing Python Modules\nGreg Ward\nEmail: distutils-sig@python.org\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.3", "length": 498, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/inst.html"} {"title": "4 Custom Installation", "text": "alt-install-windows.html | inst.html | config-syntax.html | Installing Python Modules\nPrevious:\n3 Alternate Installation (alt-install-windows.html)\nUp:\nInstalling Python Modules (inst.html)\nNext:\n5 Distutils Configuration Files (config-syntax.html)\n---\n- 4.1 Modifying Python's Search Path (search-path.html#SECTION000410000000000000000)\n---\n# 4 Custom Installation\nSometimes, the alternate installation schemes described in\nsection 3 (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\nprefix. Of course, you also have to ensure that these\ndirectories are in Python's module search path, such as by putting a\n.pth file in prefix. See section 4.1 (search-path.html#search-path)\nto find out how to modify Python's search path.\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 5 (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.\nIn fact, you can use environment variables in config files on\nplatforms that have such a notion but the Distutils additionally\ndefine a few extra variables that may not be in your environment, such\nas `$PLAT`. (And of course, on systems that don't have\nenvironment variables, such as Mac OS 9, the configuration\nvariables supplied by the Distutils are the only ones you can use.)\nSee section 5 (config-syntax.html#config-files) for details.\n## 4.1 Modifying Python's Search Path\nWhen the Python interpreter executes an import statement, it\nsearches for both Python code and extension modules along a search\npath. A default value for the path is configured into the Python\nbinary when the interpreter is built. You can determine the path by\nimporting the sys module and printing the value of\n`sys.path`.\n```text\n\n$ python\nPython 2.2 (#11, Oct 3 2002, 13:31:27)\n[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2\nType ``help'', ``copyright'', ``credits'' or ``license'' for more information.\n>>> import sys\n>>> sys.path\n['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',\n'/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload',\n'/usr/local/lib/python2.3/site-packages']\n>>>\n```\nThe null string in `sys.path` represents the current working\ndirectory.\nThe expected convention for locally installed packages is to put them\nin the .../site-packages/ directory, but you may want to\ninstall Python modules into some arbitrary directory. For example,\nyour site may have a convention of keeping all software related to the\nweb server under /www. Add-on Python modules might then belong\nin /www/python, and in order to import them, this directory\nmust be added to `sys.path`. There are several different ways to\nadd the directory.\nThe most convenient way is to add a path configuration file to a\ndirectory that's already on Python's path, usually to the\n.../site-packages/ directory. Path configuration files have an\nextension of .pth, and each line must contain a single path\nthat will be appended to `sys.path`. (Because the new paths are\nappended to `sys.path`, modules in the added directories will not\noverride standard modules. This means you can't use this mechanism\nfor installing fixed versions of standard modules.)\nPaths can be absolute or relative, in which case they're relative to\nthe directory containing the .pth file. Any directories added\nto the search path will be scanned in turn for .pth files. See\nsite module\"\n>the\ndocumentation for the site module (http://www.python.org/dev/doc/devel/lib/module-site.html) for more information.\nA slightly less convenient way is to edit the site.py file in\nPython's standard library, and modify `sys.path`. site.py\nis automatically imported when the Python interpreter is executed,\nunless the -S switch is supplied to suppress this\nbehaviour. So you could simply edit site.py and add two lines to it:\n```text\n\nimport sys\nsys.path.append('/www/python/')\n```\nHowever, if you reinstall the same major version of Python (perhaps\nwhen upgrading from 2.2 to 2.2.2, for example) site.py will be\noverwritten by the stock version. You'd have to remember that it was\nmodified and save a copy before doing the installation.\nThere are two environment variables that can modify `sys.path`.\nPYTHONHOME sets an alternate value for the prefix of the\nPython installation. For example, if PYTHONHOME is set to\n\"/www/python\", the search path will be set to `['',\n'/www/python/lib/python2.2/', '/www/python/lib/python2.3/plat-linux2',\n...]`.\nThe PYTHONPATH variable can be set to a list of paths that\nwill be added to the beginning of `sys.path`. For example, if\nPYTHONPATH is set to \"/www/python:/opt/py\", the search\npath will begin with `['/www/python', '/opt/py']`. (Note that\ndirectories must exist in order to be added to `sys.path`; the\nsite module removes paths that don't exist.)\nFinally, `sys.path` is just a regular Python list, so any Python\napplication can modify it by adding or removing entries.", "python_version": "2.3", "length": 9113, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/search-path.html"} {"title": "2 Standard Build and Install", "text": "trivial-install.html | inst.html | alt-install-windows.html | Installing Python Modules\nPrevious:\n1 Introduction (trivial-install.html)\nUp:\nInstalling Python Modules (inst.html)\nNext:\n3 Alternate Installation (alt-install-windows.html)\n---\n- 2.1 Platform variations (standard-install.html#SECTION000210000000000000000)\n 2.2 Splitting the job up (standard-install.html#SECTION000220000000000000000)\n 2.3 How building works (standard-install.html#SECTION000230000000000000000)\n 2.4 How installation works (standard-install.html#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 9, you double-click the setup.py script. It will bring\nup a dialog where you can select the `install` command. Then\nselecting the `run` button will install your distribution.\nThe dialog is built dynamically, so all commands and options for this\nspecific distribution are listed.\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--for example, 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```\nIf 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 5 (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 9, start PythonInterpreter.\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 3 (alt-install-windows.html#alt-install). If you want to\ncustomize your installation directories more heavily, see\nsection 4 (search-path.html#custom-install) on custom installations.", "python_version": "2.3", "length": 7390, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/standard-install.html"} {"title": "1 Introduction", "text": "inst.html | inst.html | standard-install.html | Installing Python Modules\nPrevious:\nInstalling Python Modules (inst.html)\nUp:\nInstalling Python Modules (inst.html)\nNext:\n2 Standard Build and (standard-install.html)\n---\n- 1.1 Best case: trivial installation (trivial-install.html#SECTION000110000000000000000)\n 1.2 The new standard: Distutils (trivial-install.html#SECTION000120000000000000000)\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 changed.\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, 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 file named README.txt or possibly\njust README, 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.", "python_version": "2.3", "length": 4023, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/trivial-install.html"} {"title": "6 Building Extensions: Tips and Tricks", "text": "config-syntax.html | inst.html | about.html | Installing Python Modules\nPrevious:\n5 Distutils Configuration Files (config-syntax.html)\nUp:\nInstalling Python Modules (inst.html)\nNext:\nAbout this document ... (about.html)\n---\n- 6.1 Tweaking compiler/linker flags (tweak-flags.html#SECTION000610000000000000000)\n 6.2 Using non-Microsoft compilers on Windows (tweak-flags.html#SECTION000620000000000000000)\n - 6.2.1 Borland C++ (tweak-flags.html#SECTION000621000000000000000)\n 6.2.2 GNU C / Cygwin / MinGW (tweak-flags.html#SECTION000622000000000000000)\n---\n# 6 Building Extensions: Tips and Tricks\nWhenever possible, the Distutils try to use the configuration\ninformation made available by the Python interpreter used to run the\nsetup.py script. For example, the same compiler and linker\nflags used to compile Python will also be used for compiling\nextensions. Usually this will work well, but in complicated\nsituations this might be inappropriate. This section discusses how to\noverride the usual Distutils behaviour.\n## 6.1 Tweaking compiler/linker flags\nCompiling a Python extension written in C or C++will sometimes\nrequire specifying custom flags for the compiler and linker in order\nto use a particular library or produce a special kind of object code.\nThis is especially true if the extension hasn't been tested on your\nplatform, or if you're trying to cross-compile Python.\nIn the most general case, the extension author might have foreseen\nthat compiling the extensions would be complicated, and provided a\nSetup file for you to edit. This will likely only be done if\nthe module distribution contains many separate extension modules, or\nif they often require elaborate sets of compiler flags in order to work.\nA Setup file, if present, is parsed in order to get a list of\nextensions to build. Each line in a Setup describes a single\nmodule. Lines have the following structure:\n```text\n\nmodule\n... [\nsourcefile\n...] [\ncpparg\n...] [\nlibrary\n...]\n```\nLet's examine each of the fields in turn.\n- module is the name of the extension module to be built,\nand should be a valid Python identifier. You can't just change\nthis in order to rename a module (edits to the source code would\nalso be needed), so this should be left alone.\n- sourcefile is anything that's likely to be a source code\nfile, at least judging by the filename. Filenames ending in\n.c are assumed to be written in C, filenames ending in\n.C, .cc, and .c++ are assumed to be\nC++, and filenames ending in .m or .mm are\nassumed to be in Objective C.\n- cpparg is an argument for the C preprocessor,\nand is anything starting with -I, -D,\n-U or -C.\n- library is anything ending in .a or beginning with\n-l or -L.\nIf a particular platform requires a special library on your platform,\nyou can add it by editing the Setup file and running\n`python setup.py build`. For example, if the module defined by the line\n```text\n\nfoo foomodule.c\n```\nmust be linked with the math library libm.a on your platform,\nsimply add -lm to the line:\n```text\n\nfoo foomodule.c -lm\n```\nArbitrary switches intended for the compiler or the linker can be\nsupplied with the -Xcompiler arg and\n-Xlinker arg options:\n```text\n\nfoo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm\n```\nThe next option after -Xcompiler and\n-Xlinker will be appended to the proper command line, so\nin the above example the compiler will be passed the -o32\noption, and the linker will be passed -shared. If a\ncompiler option requires an argument, you'll have to supply multiple\n-Xcompiler options; for example, to pass `-x c++` the\nSetup file would have to contain\n`-Xcompiler -x -Xcompiler c++`.\nCompiler flags can also be supplied through setting the\nCFLAGS environment variable. If set, the contents of\nCFLAGS will be added to the compiler flags specified in the\nSetup file.\n## 6.2 Using non-Microsoft compilers on Windows\n### 6.2.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 Borland's object file format (OMF) is\ndifferent from the format used by the Python version you can download\nfrom the Python or ActiveState Web site. (Python is built with\nMicrosoft Visual C++, which uses COFF as the object file format.)\nFor this reason you have to convert Python's library\npython20.lib into the Borland format. You can do this as\nfollows:\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 (#foot509)\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 the default, you\ncould specify this in your personal or system-wide configuration file\nfor Distutils (see section 5 (config-syntax.html#config-files).)\nSee Also:\n### 6.2.2 GNU C / Cygwin / MinGW\nThis section describes the necessary steps to use Distutils with the\nGNU C/C++ compilers in their Cygwin and MinGW\ndistributions.2 (#foot603)For a Python interpreter that was built with Cygwin, everything should\nwork without any of these following steps.\nThese compilers require some special libraries.\nThis task is more complex than for Borland's C++, because there is no\nprogram to convert the library.\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 (#foot604) or for MinGW 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 5 (config-syntax.html#config-files).)\nSee Also:", "python_version": "2.3", "length": 6999, "url": "https://docs.python.org/2.3/Python-Docs-2.3/inst/tweak-flags.html"} {"title": "About this document ...", "text": "genindex.html | lib.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nUp:\nPython Library Reference (lib.html)\n---\n# About this document ...\nPython Library Reference,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1664, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.6 HTTPPasswordMgr Objects (http-password-mgr.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.8 HTTPBasicAuthHandler Objects (http-basic-auth-handler.html)\n---\n## 11.5.7 AbstractBasicAuthHandler Objects", "python_version": "2.3", "length": 375, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.9 ProxyBasicAuthHandler Objects (proxy-basic-auth-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.11 HTTPDigestAuthHandler Objects (http-digest-auth-handler.html)\n---\n## 11.5.10 AbstractDigestAuthHandler Objects", "python_version": "2.3", "length": 401, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.11.1 Message Objects (message-objects.html)\nUp:\n12.11 rfc822 (module-rfc822.html)\nNext:\n12.12 base64 (module-base64.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.3", "length": 424, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.1 al (module-al.html)\nUp:\n20.1 al (module-al.html)\nNext:\n20.1.2 Port Objects (al-port-objects.html)\n---\n## 20.1.1 Configuration Objects\nConfiguration objects returned by newconfig() have the\nfollowing methods:", "python_version": "2.3", "length": 352, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.1.1 Configuration Objects (al-config-objects.html)\nUp:\n20.1 al (module-al.html)\nNext:\n20.2 AL (module-al-constants.html)\n---\n## 20.1.2 Port Objects\nPort objects, as returned by openport(), have the following\nmethods:", "python_version": "2.3", "length": 371, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/al-port-objects.html"} {"title": "6. Generic Operating System Services", "text": "shlex-parsing-rules.html | lib.html | module-os.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.19.3 Parsing Rules (shlex-parsing-rules.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n6.1 os (module-os.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.3", "length": 608, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/allos.html"} {"title": "11.24.2 asynchat Example", "text": "node485.html | module-asynchat.html | netdata.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.24.1 asynchat - Auxiliary (node485.html)\nUp:\n11.24 asynchat (module-asynchat.html)\nNext:\n12. Internet Data Handling (netdata.html)\n---\n## 11.24.2 asynchat Example\nThe following partial example shows how HTTP requests can be read with\nasync_chat. A web server might create an http_request_handler object for\neach incoming client connection. Notice that initially the\nchannel terminator is set to match the blank line at the end of the HTTP\nheaders, and a flag indicates that the headers are being read.\nOnce the headers have been read, if the request is of type POST\n(indicating that further data are present in the input stream) then the\n`Content-Length:` header is used to set a numeric terminator to\nread the right amount of data from the channel.\nThe handle_request() method is called once all relevant input\nhas been marshalled, after setting the channel terminator to `None`\nto ensure that any extraneous data sent by the web client are ignored.\n```text\n\nclass http_request_handler(asynchat.async_chat):\n\ndef __init__(self, conn, addr, sessions, log):\nasynchat.async_chat.__init__(self, conn=conn)\nself.addr = addr\nself.sessions = sessions\nself.ibuffer = []\nself.obuffer = \"\"\nself.set_terminator(\"\\r\\n\\r\\n\")\nself.reading_headers = True\nself.handling = False\nself.cgi_data = None\nself.log = log\n\ndef collect_incoming_data(self, data):\n\"\"\"Buffer the data\"\"\"\nself.ibuffer.append(data)\n\ndef found_terminator(self):\nif self.reading_headers:\nself.reading_headers = False\nself.parse_headers(\"\".join(self.ibuffer))\nself.ibuffer = []\nif self.op.upper() == \"POST\":\nclen = self.headers.getheader(\"content-length\")\nself.set_terminator(int(clen))\nelse:\nself.handling = True\nself.set_terminator(None)\nself.handle_request()\nelif not self.handling:\nself.set_terminator(None) # browsers sometimes over-send\nself.cgi_data = parse(self.headers, \"\".join(self.ibuffer))\nself.handling = True\nself.ibuffer = []\nself.handle_request()\n```", "python_version": "2.3", "length": 2057, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/asynchat-example.html"} {"title": "11.23.1 asyncore Example basic HTTP client", "text": "module-asyncore.html | module-asyncore.html | module-asynchat.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.23 asyncore (module-asyncore.html)\nUp:\n11.23 asyncore (module-asyncore.html)\nNext:\n11.24 asynchat (module-asynchat.html)\n---\n## 11.23.1 asyncore 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:", "python_version": "2.3", "length": 444, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.5 atexit (module-atexit.html)\nUp:\n3.5 atexit (module-atexit.html)\nNext:\n3.6 types (module-types.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.\n```text\n\ntry:\n_count = int(open(\"/tmp/counter\").read())\nexcept IOError:\n_count = 0\n\ndef incrcounter(n):\nglobal _count\n_count = _count + n\n\ndef savecounter():\nopen(\"/tmp/counter\", \"w\").write(\"%d\" % _count)\n\nimport atexit\natexit.register(savecounter)\n```\nPositional and keyword arguments may also be passed to\nregister() to be passed along to the registered function\nwhen it is called:", "python_version": "2.3", "length": 943, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/atexit-example.html"} {"title": "13.12.6 The AttributesNS Interface", "text": "attributes-objects.html | module-xml.sax.xmlreader.html | module-xmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.12.5 The Attributes Interface (attributes-objects.html)\nUp:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)\nNext:\n13.13 xmllib (module-xmllib.html)\n---\n## 13.12.6 The AttributesNS Interface\nThis interface is a subtype of the Attributes\ninterface (attributes-objects.html) (see\nsection 13.12.5 (attributes-objects.html#attributes-objects)). All methods supported by that\ninterface are also available on AttributesNS objects.\nThe following methods are also available:", "python_version": "2.3", "length": 638, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/attributes-ns-objects.html"} {"title": "13.12.5 The Attributes Interface", "text": "input-source-objects.html | module-xml.sax.xmlreader.html | attributes-ns-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.12.4 InputSource Objects (input-source-objects.html)\nUp:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)\nNext:\n13.12.6 The AttributesNS Interface (attributes-ns-objects.html)\n---\n## 13.12.5 The Attributes Interface\nAttributes objects implement a portion of the mapping\nprotocol, including the methods copy(), get(),\nhas_key(), items(), keys(), and\nvalues(). The following methods are also provided:", "python_version": "2.3", "length": 581, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/attributes-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\nPrevious:\n14.4 sunau (module-sunau.html)\nUp:\n14.4 sunau (module-sunau.html)\nNext:\n14.4.2 AU_write Objects (au-write-objects.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.3", "length": 627, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.4.1 AU_read Objects (au-read-objects.html)\nUp:\n14.4 sunau (module-sunau.html)\nNext:\n14.5 wave (module-wave.html)\n---\n## 14.4.2 AU_write Objects\nAU_write objects, as returned by open() above, have the\nfollowing methods:", "python_version": "2.3", "length": 366, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n21.1 sunaudiodev (module-sunaudiodev.html)\nUp:\n21.1 sunaudiodev (module-sunaudiodev.html)\nNext:\n21.2 SUNAUDIODEV (module-sunaudiodev-constants.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.3", "length": 901, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.2 OpenerDirector Objects (opener-director-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.4 HTTPRedirectHandler Objects (http-redirect-handler.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.3", "length": 625, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.20.3 DateTime Objects (datetime-objects.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.20.5 Fault Objects (fault-objects.html)\n---\n## 11.20.4 Binary Objects\nThis class may initialized from string data (which may include NULs).\nThe primary acess to the content of a Binary object is\nprovided by an attribute:\nBinary objects have the following methods, supported mainly\nfor internal use by the marshalling/unmarshalling code:\nIt also supports certain of Python's built-in operators through a\n_cmp__() method.", "python_version": "2.3", "length": 673, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.14 binhex (module-binhex.html)\nUp:\n12.14 binhex (module-binhex.html)\nNext:\n12.15 quopri (module-quopri.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.3", "length": 527, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/binhex-notes.html"} {"title": "5.9.1 Examples", "text": "module-bisect.html | module-bisect.html | module-heapq.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.9 bisect (module-bisect.html)\nUp:\n5.9 bisect (module-bisect.html)\nNext:\n5.10 heapq (module-heapq.html)\n---\n## 5.9.1 Examples\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.\n```text\n\n>>> grades = \"FEDCBA\"\n>>> breakpoints = [30, 44, 66, 75, 85]\n>>> from bisect import bisect\n>>> def grade(total):\n... return grades[bisect(breakpoints, total)]\n...\n>>> grade(66)\n'C'\n>>> map(grade, [33, 99, 77, 44, 12, 88])\n['E', 'A', 'B', 'D', 'F', 'A']\n```\nThe bisect module can be used with the Queue module to implement a priority\nqueue (example courtesy of Fredrik Lundh):", "python_version": "2.3", "length": 896, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.4 Numeric Types (typesnumeric.html)\nUp:\n2.2.4 Numeric Types (typesnumeric.html)\nNext:\n2.2.5 Iterator Types (typeiter.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.3", "length": 1218, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9.4 Methods (typesmethods.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.6 Type Objects (bltin-type-objects.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.3", "length": 902, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/bltin-code-objects.html"} {"title": "2.2.9.8 The Ellipsis Object", "text": "bltin-null-object.html | typesother.html | node29.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n2.2.9.7 The Null Object (bltin-null-object.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.9 Boolean Values (node29.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.3", "length": 552, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.7 Mapping Types (typesmapping.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.9 Other Built-in Types (typesother.html)\n---\n## 2.2.8 File Objects\nFile objects are 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 (#foot3223)File objects 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.3", "length": 1275, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9.6 Type Objects (bltin-type-objects.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.8 The Ellipsis Object (bltin-ellipsis-object.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.3", "length": 547, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9.5 Code Objects (bltin-code-objects.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.7 The Null Object (bltin-null-object.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.3", "length": 602, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/bltin-type-objects.html"} {"title": "11.20.2 Boolean Objects", "text": "serverproxy-objects.html | module-xmlrpclib.html | datetime-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.20.1 ServerProxy Objects (serverproxy-objects.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.20.3 DateTime Objects (datetime-objects.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.3", "length": 688, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.1 Truth Value Testing (truth.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.3 Comparisons (comparisons.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.3", "length": 573, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.1 webbrowser (module-webbrowser.html)\nUp:\n11.1 webbrowser (module-webbrowser.html)\nNext:\n11.2 cgi (module-cgi.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.3", "length": 412, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/browser-controllers.html"} {"title": "7.13.1 Hash, BTree and Record Objects", "text": "module-bsddb.html | module-bsddb.html | module-dumbdbm.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.13 bsddb (module-bsddb.html)\nUp:\n7.13 bsddb (module-bsddb.html)\nNext:\n7.14 dumbdbm (module-dumbdbm.html)\n---\n## 7.13.1 Hash, BTree and Record Objects\nOnce instantiated, hash, btree and record objects support the following\nmethods:\nExample:", "python_version": "2.3", "length": 386, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2. Built-In Objects (builtin.html)\nUp:\n2. Built-In Objects (builtin.html)\nNext:\n2.2 Built-in Types (types.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.3", "length": 400, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/built-in-funcs.html"} {"title": "2. Built-In Objects", "text": "intro.html | lib.html | built-in-funcs.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n1. Introduction (intro.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n2.1 Built-in Functions (built-in-funcs.html)\n---\n# 2. Built-In Objects\nNames for built-in exceptions and functions and a number of constants are\nfound 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\n... reference.2.1 (builtin.html#tex2html1): Most descriptions sorely lack explanations of the exceptions\nthat may be raised -- this will be fixed in a future version of\nthis manual.", "python_version": "2.3", "length": 1259, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.10 dis (module-dis.html)\nUp:\n18.10 dis (module-dis.html)\nNext:\n18.11 distutils (module-distutils.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.\nMiscellaneous opcodes.\nAll of the following opcodes expect arguments. An argument is two\nbytes, with the more significant byte last.", "python_version": "2.3", "length": 1186, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.16 FTPHandler Objects (ftp-handler-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.18 GopherHandler Objects (gopher-handler.html)\n---\n## 11.5.17 CacheFTPHandler Objects\nCacheFTPHandler objects are FTPHandler objects with\nthe following additional methods:", "python_version": "2.3", "length": 429, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.3.1 Player Objects (player-objects.html)\nUp:\n20.3 cd (module-cd.html)\nNext:\n20.4 fl (module-fl.html)\n---\n## 20.3.2 Parser Objects\nParser objects (returned by createparser()) have the\nfollowing methods:", "python_version": "2.3", "length": 343, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/cd-parser-objects.html"} {"title": "11.2.1 Introduction", "text": "module-cgi.html | module-cgi.html | node403.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2 cgi (module-cgi.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.2 Using the cgi (node403.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.3", "length": 1886, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/cgi-intro.html"} {"title": "11.2.6 Caring about security", "text": "node406.html | module-cgi.html | node408.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.5 Functions (node406.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.7 Installing your CGI (node408.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.3", "length": 964, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/cgi-security.html"} {"title": "5.18.1 Cmd Objects", "text": "module-cmd.html | module-cmd.html | module-shlex.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.18 cmd (module-cmd.html)\nUp:\n5.18 cmd (module-cmd.html)\nNext:\n5.19 shlex (module-shlex.html)\n---\n## 5.18.1 Cmd Objects\nA Cmd instance has the following methods:\nInstances of Cmd subclasses have some public instance variables:", "python_version": "2.3", "length": 366, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/Cmd-objects.html"} {"title": "4.9.1.1 Codec Objects", "text": "node120.html | node120.html | stream-writer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.1 Codec Base Classes (node120.html)\nUp:\n4.9.1 Codec Base Classes (node120.html)\nNext:\n4.9.1.2 StreamWriter Objects (stream-writer-objects.html)\n---\n### 4.9.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.3", "length": 639, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.2 Boolean Operations (boolean.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.4 Numeric Types (typesnumeric.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`!=` is the preferred spelling; `<>` is obsolescent.\nObjects of different types, except different numeric types and different string 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. The `<`, `<=`, `>` and `>=`\noperators will raise a TypeError exception when any operand\nis a complex number.\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.3", "length": 1903, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.11 distutils (module-distutils.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n19.1 The basic interface (module-compiler.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.3", "length": 1591, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/compiler.html"} {"title": "7.21.1 Completer Objects", "text": "module-rlcompleter.html | module-rlcompleter.html | unix.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.21 rlcompleter (module-rlcompleter.html)\nUp:\n7.21 rlcompleter (module-rlcompleter.html)\nNext:\n8. Unix Specific Services (unix.html)\n---\n## 7.21.1 Completer Objects\nCompleter objects have the following method:", "python_version": "2.3", "length": 357, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.2 RLock Objects (rlock-objects.html)\nUp:\n7.5 threading (module-threading.html)\nNext:\n7.5.4 Semaphore Objects (semaphore-objects.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.3", "length": 2481, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/condition-objects.html"} {"title": "5.14.2 ConfigParser Objects", "text": "RawConfigParser-objects.html | module-ConfigParser.html | module-fileinput.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.14.1 RawConfigParser Objects (RawConfigParser-objects.html)\nUp:\n5.14 ConfigParser (module-ConfigParser.html)\nNext:\n5.15 fileinput (module-fileinput.html)\n---\n## 5.14.2 ConfigParser Objects\nThe ConfigParser class extends some methods of the\nRawConfigParser interface, adding some optional arguments.", "python_version": "2.3", "length": 465, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/ConfigParser-objects.html"} {"title": "3.23.2 Interactive Console Objects", "text": "interpreter-objects.html | module-code.html | module-codeop.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.23.1 Interactive Interpreter Objects (interpreter-objects.html)\nUp:\n3.23 code (module-code.html)\nNext:\n3.24 codeop (module-codeop.html)\n---\n## 3.23.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.3", "length": 492, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.10 xml.sax.handler (module-xml.sax.handler.html)\nUp:\n13.10 xml.sax.handler (module-xml.sax.handler.html)\nNext:\n13.10.2 DTDHandler Objects (dtd-handler-objects.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.3", "length": 547, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/content-handler-objects.html"} {"title": "Contents", "text": "front.html | lib.html | intro.html | Python Library Reference | modindex.html | genindex.html\nPrevious:\nFront Matter (front.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n1. Introduction (intro.html)\n---\n## Contents\nTable of Contents\n- Front Matter (front.html)\n 1. Introduction (intro.html)\n 2. Built-In Objects (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 2.4 Built-in Constants (node33.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 (node43.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 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 (node61.html)\n 3.14.2 Data stream format (node62.html)\n 3.14.3 Usage (node63.html)\n 3.14.4 What can be pickled and unpickled? (node64.html)\n 3.14.5 The pickle protocol (pickle-protocol.html)\n 3.14.6 Subclassing Unpicklers (pickle-sub.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.17.1 Restrictions (node74.html)\n 3.17.2 Example (node75.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 pkgutil -- Package extension utility (module-pkgutil.html)\n 3.23 code -- Interpreter base classes (module-code.html)\n - 3.23.1 Interactive Interpreter Objects (interpreter-objects.html)\n 3.23.2 Interactive Console Objects (console-objects.html)\n 3.24 codeop -- Compile Python code (module-codeop.html)\n 3.25 pprint -- Data pretty printer (module-pprint.html)\n - 3.25.1 PrettyPrinter Objects (node90.html)\n 3.26 repr -- Alternate repr() implementation (module-repr.html)\n - 3.26.1 Repr Objects (Repr-objects.html)\n 3.26.2 Subclassing Repr Objects (subclassing-reprs.html)\n 3.27 new -- Creation of runtime internal objects (module-new.html)\n 3.28 site -- Site-specific configuration hook (module-site.html)\n 3.29 user -- User-specific configuration hook (module-user.html)\n 3.30 __builtin__ -- Built-in functions (module-builtin.html)\n 3.31 __main__ -- Top-level script environment (module-main.html)\n 3.32 __future__ -- Future statement definitions (module-future.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 (node105.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 (node108.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 textwrap -- Text wrapping and filling (module-textwrap.html)\n 4.9 codecs -- Codec registry and base classes (module-codecs.html)\n - 4.9.1 Codec Base Classes (node120.html)\n 4.9.2 Standard Encodings (node126.html)\n 4.9.3 encodings.idna -- Internationalized Domain Names in Applications (module-encodings.idna.html)\n 4.10 unicodedata -- Unicode Database (module-unicodedata.html)\n 4.11 stringprep -- Internet String Preparation (module-stringprep.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 (node133.html)\n 5.2.2 Which Docstrings Are Examined? (node134.html)\n 5.2.3 What's the Execution Context? (node135.html)\n 5.2.4 What About Exceptions? (node136.html)\n 5.2.5 Advanced Usage (node137.html)\n 5.2.6 How are Docstring Examples Recognized? (node138.html)\n 5.2.7 Warnings (node139.html)\n 5.2.8 Soapbox (node140.html)\n 5.3 unittest -- Unit testing framework (module-unittest.html)\n - 5.3.1 Minimal example (minimal-example.html)\n 5.3.2 Organizing test code (organizing-tests.html)\n 5.3.3 Re-using old test code (legacy-unit-tests.html)\n 5.3.4 Classes and functions (unittest-contents.html)\n 5.3.5 TestCase Objects (testcase-objects.html)\n 5.3.6 TestSuite Objects (testsuite-objects.html)\n 5.3.7 TestResult Objects (testresult-objects.html)\n 5.3.8 TestLoader Objects (testloader-objects.html)\n 5.3.9 Getting Extended Error Information (unittest-error-info.html)\n 5.4 test -- Regression tests package for Python (module-test.html)\n - 5.4.1 [test.testsupport]test.test_support -- -- Utility functions for tests (module-test.testsupport.html)\n 5.4.2 Writing Unit Tests for the test package (writing-tests.html)\n 5.4.3 Running tests Using regrtest.py (regrtest.html)\n 5.5 math -- Mathematical functions (module-math.html)\n 5.6 cmath -- Mathematical functions for complex numbers (module-cmath.html)\n 5.7 random -- Generate pseudo-random numbers (module-random.html)\n 5.8 whrandom -- Pseudo-random number generator (module-whrandom.html)\n 5.9 bisect -- Array bisection algorithm (module-bisect.html)\n - 5.9.1 Examples (bisect-example.html)\n 5.10 heapq -- Heap queue algorithm (module-heapq.html)\n - 5.10.1 Theory (node162.html)\n 5.11 array -- Efficient arrays of numeric values (module-array.html)\n 5.12 sets -- Unordered collections of unique elements (module-sets.html)\n - 5.12.1 Set Objects (set-objects.html)\n 5.12.2 Example (set-example.html)\n 5.12.3 Protocol for automatic conversion to immutable (immutable-transforms.html)\n 5.13 itertools -- Functions creating iterators for efficient looping (module-itertools.html)\n - 5.13.1 Itertool functions (itertools-functions.html)\n 5.13.2 Examples (itertools-example.html)\n 5.14 ConfigParser -- Configuration file parser (module-ConfigParser.html)\n - 5.14.1 RawConfigParser Objects (RawConfigParser-objects.html)\n 5.14.2 ConfigParser Objects (ConfigParser-objects.html)\n 5.15 fileinput -- Iterate over lines from multiple input streams (module-fileinput.html)\n 5.16 xreadlines -- Efficient iteration over a file (module-xreadlines.html)\n 5.17 calendar -- General calendar-related functions (module-calendar.html)\n 5.18 cmd -- Support for line-oriented command interpreters (module-cmd.html)\n - 5.18.1 Cmd Objects (Cmd-objects.html)\n 5.19 shlex -- Simple lexical analysis (module-shlex.html)\n - 5.19.1 Module Contents (node180.html)\n 5.19.2 shlex Objects (shlex-objects.html)\n 5.19.3 Parsing Rules (shlex-parsing-rules.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.8.2 Flow Control Issues (popen2-flow-control.html)\n 6.9 datetime -- Basic date and time types (module-datetime.html)\n - 6.9.1 Available Types (node202.html)\n 6.9.2 timedelta Objects (datetime-timedelta.html)\n 6.9.3 date Objects (datetime-date.html)\n 6.9.4 datetime Objects (datetime-datetime.html)\n 6.9.5 time Objects (datetime-time.html)\n 6.9.6 tzinfo Objects (datetime-tzinfo.html)\n 6.9.7 strftime() Behavior (node208.html)\n 6.10 time -- Time access and conversions (module-time.html)\n 6.11 sched -- Event scheduler (module-sched.html)\n - 6.11.1 Scheduler Objects (scheduler-objects.html)\n 6.12 mutex -- Mutual exclusion support (module-mutex.html)\n - 6.12.1 Mutex Objects (mutex-objects.html)\n 6.13 getpass -- Portable password input (module-getpass.html)\n 6.14 curses -- Terminal handling for character-cell displays (module-curses.html)\n - 6.14.1 Functions (curses-functions.html)\n 6.14.2 Window Objects (curses-window-objects.html)\n 6.14.3 Constants (node218.html)\n 6.15 curses.textpad -- Text input widget for curses programs (module-curses.textpad.html)\n - 6.15.1 Textbox objects (curses-textpad-objects.html)\n 6.16 curses.wrapper -- Terminal handler for curses programs (module-curses.wrapper.html)\n 6.17 curses.ascii -- Utilities for ASCII characters (module-curses.ascii.html)\n 6.18 curses.panel -- A panel stack extension for curses. (module-curses.panel.html)\n - 6.18.1 Functions (cursespanel-functions.html)\n 6.18.2 Panel Objects (curses-panel-objects.html)\n 6.19 getopt -- Parser for command line options (module-getopt.html)\n 6.20 optparse -- Powerful parser for command line options. (module-optparse.html)\n - 6.20.1 Philosophy (optparse-philosophy.html)\n 6.20.2 Basic Usage (optparse-basic-usage.html)\n 6.20.3 Advanced Usage (optparse-advanced-usage.html)\n 6.20.4 Callback Options (optparse-callback-options.html)\n 6.20.5 Extending optparse (optparse-extending.html)\n 6.21 tempfile -- Generate temporary files and directories (module-tempfile.html)\n 6.22 errno -- Standard errno system symbols (module-errno.html)\n 6.23 glob -- Unix style pathname pattern expansion (module-glob.html)\n 6.24 fnmatch -- Unix filename pattern matching (module-fnmatch.html)\n 6.25 shutil -- High-level file operations (module-shutil.html)\n - 6.25.1 Example (shutil-example.html)\n 6.26 locale -- Internationalization services (module-locale.html)\n - 6.26.1 Background, details, hints, tips and caveats (node264.html)\n 6.26.2 For extension writers and programs that embed Python (embedding-locale.html)\n 6.26.3 Access to message catalogs (locale-gettext.html)\n 6.27 gettext -- Multilingual internationalization services (module-gettext.html)\n - 6.27.1 GNU gettext API (node268.html)\n 6.27.2 Class-based API (node269.html)\n 6.27.3 Internationalizing your programs and modules (node274.html)\n 6.27.4 Acknowledgements (node279.html)\n 6.28 logging -- Logging facility for Python (module-logging.html)\n - 6.28.1 Logger Objects (node281.html)\n 6.28.2 Handler Objects (node282.html)\n 6.28.3 Formatter Objects (node293.html)\n 6.28.4 Filter Objects (node294.html)\n 6.28.5 LogRecord Objects (node295.html)\n 6.28.6 Thread Safety (node296.html)\n 6.28.7 Configuration (node297.html)\n 6.28.8 Using the logging package (node300.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 (node304.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 dummy_thread -- Drop-in replacement for the thread module (module-dummythread.html)\n 7.7 dummy_threading -- Drop-in replacement for the threading module (module-dummythreading.html)\n 7.8 Queue -- A synchronized queue class (module-Queue.html)\n - 7.8.1 Queue Objects (QueueObjects.html)\n 7.9 mmap --\n Memory-mapped file support (module-mmap.html)\n 7.10 anydbm -- Generic access to DBM-style databases (module-anydbm.html)\n 7.11 dbhash -- DBM-style interface to the BSD database library (module-dbhash.html)\n - 7.11.1 Database Objects (dbhash-objects.html)\n 7.12 whichdb -- Guess which DBM module created a database (module-whichdb.html)\n 7.13 bsddb -- Interface to Berkeley DB library (module-bsddb.html)\n - 7.13.1 Hash, BTree and Record Objects (bsddb-objects.html)\n 7.14 dumbdbm -- Portable DBM implementation (module-dumbdbm.html)\n - 7.14.1 Dumbdbm Objects (dumbdbm-objects.html)\n 7.15 zlib -- Compression compatible with gzip (module-zlib.html)\n 7.16 gzip -- Support for gzip files (module-gzip.html)\n 7.17 bz2 -- Compression compatible with bzip2 (module-bz2.html)\n - 7.17.1 (De)compression of files (node337.html)\n 7.17.2 Sequential (de)compression (node338.html)\n 7.17.3 One-shot (de)compression (node339.html)\n 7.18 zipfile -- Work with ZIP archives (module-zipfile.html)\n - 7.18.1 ZipFile Objects (zipfile-objects.html)\n 7.18.2 PyZipFile Objects (pyzipfile-objects.html)\n 7.18.3 ZipInfo Objects (zipinfo-objects.html)\n 7.19 tarfile -- Read and write tar archive files (module-tarfile.html)\n - 7.19.1 TarFile Objects (tarfile-objects.html)\n 7.19.2 TarInfo Objects (tarinfo-objects.html)\n 7.19.3 Examples (tar-examples.html)\n 7.20 readline -- GNU readline interface (module-readline.html)\n - 7.20.1 Example (readline-example.html)\n 7.21 rlcompleter -- Completion function for GNU readline (module-rlcompleter.html)\n - 7.21.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 (node364.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 (node373.html)\n 8.15.2 Resource Usage (node374.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 (node382.html)\n 10.2 How Is This Profiler Different From The Old Profiler? (node383.html)\n 10.3 Instant Users Manual (profile-instant.html)\n 10.4 What Is Deterministic Profiling? (node385.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 (node390.html)\n 10.9 hotshot -- High performance logging profiler (module-hotshot.html)\n - 10.9.1 Profile Objects (hotshot-objects.html)\n 10.9.2 Using hotshot data (module-hotshot.stats.html)\n 10.9.3 Example Usage (hotshot-example.html)\n 10.10 timeit -- Measure execution time of small code snippets (module-timeit.html)\n - 10.10.1 Command Line Interface (node396.html)\n 10.10.2 Examples (node397.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 (node403.html)\n 11.2.3 Higher Level Interface (node404.html)\n 11.2.4 Old classes (node405.html)\n 11.2.5 Functions (node406.html)\n 11.2.6 Caring about security (cgi-security.html)\n 11.2.7 Installing your CGI script on a Unix system (node408.html)\n 11.2.8 Testing your CGI script (node409.html)\n 11.2.9 Debugging CGI scripts (node410.html)\n 11.2.10 Common problems and solutions (node411.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 (node415.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.5.20 Examples (urllib2-examples.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 ServerProxy Objects (serverproxy-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 (node474.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.21.2 CGIXMLRPCRequestHandler (node478.html)\n 11.22 DocXMLRPCServer -- Self-documenting XML-RPC server (module-DocXMLRPCServer.html)\n - 11.22.1 DocXMLRPCServer Objects (doc-xmlrpc-servers.html)\n 11.22.2 DocCGIXMLRPCRequestHandler (node481.html)\n 11.23 asyncore -- Asynchronous socket handler (module-asyncore.html)\n - 11.23.1 asyncore Example basic HTTP client (asyncore-example.html)\n 11.24 asynchat -- Asynchronous socket command/response handler (module-asynchat.html)\n - 11.24.1 asynchat - Auxiliary Classes and Functions (node485.html)\n 11.24.2 asynchat Example (asynchat-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 (node501.html)\n 12.2.5 Internationalized headers (module-email.Header.html)\n 12.2.6 Representing character sets (module-email.Charset.html)\n 12.2.7 Encoders (module-email.Encoders.html)\n 12.2.8 Exception classes (module-email.Errors.html)\n 12.2.9 Miscellaneous utilities (module-email.Utils.html)\n 12.2.10 Iterators (module-email.Iterators.html)\n 12.2.11 Differences from email v1 (up to Python 2.2.1) (node508.html)\n 12.2.12 Differences from mimelib (node509.html)\n 12.2.13 Examples (node510.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 12.20 csv -- CSV File Reading and Writing (module-csv.html)\n - 12.20.1 Module Contents (node545.html)\n 12.20.2 Dialects and Formatting Parameters (csv-fmt-params.html)\n 12.20.3 Reader Objects (node547.html)\n 12.20.4 Writer Objects (node548.html)\n 12.20.5 Examples (node549.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 Application (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 (node564.html)\n 13.6.2 Objects in the DOM (node565.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 The Attributes Interface (attributes-objects.html)\n 13.12.6 The AttributesNS Interface (attributes-ns-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 14.11 ossaudiodev -- Access to OSS-compatible audio devices (module-ossaudiodev.html)\n - 14.11.1 Audio Device Objects (ossaudio-device-objects.html)\n 14.11.2 Mixer Device Objects (mixer-device-objects.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 (node630.html)\n 16.1.2 Tkinter Life Preserver (node631.html)\n 16.1.3 A (Very) Quick Look at Tcl/Tk (node634.html)\n 16.1.4 Mapping Basic Tk into Tkinter (tkinter-basic-mapping.html)\n 16.1.5 How Tk and Tkinter are Related (node636.html)\n 16.1.6 Handy Reference (node637.html)\n 16.2 Tix -- Extension widgets for Tk (module-Tix.html)\n - 16.2.1 Using Tix (node648.html)\n 16.2.2 Tix Widgets (node649.html)\n 16.2.3 Tix Commands (node658.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 (node663.html)\n 16.5.2 Basic editing and navigation (node668.html)\n 16.5.3 Syntax colors (node671.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 (node678.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 (node682.html)\n 18.1.2 Converting AST Objects (node683.html)\n 18.1.3 Queries on AST Objects (node684.html)\n 18.1.4 Exceptions and Error Handling (node685.html)\n 18.1.5 AST Objects (node686.html)\n 18.1.6 Examples (node687.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 (node704.html)\n 19.3 Python Abstract Syntax (node705.html)\n - 19.3.1 AST Nodes (module-compiler.ast.html)\n 19.3.2 Assignment nodes (node707.html)\n 19.3.3 Examples (node708.html)\n 19.4 Using Visitors to Walk ASTs (module-compiler.visitor.html)\n 19.5 Bytecode Generation (node710.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 (node720.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 (node735.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 (node744.html)\n A.2 Miscellaneous useful utilities (node745.html)\n A.3 Platform specific modules (node746.html)\n A.4 Multimedia (node747.html)\n A.5 Obsolete (obsolete-modules.html)\n A.6 SGI-specific Extension modules (node749.html)\n B. Reporting Bugs (reporting-bugs.html)\n C. History and License (node751.html)\n - C.1 History of the software (node752.html)\n C.2 Terms and conditions for accessing or otherwise using Python (node753.html)\n Module Index (modindex.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.3", "length": 37193, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/contents.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\nPrevious:\n11.19.2 Morsel Objects (morsel-objects.html)\nUp:\n11.19 Cookie (module-Cookie.html)\nNext:\n11.20 xmlrpclib (module-xmlrpclib.html)\n---\n## 11.19.3 Example\nThe following example demonstrates how to use the Cookie module.", "python_version": "2.3", "length": 366, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.19 Cookie (module-Cookie.html)\nUp:\n11.19 Cookie (module-Cookie.html)\nNext:\n11.19.2 Morsel Objects (morsel-objects.html)\n---\n## 11.19.1 Cookie Objects", "python_version": "2.3", "length": 299, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/cookie-objects.html"} {"title": "15. Cryptographic Services", "text": "mixer-device-objects.html | lib.html | module-hmac.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n14.11.2 Mixer Device Objects (mixer-device-objects.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n15.1 hmac (module-hmac.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.3", "length": 856, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/crypto.html"} {"title": "12.20.2 Dialects and Formatting Parameters", "text": "node545.html | module-csv.html | node547.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.20.1 Module Contents (node545.html)\nUp:\n12.20 csv (module-csv.html)\nNext:\n12.20.3 Reader Objects (node547.html)\n---\n## 12.20.2 Dialects and Formatting Parameters\nTo make it easier to specify the format of input and output records,\nspecific formatting parameters are grouped together into dialects. A\ndialect is a subclass of the Dialect class having a set of specific\nmethods and a single validate() method. When creating reader\nor writer objects, the programmer can specify a string or a subclass\nof the Dialect class as the dialect parameter. In addition to, or\ninstead of, the dialect parameter, the programmer can also specify\nindividual formatting parameters, which have the same names as the\nattributes defined above for the Dialect class.\nDialects support the following attributes:", "python_version": "2.3", "length": 922, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/csv-fmt-params.html"} {"title": "6.14.1 Functions", "text": "module-curses.html | module-curses.html | curses-window-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.14 curses (module-curses.html)\nUp:\n6.14 curses (module-curses.html)\nNext:\n6.14.2 Window Objects (curses-window-objects.html)\n---\n## 6.14.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.3", "length": 575, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/curses-functions.html"} {"title": "6.18.2 Panel Objects", "text": "cursespanel-functions.html | module-curses.panel.html | module-getopt.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.18.1 Functions (cursespanel-functions.html)\nUp:\n6.18 curses.panel (module-curses.panel.html)\nNext:\n6.19 getopt (module-getopt.html)\n---\n## 6.18.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.3", "length": 608, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/curses-panel-objects.html"} {"title": "6.15.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\nPrevious:\n6.15 curses.textpad (module-curses.textpad.html)\nUp:\n6.15 curses.textpad (module-curses.textpad.html)\nNext:\n6.16 curses.wrapper (module-curses.wrapper.html)\n---\n## 6.15.1 Textbox objects\nYou can instantiate a Textbox object as follows:\nTextbox objects have the following methods:", "python_version": "2.3", "length": 449, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/curses-textpad-objects.html"} {"title": "6.14.2 Window Objects", "text": "curses-functions.html | module-curses.html | node218.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.14.1 Functions (curses-functions.html)\nUp:\n6.14 curses (module-curses.html)\nNext:\n6.14.3 Constants (node218.html)\n---\n## 6.14.2 Window Objects\nWindow objects, as returned by initscr() and\nnewwin() above, have the\nfollowing methods:", "python_version": "2.3", "length": 376, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/curses-window-objects.html"} {"title": "6.18.1 Functions", "text": "module-curses.panel.html | module-curses.panel.html | curses-panel-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.18 curses.panel (module-curses.panel.html)\nUp:\n6.18 curses.panel (module-curses.panel.html)\nNext:\n6.18.2 Panel Objects (curses-panel-objects.html)\n---\n## 6.18.1 Functions\nThe module curses.panel defines the following functions:", "python_version": "2.3", "length": 394, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/cursespanel-functions.html"} {"title": "6.9.3 date Objects", "text": "datetime-timedelta.html | module-datetime.html | datetime-datetime.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9.2 timedelta Objects (datetime-timedelta.html)\nUp:\n6.9 datetime (module-datetime.html)\nNext:\n6.9.4 datetime Objects (datetime-datetime.html)\n---\n## 6.9.3 date Objects\nA date object represents a date (year, month and day) in an idealized\ncalendar, the current Gregorian calendar indefinitely extended in both\ndirections. January 1 of year 1 is called day number 1, January 2 of year\n1 is called day number 2, and so on. This matches the definition of the\n\"proleptic Gregorian\" calendar in Dershowitz and Reingold's book\nCalendrical Calculations, where it's the base calendar for all\ncomputations. See the book for algorithms for converting between\nproleptic Gregorian ordinals and many other calendar systems.\nOther constructors, all class methods:\nClass attributes:\nInstance attributes (read-only):\nSupported operations:\nNotes:\n(1): date2 is moved forward in time if `timedelta .days\n> 0`, or backward if `timedelta .days < 0`. Afterward\n`date2 - date1 == timedelta .days`.\n`timedelta .seconds` and\n`timedelta .microseconds` are ignored.\nOverflowError is raised if `date2 .year`\nwould be smaller than MINYEAR or larger than\nMAXYEAR.\n(2): This isn't quite equivalent to date1 +\n(-timedelta), because -timedelta in isolation can overflow in cases\nwhere date1 - timedelta does not. `timedelta .seconds`\nand `timedelta .microseconds` are ignored.\n(3): This is exact, and cannot overflow. timedelta.seconds and\ntimedelta.microseconds are 0, and date2 + timedelta == date1\nafter.\n(4): In other words, `date1 < date2`\nif and only if `date1 .toordinal() < date2 .toordinal()`.\nIn order to stop comparison from falling back to the default\nscheme of comparing object addresses, date comparison\nnormally raises TypeError if the other comparand\nisn't also a date object. However, `NotImplemented`\nis returned instead if the other comparand has a\ntimetuple attribute. This hook gives other kinds of\ndate objects a chance at implementing mixed-type comparison.\nIf not, when a date object is\ncompared to an object of a different type, TypeError is\nraised unless the comparison is `==` or `!=`. The latter\ncases return False or True, respectively.\nDates can be used as dictionary keys. In Boolean contexts, all\ndate objects are considered to be true.\nInstance methods:", "python_version": "2.3", "length": 2412, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/datetime-date.html"} {"title": "6.9.4 datetime Objects", "text": "datetime-date.html | module-datetime.html | datetime-time.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9.3 date Objects (datetime-date.html)\nUp:\n6.9 datetime (module-datetime.html)\nNext:\n6.9.5 time Objects (datetime-time.html)\n---\n## 6.9.4 datetime Objects\nA datetime object is a single object containing all the\ninformation from a date object and a time object. Like a\ndate object, datetime assumes the current Gregorian\ncalendar extended in both directions; like a time object,\ndatetime assumes there are exactly 3600*24 seconds in every\nday.\nConstructor:\nOther constructors, all class methods:\nClass attributes:\nInstance attributes (read-only):\nSupported operations:\n(1): datetime2 is a duration of timedelta removed from datetime1, moving\nforward in time if `timedelta .days` > 0, or backward if\n`timedelta .days` < 0. The result has the same tzinfo member\nas the input datetime, and datetime2 - datetime1 == timedelta after.\nOverflowError is raised if datetime2.year would be\nsmaller than MINYEAR or larger than MAXYEAR.\nNote that no time zone adjustments are done even if the input is an\naware object.\n(2): Computes the datetime2 such that datetime2 + timedelta == datetime1.\nAs for addition, the result has the same tzinfo member\nas the input datetime, and no time zone adjustments are done even\nif the input is aware.\nThis isn't quite equivalent to datetime1 + (-timedelta), because\n-timedelta in isolation can overflow in cases where\ndatetime1 - timedelta does not.\n(3): Subtraction of a datetime from a\ndatetime is defined only if both\noperands are naive, or if both are aware. If one is aware and the\nother is naive, TypeError is raised.\nIf both are naive, or both are aware and have the same tzinfo\nmember, the tzinfo members are ignored, and the result is\na timedelta object t such that\n`datetime2 + t == datetime1`. No time zone\nadjustments are done in this case.\nIf both are aware and have different tzinfo members,\n`a-b` acts as if a and b were first converted to\nnaive UTC datetimes first. The result is\n`( a .replace(tzinfo=None) - a .utcoffset()) -\n( b .replace(tzinfo=None) - b .utcoffset())`\nexcept that the implementation never overflows.\n(4): datetime1 is considered less than datetime2\nwhen datetime1 precedes datetime2 in time.\nIf one comparand is naive and\nthe other is aware, TypeError is raised. If both\ncomparands are aware, and have the same tzinfo member,\nthe common tzinfo member is ignored and the base datetimes\nare compared. If both comparands are aware and have different\ntzinfo members, the comparands are first adjusted by\nsubtracting their UTC offsets (obtained from `self.utcoffset()`).\nNote:\nIn order to stop comparison from falling back to the default\nscheme of comparing object addresses, datetime comparison\nnormally raises TypeError if the other comparand\nisn't also a datetime object. However,\n`NotImplemented` is returned instead if the other comparand\nhas a timetuple attribute. This hook gives other\nkinds of date objects a chance at implementing mixed-type\ncomparison. If not, when a datetime object is\ncompared to an object of a different type, TypeError\nis raised unless the comparison is `==` or `!=`. The\nlatter cases return False or True,\nrespectively.\ndatetime objects can be used as dictionary keys. In Boolean\ncontexts, all datetime objects are considered to be true.\nInstance methods:", "python_version": "2.3", "length": 3390, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/datetime-datetime.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\nPrevious:\n11.20.2 Boolean Objects (boolean-objects.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.20.4 Binary Objects (binary-objects.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.3", "length": 633, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/datetime-objects.html"} {"title": "6.9.5 time Objects", "text": "datetime-datetime.html | module-datetime.html | datetime-tzinfo.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9.4 datetime Objects (datetime-datetime.html)\nUp:\n6.9 datetime (module-datetime.html)\nNext:\n6.9.6 tzinfo Objects (datetime-tzinfo.html)\n---\n## 6.9.5 time Objects\nA time object represents a (local) time of day, independent of any\nparticular day, and subject to adjustment via a tzinfo object.\nClass attributes:\nInstance attributes (read-only):\nSupported operations:\n- comparison of time to time,\nwhere a is considered less than b when a precedes\nb in time. If one comparand is naive and the other is aware,\nTypeError is raised. If both comparands are aware, and\nhave the same tzinfo member, the common tzinfo\nmember is ignored and the base times are compared. If both\ncomparands are aware and have different tzinfo members,\nthe comparands are first adjusted by subtracting their UTC offsets\n(obtained from `self.utcoffset()`).\nIn order to stop mixed-type comparisons from falling back to the\ndefault comparison by object address, when a time object is\ncompared to an object of a different type, TypeError is\nraised unless the comparison is `==` or `!=`. The latter\ncases return False or True, respectively.\n- hash, use as dict key\n- efficient pickling\n- in Boolean contexts, a time object is considered to be\ntrue if and only if, after converting it to minutes and\nsubtracting utcoffset() (or `0` if that's\n`None`), the result is non-zero.\nInstance methods:", "python_version": "2.3", "length": 1512, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/datetime-time.html"} {"title": "6.9.2 timedelta Objects", "text": "node202.html | module-datetime.html | datetime-date.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9.1 Available Types (node202.html)\nUp:\n6.9 datetime (module-datetime.html)\nNext:\n6.9.3 date Objects (datetime-date.html)\n---\n## 6.9.2 timedelta Objects\nA timedelta object represents a duration, the difference\nbetween two dates or times.\nClass attributes are:\nNote that, because of normalization, `timedelta.max` >\n`-timedelta.min`. `-timedelta.max` is not representable as\na timedelta object.\nInstance attributes (read-only):\nSupported operations:\nNotes:\n(1): This is exact, but may overflow.\n(2): This is exact, and cannot overflow.\n(3): Division by 0 raises ZeroDivisionError.\n(4): -timedelta.max is not representable as a timedelta object.\nIn addition to the operations listed above timedelta objects\nsupport certain additions and subtractions with date and\ndatetime objects (see below).\nComparisons of timedelta objects are supported with the\ntimedelta object representing the smaller duration considered\nto be the smaller timedelta.\nIn order to stop mixed-type comparisons from falling back to the\ndefault comparison by object address, when a timedelta object is\ncompared to an object of a different type, TypeError is\nraised unless the comparison is `==` or `!=`. The latter\ncases return False or True, respectively.\ntimedelta objects are hashable (usable as dictionary keys),\nsupport efficient pickling, and in Boolean contexts, a timedelta\nobject is considered to be true if and only if it isn't equal to\n`timedelta(0)`.", "python_version": "2.3", "length": 1572, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/datetime-timedelta.html"} {"title": "6.9.6 tzinfo Objects", "text": "datetime-time.html | module-datetime.html | node208.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9.5 time Objects (datetime-time.html)\nUp:\n6.9 datetime (module-datetime.html)\nNext:\n6.9.7 strftime() Behavior (node208.html)\n---\n## 6.9.6 tzinfo Objects\ntzinfo is an abstract base clase, meaning that this class\nshould not be instantiated directly. You need to derive a concrete\nsubclass, and (at least) supply implementations of the standard\ntzinfo methods needed by the datetime methods you\nuse. The datetime module does not supply any concrete\nsubclasses of tzinfo.\nAn instance of (a concrete subclass of) tzinfo can be passed\nto the constructors for datetime and time objects.\nThe latter objects view their members as being in local time, and the\ntzinfo object supports methods revealing offset of local time\nfrom UTC, the name of the time zone, and DST offset, all relative to a\ndate or time object passed to them.\nSpecial requirement for pickling: A tzinfo subclass must have an\n__init__ method that can be called with no arguments, else it\ncan be pickled but possibly not unpickled again. This is a technical\nrequirement that may be relaxed in the future.\nA concrete subclass of tzinfo may need to implement the\nfollowing methods. Exactly which methods are needed depends on the\nuses made of aware datetime objects. If in doubt, simply\nimplement all of them.\nThese methods are called by a datetime or time object,\nin response to their methods of the same names. A datetime\nobject passes itself as the argument, and a time object passes\n`None` as the argument. A tzinfo subclass's methods should\ntherefore be prepared to accept a dt argument of `None`, or of\nclass datetime.\nWhen `None` is passed, it's up to the class designer to decide the\nbest response. For example, returning `None` is appropriate if the\nclass wishes to say that time objects don't participate in the\ntzinfo protocols. It may be more useful for `utcoffset(None)`\nto return the standard UTC offset, as there is no other convention for\ndiscovering the standard offset.\nWhen a datetime object is passed in response to a\ndatetime method, `dt.tzinfo` is the same object as\nself. tzinfo methods can rely on this, unless\nuser code calls tzinfo methods directly. The intent is that\nthe tzinfo methods interpret dt as being in local time,\nand not need worry about objects in other timezones.\nThere is one more tzinfo method that a subclass may wish to\noverride:\nExample tzinfo classes:\n```text\nfrom datetime import tzinfo, timedelta, datetime\n\nZERO = timedelta(0)\nHOUR = timedelta(hours=1)\n\n# A UTC class.\n\nclass UTC(tzinfo):\n\"\"\"UTC\"\"\"\n\ndef utcoffset(self, dt):\nreturn ZERO\n\ndef tzname(self, dt):\nreturn \"UTC\"\n\ndef dst(self, dt):\nreturn ZERO\n\nutc = UTC()\n\n# A class building tzinfo objects for fixed-offset time zones.\n# Note that FixedOffset(0, \"UTC\") is a different way to build a\n# UTC tzinfo object.\n\nclass FixedOffset(tzinfo):\n\"\"\"Fixed offset in minutes east from UTC.\"\"\"\n\ndef __init__(self, offset, name):\nself.__offset = timedelta(minutes = offset)\nself.__name = name\n\ndef utcoffset(self, dt):\nreturn self.__offset\n\ndef tzname(self, dt):\nreturn self.__name\n\ndef dst(self, dt):\nreturn ZERO\n\n# A class capturing the platform's idea of local time.\n\nimport time as _time\n\nSTDOFFSET = timedelta(seconds = -_time.timezone)\nif _time.daylight:\nDSTOFFSET = timedelta(seconds = -_time.altzone)\nelse:\nDSTOFFSET = STDOFFSET\n\nDSTDIFF = DSTOFFSET - STDOFFSET\n\nclass LocalTimezone(tzinfo):\n\ndef utcoffset(self, dt):\nif self._isdst(dt):\nreturn DSTOFFSET\nelse:\nreturn STDOFFSET\n\ndef dst(self, dt):\nif self._isdst(dt):\nreturn DSTDIFF\nelse:\nreturn ZERO\n\ndef tzname(self, dt):\nreturn _time.tzname[self._isdst(dt)]\n\ndef _isdst(self, dt):\ntt = (dt.year, dt.month, dt.day,\ndt.hour, dt.minute, dt.second,\ndt.weekday(), 0, -1)\nstamp = _time.mktime(tt)\ntt = _time.localtime(stamp)\nreturn tt.tm_isdst > 0\n\nLocal = LocalTimezone()\n\n# A complete implementation of current DST rules for major US time zones.\n\ndef first_sunday_on_or_after(dt):\ndays_to_go = 6 - dt.weekday()\nif days_to_go:\ndt += timedelta(days_to_go)\nreturn dt\n\n# In the US, DST starts at 2am (standard time) on the first Sunday in April.\nDSTSTART = datetime(1, 4, 1, 2)\n# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct.\n# which is the first Sunday on or after Oct 25.\nDSTEND = datetime(1, 10, 25, 1)\n\nclass USTimeZone(tzinfo):\n\ndef __init__(self, hours, reprname, stdname, dstname):\nself.stdoffset = timedelta(hours=hours)\nself.reprname = reprname\nself.stdname = stdname\nself.dstname = dstname\n\ndef __repr__(self):\nreturn self.reprname\n\ndef tzname(self, dt):\nif self.dst(dt):\nreturn self.dstname\nelse:\nreturn self.stdname\n\ndef utcoffset(self, dt):\nreturn self.stdoffset + self.dst(dt)\n\ndef dst(self, dt):\nif dt is None or dt.tzinfo is None:\n# An exception may be sensible here, in one or both cases.\n# It depends on how you want to treat them. The default\n# fromutc() implementation (called by the default astimezone()\n# implementation) passes a datetime with dt.tzinfo is self.\nreturn ZERO\nassert dt.tzinfo is self\n\n# Find first Sunday in April & the last in October.\nstart = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))\nend = first_sunday_on_or_after(DSTEND.replace(year=dt.year))\n\n# Can't compare naive to aware objects, so strip the timezone from\n# dt first.\nif start <= dt.replace(tzinfo=None) < end:\nreturn HOUR\nelse:\nreturn ZERO\n\nEastern = USTimeZone(-5, \"Eastern\", \"EST\", \"EDT\")\nCentral = USTimeZone(-6, \"Central\", \"CST\", \"CDT\")\nMountain = USTimeZone(-7, \"Mountain\", \"MST\", \"MDT\")\nPacific = USTimeZone(-8, \"Pacific\", \"PST\", \"PDT\")\n```\nDownload as text (original file name: tzinfo-examples.py). (tzinfo-examples.txt)\nNote that there are unavoidable subtleties twice per year in a\ntzinfo\nsubclass accounting for both standard and daylight time, at the DST\ntransition points. For concreteness, consider US Eastern (UTC -0500),\nwhere EDT begins the minute after 1:59 (EST) on the first Sunday in\nApril, and ends the minute after 1:59 (EDT) on the last Sunday in October:\n```text\n\nUTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM\nEST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM\nEDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM\n\nstart 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM\n\nend 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM\n```\nWhen DST starts (the \"start\" line), the local wall clock leaps from 1:59\nto 3:00. A wall time of the form 2:MM doesn't really make sense on that\nday, so `astimezone(Eastern)` won't deliver a result with\n`hour==2` on the\nday DST begins. In order for astimezone() to make this\nguarantee, the rzinfo.dst() method must consider times\nin the \"missing hour\" (2:MM for Eastern) to be in daylight time.\nWhen DST ends (the \"end\" line), there's a potentially worse problem:\nthere's an hour that can't be spelled unambiguously in local wall time:\nthe last hour of daylight time. In Eastern, that's times of\nthe form 5:MM UTC on the day daylight time ends. The local wall clock\nleaps from 1:59 (daylight time) back to 1:00 (standard time) again.\nLocal times of the form 1:MM are ambiguous. astimezone() mimics\nthe local clock's behavior by mapping two adjacent UTC hours into the\nsame local hour then. In the Eastern example, UTC times of the form\n5:MM and 6:MM both map to 1:MM when converted to Eastern. In order for\nastimezone() to make this guarantee, the tzinfo.dst()\nmethod must consider times in the \"repeated hour\" to be in\nstandard time. This is easily arranged, as in the example, by expressing\nDST switch times in the time zone's standard local time.\nApplications that can't bear such ambiguities should avoid using hybrid\ntzinfo subclasses; there are no ambiguities when using UTC, or\nany other fixed-offset tzinfo subclass (such as a class\nrepresenting only EST (fixed offset -5 hours), or only EDT (fixed offset\n-4 hours)).", "python_version": "2.3", "length": 7784, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/datetime-tzinfo.html"} {"title": "7.11.1 Database Objects", "text": "module-dbhash.html | module-dbhash.html | module-whichdb.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.11 dbhash (module-dbhash.html)\nUp:\n7.11 dbhash (module-dbhash.html)\nNext:\n7.12 whichdb (module-whichdb.html)\n---\n## 7.11.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.3", "length": 460, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n9. The Python Debugger (module-pdb.html)\nUp:\n9. The Python Debugger (module-pdb.html)\nNext:\n9.2 How It Works (debugger-hooks.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.\nj(ump) lineno: Set the next line that will be executed. Only available in the\nbottom-most frame. This lets you jump back and execute code\nagain, or jump forward to skip code that you don't want to run.\nIt should be noted that not all jumps are allowed -- for instance it\nis not possible to jump into the middle of a for loop or out\nof a finally clause.\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:\n\"print\" can also be used, but is not a debugger\ncommand -- this executes the Python print statement.\npp expression: Like the \"p\" command, except the value of the exception is\npretty-printed using the pprint module.\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.3", "length": 8042, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n9.1 Debugger Commands (debugger-commands.html)\nUp:\n9. The Python Debugger (module-pdb.html)\nNext:\n10. The Python Profiler (profile.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.3", "length": 2142, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/debugger-hooks.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\nPrevious:\n4.4.3 Differ Objects (differ-objects.html)\nUp:\n4.4 difflib (module-difflib.html)\nNext:\n4.5 fpformat (module-fpformat.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.3", "length": 1762, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.4.2 SequenceMatcher Examples (sequencematcher-examples.html)\nUp:\n4.4 difflib (module-difflib.html)\nNext:\n4.4.4 Differ Example (differ-examples.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.3", "length": 790, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/differ-objects.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\nPrevious:\n6.7 filecmp (module-filecmp.html)\nUp:\n6.7 filecmp (module-filecmp.html)\nNext:\n6.8 popen2 (module-popen2.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.3", "length": 703, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.5 dl (module-dl.html)\nUp:\n8.5 dl (module-dl.html)\nNext:\n8.6 dbm (module-dbm.html)\n---\n## 8.5.1 Dl Objects\nDl objects, as returned by open() above, have the\nfollowing methods:", "python_version": "2.3", "length": 311, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dl-objects.html"} {"title": "11.22.1 DocXMLRPCServer Objects", "text": "module-DocXMLRPCServer.html | module-DocXMLRPCServer.html | node481.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.22 DocXMLRPCServer (module-DocXMLRPCServer.html)\nUp:\n11.22 DocXMLRPCServer (module-DocXMLRPCServer.html)\nNext:\n11.22.2 DocCGIXMLRPCRequestHandler (node481.html)\n---\n## 11.22.1 DocXMLRPCServer Objects\nThe DocXMLRPCServer class is derived from\nSimpleXMLRPCServer.SimpleXMLRPCServer and provides a means of\ncreating self-documenting, stand alone XML-RPC servers. HTTP POST\nrequests are handled as XML-RPC method calls. HTTP GET requests are\nhandled by generating pydoc-style HTML documentation. This allows a\nserver to provide its own web-based documentation.", "python_version": "2.3", "length": 717, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/doc-xmlrpc-servers.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\nPrevious:\n13.6.3.1 Type Mapping (dom-type-mapping.html)\nUp:\n13.6.3 Conformance (dom-conformance.html)\nNext:\n13.7 xml.dom.minidom (module-xml.dom.minidom.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.3", "length": 1491, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-accessor-methods.html"} {"title": "13.6.2.7 Attr Objects", "text": "dom-element-objects.html | node565.html | dom-attributelist-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.6 Element Objects (dom-element-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.8 NamedNodeMap Objects (dom-attributelist-objects.html)\n---\n### 13.6.2.7 Attr Objects\nAttr inherits from Node, so inherits all its\nattributes.", "python_version": "2.3", "length": 406, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-attr-objects.html"} {"title": "13.6.2.8 NamedNodeMap Objects", "text": "dom-attr-objects.html | node565.html | dom-comment-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.7 Attr Objects (dom-attr-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.9 Comment Objects (dom-comment-objects.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.3", "length": 559, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-attributelist-objects.html"} {"title": "13.6.2.9 Comment Objects", "text": "dom-attributelist-objects.html | node565.html | dom-text-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.8 NamedNodeMap Objects (dom-attributelist-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.10 Text and CDATASection (dom-text-objects.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.3", "length": 458, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.6.2.12 Exceptions (dom-exceptions.html)\nUp:\n13.6 xml.dom (module-xml.dom.html)\nNext:\n13.6.3.1 Type Mapping (dom-type-mapping.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.3", "length": 473, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-conformance.html"} {"title": "13.6.2.5 Document Objects", "text": "dom-documenttype-objects.html | node565.html | dom-element-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.4 DocumentType Objects (dom-documenttype-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.6 Element Objects (dom-element-objects.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.3", "length": 531, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-document-objects.html"} {"title": "13.6.2.4 DocumentType Objects", "text": "dom-nodelist-objects.html | node565.html | dom-document-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.3 NodeList Objects (dom-nodelist-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.5 Document Objects (dom-document-objects.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.3", "length": 861, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-documenttype-objects.html"} {"title": "13.6.2.6 Element Objects", "text": "dom-document-objects.html | node565.html | dom-attr-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.5 Document Objects (dom-document-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.7 Attr Objects (dom-attr-objects.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.3", "length": 406, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.7.1 DOM Objects (dom-objects.html)\nUp:\n13.7 xml.dom.minidom (module-xml.dom.minidom.html)\nNext:\n13.7.3 minidom and the (minidom-and-dom.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 (original file name: minidom-example.py). (minidom-example.txt)", "python_version": "2.3", "length": 2012, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-example.html"} {"title": "13.6.2.12 Exceptions", "text": "dom-pi-objects.html | node565.html | dom-conformance.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.11 ProcessingInstruction Objects (dom-pi-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.3 Conformance (dom-conformance.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.3", "length": 1045, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-exceptions.html"} {"title": "13.6.2.1 DOMImplementation Objects", "text": "node565.html | node565.html | dom-node-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2 Objects in the (node565.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.2 Node Objects (dom-node-objects.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.3", "length": 568, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-implementation-objects.html"} {"title": "13.6.2.2 Node Objects", "text": "dom-implementation-objects.html | node565.html | dom-nodelist-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.1 DOMImplementation Objects (dom-implementation-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.3 NodeList Objects (dom-nodelist-objects.html)\n---\n### 13.6.2.2 Node Objects\nAll of the components of an XML document are subclasses of\nNode.", "python_version": "2.3", "length": 424, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-node-objects.html"} {"title": "13.6.2.3 NodeList Objects", "text": "dom-node-objects.html | node565.html | dom-documenttype-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.2 Node Objects (dom-node-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.4 DocumentType Objects (dom-documenttype-objects.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 its 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.3", "length": 1232, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.7 xml.dom.minidom (module-xml.dom.minidom.html)\nUp:\n13.7 xml.dom.minidom (module-xml.dom.minidom.html)\nNext:\n13.7.2 DOM Example (dom-example.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.3", "length": 671, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-objects.html"} {"title": "13.6.2.11 ProcessingInstruction Objects", "text": "dom-text-objects.html | node565.html | dom-exceptions.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.10 Text and CDATASection (dom-text-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.12 Exceptions (dom-exceptions.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.3", "length": 461, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dom-pi-objects.html"} {"title": "13.6.2.10 Text and CDATASection Objects", "text": "dom-comment-objects.html | node565.html | dom-pi-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.2.9 Comment Objects (dom-comment-objects.html)\nUp:\n13.6.2 Objects in the (node565.html)\nNext:\n13.6.2.11 ProcessingInstruction Objects (dom-pi-objects.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 indicate that the\nnode represents a complete CDATA marked section, only that the\ncontent of the node was part of a CDATA section. A single CDATA\nsection may be represented by more than one node in the document\ntree. There is no way to determine whether two adjacent\nCDATASection nodes represent different CDATA marked\nsections.", "python_version": "2.3", "length": 1113, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.6.3 Conformance (dom-conformance.html)\nUp:\n13.6.3 Conformance (dom-conformance.html)\nNext:\n13.6.3.2 Accessor Methods (dom-accessor-methods.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.3", "length": 778, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.8 xml.dom.pulldom (module-xml.dom.pulldom.html)\nUp:\n13.8 xml.dom.pulldom (module-xml.dom.pulldom.html)\nNext:\n13.9 xml.sax (module-xml.sax.html)\n---\n## 13.8.1 DOMEventStream Objects", "python_version": "2.3", "length": 348, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.10.1 ContentHandler Objects (content-handler-objects.html)\nUp:\n13.10 xml.sax.handler (module-xml.sax.handler.html)\nNext:\n13.10.3 EntityResolver Objects (entity-resolver-objects.html)\n---\n## 13.10.2 DTDHandler Objects\nDTDHandler instances provide the following methods:", "python_version": "2.3", "length": 446, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dtd-handler-objects.html"} {"title": "7.14.1 Dumbdbm Objects", "text": "module-dumbdbm.html | module-dumbdbm.html | module-zlib.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.14 dumbdbm (module-dumbdbm.html)\nUp:\n7.14 dumbdbm (module-dumbdbm.html)\nNext:\n7.15 zlib (module-zlib.html)\n---\n## 7.14.1 Dumbdbm Objects\nIn addition to the methods provided by the UserDict.DictMixin class,\ndumbdbm objects provide the following methods.", "python_version": "2.3", "length": 400, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/dumbdbm-objects.html"} {"title": "6.26.2 For extension writers and programs that embed Python", "text": "node264.html | module-locale.html | locale-gettext.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.26.1 Background, details, hints, (node264.html)\nUp:\n6.26 locale (module-locale.html)\nNext:\n6.26.3 Access to message (locale-gettext.html)\n---\n## 6.26.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.\nWhen Python code uses the locale module to change the locale,\nthis also affects the embedding application. If the embedding\napplication doesn't want this to happen, it should remove the\n_locale extension module (which does all the work) from the\ntable of built-in modules in the config.c file, and make sure\nthat the _locale module is not accessible as a shared library.", "python_version": "2.3", "length": 1962, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.10.2 DTDHandler Objects (dtd-handler-objects.html)\nUp:\n13.10 xml.sax.handler (module-xml.sax.handler.html)\nNext:\n13.10.4 ErrorHandler Objects (sax-error-handler.html)\n---\n## 13.10.3 EntityResolver Objects", "python_version": "2.3", "length": 372, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.4.1 Semaphore Example (semaphore-examples.html)\nUp:\n7.5 threading (module-threading.html)\nNext:\n7.5.6 Thread Objects (thread-objects.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 other threads wait 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()\nmethod. The wait() method blocks until the flag is true.", "python_version": "2.3", "length": 637, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/event-objects.html"} {"title": "3.21.1 Examples", "text": "module-imp.html | module-imp.html | module-pkgutil.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.21 imp (module-imp.html)\nUp:\n3.21 imp (module-imp.html)\nNext:\n3.22 pkgutil (module-pkgutil.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.3", "length": 1042, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.5.3 Example (expat-example.html)\nUp:\n13.5 xml.parsers.expat (module-xml.parsers.expat.html)\nNext:\n13.5.5 Expat error constants (expat-errors.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.3", "length": 844, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.5.4 Content Model Descriptions (expat-content-models.html)\nUp:\n13.5 xml.parsers.expat (module-xml.parsers.expat.html)\nNext:\n13.6 xml.dom (module-xml.dom.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.3", "length": 674, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.5.2 ExpatError Exceptions (expaterror-objects.html)\nUp:\n13.5 xml.parsers.expat (module-xml.parsers.expat.html)\nNext:\n13.5.4 Content Model Descriptions (expat-content-models.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\"\"\", 1)\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.3", "length": 1310, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.5.1 XMLParser Objects (xmlparser-objects.html)\nUp:\n13.5 xml.parsers.expat (module-xml.parsers.expat.html)\nNext:\n13.5.3 Example (expat-example.html)\n---\n## 13.5.2 ExpatError Exceptions\nExpatError exceptions have a number of interesting\nattributes:", "python_version": "2.3", "length": 410, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.20.4 Binary Objects (binary-objects.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.20.6 ProtocolError Objects (protocol-error-objects.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.3", "length": 449, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.14 HTTPSHandler Objects (https-handler-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.16 FTPHandler Objects (ftp-handler-objects.html)\n---\n## 11.5.15 FileHandler Objects", "python_version": "2.3", "length": 352, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/file-handler-objects.html"} {"title": "20.4.2 Form Objects", "text": "node720.html | module-fl.html | forms-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n20.4.1 Functions Defined in (node720.html)\nUp:\n20.4 fl (module-fl.html)\nNext:\n20.4.3 FORMS Objects (forms-objects.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.3", "length": 847, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.1.1 The Formatter Interface (formatter-interface.html)\nUp:\n12.1 formatter (module-formatter.html)\nNext:\n12.1.3 The Writer Interface (writer-interface.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.3", "length": 510, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.1 formatter (module-formatter.html)\nUp:\n12.1 formatter (module-formatter.html)\nNext:\n12.1.2 Formatter Implementations (formatter-impls.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.3", "length": 662, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.4.2 Form Objects (form-objects.html)\nUp:\n20.4 fl (module-fl.html)\nNext:\n20.5 FL (module-fl-constants.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.3", "length": 469, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/forms-objects.html"} {"title": "3.4.1 Example", "text": "module-fpectl.html | module-fpectl.html | node43.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.4 fpectl (module-fpectl.html)\nUp:\n3.4 fpectl (module-fpectl.html)\nNext:\n3.4.2 Limitations and other (node43.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.3", "length": 720, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/fpectl-example.html"} {"title": "Front Matter", "text": "lib.html | lib.html | contents.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nPython Library Reference (lib.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n---\n# Front Matter\nCopyright © 2001, 2002, 2003 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.3", "length": 2313, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.15 FileHandler Objects (file-handler-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.17 CacheFTPHandler Objects (cacheftp-handler-objects.html)\n---\n## 11.5.16 FTPHandler Objects", "python_version": "2.3", "length": 363, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.7 ftplib (module-ftplib.html)\nUp:\n11.7 ftplib (module-ftplib.html)\nNext:\n11.8 gopherlib (module-gopherlib.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.3", "length": 558, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/ftp-objects.html"} {"title": "Index", "text": "modindex.html | lib.html | about.html | Python Library Reference | contents.html | modindex.html\nPrevious:\nModule Index (modindex.html)\nUp:\nPython Library Reference (lib.html)\nNext:\nAbout this document ... (about.html)\n---\n## Index\n---\nSymbols (#letter-Symbols) |\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## Symbols\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.3", "length": 964, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.17 CacheFTPHandler Objects (cacheftp-handler-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.19 UnknownHandler Objects (unknown-handler-objects.html)\n---\n## 11.5.18 GopherHandler Objects", "python_version": "2.3", "length": 375, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n22.2 _winreg - Windows (module--winreg.html)\nUp:\n22.2 _winreg - Windows (module--winreg.html)\nNext:\n22.3 winsound (module-winsound.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.3", "length": 1335, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/handle-object.html"} {"title": "10.9.3 Example Usage", "text": "module-hotshot.stats.html | module-hotshot.html | module-timeit.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.9.2 Using hotshot data (module-hotshot.stats.html)\nUp:\n10.9 hotshot (module-hotshot.html)\nNext:\n10.10 timeit (module-timeit.html)\n---\n## 10.9.3 Example Usage\nNote that this example runs the python ``benchmark'' pystones. It can\ntake some time to run, and will produce large output files.", "python_version": "2.3", "length": 444, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/hotshot-example.html"} {"title": "10.9.1 Profile Objects", "text": "module-hotshot.html | module-hotshot.html | module-hotshot.stats.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.9 hotshot (module-hotshot.html)\nUp:\n10.9 hotshot (module-hotshot.html)\nNext:\n10.9.2 Using hotshot data (module-hotshot.stats.html)\n---\n## 10.9.1 Profile Objects\nProfile objects have the following methods:", "python_version": "2.3", "length": 362, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/hotshot-objects.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\nPrevious:\n13.3 htmllib (module-htmllib.html)\nUp:\n13.3 htmllib (module-htmllib.html)\nNext:\n13.4 htmlentitydefs (module-htmlentitydefs.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.3", "length": 450, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/html-parser-objects.html"} {"title": "13.1.1 Example HTML Parser Application", "text": "module-HTMLParser.html | module-HTMLParser.html | module-sgmllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.1 HTMLParser (module-HTMLParser.html)\nUp:\n13.1 HTMLParser (module-HTMLParser.html)\nNext:\n13.2 sgmllib (module-sgmllib.html)\n---\n## 13.1.1 Example HTML Parser Application\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.3", "length": 455, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.7 AbstractBasicAuthHandler Objects (abstract-basic-auth-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.9 ProxyBasicAuthHandler Objects (proxy-basic-auth-handler.html)\n---\n## 11.5.8 HTTPBasicAuthHandler Objects", "python_version": "2.3", "length": 403, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.10 AbstractDigestAuthHandler Objects (abstract-digest-auth-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.12 ProxyDigestAuthHandler Objects (proxy-digest-auth-handler.html)\n---\n## 11.5.11 HTTPDigestAuthHandler Objects", "python_version": "2.3", "length": 413, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.12 ProxyDigestAuthHandler Objects (proxy-digest-auth-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.14 HTTPSHandler Objects (https-handler-objects.html)\n---\n## 11.5.13 HTTPHandler Objects", "python_version": "2.3", "length": 376, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.5 ProxyHandler Objects (proxy-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.7 AbstractBasicAuthHandler Objects (abstract-basic-auth-handler.html)\n---\n## 11.5.6 HTTPPasswordMgr Objects\nThese methods are available on HTTPPasswordMgr and\nHTTPPasswordMgrWithDefaultRealm objects.", "python_version": "2.3", "length": 459, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.3 BaseHandler Objects (base-handler-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.5 ProxyHandler Objects (proxy-handler.html)\n---\n## 11.5.4 HTTPRedirectHandler Objects\nNote:\nSome HTTP redirections require action from this module's client\ncode. If this is the case, HTTPError is raised. See\nRFC 2616 (http://www.faqs.org/rfcs/rfc2616.html) for details of the precise meanings of the various\nredirection codes.", "python_version": "2.3", "length": 585, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.6 httplib (module-httplib.html)\nUp:\n11.6 httplib (module-httplib.html)\nNext:\n11.6.2 HTTPResponse Objects (httpresponse-objects.html)\n---\n## 11.6.1 HTTPConnection Objects\nHTTPConnection instances have the following methods:", "python_version": "2.3", "length": 380, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.6.2 HTTPResponse Objects (httpresponse-objects.html)\nUp:\n11.6 httplib (module-httplib.html)\nNext:\n11.7 ftplib (module-ftplib.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.3", "length": 790, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.6.1 HTTPConnection Objects (httpconnection-objects.html)\nUp:\n11.6 httplib (module-httplib.html)\nNext:\n11.6.3 Examples (httplib-examples.html)\n---\n## 11.6.2 HTTPResponse Objects\nHTTPResponse instances have the following methods and attributes:", "python_version": "2.3", "length": 404, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.13 HTTPHandler Objects (http-handler-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.15 FileHandler Objects (file-handler-objects.html)\n---\n## 11.5.14 HTTPSHandler Objects", "python_version": "2.3", "length": 353, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/https-handler-objects.html"} {"title": "16.5 Idle", "text": "pen-rawpen-objects.html | tkinter.html | node663.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.4.1 Pen and RawPen (pen-rawpen-objects.html)\nUp:\n16. Graphical User Interfaces (tkinter.html)\nNext:\n16.5.1 Menus (node663.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.3", "length": 825, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.10.1 IMAP4 Objects (imap4-objects.html)\nUp:\n11.10 imaplib (module-imaplib.html)\nNext:\n11.11 nntplib (module-nntplib.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.3", "length": 412, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.10 imaplib (module-imaplib.html)\nUp:\n11.10 imaplib (module-imaplib.html)\nNext:\n11.10.2 IMAP4 Example (imap4-example.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. Each data\nis either a string, or a tuple. If a tuple, then the first part\nis the header of the response, and the second part contains\nthe data (ie: 'literal' value).\nAn IMAP4 instance has the following methods:\nInstances of IMAP4_SSL have just one additional method:\nThe following attributes are defined on instances of IMAP4:", "python_version": "2.3", "length": 1446, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/imap4-objects.html"} {"title": "5.12.3 Protocol for automatic conversion to immutable", "text": "set-example.html | module-sets.html | module-itertools.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.12.2 Example (set-example.html)\nUp:\n5.12 sets (module-sets.html)\nNext:\n5.13 itertools (module-itertools.html)\n---\n## 5.12.3 Protocol for automatic conversion to immutable\nSets can only contain immutable elements. For convenience, mutable\nSet objects are automatically copied to an ImmutableSet\nbefore being added as a set element.\nThe mechanism is to always add a hashable element, or if it is not\nhashable, the element is checked to see if it has an\n__as_immutable__() method which returns an immutable equivalent.\nSince Set objects have a __as_immutable__() method\nreturning an instance of ImmutableSet, it is possible to\nconstruct sets of sets.\nA similar mechanism is needed by the __contains__() and\nremove() methods which need to hash an element to check\nfor membership in a set. Those methods check an element for hashability\nand, if not, check for a __as_temporarily_immutable__() method\nwhich returns the element wrapped by a class that provides temporary\nmethods for __hash__(), __eq__(), and __ne__().\nThe alternate mechanism spares the need to build a separate copy of\nthe original mutable object.\nSet objects implement the __as_temporarily_immutable__()\nmethod which returns the Set object wrapped by a new class\n_TemporarilyImmutableSet.", "python_version": "2.3", "length": 1397, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/immutable-transforms.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\nPrevious:\n13.12.1 XMLReader Objects (xmlreader-objects.html)\nUp:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)\nNext:\n13.12.3 Locator Objects (locator-objects.html)\n---\n## 13.12.2 IncrementalParser Objects\nInstances of IncrementalParser offer the following additional\nmethods:", "python_version": "2.3", "length": 438, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/incremental-parser-objects.html"} {"title": "Python Library Reference", "text": "../index.html | front.html | Python Library Reference | contents.html | modindex.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Python Library Reference\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 322, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/index.html"} {"title": "13.12.4 InputSource Objects", "text": "locator-objects.html | module-xml.sax.xmlreader.html | attributes-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.12.3 Locator Objects (locator-objects.html)\nUp:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)\nNext:\n13.12.5 The Attributes Interface (attributes-objects.html)\n---\n## 13.12.4 InputSource Objects", "python_version": "2.3", "length": 370, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.11.2 Retrieving source code (inspect-source.html)\nUp:\n3.11 inspect (module-inspect.html)\nNext:\n3.11.4 The interpreter stack (inspect-stack.html)\n---\n## 3.11.3 Classes and functions", "python_version": "2.3", "length": 330, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.11.1 Types and members (inspect-types.html)\nUp:\n3.11 inspect (module-inspect.html)\nNext:\n3.11.3 Classes and functions (inspect-classes-functions.html)\n---\n## 3.11.2 Retrieving source code", "python_version": "2.3", "length": 348, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.11.3 Classes and functions (inspect-classes-functions.html)\nUp:\n3.11 inspect (module-inspect.html)\nNext:\n3.12 traceback (module-traceback.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.\nStackframes stored directly or indirectly in local variables can\neasily cause reference cycles. Though the cycle detector will catch\nthese, destruction of the frames (and local variables) can be made\ndeterministic by removing the cycle in a finally clause.\nThis is also important if the cycle detector was disabled when Python\nwas compiled or using gc.disable(). For example:", "python_version": "2.3", "length": 1679, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.11 inspect (module-inspect.html)\nUp:\n3.11 inspect (module-inspect.html)\nNext:\n3.11.2 Retrieving source code (inspect-source.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.3", "length": 719, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/inspect-types.html"} {"title": "11. Internet Protocols and Support", "text": "node397.html | lib.html | module-webbrowser.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.10.2 Examples (node397.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n11.1 webbrowser (module-webbrowser.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.3", "length": 612, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/internet.html"} {"title": "3.23.1 Interactive Interpreter Objects", "text": "module-code.html | module-code.html | console-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.23 code (module-code.html)\nUp:\n3.23 code (module-code.html)\nNext:\n3.23.2 Interactive Console Objects (console-objects.html)\n---\n## 3.23.1 Interactive Interpreter Objects", "python_version": "2.3", "length": 315, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/interpreter-objects.html"} {"title": "1. Introduction", "text": "contents.html | lib.html | builtin.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nUp:\nPython Library Reference (lib.html)\nNext:\n2. Built-In Objects (builtin.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.3", "length": 3008, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/intro.html"} {"title": "5.13.2 Examples", "text": "itertools-functions.html | module-itertools.html | module-ConfigParser.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.13.1 Itertool functions (itertools-functions.html)\nUp:\n5.13 itertools (module-itertools.html)\nNext:\n5.14 ConfigParser (module-ConfigParser.html)\n---\n## 5.13.2 Examples\nThe following examples show common uses for each tool and\ndemonstrate ways they can be combined.\n```text\n\n>>> amounts = [120.15, 764.05, 823.14]\n>>> for checknum, amount in izip(count(1200), amounts):\n... print 'Check %d is for $%.2f' % (checknum, amount)\n...\nCheck 1200 is for $120.15\nCheck 1201 is for $764.05\nCheck 1202 is for $823.14\n\n>>> import operator\n>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):\n... print cube\n...\n1\n8\n27\n\n>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',\n'', 'martin', '', 'walter', '', 'samuele']\n>>> for name in islice(reportlines, 3, None, 2):\n... print name.title()\n...\nAlex\nLaura\nMartin\nWalter\nSamuele\n```\nThis section has further examples of how itertools can be combined.\nNote that enumerate() and iteritems() already\nhave highly efficient implementations in Python. They are only\nincluded here to illustrate how higher level tools can be created\nfrom building blocks.", "python_version": "2.3", "length": 1265, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/itertools-example.html"} {"title": "5.13.1 Itertool functions", "text": "module-itertools.html | module-itertools.html | itertools-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.13 itertools (module-itertools.html)\nUp:\n5.13 itertools (module-itertools.html)\nNext:\n5.13.2 Examples (itertools-example.html)\n---\n## 5.13.1 Itertool functions\nThe following module functions all construct and return iterators.\nSome provide streams of infinite length, so they should only be accessed\nby functions or loops that truncate the stream.", "python_version": "2.3", "length": 505, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/itertools-functions.html"} {"title": "18. Python Language Services", "text": "module-Bastion.html | lib.html | module-parser.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n17.2 Bastion (module-Bastion.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n18.1 parser (module-parser.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.3", "length": 502, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/language.html"} {"title": "5.3.3 Re-using old test code", "text": "organizing-tests.html | module-unittest.html | unittest-contents.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.2 Organizing test code (organizing-tests.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.4 Classes and functions (unittest-contents.html)\n---\n## 5.3.3 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.3", "length": 1378, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/legacy-unit-tests.html"} {"title": "Python Library Reference", "text": "../index.html | front.html | Python Library Reference | contents.html | modindex.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Python Library Reference\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 322, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/lib.html"} {"title": "6.26.3 Access to message catalogs", "text": "embedding-locale.html | module-locale.html | module-gettext.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.26.2 For extension writers (embedding-locale.html)\nUp:\n6.26 locale (module-locale.html)\nNext:\n6.27 gettext (module-gettext.html)\n---\n## 6.26.3 Access to message catalogs\nThe locale module exposes the C library's gettext interface on systems\nthat provide this interface. It consists of the functions\ngettext(), dgettext(), dcgettext(),\ntextdomain(), and bindtextdomain(). These are\nsimilar to the same functions in the gettext (module-gettext.html) module, but use\nthe C library's binary format for message catalogs, and the C\nlibrary's search algorithms for locating message catalogs.", "python_version": "2.3", "length": 736, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/locale-gettext.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\nPrevious:\n13.12.2 IncrementalParser Objects (incremental-parser-objects.html)\nUp:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)\nNext:\n13.12.4 InputSource Objects (input-source-objects.html)\n---\n## 13.12.3 Locator Objects\nInstances of Locator provide these methods:", "python_version": "2.3", "length": 441, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5 threading (module-threading.html)\nUp:\n7.5 threading (module-threading.html)\nNext:\n7.5.2 RLock Objects (rlock-objects.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.3", "length": 1402, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.4 mailbox (module-mailbox.html)\nUp:\n12.4 mailbox (module-mailbox.html)\nNext:\n12.5 mhlib (module-mhlib.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.3", "length": 481, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/mailbox-objects.html"} {"title": "13. Structured Markup Processing Tools", "text": "node549.html | lib.html | module-HTMLParser.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.20.5 Examples (node549.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n13.1 HTMLParser (module-HTMLParser.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).\nIt is important to note that modules in the xml package\nrequire that there be at least one SAX-compliant XML parser available.\nStarting with Python 2.3, the Expat parser is included with Python, so\nthe xml.parsers.expat (module-xml.parsers.expat.html) module will always be available.\nYou may still want to be aware of the PyXML add-on\npackage (http://pyxml.sourceforge.net/); that package provides an\nextended set of XML libraries for Python.\nThe documentation for the xml.dom and xml.sax\npackages are the definition of the Python bindings for the DOM and SAX\ninterfaces.\nHTMLParser (module-HTMLParser.html) | A simple parser that can handle HTML and XHTML.\nsgmllib (module-sgmllib.html) | Only as much of an SGML parser as needed to parse HTML.\nhtmllib (module-htmllib.html) | A parser for HTML documents.\nhtmlentitydefs (module-htmlentitydefs.html) | Definitions of HTML general entities.\nxml.parsers.expat (module-xml.parsers.expat.html) | An interface to the Expat non-validating XML parser.\nxml.dom (module-xml.dom.html) | Document Object Model API for Python.\nxml.dom.minidom (module-xml.dom.minidom.html) | Lightweight Document Object Model (DOM) implementation.\nxml.dom.pulldom (module-xml.dom.pulldom.html) | Support for building partial DOM trees from SAX events.\nxml.sax (module-xml.sax.html) | Package containing SAX2 base classes and convenience\nfunctions.\nxml.sax.handler (module-xml.sax.handler.html) | Base classes for SAX event handlers.\nxml.sax.saxutils (module-xml.sax.saxutils.html) | Convenience functions and classes for use with SAX.\nxml.sax.xmlreader (module-xml.sax.xmlreader.html) | Interface which SAX-compliant XML parsers must implement.\nxmllib (module-xmllib.html) | A parser for XML documents.", "python_version": "2.3", "length": 2317, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/markup.html"} {"title": "4.2.5 Match Objects", "text": "re-objects.html | module-re.html | node108.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.2.4 Regular Expression Objects (re-objects.html)\nUp:\n4.2 re (module-re.html)\nNext:\n4.2.6 Examples (node108.html)\n---\n## 4.2.5 Match Objects\nMatchObject instances support the following methods and\nattributes:", "python_version": "2.3", "length": 342, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/match-objects.html"} {"title": "4.2.2 Matching vs Searching", "text": "re-syntax.html | module-re.html | node105.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.2.1 Regular Expression Syntax (re-syntax.html)\nUp:\n4.2 re (module-re.html)\nNext:\n4.2.3 Module Contents (node105.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 \"^\":\n\"^\" 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.3", "length": 1261, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.11 rfc822 (module-rfc822.html)\nUp:\n12.11 rfc822 (module-rfc822.html)\nNext:\n12.11.2 AddressList Objects (addresslist-objects.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 [ , default ] )`,\n`m .has_key( name )`, `m .keys()`,\n`m .values()` `m .items()`, and\n`m .setdefault( name [ , default ] )` act as\nexpected, with the one difference that setdefault() uses\nan 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.3", "length": 1124, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.5.1 MH Objects (mh-objects.html)\nUp:\n12.5 mhlib (module-mhlib.html)\nNext:\n12.5.3 Message Objects (mh-message-objects.html)\n---\n## 12.5.2 Folder Objects\nFolder instances represent open folders and have the following\nmethods:", "python_version": "2.3", "length": 373, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.5.2 Folder Objects (mh-folder-objects.html)\nUp:\n12.5 mhlib (module-mhlib.html)\nNext:\n12.6 mimetools (module-mimetools.html)\n---\n## 12.5.3 Message Objects\nThe Message class adds one method to those of\nmimetools.Message:", "python_version": "2.3", "length": 373, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.5 mhlib (module-mhlib.html)\nUp:\n12.5 mhlib (module-mhlib.html)\nNext:\n12.5.2 Folder Objects (mh-folder-objects.html)\n---\n## 12.5.1 MH Objects\nMH instances have the following methods:", "python_version": "2.3", "length": 332, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.6 mimetools (module-mimetools.html)\nUp:\n12.6 mimetools (module-mimetools.html)\nNext:\n12.7 mimetypes (module-mimetypes.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.3", "length": 424, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.7 mimetypes (module-mimetypes.html)\nUp:\n12.7 mimetypes (module-mimetypes.html)\nNext:\n12.8 MimeWriter (module-MimeWriter.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.3", "length": 430, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.8 MimeWriter (module-MimeWriter.html)\nUp:\n12.8 MimeWriter (module-MimeWriter.html)\nNext:\n12.9 mimify (module-mimify.html)\n---\n## 12.8.1 MimeWriter Objects\nMimeWriter instances have the following methods:", "python_version": "2.3", "length": 360, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.7.2 DOM Example (dom-example.html)\nUp:\n13.7 xml.dom.minidom (module-xml.dom.minidom.html)\nNext:\n13.8 xml.dom.pulldom (module-xml.dom.pulldom.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.3", "length": 2772, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/minidom-and-dom.html"} {"title": "5.3.1 Minimal example", "text": "module-unittest.html | module-unittest.html | organizing-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3 unittest (module-unittest.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.2 Organizing test code (organizing-tests.html)\n---\n## 5.3.1 Minimal example\nThe unittest module provides a rich set of tools for\nconstructing and running tests. This section demonstrates that a\nsmall subset of the tools suffice to meet the needs of most users.\nHere is a short script to test three functions from the\nrandom (module-random.html) module:\n```text\n\nimport random\nimport unittest\n\nclass TestSequenceFunctions(unittest.TestCase):\n\ndef setUp(self):\nself.seq = range(10)\n\ndef testshuffle(self):\n# make sure the shuffled sequence does not lose any elements\nrandom.shuffle(self.seq)\nself.seq.sort()\nself.assertEqual(self.seq, range(10))\n\ndef testchoice(self):\nelement = random.choice(self.seq)\nself.assert_(element in self.seq)\n\ndef testsample(self):\nself.assertRaises(ValueError, random.sample, self.seq, 20)\nfor element in random.sample(self.seq, 5):\nself.assert_(element in self.seq)\n\nif __name__ == '__main__':\nunittest.main()\n```\nA testcase is created by subclassing `unittest.TestCase`.\nThe three individual tests are defined with methods whose names start with\nthe letters `test`. This naming convention informs the test runner\nabout which methods represent tests.\nThe crux of each test is a call to assertEqual() to\ncheck for an expected result; assert_() to verify a condition;\nor assertRaises() to verify that an expected exception gets\nraised. These methods are used instead of the assert statement\nso the test runner can accumulate all test results and produce a report.\nWhen a setUp() method is defined, the test runner will run that\nmethod prior to each test. Likewise, if a tearDown() method is\ndefined, the test runner will invoke that method after each test. In the\nexample, setUp() was used to create a fresh sequence for each test.\nThe final block shows a simple way to run the tests. `unittest.main()`\nprovides a command line interface to the test script. When run from the\ncommand line, the above script produces an output that looks like this:\n```text\n\n...\n----------------------------------------------------------------------\nRan 3 tests in 0.000s\n\nOK\n```\nInstead of `unittest.main()`, there are other ways to run the tests\nwith a finer level of control, less terse output, and no requirement to be\nrun from the command line. For example, the last two lines may be replaced\nwith:\n```text\n\nsuite = unittest.TestSuite()\nsuite.addTest(unittest.makeSuite(TestSequenceFunctions))\nunittest.TextTestRunner(verbosity=2).run(suite)\n```\nRunning the revised script from the interpreter or another script\nproduces the following output:\n```text\n\ntestchoice (__main__.TestSequenceFunctions) ... ok\ntestsample (__main__.TestSequenceFunctions) ... ok\ntestshuffle (__main__.TestSequenceFunctions) ... ok\n\n----------------------------------------------------------------------\nRan 3 tests in 0.110s\n\nOK\n```\nThe above examples show the most commonly used unittest features\nwhich are sufficient to meet many everyday testing needs. The remainder\nof the documentation explores the full feature set from first principles.", "python_version": "2.3", "length": 3269, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/minimal-example.html"} {"title": "5. Miscellaneous Services", "text": "module-stringprep.html | lib.html | module-pydoc.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.11 stringprep (module-stringprep.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n5.1 pydoc (module-pydoc.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.3", "length": 419, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/misc.html"} {"title": "14.11.2 Mixer Device Objects", "text": "ossaudio-device-objects.html | module-ossaudiodev.html | crypto.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n14.11.1 Audio Device Objects (ossaudio-device-objects.html)\nUp:\n14.11 ossaudiodev (module-ossaudiodev.html)\nNext:\n15. Cryptographic Services (crypto.html)\n---\n## 14.11.2 Mixer Device Objects\nFile-like interface\nMixer interface", "python_version": "2.3", "length": 380, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/mixer-device-objects.html"} {"title": "14. Multimedia Services", "text": "xml-namespace.html | lib.html | module-audioop.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.13.1 XML Namespaces (xml-namespace.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n14.1 audioop (module-audioop.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.3", "length": 502, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/mmedia.html"} {"title": "Module Index", "text": "node753.html | lib.html | genindex.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nC.2 Terms and conditions (node753.html)\nUp:\nPython Library Reference (lib.html)\nNext:\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.3", "length": 488, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/modindex.html"} {"title": "22.2 _winreg - Windows registry access", "text": "msvcrt-other.html | node735.html | handle-object.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n22.1.3 Other Functions (msvcrt-other.html)\nUp:\n22. MS Windows Specific (node735.html)\nNext:\n22.2.1 Registry Handle Objects (handle-object.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.3", "length": 855, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.2 imageop (module-imageop.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.4 sunau (module-sunau.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.3", "length": 1950, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.1.2 Port Objects (al-port-objects.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.3 cd (module-cd.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.3", "length": 617, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20. SGI IRIX Specific (sgi.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.1.1 Configuration Objects (al-config-objects.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.3", "length": 1413, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-al.html"} {"title": "7.10 anydbm -- Generic access to DBM-style databases", "text": "module-mmap.html | someos.html | module-dbhash.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.9 mmap (module-mmap.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.11 dbhash (module-dbhash.html)\n---\n# 7.10 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.", "python_version": "2.3", "length": 871, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-anydbm.html"} {"title": "5.11 array -- Efficient arrays of numeric values", "text": "node162.html | misc.html | module-sets.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.10.1 Theory (node162.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.12 sets (module-sets.html)\n---\n# 5.11 array --\nEfficient arrays of numeric values\nThis module defines an 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 type:\nArray objects support the ordinary sequence operations of\nindexing, slicing, concatenation, and multiplication. When using\nslice assignment, the assigned value must be an array object with the\nsame type code; in all other cases, TypeError is raised.\nArray objects also implement the buffer interface, and may be used\nwherever buffer objects are supported.\nThe following data items and methods are also supported:\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('u', u'hello \\textbackslash u2641')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.14])\n```", "python_version": "2.3", "length": 2148, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-array.html"} {"title": "11.24 asynchat -- Asynchronous socket command/response handler", "text": "asyncore-example.html | internet.html | node485.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.23.1 asyncore Example basic (asyncore-example.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.24.1 asynchat - Auxiliary (node485.html)\n---\n# 11.24 asynchat --\nAsynchronous socket command/response handler\nThis module builds on the asyncore (module-asyncore.html) infrastructure,\nsimplifying asynchronous clients and servers and making it easier to\nhandle protocols whose elements are terminated by arbitrary strings, or\nare of variable length. asynchat (module-asynchat.html) defines the abstract class\nasync_chat that you subclass, providing implementations of the\ncollect_incoming_data() and found_terminator()\nmethods. It uses the same asynchronous loop as asyncore (module-asyncore.html), and\nthe two types of channel, asyncore.dispatcher and\nasynchat.async_chat, can freely be mixed in the channel map.\nTypically an asyncore.dispatcher server channel generates new\nasynchat.async_chat channel objects as it receives incoming\nconnection requests.", "python_version": "2.3", "length": 1104, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-asynchat.html"} {"title": "11.23 asyncore -- Asynchronous socket handler", "text": "node481.html | internet.html | asyncore-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.22.2 DocCGIXMLRPCRequestHandler (node481.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.23.1 asyncore Example basic (asyncore-example.html)\n---\n# 11.23 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 asyncore module solves many of the difficult problems for\nyou, making the task of building sophisticated high-performance\nnetwork servers and clients a snap. For ``conversational'' applications\nand protocols the companion asynchat (module-asynchat.html) module is invaluable.\nThe basic idea behind both modules is to create one or more network\nchannels, instances of class asyncore.dispatcher and\nasynchat.async_chat. Creating the channels adds them to a global\nmap, used by the loop() function if you do not provide it\nwith your own map.\nOnce the initial channel(s) is(are) created, calling the loop()\nfunction activates channel service, which continues until the last\nchannel (including any that have been added to the map during asynchronous\nservice) is closed.\nThus, the set of channel events is larger than the basic socket events.\nThe full set of methods that can be overridden in your subclass follows:\nIn addition, each channel delegates or extends many of the socket methods.\nMost of these are nearly identical to their socket partners.", "python_version": "2.3", "length": 2457, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-asyncore.html"} {"title": "3.5 atexit -- Exit handlers", "text": "node43.html | python.html | atexit-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.4.2 Limitations and other (node43.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.5.1 atexit Example (atexit-example.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.3", "length": 1193, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14. Multimedia Services (mmedia.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.2 imageop (module-imageop.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.3", "length": 2626, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.11.2 AddressList Objects (addresslist-objects.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.13 binascii (module-binascii.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.3", "length": 1032, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.15 SocketServer (module-SocketServer.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.17 SimpleHTTPServer (module-SimpleHTTPServer.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.3", "length": 1212, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-BaseHTTPServer.html"} {"title": "17.2 Bastion -- Restricting access to objects", "text": "node678.html | restricted.html | language.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n17.1.3 An example (node678.html)\nUp:\n17. Restricted Execution (restricted.html)\nNext:\n18. Python Language Services (language.html)\n---\n# 17.2 Bastion --\nRestricting access to objects\nChanged in version 2.3:\nDisabled module.\nWarning:\nThe documentation has been left in place to help in reading old code\nthat uses the module.\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.3", "length": 900, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.12 base64 (module-base64.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.14 binhex (module-binhex.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.3", "length": 728, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.13 binascii (module-binascii.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.14.1 Notes (binhex-notes.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:\nThe following exception is also defined:\nSee Also:", "python_version": "2.3", "length": 681, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-binhex.html"} {"title": "5.9 bisect -- Array bisection algorithm", "text": "module-whrandom.html | misc.html | bisect-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.8 whrandom (module-whrandom.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.9.1 Examples (bisect-example.html)\n---\n# 5.9 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.3", "length": 793, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-bisect.html"} {"title": "7.13 bsddb -- Interface to Berkeley DB library", "text": "module-whichdb.html | someos.html | bsddb-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.12 whichdb (module-whichdb.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.13.1 Hash, BTree and (bsddb-objects.html)\n---\n# 7.13 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.\nStarting with Python 2.3 the bsddb module requires the\nBerkeley DB library version 3.1 or later (it is known to work with 3.1\nthru 4.1 at the time of this writing).\nSee Also:\nThe following is a description of the legacy bsddb interface\ncompatible with the old python bsddb module. For details about the more\nmodern Db and DbEnv object oriented interface see the above mentioned\npybsddb URL.\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:\nNote:\nBeginning in 2.3 some Unix versions of Python may have a bsddb185\nmodule. This is present only to allow backwards compatibility with\nsystems which ship with the old Berkeley DB 1.85 database library. The\nbsddb185 module should never be used directly in new code.", "python_version": "2.3", "length": 1692, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-bsddb.html"} {"title": "3.30 __builtin__ -- Built-in functions", "text": "module-user.html | python.html | module-main.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.29 user (module-user.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.31 __main__ (module-main.html)\n---\n# 3.30 __builtin__ --\nBuilt-in functions", "python_version": "2.3", "length": 292, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-builtin.html"} {"title": "7.17 bz2 -- Compression compatible with bzip2", "text": "module-gzip.html | someos.html | node337.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.16 gzip (module-gzip.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.17.1 (De)compression of files (node337.html)\n---\n# 7.17 bz2 --\nCompression compatible with bzip2\nNew in version 2.3.\nThis module provides a comprehensive interface for the bz2 compression library.\nIt implements a complete file interface, one-shot (de)compression functions,\nand types for sequential (de)compression.\nHere is a resume of the features offered by the bz2 module:\n- BZ2File class implements a complete file interface, including\nreadline(), readlines(),\nwritelines(), seek(), etc;\n- BZ2File class implements emulated seek() support;\n- BZ2File class implements universal newline support;\n- BZ2File class offers an optimized line iteration using\nthe readahead algorithm borrowed from file objects;\n- Sequential (de)compression supported by BZ2Compressor and\nBZ2Decompressor classes;\n- One-shot (de)compression supported by compress() and\ndecompress() functions;\n- Thread safety uses individual locking mechanism;\n- Complete inline documentation;", "python_version": "2.3", "length": 1169, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-bz2.html"} {"title": "5.17 calendar -- General calendar-related functions", "text": "module-xreadlines.html | misc.html | module-cmd.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.16 xreadlines (module-xreadlines.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.18 cmd (module-cmd.html)\n---\n# 5.17 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.\nMost of these functions rely on the datetime module which\nuses an idealized calendar, the current Gregorian calendar indefinitely\nextended in both directions. This matches the definition of the\n\"proleptic Gregorian\" calendar in Dershowitz and Reingold's book\n\"Calendrical Calculations\", where it's the base calendar for all\ncomputations.", "python_version": "2.3", "length": 1052, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.2 AL (module-al-constants.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.3.1 Player Objects (player-objects.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.3", "length": 1731, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.1.1 Browser Controller Objects (browser-controllers.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.2.1 Introduction (cgi-intro.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.3", "length": 488, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.17 SimpleHTTPServer (module-SimpleHTTPServer.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.19 Cookie (module-Cookie.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.3", "length": 1110, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-CGIHTTPServer.html"} {"title": "11.3 cgitb -- Traceback manager for CGI scripts", "text": "node411.html | internet.html | module-urllib.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.10 Common problems and (node411.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.4 urllib (module-urllib.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 Python\nscripts. (It's name is a bit misleading. It was originally designed to\ndisplay extensive traceback information in HTML for CGI scripts. It was\nlater generalized to also display this information in plain text.) After\nthis module is activated, if an uncaught exception occurs, a detailed,\nformatted report will be displayed. 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.3", "length": 1293, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.5.2 Wave_write Objects (Wave-write-objects.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.7 colorsys (module-colorsys.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 (#foot59264) 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.3", "length": 1348, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-chunk.html"} {"title": "5.6 cmath -- Mathematical functions for complex numbers", "text": "module-math.html | misc.html | module-random.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.5 math (module-math.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.7 random (module-random.html)\n---\n# 5.6 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.3", "length": 1462, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-cmath.html"} {"title": "5.18 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\nPrevious:\n5.17 calendar (module-calendar.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.18.1 Cmd Objects (Cmd-objects.html)\n---\n# 5.18 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.3", "length": 556, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-cmd.html"} {"title": "3.23 code -- Interpreter base classes", "text": "module-pkgutil.html | python.html | interpreter-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.22 pkgutil (module-pkgutil.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.23.1 Interactive Interpreter Objects (interpreter-objects.html)\n---\n# 3.23 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.3", "length": 565, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-code.html"} {"title": "4.9 codecs -- Codec registry and base classes", "text": "module-textwrap.html | strings.html | node120.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.8 textwrap (module-textwrap.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.9.1 Codec Base Classes (node120.html)\n---\n# 4.9 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 and error handling lookup process.\nIt defines the following functions:\nTo simplify 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.3", "length": 902, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-codecs.html"} {"title": "3.24 codeop -- Compile Python code", "text": "console-objects.html | python.html | module-pprint.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.23.2 Interactive Console Objects (console-objects.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.25 pprint (module-pprint.html)\n---\n# 3.24 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_command\n```", "python_version": "2.3", "length": 1724, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.6 chunk (module-chunk.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.8 rgbimg (module-rgbimg.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.3", "length": 977, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.17 syslog (module-syslog.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n9. The Python Debugger (module-pdb.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.3", "length": 965, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.8 py_compile (module-pycompile.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.10 dis (module-dis.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.3", "length": 718, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-compileall.html"} {"title": "19.3.1 AST Nodes", "text": "node705.html | node705.html | node707.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.3 Python Abstract Syntax (node705.html)\nUp:\n19.3 Python Abstract Syntax (node705.html)\nNext:\n19.3.2 Assignment nodes (node707.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.3", "length": 2225, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-compiler.ast.html"} {"title": "19.1 The basic interface", "text": "compiler.html | compiler.html | node704.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19. Python compiler package (compiler.html)\nUp:\n19. Python compiler package (compiler.html)\nNext:\n19.2 Limitations (node704.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.3", "length": 643, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-compiler.html"} {"title": "19.4 Using Visitors to Walk ASTs", "text": "node708.html | compiler.html | node710.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.3.3 Examples (node708.html)\nUp:\n19. Python compiler package (compiler.html)\nNext:\n19.5 Bytecode Generation (node710.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.3", "length": 848, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-compiler.visitor.html"} {"title": "5.14 ConfigParser -- Configuration file parser", "text": "itertools-example.html | misc.html | RawConfigParser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.13.2 Examples (itertools-example.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.14.1 RawConfigParser Objects (RawConfigParser-objects.html)\n---\n# 5.14 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.\nWarning:\nThis library does not interpret or write the value-type\nprefixes used in the Windows Registry extended version of INI syntax.\nThe configuration file consists of sections, led 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 on\ninitialization and retrieval. Lines beginning with \"#\" or\n\";\" are ignored and may be used to provide comments.\nFor example:\n```text\n\n[My Section]\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.3", "length": 1742, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.18 CGIHTTPServer (module-CGIHTTPServer.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.19.1 Cookie Objects (cookie-objects.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.3", "length": 1296, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-Cookie.html"} {"title": "3.18 copy -- Shallow and deep copy operations", "text": "node75.html | python.html | module-marshal.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.17.2 Example (node75.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.19 marshal (module-marshal.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.3", "length": 2619, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.15 cPickle (module-cPickle.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.17 shelve (module-shelve.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.3", "length": 658, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.14.7 Example (pickle-example.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.16 copy_reg (module-copyreg.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.11 (#foot8163).\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.3", "length": 1410, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.3 grp (module-grp.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.5 dl (module-dl.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 DES algorithm; 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.3", "length": 659, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-crypt.html"} {"title": "4.7 cStringIO -- Faster version of StringIO", "text": "module-StringIO.html | strings.html | module-textwrap.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.6 StringIO (module-StringIO.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.8 textwrap (module-textwrap.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.\nAnother difference from the StringIO (module-StringIO.html) module is that calling\nStringIO() with a string parameter creates a read-only object.\nUnlike an object created without a string parameter, it does not have\nwrite methods.\nThe following data objects are provided as well:", "python_version": "2.3", "length": 1236, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-cStringIO.html"} {"title": "12.20 csv -- CSV File Reading and Writing", "text": "module-robotparser.html | netdata.html | node545.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.19 robotparser (module-robotparser.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.20.1 Module Contents (node545.html)\n---\n# 12.20 csv -- CSV File Reading and Writing\nNew in version 2.3.\nThe so-called CSV (Comma Separated Values) format is the most common import\nand export format for spreadsheets and databases. There is no ``CSV\nstandard'', so the format is operationally defined by the many applications\nwhich read and write it. The lack of a standard means that subtle\ndifferences often exist in the data produced and consumed by different\napplications. These differences can make it annoying to process CSV files\nfrom multiple sources. Still, while the delimiters and quoting characters\nvary, the overall format is similar enough that it is possible to write a\nsingle module which can efficiently manipulate such data, hiding the details\nof reading and writing the data from the programmer.\nThe csv module implements classes to read and write tabular data in\nCSV format. It allows programmers to say, ``write this data in the format\npreferred by Excel,'' or ``read data from this file which was generated by\nExcel,'' without knowing the precise details of the CSV format used by\nExcel. Programmers can also describe the CSV formats understood by other\napplications or define their own special-purpose CSV formats.\nThe csv module's reader and writer objects read and\nwrite sequences. Programmers can also read and write data in dictionary\nform using the DictReader and DictWriter classes.\nNote:\nThis version of the csv module doesn't support Unicode\ninput. Also, there are currently some issues regarding ASCII NUL\ncharacters. Accordingly, all input should generally be printable\nASCII to be safe. These restrictions will be removed in the future.\nSee Also:", "python_version": "2.3", "length": 1916, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-csv.html"} {"title": "6.17 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\nPrevious:\n6.16 curses.wrapper (module-curses.wrapper.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.18 curses.panel (module-curses.panel.html)\n---\n# 6.17 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.3", "length": 1531, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-curses.ascii.html"} {"title": "6.14 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\nPrevious:\n6.13 getpass (module-getpass.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.14.1 Functions (curses-functions.html)\n---\n# 6.14 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.3", "length": 977, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-curses.html"} {"title": "6.18 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\nPrevious:\n6.17 curses.ascii (module-curses.ascii.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.18.1 Functions (cursespanel-functions.html)\n---\n# 6.18 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.3", "length": 582, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-curses.panel.html"} {"title": "6.15 curses.textpad -- Text input widget for curses programs", "text": "node218.html | allos.html | curses-textpad-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.14.3 Constants (node218.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.15.1 Textbox objects (curses-textpad-objects.html)\n---\n# 6.15 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.3", "length": 779, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-curses.textpad.html"} {"title": "6.16 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\nPrevious:\n6.15.1 Textbox objects (curses-textpad-objects.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.17 curses.ascii (module-curses.ascii.html)\n---\n# 6.16 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.3", "length": 679, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-curses.wrapper.html"} {"title": "6.9 datetime -- Basic date and time types", "text": "popen2-flow-control.html | allos.html | node202.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.8.2 Flow Control Issues (popen2-flow-control.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.9.1 Available Types (node202.html)\n---\n# 6.9 datetime --\nBasic date and time types\nNew in version 2.3.\nThe datetime module supplies classes for manipulating dates\nand times in both simple and complex ways. While date and time\narithmetic is supported, the focus of the implementation is on\nefficient member extraction for output formatting and manipulation.\nThere are two kinds of date and time objects: ``naive'' and ``aware''.\nThis distinction refers to whether the object has any notion of time\nzone, daylight saving time, or other kind of algorithmic or political\ntime adjustment. Whether a naive datetime object represents\nCoordinated Universal Time (UTC), local time, or time in some other\ntimezone is purely up to the program, just like it's up to the program\nwhether a particular number represents meters, miles, or mass. Naive\ndatetime objects are easy to understand and to work with, at\nthe cost of ignoring some aspects of reality.\nFor applications requiring more, datetime and time\nobjects have an optional time zone information member,\ntzinfo, that can contain an instance of a subclass of\nthe abstract tzinfo class. These tzinfo objects\ncapture information about the offset from UTC time, the time zone\nname, and whether Daylight Saving Time is in effect. Note that no\nconcrete tzinfo classes are supplied by the datetime\nmodule. Supporting timezones at whatever level of detail is required\nis up to the application. The rules for time adjustment across the\nworld are more political than rational, and there is no standard\nsuitable for every application.\nThe datetime module exports the following constants:\nSee Also:", "python_version": "2.3", "length": 1874, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-datetime.html"} {"title": "7.11 dbhash -- DBM-style interface to the BSD database library", "text": "module-anydbm.html | someos.html | dbhash-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.10 anydbm (module-anydbm.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.11.1 Database Objects (dbhash-objects.html)\n---\n# 7.11 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.3", "length": 691, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.5.1 Dl Objects (dl-objects.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.7 gdbm (module-gdbm.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.3", "length": 875, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.8 gl (module-gl.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.10 GL (module-gl-constants.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.3", "length": 498, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.3 struct (module-struct.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.4.1 SequenceMatcher Objects (sequence-matcher.html)\n---\n# 4.4 difflib --\nHelpers for computing deltas\nNew in version 2.1.\nSee Also:", "python_version": "2.3", "length": 352, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.2 os.path (module-os.path.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.4 stat (module-stat.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.3", "length": 573, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.9 compileall (module-compileall.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.10.1 Python Byte Code (bytecodes.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)\n2 0 LOAD_GLOBAL 0 (len)\n3 LOAD_FAST 0 (alist)\n6 CALL_FUNCTION 1\n9 RETURN_VALUE\n10 LOAD_CONST 0 (None)\n13 RETURN_VALUE\n```\n(The ``2'' is a line number).\nThe dis module defines the following functions and constants:", "python_version": "2.3", "length": 1037, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.10.1 Python Byte Code (bytecodes.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n19. Python compiler package (compiler.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.3", "length": 1030, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.4 crypt (module-crypt.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.5.1 Dl Objects (dl-objects.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.3", "length": 1105, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-dl.html"} {"title": "5.2 doctest -- Test docstrings represent reality", "text": "module-pydoc.html | misc.html | node133.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.1 pydoc (module-pydoc.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.2.1 Normal Usage (node133.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: # catch a value like 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,\ndoctest works its magic:\n```text\n\n$ python example.py\n$\n```\nThere's no output! That's normal, and it means all the examples\nworked. Pass -v to the script, and doctest\nprints a detailed log of what it's trying, and prints a summary at the\nend:\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\ndoctest! Jump in. The docstrings in doctest.py contain\ndetailed information about all aspects of doctest, and we'll\njust cover the more important points here.", "python_version": "2.3", "length": 3180, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-doctest.html"} {"title": "11.22 DocXMLRPCServer -- Self-documenting XML-RPC server", "text": "node478.html | internet.html | doc-xmlrpc-servers.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.21.2 CGIXMLRPCRequestHandler (node478.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.22.1 DocXMLRPCServer Objects (doc-xmlrpc-servers.html)\n---\n# 11.22 DocXMLRPCServer --\nSelf-documenting XML-RPC server\nNew in version 2.3.\nThe DocXMLRPCServer module extends the classes found in\nSimpleXMLRPCServer to serve HTML documentation in response to\nHTTP GET requests. Servers can either be free standing, using\nDocXMLRPCServer, or embedded in a CGI environment, using\nDocCGIXMLRPCRequestHandler.", "python_version": "2.3", "length": 645, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-DocXMLRPCServer.html"} {"title": "7.14 dumbdbm -- Portable DBM implementation", "text": "bsddb-objects.html | someos.html | dumbdbm-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.13.1 Hash, BTree and (bsddb-objects.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.14.1 Dumbdbm Objects (dumbdbm-objects.html)\n---\n# 7.14 dumbdbm --\nPortable DBM implementation\nNote:\nThe dumbdbm module is intended as a last resort fallback for\nthe anydbm (module-anydbm.html) module when no more robust module is available.\nThe dumbdbm module is not written for speed and is not nearly as\nheavily used as the other database modules.\nThe dumbdbm module provides a persistent dictionary-like interface\nwhich is written entirely in Python. Unlike other modules such as\ngdbm (module-gdbm.html) and bsddb (module-bsddb.html), no external library is required. As\nwith other persistent mappings, the keys and values must always be strings.\nThe module defines the following:\nSee Also:", "python_version": "2.3", "length": 933, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-dumbdbm.html"} {"title": "7.6 dummy_thread -- Drop-in replacement for the thread module", "text": "timer-objects.html | someos.html | module-dummythreading.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.5.7 Timer Objects (timer-objects.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.7 dummy_threading (module-dummythreading.html)\n---\n# 7.6 dummy_thread --\nDrop-in replacement for the thread module\nThis module provides a duplicate interface to the thread (module-thread.html)\nmodule. It is meant to be imported when the thread (module-thread.html) module\nis not provided on a platform.\nSuggested usage is:\n```text\n\ntry:\nimport thread as _thread\nexcept ImportError:\nimport dummy_thread as _thread\n```", "python_version": "2.3", "length": 659, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-dummythread.html"} {"title": "7.7 dummy_threading -- Drop-in replacement for the threading module", "text": "module-dummythread.html | someos.html | module-Queue.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.6 dummy_thread (module-dummythread.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.8 Queue (module-Queue.html)\n---\n# 7.7 dummy_threading --\nDrop-in replacement for the threading module\nThis module provides a duplicate interface to the\nthreading (module-threading.html) module. It is meant to be imported when the\nthread (module-thread.html) module is not provided on a platform.\nSuggested usage is:\n```text\n\ntry:\nimport threading as _threading\nexcept ImportError:\nimport dummy_threading as _threading\n```", "python_version": "2.3", "length": 662, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-dummythreading.html"} {"title": "12.2.6 Representing character sets", "text": "module-email.Header.html | module-email.html | module-email.Encoders.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.5 Internationalized headers (module-email.Header.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.7 Encoders (module-email.Encoders.html)\n---\n## 12.2.6 Representing character sets\nThis module provides a class Charset for representing\ncharacter sets and character set conversions in email messages, as\nwell as a character set registry and several convenience methods for\nmanipulating this registry. Instances of Charset are used in\nseveral other modules within the email package.\nNew in version 2.2.2.\nCharset instances have the following data attributes:\nCharset instances also have the following methods:\nThe Charset class also provides a number of methods to support\nstandard operations and built-in functions.\nThe email.Charset module also provides the following\nfunctions for adding new entries to the global character set, alias,\nand codec registries:", "python_version": "2.3", "length": 1023, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Charset.html"} {"title": "12.2.7 Encoders", "text": "module-email.Charset.html | module-email.html | module-email.Errors.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.6 Representing character sets (module-email.Charset.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.8 Exception classes (module-email.Errors.html)\n---\n## 12.2.7 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.3", "length": 1030, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Encoders.html"} {"title": "12.2.8 Exception classes", "text": "module-email.Encoders.html | module-email.html | module-email.Utils.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.7 Encoders (module-email.Encoders.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.9 Miscellaneous utilities (module-email.Utils.html)\n---\n## 12.2.8 Exception classes\nThe following exception classes are defined in the\nemail.Errors module:", "python_version": "2.3", "length": 404, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Errors.html"} {"title": "12.2.3 Generating MIME documents", "text": "node498.html | module-email.html | node500.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.2.2 Additional notes (node498.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.3.1 Deprecated methods (node500.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 structure. 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 structure 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 a message structure via the\nParser class, and back to flat text, is idempotent (the input\nis identical to the output).\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).\nThe email.Generator module also provides a derived class,\ncalled DecodedGenerator which is like the Generator\nbase class, except that non-text parts are substituted with\na format string representing the part.", "python_version": "2.3", "length": 1770, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Generator.html"} {"title": "12.2.5 Internationalized headers", "text": "node501.html | module-email.html | module-email.Charset.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.4 Creating email and (node501.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.6 Representing character sets (module-email.Charset.html)\n---\n## 12.2.5 Internationalized headers\nRFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) is the base standard that describes the format of email\nmessages. It derives from the older RFC 822 (http://www.faqs.org/rfcs/rfc822.html) standard which came\ninto widespread use at a time when most email was composed of ASCII\ncharacters only. RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) is a specification written assuming email\ncontains only 7-bit ASCII characters.\nOf course, as email has been deployed worldwide, it has become\ninternationalized, such that language specific character sets can now\nbe used in email messages. The base standard still requires email\nmessages to be transfered using only 7-bit ASCII characters, so a\nslew of RFCs have been written describing how to encode email\ncontaining non-ASCII characters into RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html)-compliant format.\nThese RFCs include RFC 2045 (http://www.faqs.org/rfcs/rfc2045.html), RFC 2046 (http://www.faqs.org/rfcs/rfc2046.html), RFC 2047 (http://www.faqs.org/rfcs/rfc2047.html), and RFC 2231 (http://www.faqs.org/rfcs/rfc2231.html).\nThe email package supports these standards in its\nemail.Header and email.Charset modules.\nIf you want to include non-ASCII characters in your email headers,\nsay in the Subject: or To: fields, you should\nuse the Header class and assign the field in the\nMessage object to an instance of Header instead of\nusing a string for the header value. For example:\n```text\n\n>>> from email.Message import Message\n>>> from email.Header import Header\n>>> msg = Message()\n>>> h = Header('p\\xf6stal', 'iso-8859-1')\n>>> msg['Subject'] = h\n>>> print msg.as_string()\nSubject: =?iso-8859-1?q?p=F6stal?=\n```\nNotice here how we wanted the Subject: field to contain a\nnon-ASCII character? We did this by creating a Header\ninstance and passing in the character set that the byte string was\nencoded in. When the subsequent Message instance was\nflattened, the Subject: field was properly RFC 2047 (http://www.faqs.org/rfcs/rfc2047.html)\nencoded. MIME-aware mail readers would show this header using the\nembedded ISO-8859-1 character.\nNew in version 2.2.2.\nHere is the Header class description:\nOptional errors is passed straight through to the\nappend() method.\nThe Header class also provides a number of methods to support\nstandard operators and built-in functions.\nThe email.Header module also provides the following\nconvenient functions.", "python_version": "2.3", "length": 2719, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Header.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\nPrevious:\n12.1.4 Writer Implementations (writer-impls.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.2.1 Representing an email (module-email.Message.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) module. The email\npackage attempts to be as RFC-compliant as possible, supporting in\naddition to RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html), such MIME-related RFCs as\nRFC 2045 (http://www.faqs.org/rfcs/rfc2045.html)-RFC 2047 (http://www.faqs.org/rfcs/rfc2047.html), and RFC 2231 (http://www.faqs.org/rfcs/rfc2231.html).\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 the\nobject structure of the email message, this structure is manipulated,\nand finally rendered back into flat text.\nIt is perfectly feasible to create the object structure out of whole\ncloth -- i.e. completely from scratch. From there, a similar\nprogression can 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, or previous versions of the email\npackage, a section on differences and porting is provided.\nSee Also:", "python_version": "2.3", "length": 2904, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.html"} {"title": "12.2.10 Iterators", "text": "module-email.Utils.html | module-email.html | node508.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.9 Miscellaneous utilities (module-email.Utils.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.11 Differences from email (node508.html)\n---\n## 12.2.10 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.\nThe following function has been added as a useful debugging tool. It\nshould not be considered part of the supported public interface\nfor the package.", "python_version": "2.3", "length": 645, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Iterators.html"} {"title": "12.2.1 Representing an email message", "text": "module-email.html | module-email.html | node495.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2 email (module-email.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.1.1 Deprecated methods (node495.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 envelope\nheader, also known as the Unix-From header or the\n`From_` header. The payload is either a string in the case of\nsimple message objects or a list of Message objects for\nMIME container documents (e.g. multipart/* and\nmessage/rfc822).\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'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, headers are always\nreturned in the order they appeared in the original message, or were\nadded to the message later. Any header deleted and then re-added are\nalways appended to the end of the header list.\nThese semantic differences are intentional and are biased toward\nmaximal convenience.\nNote that in all cases, any envelope header present in the message is\nnot 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.3", "length": 2613, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Message.html"} {"title": "12.2.2 Parsing email messages", "text": "node495.html | module-email.html | node497.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.1.1 Deprecated methods (node495.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.2.1 Parser class API (node497.html)\n---\n## 12.2.2 Parsing email messages\nMessage object structures can be created in one of two ways: they can be\ncreated from whole cloth by instantiating Message objects and\nstringing them together via attach() 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 structure. 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 any way it finds 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. Two modes of parsing are supported,\nstrict parsing, which will usually reject any non-RFC compliant\nmessage, and lax parsing, which attempts to adjust for common\nMIME formatting problems.\nThe email.Parser module also provides a second class, called\nHeaderParser which can be used if you're only interested in\nthe headers of the message. HeaderParser can be much faster in\nthese situations, since it does not attempt to parse the message body,\ninstead setting the payload to the raw body as a string.\nHeaderParser has the same API as the Parser class.", "python_version": "2.3", "length": 2163, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Parser.html"} {"title": "12.2.9 Miscellaneous utilities", "text": "module-email.Errors.html | module-email.html | module-email.Iterators.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.8 Exception classes (module-email.Errors.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.10 Iterators (module-email.Iterators.html)\n---\n## 12.2.9 Miscellaneous utilities\nThere are several useful utilities provided with the email\npackage.\nThe following functions have been deprecated:", "python_version": "2.3", "length": 452, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-email.Utils.html"} {"title": "4.9.3 encodings.idna -- Internationalized Domain Names in Applications", "text": "node126.html | module-codecs.html | module-unicodedata.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.2 Standard Encodings (node126.html)\nUp:\n4.9 codecs (module-codecs.html)\nNext:\n4.10 unicodedata (module-unicodedata.html)\n---\n## 4.9.3 encodings.idna --\nInternationalized Domain Names in Applications\nNew in version 2.3.\nThis module implements RFC 3490 (http://www.faqs.org/rfcs/rfc3490.html) (Internationalized Domain Names in\nApplications) and RFC 3492 (http://www.faqs.org/rfcs/rfc3492.html) (Nameprep: A Stringprep Profile for\nInternationalized Domain Names (IDN)). It builds upon the\n`punycode` encoding and stringprep (module-stringprep.html).\nThese RFCs together define a protocol to support non-ASCII characters\nin domain names. A domain name containing non-ASCII characters (such\nas ``www.Alliancefrançaise.nu'') is converted into an\nASCII-compatible encoding (ACE, such as\n``www.xn-alliancefranaise-npb.nu''). The ACE form of the domain name\nis then used in all places where arbitrary characters are not allowed\nby the protocol, such as DNS queries, HTTP Host: fields, and so\non. This conversion is carried out in the application; if possible\ninvisible to the user: The application should transparently convert\nUnicode domain labels to IDNA on the wire, and convert back ACE labels\nto Unicode before presenting them to the user.\nPython supports this conversion in several ways: The `idna` codec\nallows to convert between Unicode and the ACE. Furthermore, the\nsocket (module-socket.html) module transparently converts Unicode host names to\nACE, so that applications need not be concerned about converting host\nnames themselves when they pass them to the socket module. On top of\nthat, modules that have host names as function parameters, such as\nhttplib (module-httplib.html) and ftplib (module-ftplib.html), accept Unicode host names\n(httplib (module-httplib.html) then also transparently sends an IDNA hostname in\nthe Host: field if it sends that field at all).\nWhen receiving host names from the wire (such as in reverse name\nlookup), no automatic conversion to Unicode is performed: Applications\nwishing to present such host names to the user should decode them to\nUnicode.\nThe module encodings.idna also implements the nameprep\nprocedure, which performs certain normalizations on host names, to\nachieve case-insensitivity of international domain names, and to unify\nsimilar characters. The nameprep functions can be used directly if\ndesired.", "python_version": "2.3", "length": 2502, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-encodings.idna.html"} {"title": "6.22 errno -- Standard errno system symbols", "text": "module-tempfile.html | allos.html | module-glob.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.21 tempfile (module-tempfile.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.23 glob (module-glob.html)\n---\n# 6.22 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.3", "length": 820, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-errno.html"} {"title": "2.3 Built-in Exceptions", "text": "specialattrs.html | builtin.html | node33.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n2.2.10 Special Attributes (specialattrs.html)\nUp:\n2. Built-In Objects (builtin.html)\nNext:\n2.4 Built-in Constants (node33.html)\n---\n# 2.3 Built-in Exceptions\nExceptions should be class objects.\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.\nNote:\nIn past versions of Python string exceptions were supported. In\nPython 1.5 and newer versions, all standard exceptions have been\nconverted to class objects and users are encouraged to do the same.\nString exceptions will raise a `PendingDeprecationWarning`.\nIn future versions, support for string exceptions will be removed.\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 try statement with\nan except clause 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\nraise statement. 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-warnings.html) module for more information.\nThe class hierarchy for built-in exceptions is:", "python_version": "2.3", "length": 3268, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.11 pty (module-pty.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.13 pipes (module-pipes.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```\nNote that in the first example the return value variable rv will\nhold an integer value; in the second example it will hold a string\nvalue. The structure lay-out for the lockdata variable is\nsystem dependent -- therefore using the flock() call may be\nbetter.", "python_version": "2.3", "length": 1277, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.6 statvfs (module-statvfs.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.7.1 The dircmp class (dircmp-objects.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')\nTrue\n>>> filecmp.cmp('libundoc.tex', 'lib.tex')\nFalse\n```", "python_version": "2.3", "length": 638, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-filecmp.html"} {"title": "5.15 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\nPrevious:\n5.14.2 ConfigParser Objects (ConfigParser-objects.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.16 xreadlines (module-xreadlines.html)\n---\n# 5.15 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.3", "length": 2461, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.4.3 FORMS Objects (forms-objects.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.6 flp (module-flp.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.3", "length": 657, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-fl-constants.html"} {"title": "20.4 fl -- FORMS library for graphical user interfaces", "text": "cd-parser-objects.html | sgi.html | node720.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n20.3.2 Parser Objects (cd-parser-objects.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.4.1 Functions Defined in (node720.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.3", "length": 1925, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.5 FL (module-fl-constants.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.7 fm (module-fm.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.3", "length": 593, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.6 flp (module-flp.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.8 gl (module-gl.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.3", "length": 835, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-fm.html"} {"title": "6.24 fnmatch -- Unix filename pattern matching", "text": "module-glob.html | allos.html | module-shutil.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.23 glob (module-glob.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.25 shutil (module-shutil.html)\n---\n# 6.24 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.3", "length": 851, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12. Internet Data Handling (netdata.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.1.1 The Formatter Interface (formatter-interface.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.3", "length": 1594, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.3.3 Weak References in (weakref-extension.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.4.1 Example (fpectl-example.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.3", "length": 1818, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.4.4 Differ Example (differ-examples.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.6 StringIO (module-StringIO.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.3", "length": 614, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.6.3 Examples (httplib-examples.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.7.1 FTP Objects (ftp-objects.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 anonymous@\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.3", "length": 1557, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-ftplib.html"} {"title": "3.32 __future__ -- Future statement definitions", "text": "module-main.html | python.html | strings.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.31 __main__ (module-main.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n4. String Services (strings.html)\n---\n# 3.32 __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.3", "length": 2352, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-future.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\nPrevious:\n3.1 sys (module-sys.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.3 weakref (module-weakref.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.3", "length": 1286, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.6 dbm (module-dbm.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.8 termios (module-termios.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.3", "length": 943, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-gdbm.html"} {"title": "6.19 getopt -- Parser for command line options", "text": "curses-panel-objects.html | allos.html | module-optparse.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.18.2 Panel Objects (curses-panel-objects.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.20 optparse (module-optparse.html)\n---\n# 6.19 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.3", "length": 1527, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-getopt.html"} {"title": "6.13 getpass -- Portable password input", "text": "mutex-objects.html | allos.html | module-curses.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.12.1 Mutex Objects (mutex-objects.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.14 curses (module-curses.html)\n---\n# 6.13 getpass\n-- Portable password input\nThe getpass module provides two functions:", "python_version": "2.3", "length": 352, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-getpass.html"} {"title": "6.27 gettext -- Multilingual internationalization services", "text": "locale-gettext.html | allos.html | node268.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.26.3 Access to message (locale-gettext.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.27.1 GNU gettext API (node268.html)\n---\n# 6.27 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.3", "length": 884, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.9 DEVICE (module-DEVICE.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.11 imgfile (module-imgfile.html)\n---\n# 20.10 GL --\nConstants used with the gl module\nAvailability: IRIX.", "python_version": "2.3", "length": 320, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.7 fm (module-fm.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.9 DEVICE (module-DEVICE.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.3", "length": 2496, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-gl.html"} {"title": "6.23 glob -- Unix style pathname pattern expansion", "text": "module-errno.html | allos.html | module-fnmatch.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.22 errno (module-errno.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.24 fnmatch (module-fnmatch.html)\n---\n# 6.23 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.3", "length": 1114, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.7.1 FTP Objects (ftp-objects.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.9 poplib (module-poplib.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.3", "length": 540, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.2 pwd (module-pwd.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.4 crypt (module-crypt.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 a tuple-like object, whose\nattributes correspond to the members of the `group` structure\n(Attribute field below, see ``):\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.3", "length": 864, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-grp.html"} {"title": "7.16 gzip -- Support for gzip files", "text": "module-zlib.html | someos.html | module-bz2.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.15 zlib (module-zlib.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.17 bz2 (module-bz2.html)\n---\n# 7.16 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.3", "length": 801, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-gzip.html"} {"title": "5.10 heapq -- Heap queue algorithm", "text": "bisect-example.html | misc.html | node162.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.9.1 Examples (bisect-example.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.10.1 Theory (node162.html)\n---\n# 5.10 heapq --\nHeap queue algorithm\nNew in version 2.3.\nThis module provides an implementation of the heap queue algorithm,\nalso known as the priority queue algorithm.\nHeaps are arrays for which\n`heap [ k ] <= heap [2* k +1]` and\n`heap [ k ] <= heap [2* k +2]`\nfor all k, counting elements from zero. For the sake of\ncomparison, non-existing elements are considered to be infinite. The\ninteresting property of a heap is that `heap [0]` is always\nits smallest element.\nThe API below differs from textbook heap algorithms in two aspects:\n(a) We use zero-based indexing. This makes the relationship between the\nindex for a node and the indexes for its children slightly less\nobvious, but is more suitable since Python uses zero-based indexing.\n(b) Our pop method returns the smallest item, not the largest (called a\n\"min heap\" in textbooks; a \"max heap\" is more common in texts because\nof its suitability for in-place sorting).\nThese two make it possible to view the heap as a regular Python list\nwithout surprises: `heap [0]` is the smallest item, and\n`heap .sort()` maintains the heap invariant!\nTo create a heap, use a list initialized to `[]`, or you can\ntransform a populated list into a heap via function heapify().\nThe following functions are provided:\nExample of use:\n```text\n\n>>> from heapq import heappush, heappop\n>>> heap = []\n>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\n>>> for item in data:\n... heappush(heap, item)\n...\n>>> sorted = []\n>>> while heap:\n... sorted.append(heappop(heap))\n...\n>>> print sorted\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> data.sort()\n>>> print data == sorted\nTrue\n>>>\n```", "python_version": "2.3", "length": 1850, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-heapq.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\nPrevious:\n15. Cryptographic Services (crypto.html)\nUp:\n15. Cryptographic Services (crypto.html)\nNext:\n15.2 md5 (module-md5.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.3", "length": 477, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-hmac.html"} {"title": "10.9 hotshot -- High performance logging profiler", "text": "node390.html | profile.html | hotshot-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.8 Extensions (node390.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.9.1 Profile Objects (hotshot-objects.html)\n---\n# 10.9 hotshot --\nHigh performance logging profiler\nNew in version 2.2.\nThis module provides a nicer interface to the _hotshot C module.\nHotshot is a replacement for the existing profile (module-profile.html) module. As it's\nwritten mostly in C, it should result in a much smaller performance impact\nthan the existing profile (module-profile.html) module.", "python_version": "2.3", "length": 621, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-hotshot.html"} {"title": "10.9.2 Using hotshot data", "text": "hotshot-objects.html | module-hotshot.html | hotshot-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.9.1 Profile Objects (hotshot-objects.html)\nUp:\n10.9 hotshot (module-hotshot.html)\nNext:\n10.9.3 Example Usage (hotshot-example.html)\n---\n## 10.9.2 Using hotshot data\nNew in version 2.2.\nThis module loads hotshot profiling data into the standard pstats\nStats objects.\nSee Also:", "python_version": "2.3", "length": 429, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-hotshot.stats.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\nPrevious:\n13.3.1 HTMLParser Objects (html-parser-objects.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.5 xml.parsers.expat (module-xml.parsers.expat.html)\n---\n# 13.4 htmlentitydefs --\nDefinitions of HTML general entities\nThis module defines three dictionaries, `name2codepoint`,\n`codepoint2name`, and `entitydefs`. `entitydefs` 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 XHTML 1.0\nthat can be handled using simple textual substitution in the Latin-1\ncharacter set (ISO-8859-1).", "python_version": "2.3", "length": 776, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.2 sgmllib (module-sgmllib.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.3.1 HTMLParser Objects (html-parser-objects.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.3", "length": 2520, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13. Structured Markup Processing (markup.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.1.1 Example HTML Parser (htmlparser-example.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.3", "length": 671, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-HTMLParser.html"} {"title": "11.6 httplib -- HTTP protocol client", "text": "urllib2-examples.html | internet.html | httpconnection-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.5.20 Examples (urllib2-examples.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.6.1 HTTPConnection Objects (httpconnection-objects.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.\nNote:\nHTTPS support is only available if the socket (module-socket.html) module was\ncompiled with SSL support.\nNote:\nThe public interface for this module changed substantially in Python\n2.0. The HTTP class is retained only for backward\ncompatibility with 1.5.2. It should not be used in new code. Refer\nto the online docstrings for usage.\nThe constants defined in this module are:\nThe module provides the following classes:\nThe following exceptions are raised as appropriate:", "python_version": "2.3", "length": 1040, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.1 audioop (module-audioop.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.3 aifc (module-aifc.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.3", "length": 595, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.9.2 POP3 Example (pop3-example.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.10.1 IMAP4 Objects (imap4-objects.html)\n---\n# 11.10 imaplib --\nIMAP4 protocol client\nThis module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a\nconnection to an IMAP4 server and implement 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.\nThree classes are provided by the imaplib module, IMAP4 is the base class:\nThree exceptions are defined as attributes of the IMAP4 class:\nThere's also a subclass for secure connections:\nThe second subclass allows for connections created by a child process:\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.3", "length": 1571, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.10 GL (module-gl-constants.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n20.12 jpeg (module-jpeg.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.3", "length": 645, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.8 rgbimg (module-rgbimg.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.10 sndhdr (module-sndhdr.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.3", "length": 630, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.20.3 Available Functions (warning-functions.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.21.1 Examples (examples-imp.html)\n---\n# 3.21 imp --\nAccess the import internals\nThis module 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.3", "length": 767, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.10.1 Mapping Operators to (operator-map.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.11.1 Types and members (inspect-types.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.3", "length": 924, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-inspect.html"} {"title": "5.13 itertools -- Functions creating iterators for efficient looping", "text": "immutable-transforms.html | misc.html | itertools-functions.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.12.3 Protocol for automatic (immutable-transforms.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.13.1 Itertool functions (itertools-functions.html)\n---\n# 5.13 itertools --\nFunctions creating iterators for efficient looping\nNew in version 2.3.\nThis module implements a number of iterator building blocks inspired\nby constructs from the Haskell and SML programming languages. Each\nhas been recast in a form suitable for Python.\nThe module standardizes a core set of fast, memory efficient tools\nthat are useful by themselves or in combination. Standardization helps\navoid the readability and reliability problems which arise when many\ndifferent individuals create their own slightly varying implementations,\neach with their own quirks and naming conventions.\nThe tools are designed to combine readily with one another. This makes\nit easy to construct more specialized tools succinctly and efficiently\nin pure Python.\nFor instance, SML provides a tabulation tool: `tabulate(f)`\nwhich produces a sequence `f(0), f(1), ...`. This toolbox\nprovides imap() and count() which can be combined\nto form `imap(f, count())` and produce an equivalent result.\nLikewise, the functional tools are designed to work well with the\nhigh-speed functions provided by the operator (module-operator.html) module.\nThe module author welcomes suggestions for other basic building blocks\nto be added to future versions of the module.\nWhether cast in pure python form or C code, tools that use iterators\nare more memory efficient (and faster) than their list based counterparts.\nAdopting the principles of just-in-time manufacturing, they create\ndata when and where needed instead of consuming memory with the\ncomputer equivalent of ``inventory''.\nThe performance advantage of iterators becomes more acute as the number\nof elements increases - at some point, lists grow large enough to\nto severely impact memory cache performance and start running slowly.\nSee Also:\nThe Standard ML Basis Library,\nThe Standard ML Basis Library (http://www.standardml.org/Basis/).\nHaskell, A Purely Functional Language,\nDefinition of Haskell and the Standard Libraries (http://www.haskell.org/definition/).", "python_version": "2.3", "length": 2318, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-itertools.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\nPrevious:\n20.11 imgfile (module-imgfile.html)\nUp:\n20. SGI IRIX Specific (sgi.html)\nNext:\n21. SunOS Specific Services (sunos.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.3", "length": 892, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.3 token (module-token.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.5 tokenize (module-tokenize.html)\n---\n# 18.4 keyword --\nTesting for Python keywords\nThis module allows a Python program to determine if a string is a\nkeyword.", "python_version": "2.3", "length": 389, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.12.1 Traceback Example (traceback-example.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.14 pickle (module-pickle.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.3", "length": 700, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-linecache.html"} {"title": "6.26 locale -- Internationalization services", "text": "shutil-example.html | allos.html | node264.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.25.1 Example (shutil-example.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.26.1 Background, details, hints, (node264.html)\n---\n# 6.26 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.3", "length": 1387, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-locale.html"} {"title": "6.28 logging -- Logging facility for Python", "text": "node279.html | allos.html | node281.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.4 Acknowledgements (node279.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.28.1 Logger Objects (node281.html)\n---\n# 6.28 logging --\nLogging facility for Python\nNew in version 2.3.\nThis module defines functions and classes which implement a flexible\nerror logging system for applications.\nLogging is performed by calling methods on instances of the\nLogger class (hereafter called loggers). Each instance has a\nname, and they are conceptually arranged in a name space hierarchy\nusing dots (periods) as separators. For example, a logger named\n\"scan\" is the parent of loggers \"scan.text\", \"scan.html\" and \"scan.pdf\".\nLogger names can be anything you want, and indicate the area of an\napplication in which a logged message originates.\nLogged messages also have levels of importance associated with them.\nThe default levels provided are DEBUG, INFO,\nWARNING, ERROR and CRITICAL. As a\nconvenience, you indicate the importance of a logged message by calling\nan appropriate method of Logger. The methods are\ndebug(), info(), warning(), error() and\ncritical(), which mirror the default levels. You are not\nconstrained to use these levels: you can specify your own and use a\nmore general Logger method, log(), which takes an\nexplicit level argument.\nLevels can also be associated with loggers, being set either by the\ndeveloper or through loading a saved logging configuration. When a\nlogging method is called on a logger, the logger compares its own\nlevel with the level associated with the method call. If the logger's\nlevel is higher than the method call's, no logging message is actually\ngenerated. This is the basic mechanism controlling the verbosity of\nlogging output.\nLogging messages are encoded as instances of the LogRecord class.\nWhen a logger decides to actually log an event, an LogRecord\ninstance is created from the logging message.\nLogging messages are subjected to a dispatch mechanism through the\nuse of handlers, which are instances of subclasses of the\nHandler class. Handlers are responsible for ensuring that a logged\nmessage (in the form of a LogRecord) ends up in a particular\nlocation (or set of locations) which is useful for the target audience for\nthat message (such as end users, support desk staff, system administrators,\ndevelopers). Handlers are passed LogRecord instances intended for\nparticular destinations. Each logger can have zero, one or more handlers\nassociated with it (via the addHandler method of Logger).\nIn addition to any handlers directly associated with a logger,\nall handlers associated with all ancestors of the logger are\ncalled to dispatch the message.\nJust as for loggers, handlers can have levels associated with them.\nA handler's level acts as a filter in the same way as a logger's level does.\nIf a handler decides to actually dispatch an event, the emit() method\nis used to send the message to its destination. Most user-defined subclasses\nof Handler will need to override this emit().\nIn addition to the base Handler class, many useful subclasses\nare provided:\n1. StreamHandler instances send error messages to\nstreams (file-like objects).\n2. FileHandler instances send error messages to disk\nfiles.\n3. RotatingFileHandler instances send error messages to disk\nfiles, with support for maximum log file sizes and log file rotation.\n4. SocketHandler instances send error messages to\nTCP/IP sockets.\n5. DatagramHandler instances send error messages to UDP\nsockets.\n6. SMTPHandler instances send error messages to a\ndesignated email address.\n7. SysLogHandler instances send error messages to a\nUnix syslog daemon, possibly on a remote machine.\n8. NTEventLogHandler instances send error messages to a\nWindows NT/2000/XP event log.\n9. MemoryHandler instances send error messages to a\nbuffer in memory, which is flushed whenever specific criteria are\nmet.\n10. HTTPHandler instances send error messages to an\nHTTP server using either \"GET\" or \"POST\" semantics.\nThe StreamHandler and FileHandler classes are defined\nin the core logging package. The other handlers are defined in a sub-\nmodule, logging.handlers. (There is also another sub-module,\nlogging.config, for configuration functionality.)\nLogged messages are formatted for presentation through instances of the\nFormatter class. They are initialized with a format string\nsuitable for use with the % operator and a dictionary.\nFor formatting multiple messages in a batch, instances of\nBufferingFormatter can be used. In addition to the format string\n(which is applied to each message in the batch), there is provision for\nheader and trailer format strings.\nWhen filtering based on logger level and/or handler level is not enough,\ninstances of Filter can be added to both Logger and\nHandler instances (through their addFilter() method).\nBefore deciding to process a message further, both loggers and handlers\nconsult all their filters for permission. If any filter returns a false\nvalue, the message is not processed further.\nThe basic Filter functionality allows filtering by specific logger\nname. If this feature is used, messages sent to the named logger and its\nchildren are allowed through the filter, and all others dropped.\nIn addition to the classes described above, there are a number of module-\nlevel functions.\nSee Also:", "python_version": "2.3", "length": 5368, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-logging.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\nPrevious:\n12.3 mailcap (module-mailcap.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.4.1 Mailbox Objects (mailbox-objects.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.\nNote that because the rfc822 (module-rfc822.html) module is deprecated, it is\nrecommended that you use the email (module-email.html) package to create\nmessage objects from a mailbox. (The default can't be changed for\nbackwards compatibility reasons.) The safest way to do this is with\nbit of code:\n```text\n\nimport email\nimport email.Errors\nimport mailbox\n\ndef msgfactory(fp):\ntry:\nreturn email.message_from_file(fp)\nexcept email.Errors.MessageParseError:\n# Don't return None since that will\n# stop the mailbox iterator\nreturn ''\n\nmbox = mailbox.UnixMailbox(fp, msgfactory)\n```\nThe above wrapper is defensive against ill-formed MIME messages in the\nmailbox, but you have to be prepared to receive the empty string from\nthe mailbox's next() method. On the other hand, if you\nknow your mailbox contains only well-formed MIME messages, you can\nsimplify this to:\n```text\n\nimport email\nimport mailbox\n\nmbox = mailbox.UnixMailbox(fp, email.message_from_file)\n```\nSee Also:", "python_version": "2.3", "length": 1405, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-mailbox.html"} {"title": "12.3 mailcap -- Mailcap file handling.", "text": "node510.html | netdata.html | module-mailbox.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.13 Examples (node510.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.4 mailbox (module-mailbox.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.3", "length": 1092, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-mailcap.html"} {"title": "3.31 __main__ -- Top-level script environment", "text": "module-builtin.html | python.html | module-future.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.30 __builtin__ (module-builtin.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.32 __future__ (module-future.html)\n---\n# 3.31 __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:", "python_version": "2.3", "length": 618, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.18 copy (module-copy.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.20 warnings (module-warnings.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.12 (#foot8879)\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 instead.\nWarning:\nThe marshal module is not intended to be secure against\nerroneous or maliciously constructed data. Never unmarshal data\nreceived from an untrusted or unauthenticated source.\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.3", "length": 2698, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-marshal.html"} {"title": "5.5 math -- Mathematical functions", "text": "regrtest.html | misc.html | module-cmath.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.4.3 Running tests Using (regrtest.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.6 cmath (module-cmath.html)\n---\n# 5.5 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 are provided by this module. Except\nwhen explicitly noted otherwise, all return values are floats:\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:\nNote:\nThe math module consists mostly of thin wrappers around\nthe platform C math library functions. Behavior in exceptional cases is\nloosely specified by the C standards, and Python inherits much of its\nmath-function error-reporting behavior from the platform C\nimplementation. As a result,\nthe specific exceptions raised in error cases (and even whether some\narguments are considered to be exceptional at all) are not defined in any\nuseful cross-platform or cross-release way. For example, whether\n`math.log(0)` returns `-Inf` or raises ValueError or\nOverflowError isn't defined, and in\ncases where `math.log(0)` raises OverflowError,\n`math.log(0L)` may raise ValueError instead.", "python_version": "2.3", "length": 2111, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n15.1 hmac (module-hmac.html)\nUp:\n15. Cryptographic Services (crypto.html)\nNext:\n15.3 sha (module-sha.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.3", "length": 1416, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.4.1 Mailbox Objects (mailbox-objects.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.5.1 MH Objects (mh-objects.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.3", "length": 582, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.5.3 Message Objects (mh-message-objects.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.6.1 Additional Methods of (mimetools-message-objects.html)\n---\n# 12.6 mimetools --\nTools for parsing MIME messages\nDeprecated since release 2.3.\nThe email (module-email.html) package should be used in\npreference to the mimetools module. This\nmodule is present only to maintain backward\ncompatibility.\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.3", "length": 801, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.6.1 Additional Methods of (mimetools-message-objects.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.7.1 MimeTypes Objects (mimetypes-objects.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.3", "length": 1206, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.7.1 MimeTypes Objects (mimetypes-objects.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.8.1 MimeWriter Objects (MimeWriter-objects.html)\n---\n# 12.8 MimeWriter --\nGeneric MIME file writer\nDeprecated since release 2.3.\nThe email (module-email.html) package should be used in\npreference to the MimeWriter module. This\nmodule is present only to maintain backward\ncompatibility.\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.3", "length": 920, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.8.1 MimeWriter Objects (MimeWriter-objects.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.10 multifile (module-multifile.html)\n---\n# 12.9 mimify --\nMIME processing of mail messages\nDeprecated since release 2.3.\nThe email (module-email.html) package should be used in\npreference to the mimify module. This\nmodule is present only to maintain backward\ncompatibility.\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.3", "length": 1809, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-mimify.html"} {"title": "7.9 mmap --\nMemory-mapped file support", "text": "QueueObjects.html | someos.html | module-anydbm.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.8.1 Queue Objects (QueueObjects.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.10 anydbm (module-anydbm.html)\n---\n# 7.9 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.3", "length": 2113, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n15.3 sha (module-sha.html)\nUp:\n15. Cryptographic Services (crypto.html)\nNext:\n15.5 rotor (module-rotor.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.3", "length": 1805, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-mpz.html"} {"title": "22.1 msvcrt - Useful routines from the MS VC++ runtime", "text": "node735.html | node735.html | msvcrt-files.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n22. MS Windows Specific (node735.html)\nUp:\n22. MS Windows Specific (node735.html)\nNext:\n22.1.1 File Operations (msvcrt-files.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.3", "length": 732, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.9 mimify (module-mimify.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.10.1 MultiFile Objects (MultiFile-objects.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.\nSee Also:", "python_version": "2.3", "length": 1039, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-multifile.html"} {"title": "6.12 mutex -- Mutual exclusion support", "text": "scheduler-objects.html | allos.html | mutex-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.11.1 Scheduler Objects (scheduler-objects.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.12.1 Mutex Objects (mutex-objects.html)\n---\n# 6.12 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.3", "length": 577, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.17.3 Exceptions (xdr-exceptions.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.18.1 netrc Objects (netrc-objects.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.3", "length": 455, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-netrc.html"} {"title": "3.27 new -- Creation of runtime internal objects", "text": "subclassing-reprs.html | python.html | module-site.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.26.2 Subclassing Repr Objects (subclassing-reprs.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.28 site (module-site.html)\n---\n# 3.27 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.3", "length": 728, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-new.html"} {"title": "8.16 nis -- Interface to Sun's NIS (Yellow Pages)", "text": "node374.html | unix.html | module-syslog.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n8.15.2 Resource Usage (node374.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.17 syslog (module-syslog.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.3", "length": 613, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.10.2 IMAP4 Example (imap4-example.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.11.1 NNTP Objects (nntp-objects.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.3", "length": 1905, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.9 UserString (module-UserString.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.10.1 Mapping Operators to (operator-map.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, identity 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.3", "length": 1772, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-operator.html"} {"title": "6.20 optparse -- Powerful parser for command line options.", "text": "module-getopt.html | allos.html | optparse-philosophy.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.19 getopt (module-getopt.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.20.1 Philosophy (optparse-philosophy.html)\n---\n# 6.20 optparse --\nPowerful parser for command line options.\nNew in version 2.3.\nThe optparse module is a powerful, flexible, extensible,\neasy-to-use command-line parsing library for Python. Using\noptparse, you can add intelligent, sophisticated handling of\ncommand-line options to your scripts with very little overhead.\nHere's an example of using optparse to add some command-line\noptions to a simple script:\n```text\n\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\nhelp=\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\naction=\"store_false\", dest=\"verbose\", default=True,\nhelp=\"don't print status messages to stdout\")\n\n(options, args) = parser.parse_args()\n```\nWith these few lines of code, users of your script can now do the\n``usual thing'' on the command-line:\n```text\n\n$ -f outfile --quiet\n$ -qfoutfile\n$ --file=outfile -q\n$ --quiet --file outfile\n```\n(All of these result in `options.filename == \"outfile\"` and\n`options.verbose == False`, just as you might expect.)\nEven niftier, users can run one of\n```text\n\n$ -h\n$ --help\n```\nand optparse will print out a brief summary of your script's\noptions:\n```text\n\nusage: [options]\n\noptions:\n-h, --help show this help message and exit\n-fFILE, --file=FILE write report to FILE\n-q, --quiet don't print status messages to stdout\n```\nThat's just a taste of the flexibility optparse gives you in\nparsing your command-line.", "python_version": "2.3", "length": 1822, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-optparse.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\nPrevious:\n6. Generic Operating System (allos.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.1.1 Process Parameters (os-procinfo.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.3", "length": 1518, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1.6 Miscellaneous System Information (os-path.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.3 dircache (module-dircache.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.3", "length": 519, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-os.path.html"} {"title": "14.11 ossaudiodev -- Access to OSS-compatible audio devices", "text": "module-sndhdr.html | mmedia.html | ossaudio-device-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n14.10 sndhdr (module-sndhdr.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.11.1 Audio Device Objects (ossaudio-device-objects.html)\n---\n# 14.11 ossaudiodev --\nAccess to OSS-compatible audio devices\nAvailability: Linux, FreeBSD, possibly other Unix-like systems.\nThis module allows you to access the OSS (Open Sound System) audio\ninterface. OSS is available for a wide range of open-source and\ncommercial Unices, and is the standard audio interface for Linux and\nrecent versions of FreeBSD.\nSee Also:\nThe module defines a large number of constants supplied by\nthe OSS device driver; see `` on either\nLinux or FreeBSD for a listing .\nossaudiodev defines the following variables and functions:", "python_version": "2.3", "length": 866, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-ossaudiodev.html"} {"title": "18.1 parser -- Access Python parse trees", "text": "language.html | language.html | node682.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18. Python Language Services (language.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.1.1 Creating AST Objects (node682.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.3", "length": 4541, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.18 commands (module-commands.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n9.1 Debugger Commands (debugger-commands.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.3", "length": 1780, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-pdb.html"} {"title": "3.14 pickle -- Python object serialization", "text": "module-linecache.html | python.html | node61.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.13 linecache (module-linecache.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.14.1 Relationship to other (node61.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 (#foot8168) or ``flattening'',\nhowever, to avoid confusion, the terms used here are ``pickling'' and\n``unpickling''.\nThis documentation describes both the pickle module and the\ncPickle (module-cPickle.html) module.\n---\n#### Footnotes\n... ``marshalling,''3.2 (module-pickle.html#tex2html14): Don't confuse this with\nthe marshal (module-marshal.html) module", "python_version": "2.3", "length": 1098, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.12 fcntl (module-fcntl.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.13.1 Template Objects (template-objects.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.3", "length": 828, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-pipes.html"} {"title": "3.22 pkgutil -- Package extension utility", "text": "examples-imp.html | python.html | module-code.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.21.1 Examples (examples-imp.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.23 code (module-code.html)\n---\n# 3.22 pkgutil --\nPackage extension utility\nNew in version 2.3.\nWarning:\nThis is an experimental module. It may be withdrawn or completely\nchanged up to an including the release of Python 2.3 beta 1.\nThis module provides a single function:", "python_version": "2.3", "length": 495, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-pkgutil.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\nPrevious:\n6.7.1 The dircmp class (dircmp-objects.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.8.1 Popen3 and Popen4 (popen3-objects.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.3", "length": 1667, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.8 gopherlib (module-gopherlib.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.9.1 POP3 Objects (pop3-objects.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.3", "length": 967, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8. Unix Specific Services (unix.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.1.1 Large File Support (posix-large-files.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.3", "length": 1511, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.13.1 Template Objects (template-objects.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.15 resource (module-resource.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.3", "length": 2017, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-posixfile.html"} {"title": "3.25 pprint -- Data pretty printer", "text": "module-codeop.html | python.html | node90.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.24 codeop (module-codeop.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.25.1 PrettyPrinter Objects (node90.html)\n---\n# 3.25 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.3", "length": 1392, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-pprint.html"} {"title": "10.5 Reference Manual", "text": "node385.html | profile.html | profile-stats.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.4 What Is Deterministic (node385.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.5.1 The Stats Class (profile-stats.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.3", "length": 916, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.10 tty (module-tty.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.12 fcntl (module-fcntl.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.3", "length": 737, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.1.2 Module Contents (posix-contents.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.3 grp (module-grp.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 a tuple-like object, whose\nattributes correspond to the members of the `passwd` structure\n(Attribute field below, see ``):\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.3", "length": 1149, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.6 tabnanny (module-tabnanny.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.7.1 Class Descriptor Objects (pyclbr-class-objects.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.3", "length": 852, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.7.1 Class Descriptor Objects (pyclbr-class-objects.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.9 compileall (module-compileall.html)\n---\n# 18.8 py_compile --\nCompile Python source files\nThe py_compile module provides a function to generate a\nbyte-code file from a source file, and another function used when the\nmodule source file is invoked as a script.\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.\nWhen this module is run as a script, the main() is used to\ncompile all the files named on the command line.", "python_version": "2.3", "length": 866, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5. Miscellaneous Services (misc.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.2 doctest (module-doctest.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.3", "length": 2310, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-pydoc.html"} {"title": "7.8 Queue -- A synchronized queue class", "text": "module-dummythreading.html | someos.html | QueueObjects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.7 dummy_threading (module-dummythreading.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.8.1 Queue Objects (QueueObjects.html)\n---\n# 7.8 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.\nSee Also:\nThe Queue module defines the following class and exception:", "python_version": "2.3", "length": 729, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.14.1 Notes (binhex-notes.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.16 uu (module-uu.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.3", "length": 858, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-quopri.html"} {"title": "5.7 random -- Generate pseudo-random numbers", "text": "module-cmath.html | misc.html | module-whrandom.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.6 cmath (module-cmath.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.8 whrandom (module-whrandom.html)\n---\n# 5.7 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, a function to\ngenerate a random permutation of a list in-place, and a function for\nrandom sampling without replacement.\nOn the real line, there are functions to compute uniform, normal (Gaussian),\nlognormal, negative exponential, gamma, and beta distributions.\nFor generating distributions of angles, the von Mises distribution\nis 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 Mersenne Twister as\nthe core generator. It produces 53-bit precision floats and has a\nperiod of 2**19937-1. The underlying implementation in C\nis both fast and threadsafe. The Mersenne Twister is one of the most\nextensively tested random number generators in existence. However, being\ncompletely deterministic, it is not suitable for all purposes, and is\ncompletely unsuitable for cryptographic purposes.\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.\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.\nAs an example of subclassing, the random module provides\nthe WichmannHill class which implements an alternative generator\nin pure Python. The class provides a backward compatible way to\nreproduce results from earlier versions of Python which used the\nWichmann-Hill algorithm as the core generator.\nChanged in version 2.3:\nSubstituted MersenneTwister for Wichmann-Hill.\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.\nAlternative Generator", "python_version": "2.3", "length": 2742, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.1 string (module-string.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.2.1 Regular Expression Syntax (re-syntax.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.\nSee Also:", "python_version": "2.3", "length": 1520, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-re.html"} {"title": "7.20 readline -- GNU readline interface", "text": "tar-examples.html | someos.html | readline-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.19.3 Examples (tar-examples.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.20.1 Example (readline-example.html)\n---\n# 7.20 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.3", "length": 611, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-readline.html"} {"title": "3.26 repr -- Alternate repr() implementation", "text": "node90.html | python.html | Repr-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.25.1 PrettyPrinter Objects (node90.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.26.1 Repr Objects (Repr-objects.html)\n---\n# 3.26 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.3", "length": 575, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-repr.html"} {"title": "8.15 resource -- Resource usage information", "text": "module-posixfile.html | unix.html | node373.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n8.14 posixfile (module-posixfile.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.15.1 Resource Limits (node373.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.3", "length": 628, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n17. Restricted Execution (restricted.html)\nUp:\n17. Restricted Execution (restricted.html)\nNext:\n17.1.1 RExec Objects (rexec-objects.html)\n---\n# 17.1 rexec --\nRestricted execution framework\nChanged in version 2.3:\nDisabled module.\nWarning:\nThe documentation has been left in place to help in reading old code\nthat uses the module.\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.\nWarning:\nWhile the rexec module is designed to perform as described\nbelow, it does have a few known vulnerabilities which could be\nexploited by carefully written code. Thus it should not be relied\nupon in situations requiring ``production ready'' security. In such\nsituations, execution via sub-processes or very careful\n``cleansing'' of both code and data to be processed may be\nnecessary. Alternatively, help in patching known rexec\nvulnerabilities would be welcomed.\nNote:\nThe RExec class can prevent code from performing unsafe\noperations 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.3", "length": 2151, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.10.2 MultiFile Example (multifile-example.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.11.1 Message Objects (message-objects.html)\n---\n# 12.11 rfc822 --\nParse RFC 2822 mail headers\nDeprecated since release 2.3.\nThe email (module-email.html) package should be used in\npreference to the rfc822 module. This\nmodule is present only to maintain backward\ncompatibility.\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.5 (#foot52371) 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\n...2822.12.5 (module-rfc822.html#tex2html127): This module originally conformed to RFC 822 (http://www.faqs.org/rfcs/rfc822.html),\nhence the name. Since then, RFC 2822 (http://www.faqs.org/rfcs/rfc2822.html) has been released as an\nupdate to RFC 822 (http://www.faqs.org/rfcs/rfc822.html). This module should be considered\nRFC 2822 (http://www.faqs.org/rfcs/rfc2822.html)-conformant, especially in cases where the\nsyntax or semantics have changed since RFC 822 (http://www.faqs.org/rfcs/rfc822.html).", "python_version": "2.3", "length": 1683, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.7 colorsys (module-colorsys.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.9 imghdr (module-imghdr.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.3", "length": 752, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-rgbimg.html"} {"title": "7.21 rlcompleter -- Completion function for GNU readline", "text": "readline-example.html | someos.html | completer-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.20.1 Example (readline-example.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.21.1 Completer Objects (completer-objects.html)\n---\n# 7.21 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.3", "length": 1386, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-rlcompleter.html"} {"title": "12.19 robotparser -- Parser for robots.txt", "text": "netrc-objects.html | netdata.html | module-csv.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.18.1 netrc Objects (netrc-objects.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.20 csv (module-csv.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://www.robotstxt.org/wc/norobots.html.\nThe following example demonstrates basic use of the RobotFileParser class.", "python_version": "2.3", "length": 676, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n15.4 mpz (module-mpz.html)\nUp:\n15. Cryptographic Services (crypto.html)\nNext:\n16. Graphical User Interfaces (tkinter.html)\n---\n# 15.5 rotor --\nEnigma-like encryption and decryption\nDeprecated since release 2.3.\nThe encryption algorithm is insecure.\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.3", "length": 3217, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-rotor.html"} {"title": "6.11 sched -- Event scheduler", "text": "module-time.html | allos.html | scheduler-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.10 time (module-time.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.11.1 Scheduler Objects (scheduler-objects.html)\n---\n# 6.11 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.3", "length": 811, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-sched.html"} {"title": "16.3 ScrolledText -- Scrolled Text Widget", "text": "node658.html | tkinter.html | module-turtle.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.3 Tix Commands (node658.html)\nUp:\n16. Graphical User Interfaces (tkinter.html)\nNext:\n16.4 turtle (module-turtle.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.3", "length": 995, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.2.3 Example (socket-example.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.3.1 Polling Objects (poll-objects.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.3", "length": 706, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-select.html"} {"title": "5.12 sets -- Unordered collections of unique elements", "text": "module-array.html | misc.html | set-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.11 array (module-array.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.12.1 Set Objects (set-objects.html)\n---\n# 5.12 sets --\nUnordered collections of unique elements\nNew in version 2.3.\nThe sets module provides classes for constructing and manipulating\nunordered collections of unique elements. Common uses include membership\ntesting, removing duplicates from a sequence, and computing standard math\noperations on sets such as intersection, union, difference, and symmetric\ndifference.\nLike other collections, sets support `x in set`,\n`len( set )`, and `for x in set`. Being an\nunordered collection, sets do not record element position or order of\ninsertion. Accordingly, sets do not support indexing, slicing, or\nother sequence-like behavior.\nMost set applications use the Set class which provides every set\nmethod except for __hash__(). For advanced applications requiring\na hash method, the ImmutableSet class adds a __hash__()\nmethod but omits methods which alter the contents of the set. Both\nSet and ImmutableSet derive from BaseSet, an\nabstract class useful for determining whether something is a set:\n`isinstance( obj , BaseSet)`.\nThe set classes are implemented using dictionaries. As a result, sets\ncannot contain mutable elements such as lists or dictionaries.\nHowever, they can contain immutable collections such as tuples or\ninstances of ImmutableSet. For convenience in implementing\nsets of sets, inner sets are automatically converted to immutable\nform, for example, `Set([Set(['dog'])])` is transformed to\n`Set([ImmutableSet(['dog'])])`.", "python_version": "2.3", "length": 1698, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-sets.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\nPrevious:\n13.1.1 Example HTML Parser (htmlparser-example.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.3 htmllib (module-htmllib.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.3", "length": 1139, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n15.2 md5 (module-md5.html)\nUp:\n15. Cryptographic Services (crypto.html)\nNext:\n15.4 mpz (module-mpz.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.3", "length": 858, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-sha.html"} {"title": "3.17 shelve -- Python object persistence", "text": "module-copyreg.html | python.html | node74.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.16 copy_reg (module-copyreg.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.17.1 Restrictions (node74.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.\nShelve objects support all methods supported by dictionaries. This eases\nthe transition from dictionary based scripts to those requiring persistent\nstorage.", "python_version": "2.3", "length": 846, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-shelve.html"} {"title": "5.19 shlex -- Simple lexical analysis", "text": "Cmd-objects.html | misc.html | node180.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.18.1 Cmd Objects (Cmd-objects.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.19.1 Module Contents (node180.html)\n---\n# 5.19 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) or for parsing quoted strings.\nSee Also:", "python_version": "2.3", "length": 576, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-shlex.html"} {"title": "6.25 shutil -- High-level file operations", "text": "module-fnmatch.html | allos.html | shutil-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.24 fnmatch (module-fnmatch.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.25.1 Example (shutil-example.html)\n---\n# 6.25 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.3", "length": 660, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-shutil.html"} {"title": "7.1 signal -- Set handlers for asynchronous events", "text": "someos.html | someos.html | node304.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7. Optional Operating System (someos.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.1.1 Example (node304.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.3", "length": 2572, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.16 BaseHTTPServer (module-BaseHTTPServer.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.18 CGIHTTPServer (module-CGIHTTPServer.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.3", "length": 724, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.20.8 Example of Client (xmlrpc-client-example.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.21.1 SimpleXMLRPCServer Objects (simple-xmlrpc-servers.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. Servers can either\nbe free standing, using SimpleXMLRPCServer, or embedded in a\nCGI environment, using CGIXMLRPCRequestHandler.", "python_version": "2.3", "length": 614, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-SimpleXMLRPCServer.html"} {"title": "3.28 site -- Site-specific configuration hook", "text": "module-new.html | python.html | module-user.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.27 new (module-new.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.29 user (module-user.html)\n---\n# 3.28 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.3/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 it to `sys.path` and also inspects the newly added\npath for configuration 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.3 library is then\ninstalled in /usr/local/lib/python2.3 (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.3/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/python2.3/site-packages/bar\n/usr/local/lib/python2.3/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.3", "length": 2780, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.11.1 NNTP Objects (nntp-objects.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.12.1 SMTP Objects (SMTP-objects.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.3", "length": 736, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-smtplib.html"} {"title": "14.10 sndhdr -- Determine type of sound file", "text": "module-imghdr.html | mmedia.html | module-ossaudiodev.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n14.9 imghdr (module-imghdr.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.11 ossaudiodev (module-ossaudiodev.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.3", "length": 1200, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-sndhdr.html"} {"title": "7.2 socket -- Low-level networking interface", "text": "node304.html | someos.html | socket-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.1.1 Example (node304.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.2.1 Socket Objects (socket-objects.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 object whose 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\nsetblocking(). A generalization of this based on timeouts\nis supported through settimeout().\nThe module socket exports the following constants and functions:\nSee Also:", "python_version": "2.3", "length": 3800, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.14 urlparse (module-urlparse.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.16 BaseHTTPServer (module-BaseHTTPServer.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.\nWhen inheriting from ThreadingMixIn for threaded connection\nbehavior, you should explicitly declare how you want your threads\nto behave on an abrupt shutdown. The ThreadingMixIn class\ndefines an attribute daemon_threads, which indicates whether\nor not the server should wait for thread termination. You should\nset the flag explicitly if you would like threads to behave\nautonomously; the default is False, meaning that Python\nwill not exit until all threads created by ThreadingMixIn have\nexited.\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.3", "length": 2936, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.3 dircache (module-dircache.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.5 statcache (module-statcache.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.3", "length": 1835, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.4 stat (module-stat.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.6 statvfs (module-statvfs.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.3", "length": 804, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.5 statcache (module-statcache.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.7 filecmp (module-filecmp.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.3", "length": 623, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4. String Services (strings.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.2 re (module-re.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.3", "length": 764, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.5 fpformat (module-fpformat.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.7 cStringIO (module-cStringIO.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.3", "length": 616, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-StringIO.html"} {"title": "4.11 stringprep -- Internet String Preparation", "text": "module-unicodedata.html | strings.html | misc.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.10 unicodedata (module-unicodedata.html)\nUp:\n4. String Services (strings.html)\nNext:\n5. Miscellaneous Services (misc.html)\n---\n# 4.11 stringprep --\nInternet String Preparation\nWhen identifying things (such as host names) in the internet, it is\noften necessary to compare such identifications for\n``equality''. Exactly how this comparison is executed may depend on\nthe application domain, e.g. whether it should be case-insensitive or\nnot. It may be also necessary to restrict the possible\nidentifications, to allow only identifications consisting of\n``printable'' characters.\nRFC 3454 (http://www.faqs.org/rfcs/rfc3454.html) defines a procedure for ``preparing'' Unicode strings in\ninternet protocols. Before passing strings onto the wire, they are\nprocessed with the preparation procedure, after which they have a\ncertain normalized form. The RFC defines a set of tables, which can be\ncombined into profiles. Each profile must define which tables it uses,\nand what other optional parts of the `stringprep` procedure are\npart of the profile. One example of a `stringprep` profile is\n`nameprep`, which is used for internationalized domain names.\nThe module stringprep only exposes the tables from RFC\n3454. As these tables would be very large to represent them as\ndictionaries or lists, the module uses the Unicode character database\ninternally. The module source code itself was generated using the\n`mkstringprep.py` utility.\nAs a result, these tables are exposed as functions, not as data\nstructures. There are two kinds of tables in the RFC: sets and\nmappings. For a set, stringprep provides the ``characteristic\nfunction'', i.e. a function that returns true if the parameter is part\nof the set. For mappings, it provides the mapping function: given the\nkey, it returns the associated value. Below is a list of all functions\navailable in the module.", "python_version": "2.3", "length": 1989, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-stringprep.html"} {"title": "4.3 struct -- Interpret strings as packed binary data", "text": "node108.html | strings.html | module-difflib.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.2.6 Examples (node108.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.4 difflib (module-difflib.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.3", "length": 5501, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.3 aifc (module-aifc.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.4.1 AU_read Objects (au-read-objects.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.3", "length": 878, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-sunau.html"} {"title": "21.2 SUNAUDIODEV -- Constants used with sunaudiodev", "text": "audio-device-objects.html | sunos.html | node735.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n21.1.1 Audio Device Objects (audio-device-objects.html)\nUp:\n21. SunOS Specific Services (sunos.html)\nNext:\n22. MS Windows Specific (node735.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.3", "length": 646, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n21. SunOS Specific Services (sunos.html)\nUp:\n21. SunOS Specific Services (sunos.html)\nNext:\n21.1.1 Audio Device Objects (audio-device-objects.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.3", "length": 779, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-sunaudiodev.html"} {"title": "18.2 symbol -- Constants used with Python parse trees", "text": "node689.html | language.html | module-token.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.6.2 Information Discovery (node689.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.3 token (module-token.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.3", "length": 761, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3. Python Runtime Services (python.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.2 gc (module-gc.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.3", "length": 471, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.16 nis (module-nis.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.18 commands (module-commands.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.3", "length": 562, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.5 tokenize (module-tokenize.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.7 pyclbr (module-pyclbr.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.3", "length": 614, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-tabnanny.html"} {"title": "7.19 tarfile -- Read and write tar archive files", "text": "zipinfo-objects.html | someos.html | tarfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.18.3 ZipInfo Objects (zipinfo-objects.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.19.1 TarFile Objects (tarfile-objects.html)\n---\n# 7.19 tarfile -- Read and write tar archive files\nNew in version 2.3.\nThe tarfile module makes it possible to read and create tar archives.\nSome facts and figures:\n- reads and writes gzip and bzip2 compressed archives.\n- creates POSIX 1003.1-1990 compliant or GNU tar compatible archives.\n- reads GNU tar extensions longname, longlink and\nsparse.\n- stores pathnames of unlimited length using GNU tar extensions.\n- handles directories, regular files, hardlinks, symbolic links, fifos,\ncharacter devices and block devices and is able to acquire and\nrestore file information like timestamp, access permissions and owner.\n- can handle tape devices.\nSee Also:", "python_version": "2.3", "length": 947, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-tarfile.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\nPrevious:\n11.12.2 SMTP Example (SMTP-example.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.13.1 Telnet Objects (telnet-objects.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 (see below), 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.\nThe symbolic constants for the telnet commands are: IAC, DONT, DO,\nWONT, WILL, SE (Subnegotiation End), NOP (No Operation), DM (Data\nMark), BRK (Break), IP (Interrupt process), AO (Abort output), AYT\n(Are You There), EC (Erase Character), EL (Erase Line), GA (Go Ahead),\nSB (Subnegotiation Begin).\nSee Also:", "python_version": "2.3", "length": 1141, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-telnetlib.html"} {"title": "6.21 tempfile -- Generate temporary files and directories", "text": "optparse-extending-examples.html | allos.html | module-errno.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.5.4 Examples (optparse-extending-examples.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.22 errno (module-errno.html)\n---\n# 6.21 tempfile --\nGenerate temporary files and directories\nThis module generates temporary files and directories. It works on\nall supported platforms.\nIn version 2.3 of Python, this module was overhauled for enhanced\nsecurity. It now provides three new functions,\nNamedTemporaryFile(), mkstemp(), and\nmkdtemp(), which should eliminate all remaining need to use\nthe insecure mktemp() function. Temporary file names created\nby this module no longer contain the process ID; instead a string of\nsix random characters is used.\nAlso, all the user-callable functions now take additional arguments\nwhich allow direct control over the location and name of temporary\nfiles. It is no longer necessary to use the global tempdir and\ntemplate variables. To maintain backward compatibility, the\nargument order is somewhat odd; it is recommended to use keyword\narguments for clarity.\nThe module defines the following user-callable functions:\nThe module uses two global variables that tell it how to construct a\ntemporary name. They are initialized at the first call to any of the\nfunctions above. The caller may change them, but this is discouraged;\nuse the appropriate function arguments, instead.", "python_version": "2.3", "length": 1473, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-tempfile.html"} {"title": "8.8 termios -- POSIX style tty control", "text": "module-gdbm.html | unix.html | node364.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n8.7 gdbm (module-gdbm.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.8.1 Example (node364.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.3", "length": 1111, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-termios.html"} {"title": "8.9 TERMIOS -- Constants used with the termios module", "text": "node364.html | unix.html | module-tty.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n8.8.1 Example (node364.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.10 tty (module-tty.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.3", "length": 409, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-TERMIOSuppercase.html"} {"title": "5.4 test -- Regression tests package for Python", "text": "unittest-error-info.html | misc.html | module-test.testsupport.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.9 Getting Extended Error (unittest-error-info.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.4.1 [test.testsupport]test.test_support (module-test.testsupport.html)\n---\n# 5.4 test --\nRegression tests package for Python\nThe test package contains all regression tests for Python as well as\nthe modules test_support and regrtest.py.\ntest_support is used to enhance your tests while regrtest.py\ndrives the testing suite.\nEach module in the test package whose name starts with\n`'test_'` is a testing suite for a specific module or feature.\nAll new tests should be written using the unittest module; using\nunittest is not required but makes the tests more flexible and\nmaintenance of the tests easier.\nSome older tests are written to use doctest and a ``traditional''\ntesting style; these styles of tests will not be covered.\nSee Also:", "python_version": "2.3", "length": 994, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-test.html"} {"title": "5.4.1 [test.testsupport]test.test_support -- -- Utility functions for tests", "text": "module-test.html | module-test.html | writing-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.4 test (module-test.html)\nUp:\n5.4 test (module-test.html)\nNext:\n5.4.2 Writing Unit Tests (writing-tests.html)\n---\n## 5.4.1 [test.testsupport]test.test_support --\n-- Utility functions for tests\nThe test.test_support module contains functions for assisting\nwith writing regression tests.\nThe test.test_support module defines the following exceptions:\nThe test_support module defines the following constants:\nThe test_support module defines the following functions:", "python_version": "2.3", "length": 606, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-test.testsupport.html"} {"title": "4.8 textwrap -- Text wrapping and filling", "text": "module-cStringIO.html | strings.html | module-codecs.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.7 cStringIO (module-cStringIO.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.9 codecs (module-codecs.html)\n---\n# 4.8 textwrap --\nText wrapping and filling\nNew in version 2.3.\nThe textwrap module provides two convenience functions,\nwrap() and fill(), as well as\nTextWrapper, the class that does all the work, and a utility function\ndedent(). If you're just wrapping or filling one or two\ntext strings, the convenience functions should be good enough; otherwise,\nyou should use an instance of TextWrapper for efficiency.\nBoth wrap() and fill() work by creating a\nTextWrapper instance and calling a single method on it. That\ninstance is not reused, so for applications that wrap/fill many text\nstrings, it will be more efficient for you to create your own\nTextWrapper object.\nAn additional utility function, dedent(), is provided to\nremove indentation from strings that have unwanted whitespace to the\nleft of the text.\nThe TextWrapper instance attributes (and keyword arguments to\nthe constructor) are as follows:\nTextWrapper also provides two public methods, analogous to the\nmodule-level convenience functions:", "python_version": "2.3", "length": 1260, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-textwrap.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\nPrevious:\n7.3.1 Polling Objects (poll-objects.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.5 threading (module-threading.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, Linux, SGI\nIRIX, Solaris 2.x, as well as on systems that have a POSIX thread\n(a.k.a. ``pthread'') implementation. For systems lacking the thread\nmodule, the dummy_thread (module-dummythread.html) module is available.\nIt duplicates this module's interface and can be\nused as a drop-in replacement.\nIt defines the following constant and functions:\nLock objects have the following methods:\nCaveats:", "python_version": "2.3", "length": 1036, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.4 thread (module-thread.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.5.1 Lock Objects (lock-objects.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.\nThe dummy_threading (module-dummythreading.html) module is provided for\nsituations where threading cannot be used because\nthread (module-thread.html) is missing.\nThis module defines 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.3", "length": 1279, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-threading.html"} {"title": "6.10 time -- Time access and conversions", "text": "node208.html | allos.html | module-sched.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9.7 strftime() Behavior (node208.html)\nUp:\n6. Generic Operating System (allos.html)\nNext:\n6.11 sched (module-sched.html)\n---\n# 6.10 time --\nTime access and conversions\nThis module provides various time-related functions. It is always\navailable, but not all functions are available on all platforms. Most\nof the functions defined in this module call platform C library\nfunctions with the same name. It may sometimes be helpful to consult\nthe platform documentation, because the semantics of these functions\nvaries among 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 struct_time\n(see below) generally require a 4-digit year. For backward\ncompatibility, 2-digit years are supported if the module variable\n`accept2dyear` is a non-zero integer; this variable is\ninitialized to `1` unless the environment variable\nPYTHONY2K is set to a non-empty string, in which case it is\ninitialized 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 value as returned by gmtime(),\nlocaltime(), and strptime(), and accepted by\nasctime(), mktime() and strftime(),\nis a sequence of 9 integers. The return values of gmtime(),\nlocaltime(), and strptime() also offer attribute\nnames for individual fields.\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 the\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 struct_time, or having elements of the wrong type, a\nTypeError is raised.\nChanged in version 2.2:\nThe time value sequence was changed from a tuple to a\nstruct_time, with the addition of attribute names\nfor the fields.\nThe module defines the following functions and data items:", "python_version": "2.3", "length": 4185, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-time.html"} {"title": "10.10 timeit -- Measure execution time of small code snippets", "text": "hotshot-example.html | profile.html | node396.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.9.3 Example Usage (hotshot-example.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.10.1 Command Line Interface (node396.html)\n---\n# 10.10 timeit --\nMeasure execution time of small code snippets\nNew in version 2.3.\nThis module provides a simple way to time small bits of Python code.\nIt has both command line as well as callable interfaces. It avoids a\nnumber of common traps for measuring execution times. See also Tim\nPeters' introduction to the ``Algorithms'' chapter in the\nPython Cookbook, published by O'Reilly.\nThe module defines the following public class:", "python_version": "2.3", "length": 712, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-timeit.html"} {"title": "16.2 Tix -- Extension widgets for Tk", "text": "node646.html | tkinter.html | node648.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.9 Images (node646.html)\nUp:\n16. Graphical User Interfaces (tkinter.html)\nNext:\n16.2.1 Using Tix (node648.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.3", "length": 1093, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-Tix.html"} {"title": "16.1 Tkinter -- Python interface to Tcl/Tk", "text": "tkinter.html | tkinter.html | node630.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16. Graphical User Interfaces (tkinter.html)\nUp:\n16. Graphical User Interfaces (tkinter.html)\nNext:\n16.1.1 Tkinter Modules (node630.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. Both Tk and Tkinter are\navailable on most Unix platforms, as well as on Windows and\nMacintosh systems. (Tk itself is not part of Python; it is maintained\nat ActiveState.)\nSee Also:", "python_version": "2.3", "length": 589, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.2 symbol (module-symbol.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.4 keyword (module-keyword.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.3", "length": 786, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.4 keyword (module-keyword.html)\nUp:\n18. Python Language Services (language.html)\nNext:\n18.6 tabnanny (module-tabnanny.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.3", "length": 871, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.11.4 The interpreter stack (inspect-stack.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.12.1 Traceback Example (traceback-example.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, such as in a\n``wrapper'' around the interpreter.\nThe module uses traceback objects -- this is the object type that is\nstored in the variables `sys.exc_traceback` (deprecated) and\n`sys.last_traceback` and returned as the third item from\nsys.exc_info().\nThe module defines the following functions:", "python_version": "2.3", "length": 914, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.9 TERMIOS (module-TERMIOSuppercase.html)\nUp:\n8. Unix Specific Services (unix.html)\nNext:\n8.11 pty (module-pty.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.3", "length": 543, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n16.3 ScrolledText (module-ScrolledText.html)\nUp:\n16. Graphical User Interfaces (tkinter.html)\nNext:\n16.4.1 Pen and RawPen (pen-rawpen-objects.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.3", "length": 1019, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-turtle.html"} {"title": "3.6 types -- Names for built-in types", "text": "atexit-example.html | python.html | module-UserDict.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.5.1 atexit Example (atexit-example.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.7 UserDict (module-UserDict.html)\n---\n# 3.6 types --\nNames for built-in types\nThis module defines names for some object types that are used by\nthe standard Python interpreter, but not for the types defined by various\nextension modules. Also, it does not include some of the types that\narise during processing such the `listiterator` type.\nIt 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(mylist, item):\nif type(item) is IntType:\ndel mylist[item]\nelse:\nmylist.remove(item)\n```\nStarting in Python 2.2, built-in factory functions such as\nint() and str() are also names for the\ncorresponding types. This is now the preferred way to access\nthe type instead of using the types module. Accordingly,\nthe example above should be written as follows:\n```text\n\ndef delete(mylist, item):\nif isinstance(item, int):\ndel mylist[item]\nelse:\nmylist.remove(item)\n```\nThe module defines the following names:", "python_version": "2.3", "length": 1412, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-types.html"} {"title": "4.10 unicodedata -- Unicode Database", "text": "module-encodings.idna.html | strings.html | module-stringprep.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.3 encodings.idna (module-encodings.idna.html)\nUp:\n4. String Services (strings.html)\nNext:\n4.11 stringprep (module-stringprep.html)\n---\n# 4.10 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.2.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.2.0 (see\nhttp://www.unicode.org/Public/UNIDATA/UnicodeData.html). It\ndefines the following functions:\nIn addition, the module exposes the following constant:", "python_version": "2.3", "length": 835, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-unicodedata.html"} {"title": "5.3 unittest -- Unit testing framework", "text": "node140.html | misc.html | minimal-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.8 Soapbox (node140.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.3.1 Minimal example (minimal-example.html)\n---\n# 5.3 unittest --\nUnit testing framework\nNew in version 2.1.\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 latter 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.3", "length": 2469, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.3 cgitb (module-cgitb.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.4.1 URLopener Objects (urlopener-objs.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:\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\nHTTP protocol provides type information in the\nreply header, which can be inspected by looking at the\nContent-Type: header. For the\nGopher protocol, 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.3", "length": 2323, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-urllib.html"} {"title": "11.5 urllib2 -- extensible library for opening URLs", "text": "node415.html | internet.html | request-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.4.2 Examples (node415.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.5.1 Request Objects (request-objects.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.3", "length": 632, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.13.2 Telnet Example (telnet-example.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.15 SocketServer (module-SocketServer.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.3", "length": 797, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-urlparse.html"} {"title": "3.29 user -- User-specific configuration hook", "text": "module-site.html | python.html | module-builtin.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.28 site (module-site.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.30 __builtin__ (module-builtin.html)\n---\n# 3.29 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.3", "length": 2415, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.6 types (module-types.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.8 UserList (module-UserList.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 dict 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 module also defines a mixin defining all dictionary methods for\nclasses that already have a minimum mapping interface. This greatly\nsimplifies writing classes that need to be substitutable for\ndictionaries (such as the shelve module).\nThe UserDict module defines the UserDict class\nand DictMixin:\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.3", "length": 1289, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.7 UserDict (module-UserDict.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.9 UserString (module-UserString.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.3", "length": 1901, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.8 UserList (module-UserList.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.10 operator (module-operator.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.3", "length": 1337, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.15 quopri (module-quopri.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.17 xdrlib (module-xdrlib.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.\nThis code was contributed by Lance Ellinghouse, and modified by Jack\nJansen.\nThe uu module defines the following functions:", "python_version": "2.3", "length": 1028, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.19 marshal (module-marshal.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.20.1 Warning Categories (warning-categories.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.3", "length": 2004, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.4.2 AU_write Objects (au-write-objects.html)\nUp:\n14. Multimedia Services (mmedia.html)\nNext:\n14.5.1 Wave_read Objects (Wave-read-objects.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.3", "length": 550, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.2 gc (module-gc.html)\nUp:\n3. Python Runtime Services (python.html)\nNext:\n3.3.1 Weak Reference Objects (weakref-objects.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 can\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.3", "length": 916, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11. Internet Protocols and (internet.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.1.1 Browser Controller Objects (browser-controllers.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.3", "length": 2470, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-webbrowser.html"} {"title": "7.12 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\nPrevious:\n7.11.1 Database Objects (dbhash-objects.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.13 bsddb (module-bsddb.html)\n---\n# 7.12 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.3", "length": 556, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-whichdb.html"} {"title": "5.8 whrandom -- Pseudo-random number generator", "text": "module-random.html | misc.html | module-bisect.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.7 random (module-random.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.9 bisect (module-bisect.html)\n---\n# 5.8 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.3", "length": 1289, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-whrandom.html"} {"title": "22.3 winsound -- Sound-playing interface for Windows", "text": "handle-object.html | node735.html | undoc.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n22.2.1 Registry Handle Objects (handle-object.html)\nUp:\n22. MS Windows Specific (node735.html)\nNext:\nA. Undocumented Modules (undoc.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.3", "length": 526, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.16 uu (module-uu.html)\nUp:\n12. Internet Data Handling (netdata.html)\nNext:\n12.17.1 Packer Objects (xdr-packer-objects.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.3", "length": 742, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-xdrlib.html"} {"title": "13.6 xml.dom -- The Document Object Model API", "text": "expat-errors.html | markup.html | node564.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.5.5 Expat error constants (expat-errors.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.6.1 Module Contents (node564.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. The mapping of\nthe Level 3 specification, currently only available in draft form, is\nbeing developed by the Python XML Special Interest\nGroup (http://www.python.org/sigs/xml-sig/) as part of the\nPyXML package (http://pyxml.sourceforge.net/). Refer to the\ndocumentation bundled with that package for information on the current\nstate of DOM Level 3 support.\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 no way to access an XML\nreader/parser/Document builder in an implementation-independent way.\nThere is also no well-defined way to access these methods without an\nexisting Document object. In Python, each DOM implementation\nwill provide a function getDOMImplementation(). DOM Level 3\nadds a Load/Store specification, which defines an interface to the\nreader, but this is not yet available in the Python standard library.\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.3", "length": 3448, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.6.3.2 Accessor Methods (dom-accessor-methods.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.7.1 DOM Objects (dom-objects.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\nfile 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.\nWhat the parse() and parseString() functions do\nis connect an XML parser with a ``DOM builder'' that can accept parse\nevents from any SAX parser and convert them into a DOM tree. The name\nof the functions are perhaps misleading, but are easy to grasp when\nlearning the interfaces. The parsing of the document will be\ncompleted before these functions return; it's simply that these\nfunctions do not provide a parser implementation themselves.\nYou can also create a Document by calling a method on a ``DOM\nImplementation'' object. You can get this object either by calling\nthe getDOMImplementation() function in the\nxml.dom (module-xml.dom.html) package or the xml.dom.minidom module.\nUsing the implementation from the xml.dom.minidom module will\nalways return a Document instance from the minidom\nimplementation, while the version from xml.dom (module-xml.dom.html) may provide\nan alternate implementation (this is likely if you have the\nPyXML package (http://pyxml.sourceforge.net/) installed). Once\nyou have a Document, you can add child nodes to it to populate\nthe DOM:\n```text\n\nfrom xml.dom.minidom import getDOMImplementation\n\nimpl = getDOMImplementation()\n\nnewdoc = impl.createDocument(None, \"some_tag\", None)\ntop_element = newdoc.documentElement\ntext = newdoc.createTextNode('Some textual content.')\ntop_element.appendChild(text)\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.3", "length": 3591, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.7.3 minidom and the (minidom-and-dom.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.8.1 DOMEventStream Objects (domeventstream-objects.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.3", "length": 529, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.4 htmlentitydefs (module-htmlentitydefs.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.5.1 XMLParser Objects (xmlparser-objects.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:\nSee Also:", "python_version": "2.3", "length": 1072, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.9.1 SAXException Objects (sax-exception-objects.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.10.1 ContentHandler Objects (content-handler-objects.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.3", "length": 955, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.8.1 DOMEventStream Objects (domeventstream-objects.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.9.1 SAXException Objects (sax-exception-objects.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,\nAttributes, AttributesNS, 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.3", "length": 2182, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.10.4 ErrorHandler Objects (sax-error-handler.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.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.3", "length": 556, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.11 xml.sax.saxutils (module-xml.sax.saxutils.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.12.1 XMLReader Objects (xmlreader-objects.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.3", "length": 627, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-xml.sax.xmlreader.html"} {"title": "13.13 xmllib -- A parser for XML documents", "text": "attributes-ns-objects.html | markup.html | xml-namespace.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.12.6 The AttributesNS Interface (attributes-ns-objects.html)\nUp:\n13. Structured Markup Processing (markup.html)\nNext:\n13.13.1 XML Namespaces (xml-namespace.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\n...\narguments.13.1 (module-xmllib.html#tex2html149): Actually, a number of keyword arguments are\nrecognized which influence the parser to accept certain non-standard\nconstructs. The following keyword arguments are currently\nrecognized. The defaults for all of these is `0` (false) except\nfor the last one for which the default is `1` (true).\naccept_unquoted_attributes (accept certain attribute values\nwithout requiring quotes), accept_missing_endtag_name (accept\nend tags that look like ``), map_case (map upper case to\nlower case in tags and attributes), accept_utf8 (allow UTF-8\ncharacters in input; this is required according to the XML standard,\nbut Python does not as yet deal properly with these characters, so\nthis is not the default), translate_attribute_references (don't\nattempt to translate character and entity references in attribute values).", "python_version": "2.3", "length": 1640, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-xmllib.html"} {"title": "11.20 xmlrpclib -- XML-RPC client access", "text": "cookie-example.html | internet.html | serverproxy-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.19.3 Example (cookie-example.html)\nUp:\n11. Internet Protocols and (internet.html)\nNext:\n11.20.1 ServerProxy Objects (serverproxy-objects.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.3", "length": 737, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-xmlrpclib.html"} {"title": "5.16 xreadlines -- Efficient iteration over a file", "text": "module-fileinput.html | misc.html | module-calendar.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.15 fileinput (module-fileinput.html)\nUp:\n5. Miscellaneous Services (misc.html)\nNext:\n5.17 calendar (module-calendar.html)\n---\n# 5.16 xreadlines --\nEfficient iteration over a file\nNew in version 2.1.\nDeprecated since release 2.3.\nUse `for line in file` instead.\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.3", "length": 1154, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-xreadlines.html"} {"title": "7.18 zipfile -- Work with ZIP archives", "text": "node339.html | someos.html | zipfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.17.3 One-shot (de)compression (node339.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.18.1 ZipFile Objects (zipfile-objects.html)\n---\n# 7.18 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.3", "length": 801, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/module-zipfile.html"} {"title": "7.15 zlib -- Compression compatible with gzip", "text": "dumbdbm-objects.html | someos.html | module-gzip.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.14.1 Dumbdbm Objects (dumbdbm-objects.html)\nUp:\n7. Optional Operating System (someos.html)\nNext:\n7.16 gzip (module-gzip.html)\n---\n# 7.15 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.3", "length": 913, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.19.1 Cookie Objects (cookie-objects.html)\nUp:\n11.19 Cookie (module-Cookie.html)\nNext:\n11.19.3 Example (cookie-example.html)\n---\n## 11.19.2 Morsel Objects", "python_version": "2.3", "length": 304, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n22.1.1 File Operations (msvcrt-files.html)\nUp:\n22.1 msvcrt - Useful (module-msvcrt.html)\nNext:\n22.1.3 Other Functions (msvcrt-other.html)\n---\n## 22.1.2 Console I/O", "python_version": "2.3", "length": 307, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n22.1 msvcrt - Useful (module-msvcrt.html)\nUp:\n22.1 msvcrt - Useful (module-msvcrt.html)\nNext:\n22.1.2 Console I/O (msvcrt-console.html)\n---\n## 22.1.1 File Operations", "python_version": "2.3", "length": 311, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n22.1.2 Console I/O (msvcrt-console.html)\nUp:\n22.1 msvcrt - Useful (module-msvcrt.html)\nNext:\n22.2 _winreg - Windows (module--winreg.html)\n---\n## 22.1.3 Other Functions", "python_version": "2.3", "length": 315, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.10.1 MultiFile Objects (MultiFile-objects.html)\nUp:\n12.10 multifile (module-multifile.html)\nNext:\n12.11 rfc822 (module-rfc822.html)\n---\n## 12.10.2 MultiFile Example", "python_version": "2.3", "length": 320, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.10 multifile (module-multifile.html)\nUp:\n12.10 multifile (module-multifile.html)\nNext:\n12.10.2 MultiFile Example (multifile-example.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.3", "length": 442, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/MultiFile-objects.html"} {"title": "6.12.1 Mutex Objects", "text": "module-mutex.html | module-mutex.html | module-getpass.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.12 mutex (module-mutex.html)\nUp:\n6.12 mutex (module-mutex.html)\nNext:\n6.13 getpass (module-getpass.html)\n---\n## 6.12.1 Mutex Objects\nmutex objects have following methods:", "python_version": "2.3", "length": 317, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/mutex-objects.html"} {"title": "12. Internet Data Handling", "text": "asynchat-example.html | lib.html | module-formatter.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.24.2 asynchat Example (asynchat-example.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n12.1 formatter (module-formatter.html)\n---\n# 12. Internet Data Handling\nThis chapter describes modules which support handling data formats\ncommonly used on the Internet.", "python_version": "2.3", "length": 406, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.18 netrc (module-netrc.html)\nUp:\n12.18 netrc (module-netrc.html)\nNext:\n12.19 robotparser (module-robotparser.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.3", "length": 390, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.11 nntplib (module-nntplib.html)\nUp:\n11.11 nntplib (module-nntplib.html)\nNext:\n11.12 smtplib (module-smtplib.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.3", "length": 589, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/nntp-objects.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\nPrevious:\n4.2.2 Matching vs Searching (matching-searching.html)\nUp:\n4.2 re (module-re.html)\nNext:\n4.2.4 Regular Expression Objects (re-objects.html)\n---\n## 4.2.3 Module Contents\nThe module defines the following functions and constants, and an exception:", "python_version": "2.3", "length": 387, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node105.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\nPrevious:\n4.2.5 Match Objects (match-objects.html)\nUp:\n4.2 re (module-re.html)\nNext:\n4.3 struct (module-struct.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```\nAvoiding recursion\nIf you create regular expressions that require the engine to perform a\nlot of recursion, you may encounter a RuntimeError exception with\nthe message `maximum recursion limit` exceeded. For example,\n```text\n\n>>> import re\n>>> s = 'Begin ' + 1000*'a very long string ' + 'end'\n>>> re.match('Begin (\\w| )*? end', s).end()\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nFile \"/usr/local/lib/python2.3/sre.py\", line 132, in match\nreturn _compile(pattern, flags).match(string)\nRuntimeError: maximum recursion limit exceeded\n```\nYou can often restructure your regular expression to avoid recursion.", "python_version": "2.3", "length": 1474, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node108.html"} {"title": "4.9.1 Codec Base Classes", "text": "module-codecs.html | module-codecs.html | codec-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9 codecs (module-codecs.html)\nUp:\n4.9 codecs (module-codecs.html)\nNext:\n4.9.1.1 Codec Objects (codec-objects.html)\n---\n## 4.9.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:\nThe set of allowed values can be extended via register_error.", "python_version": "2.3", "length": 1078, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node120.html"} {"title": "4.9.2 Standard Encodings", "text": "stream-recoder-objects.html | module-codecs.html | module-encodings.idna.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.1.5 StreamRecoder Objects (stream-recoder-objects.html)\nUp:\n4.9 codecs (module-codecs.html)\nNext:\n4.9.3 encodings.idna (module-encodings.idna.html)\n---\n## 4.9.2 Standard Encodings\nPython comes with a number of codecs builtin, either implemented as C\nfunctions, or with dictionaries as mapping tables. The following table\nlists the codecs by name, together with a few common aliases, and the\nlanguages for which the encoding is likely used. Neither the list of\naliases nor the list of languages is meant to be exhaustive. Notice\nthat spelling alternatives that only differ in case or use a hyphen\ninstead of an underscore are also valid aliases.\nMany of the character sets support the same languages. They vary in\nindividual characters (e.g. whether the EURO SIGN is supported or\nnot), and in the assignment of characters to code positions. For the\nEuropean languages in particular, the following variants typically\nexist:\n- an ISO 8859 codeset\n- a Microsoft Windows code page, which is typically derived from\na 8859 codeset, but replaces control characters with additional\ngraphic characters\n- an IBM EBCDIC code page\n- an IBM PC code page, which is ASCII compatible\nA number of codecs are specific to Python, so their codec names have\nno meaning outside Python. Some of them don't convert from Unicode\nstrings to byte strings, but instead use the property of the Python\ncodecs machinery that any bijective function with one argument can be\nconsidered as an encoding.\nFor the codecs listed below, the result in the ``encoding'' direction\nis always a byte string. The result of the ``decoding'' direction is\nlisted as operand type in the table.", "python_version": "2.3", "length": 1810, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node126.html"} {"title": "5.2.1 Normal Usage", "text": "module-doctest.html | module-doctest.html | node134.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2 doctest (module-doctest.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.2.2 Which Docstrings Are (node134.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```\nIf you want to test the module as the main module, you don't need to\npass M to testmod(); in this case, it will test the current\nmodule.\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 standard\noutput, along with assorted summaries at the end.\nYou can force verbose mode by passing `verbose=1` to\ntestmod(), 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.3", "length": 1467, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node133.html"} {"title": "5.2.2 Which Docstrings Are Examined?", "text": "node133.html | module-doctest.html | node135.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.1 Normal Usage (node133.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.2.3 What's the Execution (node135.html)\n---\n## 5.2.2 Which Docstrings Are Examined?\nSee the docstrings in doctest.py for all the details. They're\nunsurprising: the module docstring, and all function, class and method\ndocstrings are searched. Optionally, the tester can be directed to\nexclude docstrings attached to objects with private names. Objects\nimported 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 the tester has been\ndirected to skip over private names in the rest of the module.\nIn output, a 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 can be optionally skipped, all names reached from\n`M.__test__` are searched.", "python_version": "2.3", "length": 1263, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node134.html"} {"title": "5.2.3 What's the Execution Context?", "text": "node134.html | module-doctest.html | node136.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.2 Which Docstrings Are (node134.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.2.4 What About Exceptions? (node136.html)\n---\n## 5.2.3 What's the Execution Context?\nBy default, each time testmod() finds a docstring to test, it uses\na copy 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.3", "length": 909, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node135.html"} {"title": "5.2.4 What About Exceptions?", "text": "node135.html | module-doctest.html | node137.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.3 What's the Execution (node135.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.2.5 Advanced Usage (node137.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.3", "length": 781, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node136.html"} {"title": "5.2.5 Advanced Usage", "text": "node136.html | module-doctest.html | node138.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.4 What About Exceptions? (node136.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.2.6 How are Docstring (node138.html)\n---\n## 5.2.5 Advanced Usage\nSeveral module level functions are available for controlling how doctests\nare run.", "python_version": "2.3", "length": 372, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node137.html"} {"title": "5.2.6 How are Docstring Examples Recognized?", "text": "node137.html | module-doctest.html | node139.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.5 Advanced Usage (node137.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.2.7 Warnings (node139.html)\n---\n## 5.2.6 How are Docstring Examples Recognized?\nIn most cases a copy-and-paste of an interactive console session works\nfine--just make sure the leading whitespace is rigidly consistent\n(you can mix tabs and spaces if you're too lazy to do it right, but\ndoctest is not in the business of guessing what you think a tab\nmeans).\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.3", "length": 1796, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node138.html"} {"title": "5.2.7 Warnings", "text": "node138.html | module-doctest.html | node140.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.6 How are Docstring (node138.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.2.8 Soapbox (node140.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()\n```\n3. WYSIWYG isn't always the case, starting in Python 2.3. The\nstring form of boolean results changed from `'0'` and\n`'1'` to `'False'` and `'True'` in Python 2.3.\nThis makes it clumsy to write a doctest showing boolean results that\npasses under multiple versions of Python. In Python 2.3, by default,\nand as a special case, if an expected output block consists solely\nof `'0'` and the actual output block consists solely of\n`'False'`, that's accepted as an exact match, and similarly for\n`'1'` versus `'True'`. This behavior can be turned off by\npassing the new (in 2.3) module constant\nDONT_ACCEPT_TRUE_FOR_1 as the value of testmod()'s\nnew (in 2.3) optional optionflags argument. Some years after\nthe integer spellings of booleans are history, this hack will\nprobably be removed again.", "python_version": "2.3", "length": 2795, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node139.html"} {"title": "5.2.8 Soapbox", "text": "node139.html | module-doctest.html | module-unittest.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.2.7 Warnings (node139.html)\nUp:\n5.2 doctest (module-doctest.html)\nNext:\n5.3 unittest (module-unittest.html)\n---\n## 5.2.8 Soapbox\nThe first word in ``doctest'' is ``doc,'' and that's why the author\nwrote doctest (module-doctest.html): to keep documentation up to date. It so\nhappens that doctest (module-doctest.html) makes a pleasant unit testing\nenvironment, but that's not its primary purpose.\nChoose docstring examples with care. There's an art to this that\nneeds to be learned--it may not be natural at first. Examples should\nadd genuine value to the documentation. A good example can often be\nworth many words. If possible, show just a few normal cases, show\nendcases, show interesting subtle cases, and show an example of each\nkind of exception that can be raised. You're probably testing for\nendcases and subtle cases anyway in an interactive shell:\ndoctest (module-doctest.html) wants to make it as easy as possible to capture\nthose sessions, and will verify they continue to work as designed\nforever after.\nIf done with care, the examples will be invaluable for your users, and\nwill pay back the time it takes to collect them many times over as the\nyears go by and things change. I'm still amazed at how often one of\nmy doctest (module-doctest.html) examples stops working after a ``harmless''\nchange.", "python_version": "2.3", "length": 1455, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node140.html"} {"title": "5.10.1 Theory", "text": "module-heapq.html | module-heapq.html | module-array.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.10 heapq (module-heapq.html)\nUp:\n5.10 heapq (module-heapq.html)\nNext:\n5.11 array (module-array.html)\n---\n## 5.10.1 Theory\n(This explanation is due to François Pinard. The Python\ncode for this module was contributed by Kevin O'Connor.)\nHeaps are arrays for which `a[ k ] <= a[2* k +1]` and\n`a[ k ] <= a[2* k +2]`\nfor all k, counting elements from 0. For the sake of comparison,\nnon-existing elements are considered to be infinite. The interesting\nproperty of a heap is that `a[0]` is always its smallest element.\nThe strange invariant above is meant to be an efficient memory\nrepresentation for a tournament. The numbers below are k, not\n`a[ k ]`:\n```text\n\n0\n\n1 2\n\n3 4 5 6\n\n7 8 9 10 11 12 13 14\n\n15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n```\nIn the tree above, each cell k is topping `2* k +1` and\n`2* k +2`.\nIn an usual binary tournament we see in sports, each cell is the winner\nover the two cells it tops, and we can trace the winner down the tree\nto see all opponents s/he had. However, in many computer applications\nof such tournaments, we do not need to trace the history of a winner.\nTo be more memory efficient, when a winner is promoted, we try to\nreplace it by something else at a lower level, and the rule becomes\nthat a cell and the two cells it tops contain three different items,\nbut the top cell \"wins\" over the two topped cells.\nIf this heap invariant is protected at all time, index 0 is clearly\nthe overall winner. The simplest algorithmic way to remove it and\nfind the \"next\" winner is to move some loser (let's say cell 30 in the\ndiagram above) into the 0 position, and then percolate this new 0 down\nthe tree, exchanging values, until the invariant is re-established.\nThis is clearly logarithmic on the total number of items in the tree.\nBy iterating over all items, you get an O(n log n) sort.\nA nice feature of this sort is that you can efficiently insert new\nitems while the sort is going on, provided that the inserted items are\nnot \"better\" than the last 0'th element you extracted. This is\nespecially useful in simulation contexts, where the tree holds all\nincoming events, and the \"win\" condition means the smallest scheduled\ntime. When an event schedule other events for execution, they are\nscheduled into the future, so they can easily go into the heap. So, a\nheap is a good structure for implementing schedulers (this is what I\nused for my MIDI sequencer :-).\nVarious structures for implementing schedulers have been extensively\nstudied, and heaps are good for this, as they are reasonably speedy,\nthe speed is almost constant, and the worst case is not much different\nthan the average case. However, there are other representations which\nare more efficient overall, yet the worst cases might be terrible.\nHeaps are also very useful in big disk sorts. You most probably all\nknow that a big sort implies producing \"runs\" (which are pre-sorted\nsequences, which size is usually related to the amount of CPU memory),\nfollowed by a merging passes for these runs, which merging is often\nvery cleverly organised5.1 (#foot17457).\nIt is very important that the initial\nsort produces the longest runs possible. Tournaments are a good way\nto that. If, using all the memory available to hold a tournament, you\nreplace and percolate items that happen to fit the current run, you'll\nproduce runs which are twice the size of the memory for random input,\nand much better for input fuzzily ordered.\nMoreover, if you output the 0'th item on disk and get an input which\nmay not fit in the current tournament (because the value \"wins\" over\nthe last output value), it cannot fit in the heap, so the size of the\nheap decreases. The freed memory could be cleverly reused immediately\nfor progressively building a second heap, which grows at exactly the\nsame rate the first heap is melting. When the first heap completely\nvanishes, you switch heaps and start a new run. Clever and quite\neffective!", "python_version": "2.3", "length": 4053, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node162.html"} {"title": "5.19.1 Module Contents", "text": "module-shlex.html | module-shlex.html | shlex-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.19 shlex (module-shlex.html)\nUp:\n5.19 shlex (module-shlex.html)\nNext:\n5.19.2 shlex Objects (shlex-objects.html)\n---\n## 5.19.1 Module Contents\nThe shlex module defines the following functions:\nThe shlex module defines the following classes:", "python_version": "2.3", "length": 385, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node180.html"} {"title": "6.9.1 Available Types", "text": "module-datetime.html | module-datetime.html | datetime-timedelta.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9 datetime (module-datetime.html)\nUp:\n6.9 datetime (module-datetime.html)\nNext:\n6.9.2 timedelta Objects (datetime-timedelta.html)\n---\n## 6.9.1 Available Types\nObjects of these types are immutable.\nObjects of the date type are always naive.\nAn object d of type time or datetime may be\nnaive or aware. d is aware if `d .tzinfo` is not\n`None` and `d .tzinfo.utcoffset( d )` does not return\n`None`. If `d .tzinfo` is `None`, or if\n`d .tzinfo` is not `None` but\n`d .tzinfo.utcoffset( d )` returns `None`, d\nis naive.\nThe distinction between naive and aware doesn't apply to\n`timedelta` objects.\nSubclass relationships:\n```text\n\nobject\ntimedelta\ntzinfo\ntime\ndate\ndatetime\n```", "python_version": "2.3", "length": 826, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node202.html"} {"title": "6.9.7 strftime() Behavior", "text": "datetime-tzinfo.html | module-datetime.html | module-time.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.9.6 tzinfo Objects (datetime-tzinfo.html)\nUp:\n6.9 datetime (module-datetime.html)\nNext:\n6.10 time (module-time.html)\n---\n## 6.9.7 strftime() Behavior\ndate, datetime, and time\nobjects all support a `strftime( format )`\nmethod, to create a string representing the time under the control of\nan explicit format string. Broadly speaking,\n`d.strftime(fmt)`\nacts like the time (module-time.html) module's\n`time.strftime(fmt, d.timetuple())`\nalthough not all objects support a timetuple() method.\nFor time objects, the format codes for\nyear, month, and day should not be used, as time objects have no such\nvalues. If they're used anyway, `1900` is substituted for the\nyear, and `0` for the month and day.\nFor date objects, the format codes for hours, minutes, and\nseconds should not be used, as date objects have no such\nvalues. If they're used anyway, `0` is substituted for them.\nFor a naive object, the `%z` and `%Z` format codes are\nreplaced by empty strings.\nFor an aware object:\n`%z`: utcoffset() is transformed into a 5-character string of\nthe form +HHMM or -HHMM, where HH is a 2-digit string giving the\nnumber of UTC offset hours, and MM is a 2-digit string giving the\nnumber of UTC offset minutes. For example, if\nutcoffset() returns `timedelta(hours=-3, minutes=-30)`,\n`%z` is replaced with the string `'-0330'`.\n`%Z`: If tzname() returns `None`, `%Z` is replaced\nby an empty string. Otherwise `%Z` is replaced by the returned\nvalue, which must be a string.\nThe full set of format codes supported varies across platforms,\nbecause Python calls the platform C library's strftime()\nfunction, and platform variations are common. The documentation for\nPython's time (module-time.html) module lists the format codes that the C\nstandard (1989 version) requires, and those work on all platforms\nwith a standard C implementation. Note that the 1999 version of the\nC standard added additional format codes.", "python_version": "2.3", "length": 2049, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node208.html"} {"title": "6.14.3 Constants", "text": "curses-window-objects.html | module-curses.html | module-curses.textpad.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.14.2 Window Objects (curses-window-objects.html)\nUp:\n6.14 curses (module-curses.html)\nNext:\n6.15 curses.textpad (module-curses.textpad.html)\n---\n## 6.14.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.3", "length": 1427, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node218.html"} {"title": "6.26.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\nPrevious:\n6.26 locale (module-locale.html)\nUp:\n6.26 locale (module-locale.html)\nNext:\n6.26.2 For extension writers (embedding-locale.html)\n---\n## 6.26.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(such as 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.3", "length": 2158, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node264.html"} {"title": "6.27.1 GNU gettext API", "text": "module-gettext.html | module-gettext.html | node269.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27 gettext (module-gettext.html)\nUp:\n6.27 gettext (module-gettext.html)\nNext:\n6.27.2 Class-based API (node269.html)\n---\n## 6.27.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.3", "length": 1135, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node268.html"} {"title": "6.27.2 Class-based API", "text": "node268.html | module-gettext.html | node270.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.1 GNU gettext API (node268.html)\nUp:\n6.27 gettext (module-gettext.html)\nNext:\n6.27.2.1 The NullTranslations class (node270.html)\n---\n## 6.27.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\n... used.6.3 (node269.html#tex2html42): See the footnote for\nbindtextdomain() above.", "python_version": "2.3", "length": 872, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node269.html"} {"title": "6.27.2.1 The NullTranslations class", "text": "node269.html | node269.html | node271.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.2 Class-based API (node269.html)\nUp:\n6.27.2 Class-based API (node269.html)\nNext:\n6.27.2.2 The GNUTranslations class (node271.html)\n---\n### 6.27.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.3", "length": 650, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node270.html"} {"title": "6.27.2.2 The GNUTranslations class", "text": "node270.html | node269.html | node272.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.2.1 The NullTranslations class (node270.html)\nUp:\n6.27.2 Class-based API (node269.html)\nNext:\n6.27.2.3 Solaris message catalog (node272.html)\n---\n### 6.27.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 coerces both message ids and message strings to Unicode.\nGNUTranslations parses optional meta-data out of the\ntranslation catalog. It is convention with GNU gettext to\ninclude meta-data as the translation for the empty string. This\nmeta-data is in RFC 822 (http://www.faqs.org/rfcs/rfc822.html)-style `key: value` pairs, and should\ncontain the `Project-Id-Version` key. If the key\n`Content-Type` is found, then the `charset` property is used\nto initialize the ``protected'' _charset instance variable,\ndefaulting to `None` if not found. If the charset encoding is\nspecified, then all message ids and message strings read from the\ncatalog are converted to Unicode using this encoding. The\nugettext() method always returns a Unicode, while the\ngettext() returns an encoded 8-bit string. For the message\nid arguments of both methods, either Unicode strings or 8-bit strings\ncontaining only US-ASCII characters are acceptable. Note that the\nUnicode version of the methods (i.e. ugettext() and\nungettext()) are the recommended interface to use for\ninternationalized Python programs.\nThe entire set of key/value pairs are placed into a dictionary and set\nas the ``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 following methods are overridden from the base class implementation:", "python_version": "2.3", "length": 1963, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node271.html"} {"title": "6.27.2.3 Solaris message catalog support", "text": "node271.html | node269.html | node273.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.2.2 The GNUTranslations class (node271.html)\nUp:\n6.27.2 Class-based API (node269.html)\nNext:\n6.27.2.4 The Catalog constructor (node273.html)\n---\n### 6.27.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.3", "length": 481, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node272.html"} {"title": "6.27.2.4 The Catalog constructor", "text": "node272.html | node269.html | node274.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.2.3 Solaris message catalog (node272.html)\nUp:\n6.27.2 Class-based API (node269.html)\nNext:\n6.27.3 Internationalizing your programs (node274.html)\n---\n### 6.27.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.3", "length": 870, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node273.html"} {"title": "6.27.3 Internationalizing your programs and modules", "text": "node273.html | module-gettext.html | node275.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.2.4 The Catalog constructor (node273.html)\nUp:\n6.27 gettext (module-gettext.html)\nNext:\n6.27.3.1 Localizing your module (node275.html)\n---\n## 6.27.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 (#foot31357) 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 (#foot31358) 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\n...pygettext6.4 (node274.html#tex2html44): François Pinard has\nwritten a program called\nxpot which does a similar job. It is available as part of\nhis po-utils package at\nhttp://www.iro.umontreal.ca/contrib/po-utils/HTML/.\n...msgfmt.py6.5 (node274.html#tex2html45): msgfmt.py is binary\ncompatible with GNU msgfmt except that it provides a\nsimpler, all-Python implementation. With this and\npygettext.py, you generally won't need to install the GNU\ngettext package to internationalize your Python\napplications.", "python_version": "2.3", "length": 3719, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node274.html"} {"title": "6.27.3.1 Localizing your module", "text": "node274.html | node274.html | node276.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.3 Internationalizing your programs (node274.html)\nUp:\n6.27.3 Internationalizing your programs (node274.html)\nNext:\n6.27.3.2 Localizing your application (node276.html)\n---\n### 6.27.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.3", "length": 1025, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node275.html"} {"title": "6.27.3.2 Localizing your application", "text": "node275.html | node274.html | node277.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.3.1 Localizing your module (node275.html)\nUp:\n6.27.3 Internationalizing your programs (node274.html)\nNext:\n6.27.3.3 Changing languages on (node277.html)\n---\n### 6.27.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.3", "length": 995, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node276.html"} {"title": "6.27.3.3 Changing languages on the fly", "text": "node276.html | node274.html | node278.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.3.2 Localizing your application (node276.html)\nUp:\n6.27.3 Internationalizing your programs (node274.html)\nNext:\n6.27.3.4 Deferred translations (node278.html)\n---\n### 6.27.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.3", "length": 845, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node277.html"} {"title": "6.27.3.4 Deferred translations", "text": "node277.html | node274.html | node279.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.3.3 Changing languages on (node277.html)\nUp:\n6.27.3 Internationalizing your programs (node274.html)\nNext:\n6.27.4 Acknowledgements (node279.html)\n---\n### 6.27.3.4 Deferred translations\nIn most coding situations, strings are translated where 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 (#foot31359) 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.3", "length": 1970, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node278.html"} {"title": "6.27.4 Acknowledgements", "text": "node278.html | module-gettext.html | module-logging.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.27.3.4 Deferred translations (node278.html)\nUp:\n6.27 gettext (module-gettext.html)\nNext:\n6.28 logging (module-logging.html)\n---\n## 6.27.4 Acknowledgements\nThe following people contributed code, feedback, design suggestions,\nprevious implementations, and valuable experience to the creation of\nthis module:", "python_version": "2.3", "length": 449, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node279.html"} {"title": "6.28.1 Logger Objects", "text": "module-logging.html | module-logging.html | node282.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28 logging (module-logging.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.2 Handler Objects (node282.html)\n---\n## 6.28.1 Logger Objects\nLoggers have the following attributes and methods. Note that Loggers are\nnever instantiated directly, but always through the module-level function\nlogging.getLogger(name).", "python_version": "2.3", "length": 460, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node281.html"} {"title": "6.28.2 Handler Objects", "text": "node281.html | module-logging.html | node283.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.1 Logger Objects (node281.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.2.1 StreamHandler (node283.html)\n---\n## 6.28.2 Handler Objects\nHandlers have the following attributes and methods. Note that\nHandler is never instantiated directly; this class acts as a\nbase for more useful subclasses. However, the __init__()\nmethod in subclasses needs to call Handler.__init__().", "python_version": "2.3", "length": 519, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node282.html"} {"title": "6.28.2.1 StreamHandler", "text": "node282.html | node282.html | node284.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2 Handler Objects (node282.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.2 FileHandler (node284.html)\n---\n### 6.28.2.1 StreamHandler\nThe StreamHandler class sends logging output to streams such as\nsys.stdout, sys.stderr or any file-like object (or, more\nprecisely, any object which supports write() and flush()\nmethods).", "python_version": "2.3", "length": 468, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node283.html"} {"title": "6.28.2.2 FileHandler", "text": "node283.html | node282.html | node285.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.1 StreamHandler (node283.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.3 RotatingFileHandler (node285.html)\n---\n### 6.28.2.2 FileHandler\nThe FileHandler class sends logging output to a disk file.\nIt inherits the output functionality from StreamHandler.", "python_version": "2.3", "length": 402, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node284.html"} {"title": "6.28.2.3 RotatingFileHandler", "text": "node284.html | node282.html | node286.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.2 FileHandler (node284.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.4 SocketHandler (node286.html)\n---\n### 6.28.2.3 RotatingFileHandler\nThe RotatingFileHandler class supports rotation of disk log files.", "python_version": "2.3", "length": 353, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node285.html"} {"title": "6.28.2.4 SocketHandler", "text": "node285.html | node282.html | node287.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.3 RotatingFileHandler (node285.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.5 DatagramHandler (node287.html)\n---\n### 6.28.2.4 SocketHandler\nThe SocketHandler class sends logging output to a network\nsocket. The base class uses a TCP socket.", "python_version": "2.3", "length": 390, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node286.html"} {"title": "6.28.2.5 DatagramHandler", "text": "node286.html | node282.html | node288.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.4 SocketHandler (node286.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.6 SysLogHandler (node288.html)\n---\n### 6.28.2.5 DatagramHandler\nThe DatagramHandler class inherits from SocketHandler\nto support sending logging messages over UDP sockets.", "python_version": "2.3", "length": 392, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node287.html"} {"title": "6.28.2.6 SysLogHandler", "text": "node287.html | node282.html | node289.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.5 DatagramHandler (node287.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.7 NTEventLogHandler (node289.html)\n---\n### 6.28.2.6 SysLogHandler\nThe SysLogHandler class supports sending logging messages to a\nremote or local Unix syslog.", "python_version": "2.3", "length": 380, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node288.html"} {"title": "6.28.2.7 NTEventLogHandler", "text": "node288.html | node282.html | node290.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.6 SysLogHandler (node288.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.8 SMTPHandler (node290.html)\n---\n### 6.28.2.7 NTEventLogHandler\nThe NTEventLogHandler class supports sending logging messages\nto a local Windows NT, Windows 2000 or Windows XP event log. Before\nyou can use it, you need Mark Hammond's Win32 extensions for Python\ninstalled.", "python_version": "2.3", "length": 493, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node289.html"} {"title": "2.2.9.9 Boolean Values", "text": "bltin-ellipsis-object.html | typesother.html | typesinternal.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n2.2.9.8 The Ellipsis Object (bltin-ellipsis-object.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.10 Internal Objects (typesinternal.html)\n---\n### 2.2.9.9 Boolean Values\nBoolean values are the two constant objects `False` and\n`True`. They are used to represent truth values (although other\nvalues can also be considered false or true). In numeric contexts\n(for example when used as the argument to an arithmetic operator),\nthey behave like the integers 0 and 1, respectively. The built-in\nfunction bool() can be used to cast any value to a Boolean,\nif the value can be interpreted as a truth value (see section Truth\nValue Testing above).\nThey are written as `False` and `True`, respectively.", "python_version": "2.3", "length": 863, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node29.html"} {"title": "6.28.2.8 SMTPHandler", "text": "node289.html | node282.html | node291.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.7 NTEventLogHandler (node289.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.9 MemoryHandler (node291.html)\n---\n### 6.28.2.8 SMTPHandler\nThe SMTPHandler class supports sending logging messages to an email\naddress via SMTP.", "python_version": "2.3", "length": 370, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node290.html"} {"title": "6.28.2.9 MemoryHandler", "text": "node290.html | node282.html | node292.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.8 SMTPHandler (node290.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.2.10 HTTPHandler (node292.html)\n---\n### 6.28.2.9 MemoryHandler\nThe MemoryHandler supports buffering of logging records in memory,\nperiodically flushing them to a target handler. Flushing occurs\nwhenever the buffer is full, or when an event of a certain severity or\ngreater is seen.\nMemoryHandler is a subclass of the more general\nBufferingHandler, which is an abstract class. This buffers logging\nrecords in memory. Whenever each record is added to the buffer, a\ncheck is made by calling shouldFlush() to see if the buffer\nshould be flushed. If it should, then flush() is expected to\ndo the needful.", "python_version": "2.3", "length": 816, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node291.html"} {"title": "6.28.2.10 HTTPHandler", "text": "node291.html | node282.html | node293.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.9 MemoryHandler (node291.html)\nUp:\n6.28.2 Handler Objects (node282.html)\nNext:\n6.28.3 Formatter Objects (node293.html)\n---\n### 6.28.2.10 HTTPHandler\nThe HTTPHandler class supports sending logging messages to a\nWeb server, using either \"GET\" or \"POST\" semantics.", "python_version": "2.3", "length": 396, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node292.html"} {"title": "6.28.3 Formatter Objects", "text": "node292.html | module-logging.html | node294.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.2.10 HTTPHandler (node292.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.4 Filter Objects (node294.html)\n---\n## 6.28.3 Formatter Objects\nFormatters have the following attributes and methods. They are\nresponsible for converting a LogRecord to (usually) a string\nwhich can be interpreted by either a human or an external system. The\nbase\nFormatter allows a formatting string to be specified. If none is\nsupplied, the default value of `'%(message)s\\'` is used.\nA Formatter can be initialized with a format string which makes use of\nknowledge of the LogRecord attributes - such as the default value\nmentioned above making use of the fact that the user's message and\narguments are pre-formatted into a LogRecord's message\nattribute. This format string contains standard python %-style\nmapping keys. See section 2.2.6 (typesseq-strings.html#typesseq-strings), ``String Formatting\nOperations,'' for more information on string formatting.\nCurrently, the useful mapping keys in a LogRecord are:", "python_version": "2.3", "length": 1134, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node293.html"} {"title": "6.28.4 Filter Objects", "text": "node293.html | module-logging.html | node295.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.3 Formatter Objects (node293.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.5 LogRecord Objects (node295.html)\n---\n## 6.28.4 Filter Objects\nFilters can be used by Handlers and Loggers for\nmore sophisticated filtering than is provided by levels. The base filter\nclass only allows events which are below a certain point in the logger\nhierarchy. For example, a filter initialized with \"A.B\" will allow events\nlogged by loggers \"A.B\", \"A.B.C\", \"A.B.C.D\", \"A.B.D\" etc. but not \"A.BB\",\n\"B.A.B\" etc. If initialized with the empty string, all events are passed.", "python_version": "2.3", "length": 702, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node294.html"} {"title": "6.28.5 LogRecord Objects", "text": "node294.html | module-logging.html | node296.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.4 Filter Objects (node294.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.6 Thread Safety (node296.html)\n---\n## 6.28.5 LogRecord Objects\nLogRecord instances are created every time something is logged. They\ncontain all the information pertinent to the event being logged. The\nmain information passed in is in msg and args, which are combined\nusing msg % args to create the message field of the record. The record\nalso includes information such as when the record was created, the\nsource line where the logging call was made, and any exception\ninformation to be logged.\nLogRecord has no methods; it's just a repository for information about the\nlogging event. The only reason it's a class rather than a dictionary is to\nfacilitate extension.", "python_version": "2.3", "length": 887, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node295.html"} {"title": "6.28.6 Thread Safety", "text": "node295.html | module-logging.html | node297.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.5 LogRecord Objects (node295.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.7 Configuration (node297.html)\n---\n## 6.28.6 Thread Safety\nThe logging module is intended to be thread-safe without any special work\nneeding to be done by its clients. It achieves this though using threading\nlocks; there is one lock to serialize access to the module's shared data,\nand each handler also creates a lock to serialize access to its underlying\nI/O.", "python_version": "2.3", "length": 586, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node296.html"} {"title": "6.28.7 Configuration", "text": "node296.html | module-logging.html | node298.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.6 Thread Safety (node296.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.7.1 Configuration functions (node298.html)\n---\n## 6.28.7 Configuration", "python_version": "2.3", "length": 291, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node297.html"} {"title": "6.28.7.1 Configuration functions", "text": "node297.html | node297.html | node299.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.7 Configuration (node297.html)\nUp:\n6.28.7 Configuration (node297.html)\nNext:\n6.28.7.2 Configuration file format (node299.html)\n---\n### 6.28.7.1 Configuration functions\nThe following functions allow the logging module to be\nconfigured. Before they can be used, you must import\nlogging.config. Their use is optional -- you can configure\nthe logging module entirely by making calls to the main API (defined\nin logging itself) and defining handlers which are declared\neither in logging or logging.handlers.", "python_version": "2.3", "length": 635, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node298.html"} {"title": "6.28.7.2 Configuration file format", "text": "node298.html | node297.html | node300.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.7.1 Configuration functions (node298.html)\nUp:\n6.28.7 Configuration (node297.html)\nNext:\n6.28.8 Using the logging (node300.html)\n---\n### 6.28.7.2 Configuration file format\nThe configuration file format understood by fileConfig is\nbased on ConfigParser functionality. The file must contain sections\ncalled `[loggers]`, `[handlers]` and `[formatters]`\nwhich identify by name the entities of each type which are defined in\nthe file. For each such entity, there is a separate section which\nidentified how that entity is configured. Thus, for a logger named\n`log01` in the `[loggers]` section, the relevant\nconfiguration details are held in a section\n`[logger_log01]`. Similarly, a handler called `hand01` in\nthe `[handlers]` section will have its configuration held in a\nsection called `[handler_hand01]`, while a formatter called\n`form01` in the `[formatters]` section will have its\nconfiguration specified in a section called\n`[formatter_form01]`. The root logger configuration must be\nspecified in a section called `[logger_root]`.\nExamples of these sections in the file are given below.\n```text\n\n[loggers]\nkeys=root,log02,log03,log04,log05,log06,log07\n\n[handlers]\nkeys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09\n\n[formatters]\nkeys=form01,form02,form03,form04,form05,form06,form07,form08,form09\n```\nThe root logger must specify a level and a list of handlers. An\nexample of a root logger section is given below.\n```text\n\n[logger_root]\nlevel=NOTSET\nhandlers=hand01\n```\nThe `level` entry can be one of `DEBUG, INFO, WARNING,\nERROR, CRITICAL` or `NOTSET`. For the root logger only,\n`NOTSET` means that all messages will be logged. Level values are\neval()uated in the context of the `logging` package's\nnamespace.\nThe `handlers` entry is a comma-separated list of handler names,\nwhich must appear in the `[handlers]` section. These names must\nappear in the `[handlers]` section and have corresponding\nsections in the configuration file.\nFor loggers other than the root logger, some additional information is\nrequired. This is illustrated by the following example.\n```text\n\n[logger_parser]\nlevel=DEBUG\nhandlers=hand01\npropagate=1\nqualname=compiler.parser\n```\nThe `level` and `handlers` entries are interpreted as for\nthe root logger, except that if a non-root logger's level is specified\nas `NOTSET`, the system consults loggers higher up the hierarchy\nto determine the effective level of the logger. The `propagate`\nentry is set to 1 to indicate that messages must propagate to handlers\nhigher up the logger hierarchy from this logger, or 0 to indicate that\nmessages are not propagated to handlers up the hierarchy. The\n`qualname` entry is the hierarchical channel name of the logger,\nfor example, the name used by the application to get the logger.\nSections which specify handler configuration are exemplified by the\nfollowing.\n```text\n\n[handler_hand01]\nclass=StreamHandler\nlevel=NOTSET\nformatter=form01\nargs=(sys.stdout,)\n```\nThe `class` entry indicates the handler's class (as determined by\neval() in the `logging` package's namespace). The\n`level` is interpreted as for loggers, and `NOTSET` is taken\nto mean \"log everything\".\nThe `formatter` entry indicates the key name of the formatter for\nthis handler. If blank, a default formatter\n(`logging._defaultFormatter`) is used. If a name is specified, it\nmust appear in the `[formatters]` section and have a\ncorresponding section in the configuration file.\nThe `args` entry, when eval()uated in the context of\nthe `logging` package's namespace, is the list of arguments to\nthe constructor for the handler class. Refer to the constructors for\nthe relevant handlers, or to the examples below, to see how typical\nentries are constructed.\n```text\n\n[handler_hand02]\nclass=FileHandler\nlevel=DEBUG\nformatter=form02\nargs=('python.log', 'w')\n\n[handler_hand03]\nclass=handlers.SocketHandler\nlevel=INFO\nformatter=form03\nargs=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)\n\n[handler_hand04]\nclass=handlers.DatagramHandler\nlevel=WARN\nformatter=form04\nargs=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)\n\n[handler_hand05]\nclass=handlers.SysLogHandler\nlevel=ERROR\nformatter=form05\nargs=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)\n\n[handler_hand06]\nclass=NTEventLogHandler\nlevel=CRITICAL\nformatter=form06\nargs=('Python Application', '', 'Application')\n\n[handler_hand07]\nclass=SMTPHandler\nlevel=WARN\nformatter=form07\nargs=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')\n\n[handler_hand08]\nclass=MemoryHandler\nlevel=NOTSET\nformatter=form08\ntarget=\nargs=(10, ERROR)\n\n[handler_hand09]\nclass=HTTPHandler\nlevel=NOTSET\nformatter=form09\nargs=('localhost:9022', '/log', 'GET')\n```\nSections which specify formatter configuration are typified by the following.\n```text\n\n[formatter_form01]\nformat=F1 %(asctime)s %(levelname)s %(message)s\ndatefmt=\n```\nThe `format` entry is the overall format string, and the\n`datefmt` entry is the strftime()-compatible date/time format\nstring. If empty, the package substitutes ISO8601 format date/times, which\nis almost equivalent to specifying the date format string \"The ISO8601 format also specifies milliseconds, which are appended to the\nresult of using the above format string, with a comma separator. An example\ntime in ISO8601 format is `2003-01-23 00:29:50,411`.", "python_version": "2.3", "length": 5435, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node299.html"} {"title": "6.28.8 Using the logging package", "text": "node299.html | module-logging.html | node301.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.7.2 Configuration file format (node299.html)\nUp:\n6.28 logging (module-logging.html)\nNext:\n6.28.8.1 Basic example - (node301.html)\n---\n## 6.28.8 Using the logging package", "python_version": "2.3", "length": 309, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node300.html"} {"title": "6.28.8.1 Basic example - log to a file", "text": "node300.html | node300.html | someos.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.8 Using the logging (node300.html)\nUp:\n6.28.8 Using the logging (node300.html)\nNext:\n7. Optional Operating System (someos.html)\n---\n### 6.28.8.1 Basic example - log to a file\nHere's a simple logging example that just logs to a file. In order,\nit creates a Logger instance, then a FileHandler\nand a Formatter. It attaches the Formatter to the\nFileHandler, then the FileHandler to the Logger.\nFinally, it sets a debug level for the logger.\n```text\n\nimport logging\nlogger = logging.getLogger('myapp')\nhdlr = logging.FileHandler('/var/tmp/myapp.log')\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\nhdlr.setFormatter(formatter)\nlogger.addHandler(hdlr)\nlogger.setLevel(logging.WARNING)\n```\nWe can use this logger object now to write entries to the log file:\n```text\n\nlogger.error('We have a problem')\nlogger.info('While this is just chatty')\n```\nIf we look in the file that was created, we'll see something like this:\n```text\n\n2003-07-08 16:49:45,896 ERROR We have a problem\n```\nThe info message was not written to the file - we called the setLevel\nmethod to say we only wanted `WARNING` or worse, so the info message is\ndiscarded.\nThe timestamp is of the form\n``year-month-day hour:minutes:seconds,milliseconds.''\nNote that despite the three digits of precision in the milliseconds field,\nnot all systems provide time with this much precision.", "python_version": "2.3", "length": 1494, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node301.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\nPrevious:\n7.1 signal (module-signal.html)\nUp:\n7.1 signal (module-signal.html)\nNext:\n7.2 socket (module-socket.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.3", "length": 690, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node304.html"} {"title": "2.4 Built-in Constants", "text": "module-exceptions.html | builtin.html | python.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n2.3 Built-in Exceptions (module-exceptions.html)\nUp:\n2. Built-In Objects (builtin.html)\nNext:\n3. Python Runtime Services (python.html)\n---\n# 2.4 Built-in Constants\nA small number of constants live in the built-in namespace. They are:", "python_version": "2.3", "length": 370, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node33.html"} {"title": "7.17.1 (De)compression of files", "text": "module-bz2.html | module-bz2.html | node338.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.17 bz2 (module-bz2.html)\nUp:\n7.17 bz2 (module-bz2.html)\nNext:\n7.17.2 Sequential (de)compression (node338.html)\n---\n## 7.17.1 (De)compression of files\nHandling of compressed files is offered by the BZ2File class.", "python_version": "2.3", "length": 347, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node337.html"} {"title": "7.17.2 Sequential (de)compression", "text": "node337.html | module-bz2.html | node339.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.17.1 (De)compression of files (node337.html)\nUp:\n7.17 bz2 (module-bz2.html)\nNext:\n7.17.3 One-shot (de)compression (node339.html)\n---\n## 7.17.2 Sequential (de)compression\nSequential compression and decompression is done using the classes\nBZ2Compressor and BZ2Decompressor.", "python_version": "2.3", "length": 404, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node338.html"} {"title": "7.17.3 One-shot (de)compression", "text": "node338.html | module-bz2.html | module-zipfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.17.2 Sequential (de)compression (node338.html)\nUp:\n7.17 bz2 (module-bz2.html)\nNext:\n7.18 zipfile (module-zipfile.html)\n---\n## 7.17.3 One-shot (de)compression\nOne-shot compression and decompression is provided through the\ncompress() and decompress() functions.", "python_version": "2.3", "length": 399, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node339.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\nPrevious:\n8.8 termios (module-termios.html)\nUp:\n8.8 termios (module-termios.html)\nNext:\n8.9 TERMIOS (module-TERMIOSuppercase.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.3", "length": 875, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node364.html"} {"title": "8.15.1 Resource Limits", "text": "module-resource.html | module-resource.html | node374.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n8.15 resource (module-resource.html)\nUp:\n8.15 resource (module-resource.html)\nNext:\n8.15.2 Resource Usage (node374.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.3", "length": 1606, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node373.html"} {"title": "8.15.2 Resource Usage", "text": "node373.html | module-resource.html | module-nis.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n8.15.1 Resource Limits (node373.html)\nUp:\n8.15 resource (module-resource.html)\nNext:\n8.16 nis (module-nis.html)\n---\n## 8.15.2 Resource Usage\nThese functions 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.3", "length": 477, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node374.html"} {"title": "10.1 Introduction to the profiler", "text": "profile.html | profile.html | node383.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10. The Python Profiler (profile.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.2 How Is This (node383.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.3", "length": 694, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node382.html"} {"title": "10.2 How Is This Profiler Different From The Old Profiler?", "text": "node382.html | profile.html | profile-instant.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.1 Introduction to the (node382.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.3 Instant Users Manual (profile-instant.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.3", "length": 1657, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node383.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\nPrevious:\n10.3 Instant Users Manual (profile-instant.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.5 Reference Manual (module-profile.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.3", "length": 2006, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node385.html"} {"title": "10.8 Extensions -- Deriving Better Profilers", "text": "profile-calibration.html | profile.html | module-hotshot.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.7 Calibration (profile-calibration.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.9 hotshot (module-hotshot.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.", "python_version": "2.3", "length": 1257, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node390.html"} {"title": "10.10.1 Command Line Interface", "text": "module-timeit.html | module-timeit.html | node397.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.10 timeit (module-timeit.html)\nUp:\n10.10 timeit (module-timeit.html)\nNext:\n10.10.2 Examples (node397.html)\n---\n## 10.10.1 Command Line Interface\nWhen called as a program from the command line, the following form is used:\n```text\n\npython timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]\n```\nwhere the following options are understood:\n-n N/-number=N: how many times to execute 'statement'\n-r N/-repeat=N: how many times to repeat the timer (default 3)\n-s S/-setup=S: statement to be executed once initially (default\n`'pass'`)\n-t/-time: use time.time()\n(default on all platforms but Windows)\n-c/-clock: use time.clock() (default on Windows)\n-v/-verbose: print raw timing results; repeat for more digits\nprecision\n-h/-help: print a short usage message and exit\nA multi-line statement may be given by specifying each line as a\nseparate statement argument; indented lines are possible by enclosing\nan argument in quotes and using leading spaces. Multiple\n-s options are treated similarly.\nIf -n is not given, a suitable number of loops is\ncalculated by trying successive powers of 10 until the total time is\nat least 0.2 seconds.\nThe default timer function is platform dependent. On Windows,\ntime.clock() has microsecond granularity but\ntime.time()'s granularity is 1/60th of a second; on Unix,\ntime.clock() has 1/100th of a second granularity and\ntime.time() is much more precise. On either platform, the\ndefault timer functions measures wall clock time, not the CPU time.\nThis means that other processes running on the same computer may\ninterfere with the timing. The best thing to do when accurate timing\nis necessary is to repeat the timing a few times and use the best\ntime. The -r option is good for this; the default of 3\nrepetitions is probably enough in most cases. On Unix, you can use\ntime.clock() to measure CPU time.\nNote:\nThere is a certain baseline overhead associated with executing a\npass statement. The code here doesn't try to hide it, but you\nshould be aware of it. The baseline overhead can be measured by\ninvoking the program without arguments.\nThe baseline overhead differs between Python versions! Also, to\nfairly compare older Python versions to Python 2.3, you may want to\nuse Python's -O option for the older versions to avoid\ntiming `SET_LINENO` instructions.", "python_version": "2.3", "length": 2438, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node396.html"} {"title": "10.10.2 Examples", "text": "node396.html | module-timeit.html | internet.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.10.1 Command Line Interface (node396.html)\nUp:\n10.10 timeit (module-timeit.html)\nNext:\n11. Internet Protocols and (internet.html)\n---\n## 10.10.2 Examples\nHere are two example sessions (one using the command line, one using\nthe module interface) that compare the cost of using\nhasattr() vs. try/except to test for\nmissing and present object attributes.\n```text\n\n% timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'\n100000 loops, best of 3: 15.7 usec per loop\n% timeit.py 'if hasattr(str, \"__nonzero__\"): pass'\n100000 loops, best of 3: 4.26 usec per loop\n% timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'\n1000000 loops, best of 3: 1.43 usec per loop\n% timeit.py 'if hasattr(int, \"__nonzero__\"): pass'\n100000 loops, best of 3: 2.23 usec per loop\n```\n```text\n\n>>> import timeit\n>>> s = \"\"\"\\\n... try:\n... str.__nonzero__\n... except AttributeError:\n... pass\n... \"\"\"\n>>> t = timeit.Timer(stmt=s)\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n17.09 usec/pass\n>>> s = \"\"\"\\\n... if hasattr(str, '__nonzero__'): pass\n... \"\"\"\n>>> t = timeit.Timer(stmt=s)\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n4.85 usec/pass\n>>> s = \"\"\"\\\n... try:\n... int.__nonzero__\n... except AttributeError:\n... pass\n... \"\"\"\n>>> t = timeit.Timer(stmt=s)\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n1.97 usec/pass\n>>> s = \"\"\"\\\n... if hasattr(int, '__nonzero__'): pass\n... \"\"\"\n>>> t = timeit.Timer(stmt=s)\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n3.15 usec/pass\n```\nTo give the timeit module access to functions you\ndefine, you can pass a `setup` parameter which contains an import\nstatement:\n```text\n\ndef test():\n\"Stupid test function\"\nL = []\nfor i in range(100):\nL.append(i)\n\nif __name__=='__main__':\nfrom timeit import Timer\nt = Timer(\"test()\", \"from __main__ import test\")\nprint t.timeit()\n```", "python_version": "2.3", "length": 2047, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node397.html"} {"title": "11.2.2 Using the cgi module", "text": "cgi-intro.html | module-cgi.html | node404.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.1 Introduction (cgi-intro.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.3 Higher Level Interface (node404.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 isinstance() 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\nvalue = form.getvalue(\"username\", \"\")\nif isinstance(value, list):\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.3", "length": 4965, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node403.html"} {"title": "11.2.3 Higher Level Interface", "text": "node403.html | module-cgi.html | node405.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.2 Using the cgi (node403.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.4 Old classes (node405.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\nitem = form.getvalue(\"item\")\nif isinstance(item, list):\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.3", "length": 2669, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node404.html"} {"title": "11.2.4 Old classes", "text": "node404.html | module-cgi.html | node406.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.3 Higher Level Interface (node404.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.5 Functions (node406.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.3", "length": 976, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node405.html"} {"title": "11.2.5 Functions", "text": "node405.html | module-cgi.html | cgi-security.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.4 Old classes (node405.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.6 Caring about security (cgi-security.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.3", "length": 421, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node406.html"} {"title": "11.2.7 Installing your CGI script on a Unix system", "text": "cgi-security.html | module-cgi.html | node409.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.6 Caring about security (cgi-security.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.8 Testing your CGI (node409.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.3", "length": 2165, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node408.html"} {"title": "11.2.8 Testing your CGI script", "text": "node408.html | module-cgi.html | node410.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.7 Installing your CGI (node408.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.9 Debugging CGI scripts (node410.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.3", "length": 831, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node409.html"} {"title": "11.2.9 Debugging CGI scripts", "text": "node409.html | module-cgi.html | node411.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.8 Testing your CGI (node409.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.2.10 Common problems and (node411.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.3", "length": 3295, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node410.html"} {"title": "11.2.10 Common problems and solutions", "text": "node410.html | module-cgi.html | module-cgitb.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.2.9 Debugging CGI scripts (node410.html)\nUp:\n11.2 cgi (module-cgi.html)\nNext:\n11.3 cgitb (module-cgitb.html)\n---\n## 11.2.10 Common problems and solutions", "python_version": "2.3", "length": 292, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node411.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\nPrevious:\n11.4.1 URLopener Objects (urlopener-objs.html)\nUp:\n11.4 urllib (module-urllib.html)\nNext:\n11.5 urllib2 (module-urllib2.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:\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\", params)\n>>> print f.read()\n```\nThe following example uses an explicitly specified HTTP proxy,\noverriding environment settings:\n```text\n\n>>> import urllib\n>>> proxies = {'http': 'http://proxy.example.com:8080/'}\n>>> opener = urllib.FancyURLopener(proxies)\n>>> f = opener.open(\"http://www.python.org\")\n>>> f.read()\n```\nThe following example uses no proxies at all, overriding environment\nsettings:", "python_version": "2.3", "length": 1189, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node415.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\nPrevious:\n3.4.1 Example (fpectl-example.html)\nUp:\n3.4 fpectl (module-fpectl.html)\nNext:\n3.5 atexit (module-atexit.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.3", "length": 857, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node43.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\nPrevious:\n11.20.6 ProtocolError Objects (protocol-error-objects.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.20.8 Example of Client (xmlrpc-client-example.html)\n---\n## 11.20.7 Convenience Functions", "python_version": "2.3", "length": 367, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node474.html"} {"title": "11.21.2 CGIXMLRPCRequestHandler", "text": "simple-xmlrpc-servers.html | module-SimpleXMLRPCServer.html | module-DocXMLRPCServer.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.21.1 SimpleXMLRPCServer Objects (simple-xmlrpc-servers.html)\nUp:\n11.21 SimpleXMLRPCServer (module-SimpleXMLRPCServer.html)\nNext:\n11.22 DocXMLRPCServer (module-DocXMLRPCServer.html)\n---\n## 11.21.2 CGIXMLRPCRequestHandler\nThe CGIXMLRPCRequestHandler class can be used to\nhandle XML-RPC requests sent to Python CGI scripts.\nExample:", "python_version": "2.3", "length": 507, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node478.html"} {"title": "11.22.2 DocCGIXMLRPCRequestHandler", "text": "doc-xmlrpc-servers.html | module-DocXMLRPCServer.html | module-asyncore.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.22.1 DocXMLRPCServer Objects (doc-xmlrpc-servers.html)\nUp:\n11.22 DocXMLRPCServer (module-DocXMLRPCServer.html)\nNext:\n11.23 asyncore (module-asyncore.html)\n---\n## 11.22.2 DocCGIXMLRPCRequestHandler\nThe DocCGIXMLRPCRequestHandler class is derived from\nSimpleXMLRPCServer.CGIXMLRPCRequestHandler and provides a means\nof creating self-documenting, XML-RPC CGI scripts. HTTP POST requests\nare handled as XML-RPC method calls. HTTP GET requests are handled by\ngenerating pydoc-style HTML documentation. This allows a server to\nprovide its own web-based documentation.", "python_version": "2.3", "length": 726, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node481.html"} {"title": "11.24.1 asynchat - Auxiliary Classes and Functions", "text": "module-asynchat.html | module-asynchat.html | asynchat-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.24 asynchat (module-asynchat.html)\nUp:\n11.24 asynchat (module-asynchat.html)\nNext:\n11.24.2 asynchat Example (asynchat-example.html)\n---\n## 11.24.1 asynchat - Auxiliary Classes and Functions\nThe asynchat module also defines one utility function, which may be\nof use in network and textual analysis operations.", "python_version": "2.3", "length": 464, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node485.html"} {"title": "12.2.1.1 Deprecated methods", "text": "module-email.Message.html | module-email.Message.html | module-email.Parser.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.1 Representing an email (module-email.Message.html)\nUp:\n12.2.1 Representing an email (module-email.Message.html)\nNext:\n12.2.2 Parsing email messages (module-email.Parser.html)\n---\n### 12.2.1.1 Deprecated methods\nThe following methods are deprecated in email version 2.\nThey are documented here for completeness.", "python_version": "2.3", "length": 482, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node495.html"} {"title": "12.2.2.1 Parser class API", "text": "module-email.Parser.html | module-email.Parser.html | node498.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.2 Parsing email messages (module-email.Parser.html)\nUp:\n12.2.2 Parsing email messages (module-email.Parser.html)\nNext:\n12.2.2.2 Additional notes (node498.html)\n---\n### 12.2.2.1 Parser class API\nThe other public Parser methods are:\nSince creating a message object structure from a string or a file\nobject is such a common task, two functions are provided as a\nconvenience. They are available in the top-level email\npackage 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.3", "length": 742, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node497.html"} {"title": "12.2.2.2 Additional notes", "text": "node497.html | module-email.Parser.html | module-email.Generator.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.2.1 Parser class API (node497.html)\nUp:\n12.2.2 Parsing email messages (module-email.Parser.html)\nNext:\n12.2.3 Generating MIME documents (module-email.Generator.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\n`False` for is_multipart(). Their\nget_payload() method will return a string object.\n- All multipart type messages will be parsed as a\ncontainer message object with a list of sub-message objects for\ntheir payload. The outer container message will return\n`True` for is_multipart() and their\nget_payload() method will return the list of\nMessage subparts.\n- Most messages with a content type of message/*\n(e.g. message/deliver-status and\nmessage/rfc822) will also be parsed as container\nobject containing a list payload of length 1. Their\nis_multipart() method will return `True`. The\nsingle element in the list payload will be a sub-message object.", "python_version": "2.3", "length": 1173, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node498.html"} {"title": "12.2.3.1 Deprecated methods", "text": "module-email.Generator.html | module-email.Generator.html | node501.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.3 Generating MIME documents (module-email.Generator.html)\nUp:\n12.2.3 Generating MIME documents (module-email.Generator.html)\nNext:\n12.2.4 Creating email and (node501.html)\n---\n### 12.2.3.1 Deprecated methods\nThe following methods are deprecated in email version 2.\nThey are documented here for completeness.", "python_version": "2.3", "length": 470, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node500.html"} {"title": "12.2.4 Creating email and MIME objects from scratch", "text": "node500.html | module-email.html | module-email.Header.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.3.1 Deprecated methods (node500.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.5 Internationalized headers (module-email.Header.html)\n---\n## 12.2.4 Creating email and MIME objects from scratch\nOrdinarily, you get a message object structure by passing a file or\nsome text to a parser, which parses the text and returns the root\nmessage object. However you can also build a complete message\nstructure from scratch, or even individual Message objects by\nhand. In fact, you can also take an existing structure and add new\nMessage objects, move them around, etc. This makes a very\nconvenient interface for slicing-and-dicing MIME messages.\nYou can create a new object structure by creating Message\ninstances, adding attachments and all the appropriate headers manually.\nFor MIME messages though, the email package provides some\nconvenient subclasses 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.3", "length": 1270, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node501.html"} {"title": "12.2.11 Differences from email v1 (up to Python 2.2.1)", "text": "module-email.Iterators.html | module-email.html | node509.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.10 Iterators (module-email.Iterators.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.12 Differences from mimelib (node509.html)\n---\n## 12.2.11 Differences from email v1 (up to Python 2.2.1)\nVersion 1 of the email package was bundled with Python\nreleases up to Python 2.2.1. Version 2 was developed for the Python\n2.3 release, and backported to Python 2.2.2. It was also available as\na separate distutils based package. email version 2 is\nalmost entirely backward compatible with version 1, with the\nfollowing differences:\n- The email.Header and email.Charset modules\nhave been added.\n- The pickle format for Message instances has changed.\nSince this was never (and still isn't) formally defined, this\nisn't considered a backward incompatibility. However if your\napplication pickles and unpickles Message instances, be\naware that in email version 2, Message\ninstances now have private variables _charset and\n_default_type.\n- Several methods in the Message class have been\ndeprecated, or their signatures changed. Also, many new methods\nhave been added. See the documentation for the Message\nclass for details. The changes should be completely backward\ncompatible.\n- The object structure has changed in the face of\nmessage/rfc822 content types. In email\nversion 1, such a type would be represented by a scalar payload,\ni.e. the container message's is_multipart() returned\nfalse, get_payload() was not a list object, but a single\nMessage instance.\nThis structure was inconsistent with the rest of the package, so\nthe object representation for message/rfc822 content\ntypes was changed. In email version 2, the container\ndoes return `True` from is_multipart(), and\nget_payload() returns a list containing a single\nMessage item.\nNote that this is one place that backward compatibility could\nnot be completely maintained. However, if you're already\ntesting the return type of get_payload(), you should be\nfine. You just need to make sure your code doesn't do a\nset_payload() with a Message instance on a\ncontainer with a content type of message/rfc822.\n- The Parser constructor's strict argument was\nadded, and its parse() and parsestr() methods\ngrew a headersonly argument. The strict flag was\nalso added to functions email.message_from_file()\nand email.message_from_string().\n- Generator.__call__() is deprecated; use\nGenerator.flatten() instead. The Generator\nclass has also grown the clone() method.\n- The DecodedGenerator class in the\nemail.Generator module was added.\n- The intermediate base classes MIMENonMultipart and\nMIMEMultipart have been added, and interposed in the\nclass hierarchy for most of the other MIME-related derived\nclasses.\n- The _encoder argument to the MIMEText constructor\nhas been deprecated. Encoding now happens implicitly based\non the _charset argument.\n- The following functions in the email.Utils module have\nbeen deprecated: dump_address_pairs(),\ndecode(), and encode(). The following\nfunctions have been added to the module:\nmake_msgid(), decode_rfc2231(),\nencode_rfc2231(), and decode_params().\n- The non-public function email.Iterators._structure()\nwas added.", "python_version": "2.3", "length": 3246, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node508.html"} {"title": "12.2.12 Differences from mimelib", "text": "node508.html | module-email.html | node510.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.11 Differences from email (node508.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.2.13 Examples (node510.html)\n---\n## 12.2.12 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. Backward compatibility between\nthe mimelib package and the email package was not a\npriority.\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.3 (#foot50622).\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.3", "length": 4609, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node509.html"} {"title": "12.2.13 Examples", "text": "node509.html | module-email.html | module-mailcap.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.2.12 Differences from mimelib (node509.html)\nUp:\n12.2 email (module-email.html)\nNext:\n12.3 mailcap (module-mailcap.html)\n---\n## 12.2.13 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# Import smtplib for the actual sending function\nimport smtplib\n\n# Import the email modules we'll need\nfrom email.MIMEText import MIMEText\n\n# Open a plain text file for reading. For this example, assume that\n# the text file contains only ASCII characters.\nfp = open(textfile, 'rb')\n# Create a text/plain message\nmsg = MIMEText(fp.read())\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, but don't include the\n# envelope header.\ns = smtplib.SMTP()\ns.connect()\ns.sendmail(me, [you], msg.as_string())\ns.close()\n```\nDownload as text (original file name: email-simple.py). (email-simple.txt)\nHere's an example of how to send a MIME message containing a bunch of\nfamily pictures that may be residing in a directory:\n```text\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.MIMEMultipart import MIMEMultipart\n\nCOMMASPACE = ', '\n\n# Create the container (outer) email message.\nmsg = MIMEMultipart()\nmsg['Subject'] = 'Our family reunion'\n# me == the sender's email address\n# family = the list of all recipients' email addresses\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())\ns.close()\n```\nDownload as text (original file name: email-mime.py). (email-mime.txt)\nHere's an example of how to send the entire contents of a directory as\nan email message:\n12.4 (#foot50613)\n```text\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.MIMEMultipart import MIMEMultipart\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 = MIMEMultipart()\nouter['Subject'] = 'Contents of directory %s' % os.path.abspath(dir)\nouter['To'] = COMMASPACE.join(recips)\nouter['From'] = sender\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.set_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\n# Now send the message\ns = smtplib.SMTP()\ns.connect()\ns.sendmail(sender, recips, outer.as_string())\ns.close()\n\nif __name__ == '__main__':\nmain()\n```\nDownload as text (original file name: email-dir.py). (email-dir.txt)\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.3", "length": 5825, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node510.html"} {"title": "12.20.1 Module Contents", "text": "module-csv.html | module-csv.html | csv-fmt-params.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.20 csv (module-csv.html)\nUp:\n12.20 csv (module-csv.html)\nNext:\n12.20.2 Dialects and Formatting (csv-fmt-params.html)\n---\n## 12.20.1 Module Contents\nThe csv module defines the following functions:\nThe csv module defines the following classes:\nThe Sniffer class provides a single method:\nThe csv module defines the following constants:\nThe csv module defines the following exception:", "python_version": "2.3", "length": 525, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node545.html"} {"title": "12.20.3 Reader Objects", "text": "csv-fmt-params.html | module-csv.html | node548.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.20.2 Dialects and Formatting (csv-fmt-params.html)\nUp:\n12.20 csv (module-csv.html)\nNext:\n12.20.4 Writer Objects (node548.html)\n---\n## 12.20.3 Reader Objects\nReader objects (DictReader instances and objects returned by\nthe reader()function) have the following public methods:", "python_version": "2.3", "length": 415, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node547.html"} {"title": "12.20.4 Writer Objects", "text": "node547.html | module-csv.html | node549.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.20.3 Reader Objects (node547.html)\nUp:\n12.20 csv (module-csv.html)\nNext:\n12.20.5 Examples (node549.html)\n---\n## 12.20.4 Writer Objects\nWriter objects (DictWriter instances and objects returned by\nthe writer() function) have the following public methods:", "python_version": "2.3", "length": 387, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node548.html"} {"title": "12.20.5 Examples", "text": "node548.html | module-csv.html | markup.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n12.20.4 Writer Objects (node548.html)\nUp:\n12.20 csv (module-csv.html)\nNext:\n13. Structured Markup Processing (markup.html)\n---\n## 12.20.5 Examples\nThe ``Hello, world'' of csv reading is\n```text\n\nimport csv\nreader = csv.reader(file(\"some.csv\"))\nfor row in reader:\nprint row\n```\nThe corresponding simplest possible writing example is\n```text\n\nimport csv\nwriter = csv.writer(file(\"some.csv\", \"w\"))\nfor row in someiterable:\nwriter.writerow(row)\n```", "python_version": "2.3", "length": 574, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node549.html"} {"title": "13.6.1 Module Contents", "text": "module-xml.dom.html | module-xml.dom.html | node565.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6 xml.dom (module-xml.dom.html)\nUp:\n13.6 xml.dom (module-xml.dom.html)\nNext:\n13.6.2 Objects in the (node565.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.3", "length": 871, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node564.html"} {"title": "13.6.2 Objects in the DOM", "text": "node564.html | module-xml.dom.html | dom-implementation-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n13.6.1 Module Contents (node564.html)\nUp:\n13.6 xml.dom (module-xml.dom.html)\nNext:\n13.6.2.1 DOMImplementation Objects (dom-implementation-objects.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.3", "length": 684, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node565.html"} {"title": "3.14.1 Relationship to other Python modules", "text": "module-pickle.html | module-pickle.html | node62.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14 pickle (module-pickle.html)\nUp:\n3.14 pickle (module-pickle.html)\nNext:\n3.14.2 Data stream format (node62.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.\nWarning:\nThe pickle module is not intended to be secure against\nerroneous or maliciously constructed data. Never unpickle data\nreceived from an untrusted or unauthenticated source.\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.3", "length": 3672, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node61.html"} {"title": "3.14.2 Data stream format", "text": "node61.html | module-pickle.html | node63.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.1 Relationship to other (node61.html)\nUp:\n3.14 pickle (module-pickle.html)\nNext:\n3.14.3 Usage (node63.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.\nThere are currently 3 different protocols which can be used for pickling.\n- Protocol version 0 is the original ASCII protocol and is backwards\ncompatible with earlier versions of Python.\n- Protocol version 1 is the old binary format which is also compatible\nwith earlier versions of Python.\n- Protocol version 2 was introduced in Python 2.3. It provides\nmuch more efficient pickling of new-style classes.\nRefer to PEP 307 for more information.\nIf a protocol is not specified, protocol 0 is used.\nIf protocol is specified as a negative value\nor HIGHEST_PROTOCOL,\nthe highest protocol version available will be used.\nChanged in version 2.3:\nThe bin parameter is deprecated and only provided\nfor backwards compatibility. You should use the protocol\nparameter instead.\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. A protocol version >= 1 implies use of a binary format.", "python_version": "2.3", "length": 1926, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node62.html"} {"title": "3.14.3 Usage", "text": "node62.html | module-pickle.html | node64.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.2 Data stream format (node62.html)\nUp:\n3.14 pickle (module-pickle.html)\nNext:\n3.14.4 What can be (node64.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 constant:\nThe 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.3 (#foot8173), 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.4 (#foot8175).\nUnpickler objects are defined as:\nUnpickler objects have one (or two) public methods:", "python_version": "2.3", "length": 1224, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node63.html"} {"title": "16.1.1 Tkinter Modules", "text": "module-Tkinter.html | module-Tkinter.html | node631.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1 Tkinter (module-Tkinter.html)\nUp:\n16.1 Tkinter (module-Tkinter.html)\nNext:\n16.1.2 Tkinter Life Preserver (node631.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.3", "length": 1861, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node630.html"} {"title": "16.1.2 Tkinter Life Preserver", "text": "node630.html | module-Tkinter.html | node632.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.1 Tkinter Modules (node630.html)\nUp:\n16.1 Tkinter (module-Tkinter.html)\nNext:\n16.1.2.1 How To Use (node632.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.3", "length": 1000, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node631.html"} {"title": "16.1.2.1 How To Use This Section", "text": "node631.html | node631.html | node633.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.2 Tkinter Life Preserver (node631.html)\nUp:\n16.1.2 Tkinter Life Preserver (node631.html)\nNext:\n16.1.2.2 A Simple Hello (node633.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.3", "length": 1615, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node632.html"} {"title": "16.1.2.2 A Simple Hello World Program", "text": "node632.html | node631.html | node634.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.2.1 How To Use (node632.html)\nUp:\n16.1.2 Tkinter Life Preserver (node631.html)\nNext:\n16.1.3 A (Very) Quick (node634.html)\n---\n### 16.1.2.2 A Simple Hello World Program\n```text\n\nfrom Tkinter import *\n\nclass Application(Frame):\ndef say_hi(self):\nprint \"hi there, everyone!\"\n\ndef createWidgets(self):\nself.QUIT = Button(self)\nself.QUIT[\"text\"] = \"QUIT\"\nself.QUIT[\"fg\"] = \"red\"\nself.QUIT[\"command\"] = self.quit\n\nself.QUIT.pack({\"side\": \"left\"})\n\nself.hi_there = Button(self)\nself.hi_there[\"text\"] = \"Hello\",\nself.hi_there[\"command\"] = self.say_hi\n\nself.hi_there.pack({\"side\": \"left\"})\n\ndef __init__(self, master=None):\nFrame.__init__(self, master)\nself.pack()\nself.createWidgets()\n\napp = Application()\napp.mainloop()\n```", "python_version": "2.3", "length": 849, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node633.html"} {"title": "16.1.3 A (Very) Quick Look at Tcl/Tk", "text": "node633.html | module-Tkinter.html | tkinter-basic-mapping.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.2.2 A Simple Hello (node633.html)\nUp:\n16.1 Tkinter (module-Tkinter.html)\nNext:\n16.1.4 Mapping Basic Tk (tkinter-basic-mapping.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.3", "length": 3351, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node634.html"} {"title": "16.1.5 How Tk and Tkinter are Related", "text": "tkinter-basic-mapping.html | module-Tkinter.html | node637.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.4 Mapping Basic Tk (tkinter-basic-mapping.html)\nUp:\n16.1 Tkinter (module-Tkinter.html)\nNext:\n16.1.6 Handy Reference (node637.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.3", "length": 1551, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node636.html"} {"title": "16.1.6 Handy Reference", "text": "node636.html | module-Tkinter.html | tkinter-setting-options.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.5 How Tk and (node636.html)\nUp:\n16.1 Tkinter (module-Tkinter.html)\nNext:\n16.1.6.1 Setting Options (tkinter-setting-options.html)\n---\n## 16.1.6 Handy Reference", "python_version": "2.3", "length": 314, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node637.html"} {"title": "16.1.6.2 The Packer", "text": "tkinter-setting-options.html | node637.html | node640.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.1 Setting Options (tkinter-setting-options.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.3 Packer Options (node640.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.3", "length": 1944, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node639.html"} {"title": "3.14.4 What can be pickled and unpickled?", "text": "node63.html | module-pickle.html | pickle-protocol.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.3 Usage (node63.html)\nUp:\n3.14 pickle (module-pickle.html)\nNext:\n3.14.5 The pickle protocol (pickle-protocol.html)\n---\n## 3.14.4 What can be pickled and unpickled?\nThe following types can be pickled:\n- `None`, `True`, and `False`\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.5 (#foot8176).\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.3", "length": 2483, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node64.html"} {"title": "16.1.6.3 Packer Options", "text": "node639.html | node637.html | node641.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.2 The Packer (node639.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.4 Coupling Widget Variables (node641.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.3", "length": 846, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node640.html"} {"title": "16.1.6.4 Coupling Widget Variables", "text": "node640.html | node637.html | node642.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.3 Packer Options (node640.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.5 The Window Manager (node642.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.3", "length": 2128, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node641.html"} {"title": "16.1.6.5 The Window Manager", "text": "node641.html | node637.html | node643.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.4 Coupling Widget Variables (node641.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.6 Tk Option Data (node643.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.3", "length": 1518, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node642.html"} {"title": "16.1.6.6 Tk Option Data Types", "text": "node642.html | node637.html | node644.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.5 The Window Manager (node642.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.7 Bindings and Events (node644.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 strings `\"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.3", "length": 2939, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node643.html"} {"title": "16.1.6.7 Bindings and Events", "text": "node643.html | node637.html | node645.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.6 Tk Option Data (node643.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.8 The index Parameter (node645.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.3", "length": 1824, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node644.html"} {"title": "16.1.6.8 The index Parameter", "text": "node644.html | node637.html | node646.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.7 Bindings and Events (node644.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.9 Images (node646.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.3", "length": 2314, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node645.html"} {"title": "16.1.6.9 Images", "text": "node645.html | node637.html | module-Tix.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6.8 The index Parameter (node645.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.2 Tix (module-Tix.html)\n---\n### 16.1.6.9 Images\nBitmap/Pixelmap images can be created through the subclasses of\nTkinter.Image:\n- BitmapImage can be used for X11 bitmap data.\n- PhotoImage can be used for GIF and PPM/PGM color bitmaps.\nEither type of image is created through either the `file` or the\n`data` option (other options are available as well).\nThe image object can then be used wherever an `image` option is\nsupported by some widget (e.g. labels, buttons, menus). In these\ncases, Tk will not keep a reference to the image. When the last Python\nreference to the image object is deleted, the image data is deleted as\nwell, and Tk will display an empty box wherever the image was used.", "python_version": "2.3", "length": 916, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node646.html"} {"title": "16.2.1 Using Tix", "text": "module-Tix.html | module-Tix.html | node649.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2 Tix (module-Tix.html)\nUp:\n16.2 Tix (module-Tix.html)\nNext:\n16.2.2 Tix Widgets (node649.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.3", "length": 1117, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node648.html"} {"title": "16.2.2 Tix Widgets", "text": "node648.html | module-Tix.html | node650.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.1 Using Tix (node648.html)\nUp:\n16.2 Tix (module-Tix.html)\nNext:\n16.2.2.1 Basic Widgets (node650.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.3", "length": 534, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node649.html"} {"title": "16.2.2.1 Basic Widgets", "text": "node649.html | node649.html | node651.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2 Tix Widgets (node649.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.2.2 File Selectors (node651.html)\n---\n### 16.2.2.1 Basic Widgets", "python_version": "2.3", "length": 275, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node650.html"} {"title": "16.2.2.2 File Selectors", "text": "node650.html | node649.html | node652.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.1 Basic Widgets (node650.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.2.3 Hierachical ListBox (node652.html)\n---\n### 16.2.2.2 File Selectors", "python_version": "2.3", "length": 285, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node651.html"} {"title": "16.2.2.3 Hierachical ListBox", "text": "node651.html | node649.html | node653.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.2 File Selectors (node651.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.2.4 Tabular ListBox (node653.html)\n---\n### 16.2.2.3 Hierachical ListBox", "python_version": "2.3", "length": 287, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node652.html"} {"title": "16.2.2.4 Tabular ListBox", "text": "node652.html | node649.html | node654.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.3 Hierachical ListBox (node652.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.2.5 Manager Widgets (node654.html)\n---\n### 16.2.2.4 Tabular ListBox", "python_version": "2.3", "length": 288, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node653.html"} {"title": "16.2.2.5 Manager Widgets", "text": "node653.html | node649.html | node655.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.4 Tabular ListBox (node653.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.2.6 Image Types (node655.html)\n---\n### 16.2.2.5 Manager Widgets", "python_version": "2.3", "length": 280, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node654.html"} {"title": "16.2.2.6 Image Types", "text": "node654.html | node649.html | node656.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.5 Manager Widgets (node654.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.2.7 Miscellaneous Widgets (node656.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.3", "length": 918, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node655.html"} {"title": "16.2.2.7 Miscellaneous Widgets", "text": "node655.html | node649.html | node657.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.6 Image Types (node655.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.2.8 Form Geometry Manager (node657.html)\n---\n### 16.2.2.7 Miscellaneous Widgets", "python_version": "2.3", "length": 292, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node656.html"} {"title": "16.2.2.8 Form Geometry Manager", "text": "node656.html | node649.html | node658.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.7 Miscellaneous Widgets (node656.html)\nUp:\n16.2.2 Tix Widgets (node649.html)\nNext:\n16.2.3 Tix Commands (node658.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.3", "length": 379, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node657.html"} {"title": "16.2.3 Tix Commands", "text": "node657.html | module-Tix.html | module-ScrolledText.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.2.2.8 Form Geometry Manager (node657.html)\nUp:\n16.2 Tix (module-Tix.html)\nNext:\n16.3 ScrolledText (module-ScrolledText.html)\n---\n## 16.2.3 Tix Commands", "python_version": "2.3", "length": 297, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node658.html"} {"title": "16.5.1 Menus", "text": "idle.html | idle.html | node664.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5 Idle (idle.html)\nUp:\n16.5 Idle (idle.html)\nNext:\n16.5.1.1 File menu (node664.html)\n---\n## 16.5.1 Menus", "python_version": "2.3", "length": 229, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node663.html"} {"title": "16.5.1.1 File menu", "text": "node663.html | node663.html | node665.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.1 Menus (node663.html)\nUp:\n16.5.1 Menus (node663.html)\nNext:\n16.5.1.2 Edit menu (node665.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.3", "length": 910, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node664.html"} {"title": "16.5.1.2 Edit menu", "text": "node664.html | node663.html | node666.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.1.1 File menu (node664.html)\nUp:\n16.5.1 Menus (node663.html)\nNext:\n16.5.1.3 Windows menu (node666.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.3", "length": 1545, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node665.html"} {"title": "16.5.1.3 Windows menu", "text": "node665.html | node663.html | node667.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.1.2 Edit menu (node665.html)\nUp:\n16.5.1 Menus (node663.html)\nNext:\n16.5.1.4 Debug menu (in (node667.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.3", "length": 480, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node666.html"} {"title": "16.5.1.4 Debug menu (in the Python Shell window only)", "text": "node666.html | node663.html | node668.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.1.3 Windows menu (node666.html)\nUp:\n16.5.1 Menus (node663.html)\nNext:\n16.5.2 Basic editing and (node668.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.3", "length": 599, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node667.html"} {"title": "16.5.2 Basic editing and navigation", "text": "node667.html | idle.html | node669.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.1.4 Debug menu (in (node667.html)\nUp:\n16.5 Idle (idle.html)\nNext:\n16.5.2.1 Automatic indentation (node669.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.3", "length": 542, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node668.html"} {"title": "16.5.2.1 Automatic indentation", "text": "node668.html | node668.html | node670.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.2 Basic editing and (node668.html)\nUp:\n16.5.2 Basic editing and (node668.html)\nNext:\n16.5.2.2 Python Shell window (node670.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.3", "length": 681, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node669.html"} {"title": "3.14.5.2 Pickling and unpickling extension types", "text": "pickle-inst.html | pickle-protocol.html | node68.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.5.1 Pickling and unpickling (pickle-inst.html)\nUp:\n3.14.5 The pickle protocol (pickle-protocol.html)\nNext:\n3.14.5.3 Pickling and unpickling (node68.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`.\nDeprecated since release 2.3.\nUse the tuple of arguments instead\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.\nIf the second item was `None`, then instead of calling the\ncallable directly, its __basicnew__() method is called\nwithout arguments. It should also return the unpickled object.\nDeprecated since release 2.3.\nUse the tuple of arguments instead\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.3", "length": 2623, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node67.html"} {"title": "16.5.2.2 Python Shell window", "text": "node669.html | node668.html | node671.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.2.1 Automatic indentation (node669.html)\nUp:\n16.5.2 Basic editing and (node668.html)\nNext:\n16.5.3 Syntax colors (node671.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.3", "length": 588, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node670.html"} {"title": "16.5.3 Syntax colors", "text": "node670.html | idle.html | node672.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.2.2 Python Shell window (node670.html)\nUp:\n16.5 Idle (idle.html)\nNext:\n16.5.3.1 Command line usage (node672.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.3", "length": 609, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node671.html"} {"title": "16.5.3.1 Command line usage", "text": "node671.html | node671.html | other-gui-packages.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.3 Syntax colors (node671.html)\nUp:\n16.5.3 Syntax colors (node671.html)\nNext:\n16.6 Other Graphical User (other-gui-packages.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.3", "length": 1133, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node672.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\nPrevious:\n17.1.2 Defining restricted environments (rexec-extension.html)\nUp:\n17.1 rexec (module-rexec.html)\nNext:\n17.2 Bastion (module-Bastion.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.3", "length": 498, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node678.html"} {"title": "3.14.5.3 Pickling and unpickling external objects", "text": "node67.html | pickle-protocol.html | pickle-sub.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.5.2 Pickling and unpickling (node67.html)\nUp:\n3.14.5 The pickle protocol (pickle-protocol.html)\nNext:\n3.14.6 Subclassing Unpicklers (pickle-sub.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.8 (#foot8184).\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.9 (#foot8097). Setting\npersistent_load to a list is usually used in conjunction with\nthe noload() method on the Unpickler.", "python_version": "2.3", "length": 2914, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node68.html"} {"title": "18.1.1 Creating AST Objects", "text": "module-parser.html | module-parser.html | node683.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1 parser (module-parser.html)\nUp:\n18.1 parser (module-parser.html)\nNext:\n18.1.2 Converting AST Objects (node683.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.3", "length": 474, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node682.html"} {"title": "18.1.2 Converting AST Objects", "text": "node682.html | module-parser.html | node684.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.1 Creating AST Objects (node682.html)\nUp:\n18.1 parser (module-parser.html)\nNext:\n18.1.3 Queries on AST (node684.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.3", "length": 543, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node683.html"} {"title": "18.1.3 Queries on AST Objects", "text": "node683.html | module-parser.html | node685.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.2 Converting AST Objects (node683.html)\nUp:\n18.1 parser (module-parser.html)\nNext:\n18.1.4 Exceptions and Error (node685.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.3", "length": 573, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node684.html"} {"title": "18.1.4 Exceptions and Error Handling", "text": "node684.html | module-parser.html | node686.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.3 Queries on AST (node684.html)\nUp:\n18.1 parser (module-parser.html)\nNext:\n18.1.5 AST Objects (node686.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.3", "length": 901, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node685.html"} {"title": "18.1.5 AST Objects", "text": "node685.html | module-parser.html | node687.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.4 Exceptions and Error (node685.html)\nUp:\n18.1 parser (module-parser.html)\nNext:\n18.1.6 Examples (node687.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.3", "length": 474, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node686.html"} {"title": "18.1.6 Examples", "text": "node686.html | module-parser.html | node688.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.5 AST Objects (node686.html)\nUp:\n18.1 parser (module-parser.html)\nNext:\n18.1.6.1 Emulation of compile() (node688.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.3", "length": 675, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node687.html"} {"title": "18.1.6.1 Emulation of compile()", "text": "node687.html | node687.html | node689.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.6 Examples (node687.html)\nUp:\n18.1.6 Examples (node687.html)\nNext:\n18.1.6.2 Information Discovery (node689.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.3", "length": 1207, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node688.html"} {"title": "18.1.6.2 Information Discovery", "text": "node688.html | node687.html | module-symbol.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n18.1.6.1 Emulation of compile() (node688.html)\nUp:\n18.1.6 Examples (node687.html)\nNext:\n18.2 symbol (module-symbol.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.3", "length": 13412, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node689.html"} {"title": "19.2 Limitations", "text": "module-compiler.html | compiler.html | node705.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.1 The basic interface (module-compiler.html)\nUp:\n19. Python compiler package (compiler.html)\nNext:\n19.3 Python Abstract Syntax (node705.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.3", "length": 905, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node704.html"} {"title": "19.3 Python Abstract Syntax", "text": "node704.html | compiler.html | module-compiler.ast.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.2 Limitations (node704.html)\nUp:\n19. Python compiler package (compiler.html)\nNext:\n19.3.1 AST Nodes (module-compiler.ast.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.3", "length": 1442, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node705.html"} {"title": "19.3.2 Assignment nodes", "text": "module-compiler.ast.html | node705.html | node708.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.3.1 AST Nodes (module-compiler.ast.html)\nUp:\n19.3 Python Abstract Syntax (node705.html)\nNext:\n19.3.3 Examples (node708.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.3", "length": 1450, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node707.html"} {"title": "19.3.3 Examples", "text": "node707.html | node705.html | module-compiler.visitor.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.3.2 Assignment nodes (node707.html)\nUp:\n19.3 Python Abstract Syntax (node705.html)\nNext:\n19.4 Using Visitors to (module-compiler.visitor.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.3", "length": 1979, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node708.html"} {"title": "19.5 Bytecode Generation", "text": "module-compiler.visitor.html | compiler.html | sgi.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.4 Using Visitors to (module-compiler.visitor.html)\nUp:\n19. Python compiler package (compiler.html)\nNext:\n20. SGI IRIX Specific (sgi.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.3", "length": 694, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node710.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\nPrevious:\n20.4 fl (module-fl.html)\nUp:\n20.4 fl (module-fl.html)\nNext:\n20.4.2 Form Objects (form-objects.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.3", "length": 442, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node720.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\nPrevious:\n21.2 SUNAUDIODEV (module-sunaudiodev-constants.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n22.1 msvcrt - Useful (module-msvcrt.html)\n---\n# 22. MS Windows Specific Services\nThis chapter describes modules that are only available on MS Windows\nplatforms.", "python_version": "2.3", "length": 410, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node735.html"} {"title": "3.17.1 Restrictions", "text": "module-shelve.html | module-shelve.html | node75.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.17 shelve (module-shelve.html)\nUp:\n3.17 shelve (module-shelve.html)\nNext:\n3.17.2 Example (node75.html)\n---\n## 3.17.1 Restrictions\n- The choice of which database package will be used\n(such as dbm (module-dbm.html), gdbm (module-gdbm.html) or bsddb (module-bsddb.html)) depends on\nwhich interface is available. Therefore it is not safe to open the database\ndirectly using 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- Depending on the implementation, closing a persistent dictionary may\nor may not be necessary to flush changes to disk. The __del__\nmethod of the Shelf class calls the close method, so the\nprogrammer generally need not do this explicitly.\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.3", "length": 1448, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node74.html"} {"title": "A.1 Frameworks", "text": "undoc.html | undoc.html | node745.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nA. Undocumented Modules (undoc.html)\nUp:\nA. Undocumented Modules (undoc.html)\nNext:\nA.2 Miscellaneous useful utilities (node745.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.3", "length": 538, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node744.html"} {"title": "A.2 Miscellaneous useful utilities", "text": "node744.html | undoc.html | node746.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nA.1 Frameworks (node744.html)\nUp:\nA. Undocumented Modules (undoc.html)\nNext:\nA.3 Platform specific modules (node746.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).\nplatform: -- This module tries to retrieve as much platform identifying data as\npossible. It makes this information available via function APIs.\nIf called from the command line, it prints the platform information\nconcatenated as single string to `sys.stdout`. The output format\nis useable as part of a filename.\nNew in version 2.3.\nsmtpd: -- An SMTP daemon implementation which meets the minimum requirements\nfor RFC 821 (http://www.faqs.org/rfcs/rfc821.html) conformance.", "python_version": "2.3", "length": 978, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node745.html"} {"title": "A.3 Platform specific modules", "text": "node745.html | undoc.html | node747.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nA.2 Miscellaneous useful utilities (node745.html)\nUp:\nA. Undocumented Modules (undoc.html)\nNext:\nA.4 Multimedia (node747.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.\nntpath: -- Implementation of os.path on Win32, Win64, WinCE, and\nOS/2 platforms.\nposixpath: -- Implementation of os.path on POSIX.\nbsddb185: -- Backwards compatibility module for systems which still use the Berkeley\nDB 1.85 module. It is normally only available on certain BSD Unix-based\nsystems. It should never be used directly.", "python_version": "2.3", "length": 780, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node746.html"} {"title": "A.4 Multimedia", "text": "node746.html | undoc.html | obsolete-modules.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nA.3 Platform specific modules (node746.html)\nUp:\nA. Undocumented Modules (undoc.html)\nNext:\nA.5 Obsolete (obsolete-modules.html)\n---\n# A.4 Multimedia\naudiodev: -- Platform-independent API for playing audio data.\nlinuxaudiodev: -- Play audio data on the Linux audio device. Replaced in Python 2.3\nby the ossaudiodev module.\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.\nossaudiodev: -- Play audio data via the Open Sound System API. This is usable on\nLinux, some flavors of BSD, and some commercial Unix platforms.", "python_version": "2.3", "length": 813, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node747.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\nPrevious:\nA.5 Obsolete (obsolete-modules.html)\nUp:\nA. Undocumented Modules (undoc.html)\nNext:\nB. Reporting Bugs (reporting-bugs.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.3", "length": 530, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node749.html"} {"title": "3.17.2 Example", "text": "node74.html | module-shelve.html | module-copy.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.17.1 Restrictions (node74.html)\nUp:\n3.17 shelve (module-shelve.html)\nNext:\n3.18 copy (module-copy.html)\n---\n## 3.17.2 Example\nTo summarize the interface (`key` is a string, `data` is an\narbitrary object):\n```text\n\nimport shelve\n\nd = shelve.open(filename) # open -- file may get suffix added by low-level\n# library\n\nd[key] = data # store data at key (overwrites old data if\n# using an existing key)\ndata = d[key] # retrieve a COPY of 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\n# as d was opened WITHOUT writeback=True, beware:\nd['xx'] = range(4) # this works as expected, but...\nd['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!!!\n# having opened d without writeback=True, you need to code carefully:\ntemp = d['xx'] # extracts the copy\ntemp.append(5) # mutates the copy\nd['xx'] = temp # stores the copy right back, to persist it\n# or, d=shelve.open(filename,writeback=True) would let you just code\n# d['xx'].append(5) and have it work as expected, BUT it would also\n# consume more memory and make the d.close() operation slower.\n\nd.close() # close it\n```", "python_version": "2.3", "length": 1387, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node75.html"} {"title": "C. History and License", "text": "reporting-bugs.html | lib.html | node752.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nB. Reporting Bugs (reporting-bugs.html)\nUp:\nPython Library Reference (lib.html)\nNext:\nC.1 History of the (node752.html)\n---\n# C. History and License", "python_version": "2.3", "length": 279, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node751.html"} {"title": "C.1 History of the software", "text": "node751.html | node751.html | node753.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nC. History and License (node751.html)\nUp:\nC. History and License (node751.html)\nNext:\nC.2 Terms and conditions (node753.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 Digital Creations (now Zope\nCorporation; 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. Zope Corporation 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.3", "length": 1916, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node752.html"} {"title": "C.2 Terms and conditions for accessing or otherwise using Python", "text": "node752.html | node751.html | modindex.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nC.1 History of the (node752.html)\nUp:\nC. History and License (node751.html)\nNext:\nModule Index (modindex.html)\n---\n# C.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.3\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.3 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.3 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001-2003 Python Software Foundation; All\nRights Reserved'' are retained in Python 2.3 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.3 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.3.\n4. PSF is making Python 2.3 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.3 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.3, 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.3, 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.3", "length": 9914, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node753.html"} {"title": "3.25.1 PrettyPrinter Objects", "text": "module-pprint.html | module-pprint.html | module-repr.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.25 pprint (module-pprint.html)\nUp:\n3.25 pprint (module-pprint.html)\nNext:\n3.26 repr (module-repr.html)\n---\n## 3.25.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.\nThis method is provided as a hook to allow subclasses to modify the\nway objects are converted to strings. The default implementation uses\nthe internals of the saferepr() implementation.", "python_version": "2.3", "length": 743, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/node90.html"} {"title": "A.5 Obsolete", "text": "node747.html | undoc.html | node749.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nA.4 Multimedia (node747.html)\nUp:\nA. Undocumented Modules (undoc.html)\nNext:\nA.6 SGI-specific Extension modules (node749.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.3", "length": 3694, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.1 Request Objects (request-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.3 BaseHandler Objects (base-handler-objects.html)\n---\n## 11.5.2 OpenerDirector Objects\nOpenerDirector instances have the following methods:", "python_version": "2.3", "length": 391, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.10 operator (module-operator.html)\nUp:\n3.10 operator (module-operator.html)\nNext:\n3.11 inspect (module-inspect.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.3", "length": 472, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/operator-map.html"} {"title": "6.20.5.2 Adding new actions", "text": "optparse-adding-types.html | optparse-extending.html | optparse-extending-other-reasons.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.5.1 Adding new types (optparse-adding-types.html)\nUp:\n6.20.5 Extending optparse (optparse-extending.html)\nNext:\n6.20.5.3 Other reasons to (optparse-extending-other-reasons.html)\n---\n### 6.20.5.2 Adding new actions\nAdding new actions is a bit trickier, because you have to understand\nthat optparse has a couple of classifications for actions:\nSome default ``store'' actions are store, store_const,\nappend, and count. The default ``typed'' actions are\nstore, append, and callback.\nWhen you add an action, you need to decide if it's a ``store'' action,\na ``typed'', neither, or both. Three class attributes of\nOption (or your Option subclass) control this:\nIn order to actually implement your new action, you must override\nOption's take_action() method and add a case that\nrecognizes your action.\nFor example, let's add an ``extend'' action. This is similar to the\nstandard ``append'' action, but instead of taking a single value from\nthe command-line and appending it to an existing list, ``extend'' will\ntake multiple values in a single comma-delimited string, and extend an\nexisting list with them. That is, if --names is an\n``extend'' option of type string, the command line:\n```text\n\n--names=foo,bar --names blah --names ding,dong\n```\nwould result in a list:\n```text\n\n[\"foo\", \"bar\", \"blah\", \"ding\", \"dong\"]\n```\nAgain we define a subclass of Option:\n```text\n\nclass MyOption (Option):\n\nACTIONS = Option.ACTIONS + (\"extend\",)\nSTORE_ACTIONS = Option.STORE_ACTIONS + (\"extend\",)\nTYPED_ACTIONS = Option.TYPED_ACTIONS + (\"extend\",)\n\ndef take_action (self, action, dest, opt, value, values, parser):\nif action == \"extend\":\nlvalue = value.split(\",\")\nvalues.ensure_value(dest, []).extend(lvalue)\nelse:\nOption.take_action(\nself, action, dest, opt, value, values, parser)\n```\nFeatures of note:\n- ``extend'' both expects a value on the command-line and stores that\nvalue somewhere, so it goes in both STORE_ACTIONS and\nTYPED_ACTIONS.\n- MyOption.take_action() implements just this one new\naction, and passes control back to Option.take_action() for\nthe standard optparse actions.\n- values is an instance of the Values class, which\nprovides the very useful ensure_value()\nmethod. ensure_value() is essentially getattr()\nwith a safety valve; it is called as:\n```text\n\nvalues.ensure_value(attr, value)\n```\nIf the attr attribute of values doesn't exist or is\n`None`, then ensure_value() first sets it to value, and\nthen returns value. This is very handy for actions like\n``extend'', ``append'', and ``count'', all of which accumulate data in\na variable and expect that variable to be of a certain type (a list\nfor the first two, an integer for the latter). Using\nensure_value() means that scripts using your action don't\nhave to worry about setting a default value for the option\ndestinations in question; they can just leave the default as `None` and\nensure_value() will take care of getting it right when it's\nneeded.", "python_version": "2.3", "length": 3086, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-adding-actions.html"} {"title": "6.20.5.1 Adding new types", "text": "optparse-extending.html | optparse-extending.html | optparse-adding-actions.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.5 Extending optparse (optparse-extending.html)\nUp:\n6.20.5 Extending optparse (optparse-extending.html)\nNext:\n6.20.5.2 Adding new actions (optparse-adding-actions.html)\n---\n### 6.20.5.1 Adding new types\nTo add new types, you need to define your own subclass of\noptparse's Option class. This class has a couple of\nattributes that define optparse's types: TYPES and\nTYPE_CHECKER.\nTYPES is a tuple of type names; in your subclass, simply\ndefine a new tuple TYPES that builds on the standard one.\nTYPE_CHECKER is a dictionary mapping type names to\ntype-checking functions. A type-checking function has the following\nsignature:\n```text\n\ndef check_foo (option : Option, opt : string, value : string)\n-> foo\n```\nYou can name it whatever you like, and make it return any type you\nlike. The value returned by a type-checking function will wind up in\nthe OptionValues instance returned by\nOptionParser.parse_args(), or be passed to callbacks as the\nvalue parameter.\nYour type-checking function should raise OptionValueError\nif it encounters any problems. OptionValueError takes a\nsingle string argument, which is passed as-is to\nOptionParser's error() method, which in turn prepends\nthe program name and the string ``error:'' and prints everything to\nstderr before terminating the process.\nHere's a silly example that demonstrates adding a ``complex'' option\ntype to parse Python-style complex numbers on the command line. (This\nis even sillier than it used to be, because optparse 1.3 adds\nbuilt-in support for complex numbers [purely for completeness], but\nnever mind.)\nFirst, the necessary imports:\n```text\n\nfrom copy import copy\nfrom optparse import Option, OptionValueError\n```\nYou need to define your type-checker first, since it's referred to\nlater (in the TYPE_CHECKER class attribute of your\nOption subclass):\n```text\n\ndef check_complex (option, opt, value):\ntry:\nreturn complex(value)\nexcept ValueError:\nraise OptionValueError(\n\"option %s: invalid complex value: %r\" % (opt, value))\n```\nFinally, the Option subclass:\n```text\n\nclass MyOption (Option):\nTYPES = Option.TYPES + (\"complex\",)\nTYPE_CHECKER = copy(Option.TYPE_CHECKER)\nTYPE_CHECKER[\"complex\"] = check_complex\n```\n(If we didn't make a copy() of\nOption.TYPE_CHECKER, we would end up modifying the\nTYPE_CHECKER attribute of optparse's Option class.\nThis being Python, nothing stops you from doing that except good\nmanners and common sense.)\nThat's it! Now you can write a script that uses the new option type\njust like any other optparse-based script, except you have to\ninstruct your OptionParser to use MyOption instead of\nOption:\n```text\n\nparser = OptionParser(option_class=MyOption)\nparser.add_option(\"-c\", action=\"store\", type=\"complex\", dest=\"c\")\n```\nAlternately, you can build your own option list and pass it to\nOptionParser; if you don't use add_option() in the\nabove way, you don't need to tell OptionParser which option\nclass to use:\n```text\n\noption_list = [MyOption(\"-c\", action=\"store\", type=\"complex\", dest=\"c\")]\nparser = OptionParser(option_list=option_list)\n```", "python_version": "2.3", "length": 3203, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-adding-types.html"} {"title": "6.20.3 Advanced Usage", "text": "optparse-basic-summary.html | module-optparse.html | optparse-creating-the-parser.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2.7 Putting it all (optparse-basic-summary.html)\nUp:\n6.20 optparse (module-optparse.html)\nNext:\n6.20.3.1 Creating and populating (optparse-creating-the-parser.html)\n---\n## 6.20.3 Advanced Usage", "python_version": "2.3", "length": 370, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-advanced-usage.html"} {"title": "6.20.2.7 Putting it all together", "text": "optparse-error-handling.html | optparse-basic-usage.html | optparse-advanced-usage.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2.6 Error-handling (optparse-error-handling.html)\nUp:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nNext:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\n---\n### 6.20.2.7 Putting it all together\nHere's what optparse-based scripts typically look like:\n```text\n\nfrom optparse import OptionParser\n[...]\ndef main():\nusage = \"usage: \\%prog [-f] [-v] [-q] firstarg secondarg\"\nparser = OptionParser(usage)\nparser.add_option(\"-f\", \"--file\", type=\"string\", dest=\"filename\",\nhelp=\"read data from FILENAME\")\nparser.add_option(\"-v\", \"--verbose\",\naction=\"store_true\", dest=\"verbose\")\nparser.add_option(\"-q\", \"--quiet\",\naction=\"store_false\", dest=\"verbose\")\n\n(options, args) = parser.parse_args()\nif len(args) != 1:\nparser.error(\"incorrect number of arguments\")\n\nif options.verbose:\nprint \"reading \\%s...\" \\% options.filename\n[... go to work ...]\n\nif __name__ == \"__main__\":\nmain()\n```", "python_version": "2.3", "length": 1055, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-basic-summary.html"} {"title": "6.20.2 Basic Usage", "text": "optparse-positional-arguments.html | module-optparse.html | optparse-store-action.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.1.3 What are positional (optparse-positional-arguments.html)\nUp:\n6.20 optparse (module-optparse.html)\nNext:\n6.20.2.1 The store action (optparse-store-action.html)\n---\n## 6.20.2 Basic Usage\nWhile optparse is quite flexible and powerful, you don't have\nto jump through hoops or read reams of documentation to get it working\nin basic cases. This document aims to demonstrate some simple usage\npatterns that will get you started using optparse in your\nscripts.\nTo parse a command line with optparse, you must create an\nOptionParser instance and populate it. Obviously, you'll have\nto import the OptionParser classes in any script that uses\noptparse:\n```text\n\nfrom optparse import OptionParser\n```\nEarly on in the main program, create a parser:\n```text\n\nparser = OptionParser()\n```\nThen you can start populating the parser with options. Each option is\nreally a set of synonymous option strings; most commonly, you'll have\none short option string and one long option string --\ne.g. -f and --file:\n```text\n\nparser.add_option(\"-f\", \"--file\", ...)\n```\nThe interesting stuff, of course, is what comes after the option\nstrings. For now, we'll only cover four of the things you can put\nthere: action, type, dest (destination), and\nhelp.", "python_version": "2.3", "length": 1401, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-basic-usage.html"} {"title": "6.20.4.3 Error handling", "text": "optparse-callbacks-called.html | optparse-callback-options.html | optparse-callback-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.4.2 How callbacks are (optparse-callbacks-called.html)\nUp:\n6.20.4 Callback Options (optparse-callback-options.html)\nNext:\n6.20.4.4 Examples (optparse-callback-examples.html)\n---\n### 6.20.4.3 Error handling\nThe callback function should raise OptionValueError if\nthere are any problems with the option or its\nargument(s). optparse catches this and terminates the\nprogram, printing the error message you supply to stderr. Your\nmessage should be clear, concise, accurate, and mention the option at\nfault. Otherwise, the user will have a hard time figuring out what he\ndid wrong.", "python_version": "2.3", "length": 762, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-callback-error-handling.html"} {"title": "6.20.4.4 Examples", "text": "optparse-callback-error-handling.html | optparse-callback-options.html | optparse-extending.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.4.3 Error handling (optparse-callback-error-handling.html)\nUp:\n6.20.4 Callback Options (optparse-callback-options.html)\nNext:\n6.20.5 Extending optparse (optparse-extending.html)\n---\n### 6.20.4.4 Examples\nHere's an example of a callback option that takes no arguments, and\nsimply records that the option was seen:\n```text\n\ndef record_foo_seen (option, opt, value, parser):\nparser.saw_foo = 1\n\nparser.add_option(\"--foo\", action=\"callback\", callback=record_foo_seen)\n```\nOf course, you could do that with the ``store_true'' action. Here's a\nslightly more interesting example: record the fact that\n-a is seen, but blow up if it comes after -b\nin the command-line.\n```text\n\ndef check_order (option, opt, value, parser):\nif parser.values.b:\nraise OptionValueError(\"can't use -a after -b\")\nparser.values.a = 1\n...\nparser.add_option(\"-a\", action=\"callback\", callback=check_order)\nparser.add_option(\"-b\", action=\"store_true\", dest=\"b\")\n```\nIf you want to reuse this callback for several similar options (set a\nflag, but blow up if -b has already been seen), it needs\na bit of work: the error message and the flag that it sets must be\ngeneralized.\n```text\n\ndef check_order (option, opt, value, parser):\nif parser.values.b:\nraise OptionValueError(\"can't use %s after -b\" % opt)\nsetattr(parser.values, option.dest, 1)\n...\nparser.add_option(\"-a\", action=\"callback\", callback=check_order, dest='a')\nparser.add_option(\"-b\", action=\"store_true\", dest=\"b\")\nparser.add_option(\"-c\", action=\"callback\", callback=check_order, dest='c')\n```\nOf course, you could put any condition in there--you're not limited\nto checking the values of already-defined options. For example, if\nyou have options that should not be called when the moon is full, all\nyou have to do is this:\n```text\n\ndef check_moon (option, opt, value, parser):\nif is_full_moon():\nraise OptionValueError(\"%s option invalid when moon full\" % opt)\nsetattr(parser.values, option.dest, 1)\n...\nparser.add_option(\"--foo\",\naction=\"callback\", callback=check_moon, dest=\"foo\")\n```\n(The definition of `is_full_moon()` is left as an exercise for the\nreader.)\nFixed arguments\nThings get slightly more interesting when you define callback options\nthat take a fixed number of arguments. Specifying that a callback\noption takes arguments is similar to defining a ``store'' or\n``append'' option: if you define type, then the option takes one\nargument that must be convertible to that type; if you further define\nnargs, then the option takes that many arguments.\nHere's an example that just emulates the standard ``store'' action:\n```text\n\ndef store_value (option, opt, value, parser):\nsetattr(parser.values, option.dest, value)\n...\nparser.add_option(\"--foo\",\naction=\"callback\", callback=store_value,\ntype=\"int\", nargs=3, dest=\"foo\")\n```\nNote that optparse takes care of consuming 3 arguments and\nconverting them to integers for you; all you have to do is store them.\n(Or whatever: obviously you don't need a callback for this example.\nUse your imagination!)\nVariable arguments\nThings get hairy when you want an option to take a variable number of\narguments. For this case, you have to write a callback;\noptparse doesn't provide any built-in capabilities for it.\nYou have to deal with the full-blown syntax for conventional Unix\ncommand-line parsing. (Previously, optparse took care of\nthis for you, but I got it wrong. It was fixed at the cost of making\nthis kind of callback more complex.) In particular, callbacks have to\nworry about bare -- and - arguments; the\nconvention is:\n- bare --, if not the argument to some option,\ncauses command-line processing to halt and the --\nitself is lost.\n- bare - similarly causes command-line processing to\nhalt, but the - itself is kept.\n- either -- or - can be option\narguments.\nIf you want an option that takes a variable number of arguments, there\nare several subtle, tricky issues to worry about. The exact\nimplementation you choose will be based on which trade-offs you're\nwilling to make for your application (which is why optparse\ndoesn't support this sort of thing directly).\nNevertheless, here's a stab at a callback for an option with variable\narguments:\n```text\n\ndef varargs (option, opt, value, parser):\nassert value is None\ndone = 0\nvalue = []\nrargs = parser.rargs\nwhile rargs:\narg = rargs[0]\n\n# Stop if we hit an arg like \"--foo\", \"-a\", \"-fx\", \"--file=f\",\n# etc. Note that this also stops on \"-3\" or \"-3.0\", so if\n# your option takes numeric values, you will need to handle\n# this.\nif ((arg[:2] == \"--\" and len(arg) > 2) or\n(arg[:1] == \"-\" and len(arg) > 1 and arg[1] != \"-\")):\nbreak\nelse:\nvalue.append(arg)\ndel rargs[0]\n\nsetattr(parser.values, option.dest, value)\n\n...\nparser.add_option(\"-c\", \"--callback\",\naction=\"callback\", callback=varargs)\n```\nThe main weakness with this particular implementation is that negative\nnumbers in the arguments following -c will be interpreted\nas further options, rather than as arguments to -c.\nFixing this is left as an exercise for the reader.", "python_version": "2.3", "length": 5145, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-callback-examples.html"} {"title": "6.20.4 Callback Options", "text": "optparse-conflicts.html | module-optparse.html | optparse-defining-callback-option.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.3.6 Conflicts between options (optparse-conflicts.html)\nUp:\n6.20 optparse (module-optparse.html)\nNext:\n6.20.4.1 Defining a callback (optparse-defining-callback-option.html)\n---\n## 6.20.4 Callback Options\nIf optparse's built-in actions and types just don't fit the\nbill for you, but it's not worth extending optparse to define\nyour own actions or types, you'll probably need to define a callback\noption. Defining callback options is quite easy; the tricky part is\nwriting a good callback (the function that is called when\noptparse encounters the option on the command line).", "python_version": "2.3", "length": 751, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-callback-options.html"} {"title": "6.20.4.2 How callbacks are called", "text": "optparse-defining-callback-option.html | optparse-callback-options.html | optparse-callback-error-handling.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.4.1 Defining a callback (optparse-defining-callback-option.html)\nUp:\n6.20.4 Callback Options (optparse-callback-options.html)\nNext:\n6.20.4.3 Error handling (optparse-callback-error-handling.html)\n---\n### 6.20.4.2 How callbacks are called\nAll callbacks are called as follows:\n```text\n\nfunc(option, opt, value, parser, *args, **kwargs)\n```\nwhere\nSince args and kwargs are optional (they are only passed\nif you supply callback_args and/or callback_kwargs when\nyou define your callback option), the minimal callback function is:\n```text\n\ndef my_callback (option, opt, value, parser):\npass\n```", "python_version": "2.3", "length": 790, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-callbacks-called.html"} {"title": "6.20.3.6 Conflicts between options", "text": "optparse-querying-and-manipulating.html | optparse-advanced-usage.html | optparse-callback-options.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.3.5 Querying and manipulating (optparse-querying-and-manipulating.html)\nUp:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\nNext:\n6.20.4 Callback Options (optparse-callback-options.html)\n---\n### 6.20.3.6 Conflicts between options\nIf you're not careful, it's easy to define conflicting options:\n```text\n\nparser.add_option(\"-n\", \"--dry-run\", ...)\n...\nparser.add_option(\"-n\", \"--noisy\", ...)\n```\n(This is even easier to do if you've defined your own\nOptionParser subclass with some standard options.)\nOn the assumption that this is usually a mistake, optparse\nraises an exception (OptionConflictError) by default when\nthis happens. Since this is an easily-fixed programming error, you\nshouldn't try to catch this exception--fix your mistake and get on\nwith life.\nSometimes, you want newer options to deliberately replace the option\nstrings used by older options. You can achieve this by calling:\n```text\n\nparser.set_conflict_handler(\"resolve\")\n```\nwhich instructs optparse to resolve option conflicts\nintelligently.\nHere's how it works: every time you add an option, optparse\nchecks for conflicts with previously-added options. If it finds any,\nit invokes the conflict-handling mechanism you specify either to the\nOptionParser constructor:\n```text\n\nparser = OptionParser(..., conflict_handler=\"resolve\")\n```\nor via the set_conflict_handler() method.\nThe default conflict-handling mechanism is `error`.\nHere's an example: first, define an OptionParser set to\nresolve conflicts intelligently:\n```text\n\nparser = OptionParser(conflict_handler=\"resolve\")\n```\nNow add all of our options:\n```text\n\nparser.add_option(\"-n\", \"--dry-run\", ..., help=\"original dry-run option\")\n...\nparser.add_option(\"-n\", \"--noisy\", ..., help=\"be noisy\")\n```\nAt this point, optparse detects that a previously-added option is already\nusing the -n option string. Since `conflict_handler\n== \"resolve\"`, it resolves the situation by removing -n\nfrom the earlier option's list of option strings. Now,\n--dry-run is the only way for the user to activate that\noption. If the user asks for help, the help message will reflect\nthat, e.g.:\n```text\n\noptions:\n--dry-run original dry-run option\n...\n-n, --noisy be noisy\n```\nNote that it's possible to whittle away the option strings for a\npreviously-added option until there are none left, and the user has no\nway of invoking that option from the command-line. In that case,\noptparse removes that option completely, so it doesn't show\nup in help text or anywhere else. E.g. if we carry on with our\nexisting OptionParser:\n```text\n\nparser.add_option(\"--dry-run\", ..., help=\"new dry-run option\")\n```\nAt this point, the first -n/--dry-run\noption is no longer accessible, so optparse removes it. If\nthe user asks for help, they'll get something like this:\n```text\n\noptions:\n...\n-n, --noisy be noisy\n--dry-run new dry-run option\n```", "python_version": "2.3", "length": 3029, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-conflicts.html"} {"title": "6.20.3.1 Creating and populating the parser", "text": "optparse-advanced-usage.html | optparse-advanced-usage.html | optparse-defining-options.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\nUp:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\nNext:\n6.20.3.2 Defining options (optparse-defining-options.html)\n---\n### 6.20.3.1 Creating and populating the\nparser\nThere are several ways to populate the parser with options. One way\nis to pass a list of Options to the OptionParser\nconstructor:\n```text\n\nfrom optparse import OptionParser, make_option\n[...]\nparser = OptionParser(option_list=[\nmake_option(\"-f\", \"--filename\",\naction=\"store\", type=\"string\", dest=\"filename\"),\nmake_option(\"-q\", \"--quiet\",\naction=\"store_false\", dest=\"verbose\")])\n```\n(make_option() is a factory function for generating\nOption objects.)\nFor long option lists, it may be more convenient/readable to create the\nlist separately:\n```text\n\noption_list = [make_option(\"-f\", \"--filename\",\naction=\"store\", type=\"string\", dest=\"filename\"),\n[... more options ...]\nmake_option(\"-q\", \"--quiet\",\naction=\"store_false\", dest=\"verbose\")]\nparser = OptionParser(option_list=option_list)\n```\nOr, you can use the add_option() method of\nOptionParser to add options one-at-a-time:\n```text\n\nparser = OptionParser()\nparser.add_option(\"-f\", \"--filename\",\naction=\"store\", type=\"string\", dest=\"filename\")\nparser.add_option(\"-q\", \"--quiet\",\naction=\"store_false\", dest=\"verbose\")\n```\nThis method makes it easier to track down exceptions raised by the\nOption constructor, which are common because of the complicated\ninterdependencies among the various keyword arguments. (If you get it\nwrong, optparse raises OptionError.)\nadd_option() can be called in one of two ways:\n- pass it an Option instance (as returned by make_option())\n- pass it any combination of positional and keyword arguments that\nare acceptable to make_option() (i.e., to the Option\nconstructor), and it will create the Option instance for you\n(shown above).", "python_version": "2.3", "length": 2014, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-creating-the-parser.html"} {"title": "6.20.4.1 Defining a callback option", "text": "optparse-callback-options.html | optparse-callback-options.html | optparse-callbacks-called.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.4 Callback Options (optparse-callback-options.html)\nUp:\n6.20.4 Callback Options (optparse-callback-options.html)\nNext:\n6.20.4.2 How callbacks are (optparse-callbacks-called.html)\n---\n### 6.20.4.1 Defining a callback option\nAs always, you can define a callback option either by directly\ninstantiating the Option class, or by using the\nadd_option() method of your OptionParser object. The\nonly option attribute you must specify is callback, the function\nto call:\n```text\n\nparser.add_option(\"-c\", callback=my_callback)\n```\nNote that you supply a function object here--so you must have\nalready defined a function my_callback() when you define\nthe callback option. In this simple case, optparse knows\nnothing about the arguments the -c option expects to\ntake. Usually, this means that the option doesn't take any arguments\n- the mere presence of -c on the command-line is all it\nneeds to know. In some circumstances, though, you might want your\ncallback to consume an arbitrary number of command-line arguments.\nThis is where writing callbacks gets tricky; it's covered later in\nthis document.\nThere are several other option attributes that you can supply when you\ndefine an option attribute:", "python_version": "2.3", "length": 1374, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-defining-callback-option.html"} {"title": "6.20.3.2 Defining options", "text": "optparse-creating-the-parser.html | optparse-advanced-usage.html | optparse-option-actions.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.3.1 Creating and populating (optparse-creating-the-parser.html)\nUp:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\nNext:\n6.20.3.3 Option actions (optparse-option-actions.html)\n---\n### 6.20.3.2 Defining options\nEach Option instance represents a set of synonymous\ncommand-line options, i.e. options that have the same meaning and\neffect, but different spellings. You can specify any number of short\nor long option strings, but you must specify at least one option\nstring.\nTo define an option with only a short option string:\n```text\n\nmake_option(\"-f\", ...)\n```\nAnd to define an option with only a long option string:\n```text\n\nmake_option(\"--foo\", ...)\n```\nThe ``...'' represents a set of keyword arguments that define attributes\nof the Option object. The rules governing which keyword args\nyou must supply for a given Option are fairly complicated, but\nyou always have to supply some. If you get it wrong,\noptparse raises an OptionError exception explaining\nyour mistake.\nThe most important attribute of an option is its action, i.e. what to do\nwhen we encounter this option on the command-line. The possible actions\nare:\n(If you don't supply an action, the default is ``store''. For this\naction, you may also supply type and dest keywords; see\nbelow.)\nAs you can see, most actions involve storing or updating a value\nsomewhere. optparse always creates a particular object (an\ninstance of the Values class) specifically for this\npurpose. Option arguments (and various other values) are stored as\nattributes of this object, according to the dest (destination)\nargument to make_option()/add_option().\nFor example, when you call:\n```text\n\nparser.parse_args()\n```\none of the first things optparse does is create a\n`values` object:\n```text\n\nvalues = Values()\n```\nIf one of the options in this parser is defined with:\n```text\n\nmake_option(\"-f\", \"--file\", action=\"store\", type=\"string\", dest=\"filename\")\n```\nand the command-line being parsed includes any of the following:\n```text\n\n-ffoo\n-f foo\n--file=foo\n--file foo\n```\nthen optparse, on seeing the -f or\n--file option, will do the equivalent of this:\n```text\n\nvalues.filename = \"foo\"\n```\nClearly, the type and dest arguments are almost\nas important as action. action is the only attribute that\nis meaningful for all options, though, so it is the most\nimportant.", "python_version": "2.3", "length": 2496, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-defining-options.html"} {"title": "6.20.2.6 Error-handling", "text": "optparse-print-version.html | optparse-basic-usage.html | optparse-basic-summary.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2.5 Print a version (optparse-print-version.html)\nUp:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nNext:\n6.20.2.7 Putting it all (optparse-basic-summary.html)\n---\n### 6.20.2.6 Error-handling\nThe one thing you need to know for basic usage is how\noptparse behaves when it encounters an error on the\ncommand-line--e.g. -n 4x where -n is an\ninteger-valued option. In this case, optparse prints your\nusage message to stderr, followed by a useful and human-readable error\nmessage. Then it terminates (calls sys.exit()) with a\nnon-zero exit status.\nIf you don't like this, subclass OptionParser and override the\nerror() method. See section 6.20.5 (optparse-extending.html#optparse-extending),\n``Extending optparse.''", "python_version": "2.3", "length": 887, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-error-handling.html"} {"title": "6.20.5.4 Examples", "text": "optparse-extending-other-reasons.html | optparse-extending.html | module-tempfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.5.3 Other reasons to (optparse-extending-other-reasons.html)\nUp:\n6.20.5 Extending optparse (optparse-extending.html)\nNext:\n6.21 tempfile (module-tempfile.html)\n---\n### 6.20.5.4 Examples\nHere are a few examples of extending the optparse module.\nFirst, let's change the option-parsing to be case-insensitive:\n```text\nfrom optparse import Option, OptionParser, _match_abbrev\n\n# This case-insensitive option parser relies on having a\n# case-insensitive dictionary type available. Here's one\n# for Python 2.2. Note that a *real* case-insensitive\n# dictionary type would also have to implement __new__(),\n# update(), and setdefault() -- but that's not the point\n# of this exercise.\n\nclass caseless_dict (dict):\ndef __setitem__ (self, key, value):\ndict.__setitem__(self, key.lower(), value)\n\ndef __getitem__ (self, key):\nreturn dict.__getitem__(self, key.lower())\n\ndef get (self, key, default=None):\nreturn dict.get(self, key.lower())\n\ndef has_key (self, key):\nreturn dict.has_key(self, key.lower())\n\nclass CaselessOptionParser (OptionParser):\n\ndef _create_option_list (self):\nself.option_list = []\nself._short_opt = caseless_dict()\nself._long_opt = caseless_dict()\nself._long_opts = []\nself.defaults = {}\n\ndef _match_long_opt (self, opt):\nreturn _match_abbrev(opt.lower(), self._long_opt.keys())\n\nif __name__ == \"__main__\":\nfrom optik.errors import OptionConflictError\n\n# test 1: no options to start with\nparser = CaselessOptionParser()\ntry:\nparser.add_option(\"-H\", dest=\"blah\")\nexcept OptionConflictError:\nprint \"ok: got OptionConflictError for -H\"\nelse:\nprint \"not ok: no conflict between -h and -H\"\n\nparser.add_option(\"-f\", \"--file\", dest=\"file\")\n#print `parser.get_option(\"-f\")`\n#print `parser.get_option(\"-F\")`\n#print `parser.get_option(\"--file\")`\n#print `parser.get_option(\"--fIlE\")`\n(options, args) = parser.parse_args([\"--FiLe\", \"foo\"])\nassert options.file == \"foo\", options.file\nprint \"ok: case insensitive long options work\"\n\n(options, args) = parser.parse_args([\"-F\", \"bar\"])\nassert options.file == \"bar\", options.file\nprint \"ok: case insensitive short options work\"\n```\nDownload as text (original file name: caseless.py). (caseless.txt)\nAnd two ways of implementing ``required options'' with\noptparse.\nVersion 1: Add a method to OptionParser which applications\nmust call after parsing arguments:\n```text\nimport optparse\n\nclass OptionParser (optparse.OptionParser):\n\ndef check_required (self, opt):\noption = self.get_option(opt)\n\n# Assumes the option's 'default' is set to None!\nif getattr(self.values, option.dest) is None:\nself.error(\"%s option not supplied\" % option)\n\nparser = OptionParser()\nparser.add_option(\"-v\", action=\"count\", dest=\"verbose\")\nparser.add_option(\"-f\", \"--file\", default=None)\n(options, args) = parser.parse_args()\n\nprint \"verbose:\", options.verbose\nprint \"file:\", options.file\nparser.check_required(\"-f\")\n```\nDownload as text (original file name: required_1.py). (required_1.txt)\nVersion 2: Extend Option and add a required\nattribute; extend OptionParser to ensure that required options\nare present after parsing:", "python_version": "2.3", "length": 3219, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-extending-examples.html"} {"title": "6.20.5.3 Other reasons to extend optparse", "text": "optparse-adding-actions.html | optparse-extending.html | optparse-extending-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.5.2 Adding new actions (optparse-adding-actions.html)\nUp:\n6.20.5 Extending optparse (optparse-extending.html)\nNext:\n6.20.5.4 Examples (optparse-extending-examples.html)\n---\n### 6.20.5.3 Other reasons to extend optparse\nAdding new types and new actions are the big, obvious reasons why you\nmight want to extend optparse. I can think of at least two\nother areas to play with.\nFirst, the simple one: OptionParser tries to be helpful by\ncalling sys.exit() when appropriate, i.e. when there's an\nerror on the command-line or when the user requests help. In the\nformer case, the traditional course of letting the script crash with a\ntraceback is unacceptable; it will make users think there's a bug in\nyour script when they make a command-line error. In the latter case,\nthere's generally not much point in carrying on after printing a help\nmessage.\nIf this behaviour bothers you, it shouldn't be too hard to ``fix'' it.\nYou'll have to\n1. subclass OptionParser and override the error() method\n2. subclass Option and override the take_action() method--you'll\nneed to provide your own handling of the ``help'' action that\ndoesn't call sys.exit()\nThe second, much more complex, possibility is to override the\ncommand-line syntax implemented by optparse. In this case,\nyou'd leave the whole machinery of option actions and types alone, but\nrewrite the code that processes `sys.argv`. You'll need to\nsubclass OptionParser in any case; depending on how radical a\nrewrite you want, you'll probably need to override one or all of\nparse_args(), _process_long_opt(), and\n_process_short_opts().\nBoth of these are left as an exercise for the reader. I have not\ntried to implement either myself, since I'm quite happy with\noptparse's default behaviour (naturally).\nHappy hacking, and don't forget: Use the Source, Luke.", "python_version": "2.3", "length": 1980, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-extending-other-reasons.html"} {"title": "6.20.5 Extending optparse", "text": "optparse-callback-examples.html | module-optparse.html | optparse-adding-types.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.4.4 Examples (optparse-callback-examples.html)\nUp:\n6.20 optparse (module-optparse.html)\nNext:\n6.20.5.1 Adding new types (optparse-adding-types.html)\n---\n## 6.20.5 Extending optparse\nSince the two major controlling factors in how optparse\ninterprets command-line options are the action and type of each\noption, the most likely direction of extension is to add new actions\nand new types.\nAlso, the examples section includes several demonstrations of\nextending optparse in different ways: e.g. a case-insensitive\noption parser, or two kinds of option parsers that implement\n``required options''.", "python_version": "2.3", "length": 766, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-extending.html"} {"title": "6.20.2.4 Generating help", "text": "optparse-setting-default-values.html | optparse-basic-usage.html | optparse-print-version.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2.3 Setting default values (optparse-setting-default-values.html)\nUp:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nNext:\n6.20.2.5 Print a version (optparse-print-version.html)\n---\n### 6.20.2.4 Generating help\nThe last feature that you will use in every script is\noptparse's ability to generate help messages. All you have\nto do is supply a help argument when you add an option. Let's\ncreate a new parser and populate it with user-friendly (documented)\noptions:\n```text\n\nusage = \"usage: %prog [options] arg1 arg2\"\nparser = OptionParser(usage=usage)\nparser.add_option(\"-v\", \"--verbose\",\naction=\"store_true\", dest=\"verbose\", default=True,\nhelp=\"make lots of noise [default]\")\nparser.add_option(\"-q\", \"--quiet\",\naction=\"store_false\", dest=\"verbose\",\nhelp=\"be vewwy quiet (I'm hunting wabbits)\")\nparser.add_option(\"-f\", \"--file\", dest=\"filename\",\nmetavar=\"FILE\", help=\"write output to FILE\"),\nparser.add_option(\"-m\", \"--mode\",\ndefault=\"intermediate\",\nhelp=\"interaction mode: one of 'novice', \"\n\"'intermediate' [default], 'expert'\")\n```\nIf optparse encounters either -h or\n--help on the command-line, or if you just call\nparser.print_help(), it prints the following to stdout:\n```text\n\nusage: [options] arg1 arg2\n\noptions:\n-h, --help show this help message and exit\n-v, --verbose make lots of noise [default]\n-q, --quiet be vewwy quiet (I'm hunting wabbits)\n-fFILE, --file=FILE write output to FILE\n-mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'\n[default], 'expert'\n```\nThere's a lot going on here to help optparse generate the\nbest possible help message:\n- the script defines its own usage message:\n```text\n\nusage = \"usage: %prog [options] arg1 arg2\"\n```\noptparse expands \"%prog\" in the usage string to the name of the\ncurrent script, i.e. `os.path.basename(sys.argv[0])`. The\nexpanded string is then printed before the detailed option help.\nIf you don't supply a usage string, optparse uses a bland but\nsensible default: `\"usage: %prog [options]\"`, which is fine if your\nscript doesn't take any positional arguments.\n- every option defines a help string, and doesn't worry about\nline-wrapping--optparse takes care of wrapping lines and\nmaking the help output look good.\n- options that take a value indicate this fact in their\nautomatically-generated help message, e.g. for the ``mode'' option:\n```text\n\n-mMODE, --mode=MODE\n```\nHere, ``MODE'' is called the meta-variable: it stands for the argument\nthat the user is expected to supply to\n-m/--mode. By default, optparse\nconverts the destination variable name to uppercase and uses that for\nthe meta-variable. Sometimes, that's not what you want--for\nexample, the filename option explicitly sets\n`metavar=\"FILE\"`, resulting in this automatically-generated\noption description:\n```text\n\n-fFILE, --file=FILE\n```\nThis is important for more than just saving space, though: the\nmanually written help text uses the meta-variable ``FILE'', to clue\nthe user in that there's a connection between the formal syntax\n``-fFILE'' and the informal semantic description ``write output to\nFILE''. This is a simple but effective way to make your help text a\nlot clearer and more useful for end users.\nWhen dealing with many options, it is convenient to group these\noptions for better help output. An OptionParser can contain\nseveral option groups, each of which can contain several options.\nContinuing with the parser defined above, adding an\nOptionGroup to a parser is easy:\n```text\n\ngroup = OptionGroup(parser, \"Dangerous Options\",\n\"Caution: use these options at your own risk. \"\n\"It is believed that some of them bite.\")\ngroup.add_option(\"-g\", action=\"store_true\", help=\"Group option.\")\nparser.add_option_group(group)\n```\nThis would result in the following help output:\n```text\n\nusage: [options] arg1 arg2\n\noptions:\n-h, --help show this help message and exit\n-v, --verbose make lots of noise [default]\n-q, --quiet be vewwy quiet (I'm hunting wabbits)\n-fFILE, --file=FILE write output to FILE\n-mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'\n[default], 'expert'\n\nDangerous Options:\nCaution: use of these options is at your own risk. It is believed that\nsome of them bite.\n-g Group option.\n```", "python_version": "2.3", "length": 4363, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-generating-help.html"} {"title": "6.20.3.3 Option actions", "text": "optparse-defining-options.html | optparse-advanced-usage.html | optparse-option-types.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.3.2 Defining options (optparse-defining-options.html)\nUp:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\nNext:\n6.20.3.4 Option types (optparse-option-types.html)\n---\n### 6.20.3.3 Option actions\nThe various option actions all have slightly different requirements\nand effects. Except for the ``help'' action, you must supply at least\none other keyword argument when creating the Option; the exact\nrequirements for each action are listed here.", "python_version": "2.3", "length": 627, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-option-actions.html"} {"title": "6.20.3.4 Option types", "text": "optparse-option-actions.html | optparse-advanced-usage.html | optparse-querying-and-manipulating.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.3.3 Option actions (optparse-option-actions.html)\nUp:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\nNext:\n6.20.3.5 Querying and manipulating (optparse-querying-and-manipulating.html)\n---\n### 6.20.3.4 Option types\noptparse supports six option types out of the box: string,\nint, long, choice, float and complex.\n(Of these, string, int, float, and choice are the most commonly used\n--long and complex are there mainly for completeness.) It's easy to\nadd new option types by subclassing the Option class; see\nsection 6.20.5 (optparse-extending.html#optparse-extending), ``Extending optparse.''\nArguments to string options are not checked or converted in any way:\nthe text on the command line is stored in the destination (or passed\nto the callback) as-is.\nInteger arguments are passed to int() to convert them to\nPython integers. If int() fails, so will\noptparse, although with a more useful error message.\nInternally, optparse raises OptionValueError in\noptparse.check_builtin(); at a higher level (in\nOptionParser), optparse catches this exception and\nterminates your program with a useful error message.\nLikewise, float arguments are passed to float() for\nconversion, long arguments to long(), and complex arguments\nto complex(). Apart from that, they are handled\nidentically to integer arguments.\nChoice options are a subtype of string options. A master list or\ntuple of choices (strings) must be passed to the option constructor\n(make_option() or OptionParser.add_option()) as\nthe choices keyword argument. Choice option arguments are\ncompared against this master list in\noptparse.check_choice(), and OptionValueError\nis raised if an unknown string is given.", "python_version": "2.3", "length": 1858, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-option-types.html"} {"title": "6.20.1.2 What are options for?", "text": "optparse-terminology.html | optparse-philosophy.html | optparse-positional-arguments.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.1.1 Terminology (optparse-terminology.html)\nUp:\n6.20.1 Philosophy (optparse-philosophy.html)\nNext:\n6.20.1.3 What are positional (optparse-positional-arguments.html)\n---\n### 6.20.1.2 What are options for?\nOptions are used to provide extra information to tune or customize the\nexecution of a program. In case it wasn't clear, options should be\noptional. A program should be able to run just fine with no\noptions whatsoever. (Pick a random program from the Unix or GNU\ntoolsets. Can it run without any options at all and still make sense?\nThe only exceptions I can think of are find, tar,\nand dd--all of which are mutant oddballs that have been\nrightly criticized for their non-standard syntax and confusing\ninterfaces.)\nLots of people want their programs to have ``required options''.\nThink about it. If it's required, then it's not optional! If\nthere is a piece of information that your program absolutely requires\nin order to run successfully, that's what positional arguments are\nfor. (However, if you insist on adding ``required options'' to your\nprograms, look in ``Extending Examples''\n(section 6.20.5 (optparse-extending-examples.html#optparse-extending-examples)) for two ways of\nimplementing them with optparse.)\nConsider the humble cp utility, for copying files. It\ndoesn't make much sense to try to copy files without supplying a\ndestination and at least one source. Hence, cp fails if you\nrun it with no arguments. However, it has a flexible, useful syntax\nthat does not rely on options at all:\n```text\n\n$ cp SOURCE DEST\n$ cp SOURCE ... DEST-DIR\n```\nYou can get pretty far with just that. Most cp\nimplementations provide a bunch of options to tweak exactly how the\nfiles are copied: you can preserve mode and modification time, avoid\nfollowing symlinks, ask before clobbering existing files, etc. But\nnone of this distracts from the core mission of cp, which is\nto copy one file to another, or N files to another directory.", "python_version": "2.3", "length": 2113, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-options.html"} {"title": "6.20.2.2 Other store_* actions", "text": "optparse-store-action.html | optparse-basic-usage.html | optparse-setting-default-values.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2.1 The store action (optparse-store-action.html)\nUp:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nNext:\n6.20.2.3 Setting default values (optparse-setting-default-values.html)\n---\n### 6.20.2.2 Other store_* actions\nFlag options--set a variable to true or false when a particular\noption is seen--are quite common. optparse supports them\nwith two separate actions, ``store_true'' and ``store_false''. For\nexample, you might have a verbose flag that is turned on with\n-v and off with -q:\n```text\n\nparser.add_option(\"-v\", action=\"store_true\", dest=\"verbose\")\nparser.add_option(\"-q\", action=\"store_false\", dest=\"verbose\")\n```\nHere we have two different options with the same destination, which is\nperfectly OK. (It just means you have to be a bit careful when setting\ndefault values--see below.)\nWhen optparse sees -v on the command line, it sets\n`options.verbose` to `True`; when it sees -q, it\nsets `options.verbose` to `False`.", "python_version": "2.3", "length": 1111, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-other-store-actions.html"} {"title": "6.20.1 Philosophy", "text": "module-optparse.html | module-optparse.html | optparse-terminology.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20 optparse (module-optparse.html)\nUp:\n6.20 optparse (module-optparse.html)\nNext:\n6.20.1.1 Terminology (optparse-terminology.html)\n---\n## 6.20.1 Philosophy\nThe purpose of optparse is to make it very easy to provide the\nmost standard, obvious, straightforward, and user-friendly user\ninterface for Unix command-line programs. The optparse\nphilosophy is heavily influenced by the Unix and GNU toolkits, and\nthis section is meant to explain that philosophy.", "python_version": "2.3", "length": 613, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-philosophy.html"} {"title": "6.20.1.3 What are positional arguments for?", "text": "optparse-options.html | optparse-philosophy.html | optparse-basic-usage.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.1.2 What are options (optparse-options.html)\nUp:\n6.20.1 Philosophy (optparse-philosophy.html)\nNext:\n6.20.2 Basic Usage (optparse-basic-usage.html)\n---\n### 6.20.1.3 What are positional arguments for?\nIn case it wasn't clear from the above example: positional arguments\nare for those pieces of information that your program absolutely,\npositively requires to run.\nA good user interface should have as few absolute requirements as\npossible. If your program requires 17 distinct pieces of information in\norder to run successfully, it doesn't much matter how you get that\ninformation from the user--most people will give up and walk away\nbefore they successfully run the program. This applies whether the user\ninterface is a command-line, a configuration file, a GUI, or whatever:\nif you make that many demands on your users, most of them will just give\nup.\nIn short, try to minimize the amount of information that users are\nabsolutely required to supply--use sensible defaults whenever\npossible. Of course, you also want to make your programs reasonably\nflexible. That's what options are for. Again, it doesn't matter if\nthey are entries in a config file, checkboxes in the ``Preferences''\ndialog of a GUI, or command-line options--the more options you\nimplement, the more flexible your program is, and the more complicated\nits implementation becomes. It's quite easy to overwhelm users (and\nyourself!) with too much flexibility, so be careful there.", "python_version": "2.3", "length": 1613, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-positional-arguments.html"} {"title": "6.20.2.5 Print a version number", "text": "optparse-generating-help.html | optparse-basic-usage.html | optparse-error-handling.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2.4 Generating help (optparse-generating-help.html)\nUp:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nNext:\n6.20.2.6 Error-handling (optparse-error-handling.html)\n---\n### 6.20.2.5 Print a version number\nSimilar to the brief usage string, optparse can also print a\nversion string for your program. You have to supply the string, as\nthe version argument to OptionParser:\n```text\n\nparser = OptionParser(usage=\"%prog [-f] [-q]\", version=\"%prog 1.0\")\n```\nversion can contain anything you like; `%prog` is expanded\nin version just as with usage. When you supply it,\noptparse automatically adds a --version option\nto your parser. If it encounters this option on the command line, it\nexpands your version string (by replacing `%prog`), prints\nit to stdout, and exits.\nFor example, if your script is called /usr/bin/foo, a user might do:\n```text\n\n$ /usr/bin/foo --version\nfoo 1.0\n```", "python_version": "2.3", "length": 1054, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-print-version.html"} {"title": "6.20.3.5 Querying and manipulating your option parser", "text": "optparse-option-types.html | optparse-advanced-usage.html | optparse-conflicts.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.3.4 Option types (optparse-option-types.html)\nUp:\n6.20.3 Advanced Usage (optparse-advanced-usage.html)\nNext:\n6.20.3.6 Conflicts between options (optparse-conflicts.html)\n---\n### 6.20.3.5 Querying and manipulating your option parser\nSometimes, it's useful to poke around your option parser and see what's\nthere. OptionParser provides a couple of methods to help you out:", "python_version": "2.3", "length": 543, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-querying-and-manipulating.html"} {"title": "6.20.2.3 Setting default values", "text": "optparse-other-store-actions.html | optparse-basic-usage.html | optparse-generating-help.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2.2 Other store_* actions (optparse-other-store-actions.html)\nUp:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nNext:\n6.20.2.4 Generating help (optparse-generating-help.html)\n---\n### 6.20.2.3 Setting default values\nAll of the above examples involve setting some variable (the\n``destination'') when certain command-line options are seen. What\nhappens if those options are never seen? Since we didn't supply any\ndefaults, they are all set to `None`. Sometimes, this is just fine (which\nis why it's the default), but sometimes, you want more control. To\naddress that need, optparse lets you supply a default value for\neach destination, which is assigned before the command-line is parsed.\nFirst, consider the verbose/quiet example. If we want\noptparse to set verbose to `True` unless\n-q is seen, then we can do this:\n```text\n\nparser.add_option(\"-v\", action=\"store_true\", dest=\"verbose\", default=True)\nparser.add_option(\"-q\", action=\"store_false\", dest=\"verbose\")\n```\nOddly enough, this is exactly equivalent:\n```text\n\nparser.add_option(\"-v\", action=\"store_true\", dest=\"verbose\")\nparser.add_option(\"-q\", action=\"store_false\", dest=\"verbose\", default=True)\n```\nThose are equivalent because you're supplying a default value for the\noption's destination, and these two options happen to have the same\ndestination (the verbose variable).\nConsider this:\n```text\n\nparser.add_option(\"-v\", action=\"store_true\", dest=\"verbose\", default=False)\nparser.add_option(\"-q\", action=\"store_false\", dest=\"verbose\", default=True)\n```\nAgain, the default value for verbose will be `True`: the last\ndefault value supplied for any particular destination is the one that\ncounts.", "python_version": "2.3", "length": 1834, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-setting-default-values.html"} {"title": "6.20.2.1 The store action", "text": "optparse-basic-usage.html | optparse-basic-usage.html | optparse-other-store-actions.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nUp:\n6.20.2 Basic Usage (optparse-basic-usage.html)\nNext:\n6.20.2.2 Other store_* actions (optparse-other-store-actions.html)\n---\n### 6.20.2.1 The store action\nThe action tells optparse what to do when it sees one of the\noption strings for this option on the command-line. For example, the\naction store means: take the next argument (or the remainder of\nthe current argument), ensure that it is of the correct type, and\nstore it to your chosen destination.\nFor example, let's fill in the ``...'' of that last option:\n```text\n\nparser.add_option(\"-f\", \"--file\",\naction=\"store\", type=\"string\", dest=\"filename\")\n```\nNow let's make up a fake command-line and ask optparse to\nparse it:\n```text\n\nargs = [\"-f\", \"foo.txt\"]\n(options, args) = parser.parse_args(args)\n```\n(Note that if you don't pass an argument list to\nparse_args(), it automatically uses `sys.argv[1:]`.)\nWhen optparse sees the -f, it consumes the next\nargument--`foo.txt`--and stores it in the filename\nattribute of a special object. That object is the first return value\nfrom parse_args(), so:\n```text\n\nprint options.filename\n```\nwill print `foo.txt`.\nOther option types supported by optparse are `int` and\n`float`. Here's an option that expects an integer argument:\n```text\n\nparser.add_option(\"-n\", type=\"int\", dest=\"num\")\n```\nThis example doesn't provide a long option, which is perfectly\nacceptable. It also doesn't specify the action--it defaults to\n``store''.\nLet's parse another fake command-line. This time, we'll jam the option\nargument right up against the option, since -n42 (one\nargument) is equivalent to -n 42 (two arguments).\n```text\n\n(options, args) = parser.parse_args([\"-n42\"])\nprint options.num\n```\nThis prints `42`.\nTrying out the ``float'' type is left as an exercise for the reader.\nIf you don't specify a type, optparse assumes ``string''.\nCombined with the fact that the default action is ``store'', that\nmeans our first example can be a lot shorter:\n```text\n\nparser.add_option(\"-f\", \"--file\", dest=\"filename\")\n```\nIf you don't supply a destination, optparse figures out a\nsensible default from the option strings: if the first long option\nstring is --foo-bar, then the default destination is\nfoo_bar. If there are no long option strings,\noptparse looks at the first short option: the default\ndestination for -f is f.\nAdding types is fairly easy; please refer to\nsection 6.20.5 (optparse-adding-types.html#optparse-adding-types), ``Adding new types.''", "python_version": "2.3", "length": 2653, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-store-action.html"} {"title": "6.20.1.1 Terminology", "text": "optparse-philosophy.html | optparse-philosophy.html | optparse-options.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.20.1 Philosophy (optparse-philosophy.html)\nUp:\n6.20.1 Philosophy (optparse-philosophy.html)\nNext:\n6.20.1.2 What are options (optparse-options.html)\n---\n### 6.20.1.1 Terminology\nFirst, we need to establish some terminology.\nFor example, consider this hypothetical command-line:\n```text\n\nprog -v --report /tmp/report.txt foo bar\n```\n-v and --report are both options. Assuming\nthe --report option takes one argument,\n`/tmp/report.txt` is an option argument. `foo` and `bar`\nare positional arguments.", "python_version": "2.3", "length": 659, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/optparse-terminology.html"} {"title": "5.3.2 Organizing test code", "text": "minimal-example.html | module-unittest.html | legacy-unit-tests.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.1 Minimal example (minimal-example.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.3 Re-using old test (legacy-unit-tests.html)\n---\n## 5.3.2 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.3", "length": 7191, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1.2 File Object Creation (os-newstreams.html)\nUp:\n6.1 os (module-os.html)\nNext:\n6.1.4 Files and Directories (os-file-dir.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.3", "length": 490, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1.3 File Descriptor Operations (os-fd-ops.html)\nUp:\n6.1 os (module-os.html)\nNext:\n6.1.5 Process Management (os-process.html)\n---\n## 6.1.4 Files and Directories", "python_version": "2.3", "length": 296, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1.1 Process Parameters (os-procinfo.html)\nUp:\n6.1 os (module-os.html)\nNext:\n6.1.3 File Descriptor Operations (os-fd-ops.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.\nFor a discussion of possible deadlock conditions related to the use\nof these functions, see ``Flow Control\nIssues (popen2-flow-control.html)''\n(section 6.8.2 (popen2-flow-control.html#popen2-flow-control)).\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.3", "length": 1330, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1.5 Process Management (os-process.html)\nUp:\n6.1 os (module-os.html)\nNext:\n6.2 os.path (module-os.path.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.3", "length": 500, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1.4 Files and Directories (os-file-dir.html)\nUp:\n6.1 os (module-os.html)\nNext:\n6.1.6 Miscellaneous System Information (os-path.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 exit codes are a defined, and can be used with\n_exit(), although they are not required. These are\ntypically used for system programs written in Python, such as a\nmail server's external command delivery program.\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.3", "length": 1213, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.1 os (module-os.html)\nUp:\n6.1 os (module-os.html)\nNext:\n6.1.2 File Object Creation (os-newstreams.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.3", "length": 371, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/os-procinfo.html"} {"title": "14.11.1 Audio Device Objects", "text": "module-ossaudiodev.html | module-ossaudiodev.html | mixer-device-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n14.11 ossaudiodev (module-ossaudiodev.html)\nUp:\n14.11 ossaudiodev (module-ossaudiodev.html)\nNext:\n14.11.2 Mixer Device Objects (mixer-device-objects.html)\n---\n## 14.11.1 Audio Device Objects\nBefore you can write to or read from an audio device, you must call\nthree methods in the correct order:\n1. setfmt() to set the output format\n2. channels() to set the number of channels\n3. speed() to set the sample rate\nAlternately, you can use the setparameters() method to set all\nthree audio parameters at once. This is more convenient, but may not be\nas flexible in all cases.\nThe audio device objects returned by open() define the\nfollowing methods:\nThe following methods each map to exactly one\nioctl() system call. The correspondence is obvious: for\nexample, setfmt() corresponds to the `SNDCTL_DSP_SETFMT`\nioctl, and sync() to `SNDCTL_DSP_SYNC` (this can be useful\nwhen consulting the OSS documentation). If the underlying\nioctl() fails, they all raise IOError.\nThe following convenience methods combine several ioctls, or one ioctl\nand some simple calculations.", "python_version": "2.3", "length": 1223, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/ossaudio-device-objects.html"} {"title": "16.6 Other Graphical User Interface Packages", "text": "node672.html | tkinter.html | restricted.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.5.3.1 Command line usage (node672.html)\nUp:\n16. Graphical User Interfaces (tkinter.html)\nNext:\n17. Restricted Execution (restricted.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.3", "length": 479, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n16.4 turtle (module-turtle.html)\nUp:\n16.4 turtle (module-turtle.html)\nNext:\n16.5 Idle (idle.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.3", "length": 468, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pen-rawpen-objects.html"} {"title": "3.14.7 Example", "text": "pickle-sub.html | module-pickle.html | module-cPickle.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.6 Subclassing Unpicklers (pickle-sub.html)\nUp:\n3.14 pickle (module-pickle.html)\nNext:\n3.15 cPickle (module-cPickle.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.3", "length": 2195, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pickle-example.html"} {"title": "3.14.5.1 Pickling and unpickling normal class instances", "text": "pickle-protocol.html | pickle-protocol.html | node67.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.5 The pickle protocol (pickle-protocol.html)\nUp:\n3.14.5 The pickle protocol (pickle-protocol.html)\nNext:\n3.14.5.2 Pickling and unpickling (node67.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.6 (#foot8046). If there is no __setstate__() method, the\npickled state 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\nwant.3.7 (#foot8183)\nWarning:\nFor new-style classes, if __getstate__() returns a false\nvalue, the __setstate__() method will not be called.", "python_version": "2.3", "length": 1661, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pickle-inst.html"} {"title": "3.14.5 The pickle protocol", "text": "node64.html | module-pickle.html | pickle-inst.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.4 What can be (node64.html)\nUp:\n3.14 pickle (module-pickle.html)\nNext:\n3.14.5.1 Pickling and unpickling (pickle-inst.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\nslightly safer from untrusted pickle data streams; see section 3.14.6 (pickle-sub.html#pickle-sub)\nfor more details.", "python_version": "2.3", "length": 820, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pickle-protocol.html"} {"title": "3.14.6 Subclassing Unpicklers", "text": "node68.html | module-pickle.html | pickle-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.14.5.3 Pickling and unpickling (node68.html)\nUp:\n3.14 pickle (module-pickle.html)\nNext:\n3.14.7 Example (pickle-example.html)\n---\n## 3.14.6 Subclassing Unpicklers\nBy default, unpickling will import any class that it finds in the\npickle data. You can control exactly what gets unpickled and what\ngets called by customizing your unpickler. Unfortunately, exactly how\nyou do this is different depending on whether you're using\npickle or cPickle.3.10 (#foot8186).\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 looks 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__().\nYour 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. Refer to the source code to make this work.\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 and 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.3", "length": 2247, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pickle-sub.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\nPrevious:\n20.3 cd (module-cd.html)\nUp:\n20.3 cd (module-cd.html)\nNext:\n20.3.2 Parser Objects (cd-parser-objects.html)\n---\n## 20.3.1 Player Objects\nPlayer objects (returned by open()) have the following\nmethods:", "python_version": "2.3", "length": 341, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.3 select (module-select.html)\nUp:\n7.3 select (module-select.html)\nNext:\n7.4 thread (module-thread.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.3", "length": 763, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.9.1 POP3 Objects (pop3-objects.html)\nUp:\n11.9 poplib (module-poplib.html)\nNext:\n11.10 imaplib (module-imaplib.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.3", "length": 614, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.9 poplib (module-poplib.html)\nUp:\n11.9 poplib (module-poplib.html)\nNext:\n11.9.2 POP3 Example (pop3-example.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.3", "length": 459, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pop3-objects.html"} {"title": "6.8.2 Flow Control Issues", "text": "popen3-objects.html | module-popen2.html | module-datetime.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.8.1 Popen3 and Popen4 (popen3-objects.html)\nUp:\n6.8 popen2 (module-popen2.html)\nNext:\n6.9 datetime (module-datetime.html)\n---\n## 6.8.2 Flow Control Issues\nAny time you are working with any form of inter-process communication,\ncontrol flow needs to be carefully thought out. This remains the case\nwith the file objects provided by this module (or the os (module-os.html)\nmodule equivalents).\nWhen reading output from a child process that writes a lot of data to\nstandard error while the parent is reading from the child's standard\noutput, a deadlock can occur. A similar situation can occur with other\ncombinations of reads and writes. The essential factors are that more\nthan _PC_PIPE_BUF bytes are being written by one process in\na blocking fashion, while the other process is reading from the other\nprocess, also in a blocking fashion.\nThere are several ways to deal with this situation.\nThe simplest application change, in many cases, will be to follow this\nmodel in the parent process:\n```text\n\nimport popen2\n\nr, w, e = popen2.popen3('python slave.py')\ne.readlines()\nr.readlines()\nr.close()\ne.close()\nw.close()\n```\nwith code like this in the child:\n```text\n\nimport os\nimport sys\n\n# note that each of these print statements\n# writes a single long string\n\nprint >>sys.stderr, 400 * 'this is a test\\n'\nos.close(sys.stderr.fileno())\nprint >>sys.stdout, 400 * 'this is another test\\n'\n```\nIn particular, note that `sys.stderr` must be closed after\nwriting all data, or readlines() won't return. Also note\nthat os.close() must be used, as `sys.stderr.close()`\nwon't close `stderr` (otherwise assigning to `sys.stderr`\nwill silently close it, so no further errors can be printed).\nApplications which need to support a more general approach should\nintegrate I/O over pipes with their select() loops, or use\nseparate threads to read each of the individual files provided by\nwhichever popen*() function or Popen* class was\nused.", "python_version": "2.3", "length": 2073, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/popen2-flow-control.html"} {"title": "6.8.1 Popen3 and Popen4 Objects", "text": "module-popen2.html | module-popen2.html | popen2-flow-control.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.8 popen2 (module-popen2.html)\nUp:\n6.8 popen2 (module-popen2.html)\nNext:\n6.8.2 Flow Control Issues (popen2-flow-control.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.3", "length": 433, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.1.1 Large File Support (posix-large-files.html)\nUp:\n8.1 posix (module-posix.html)\nNext:\n8.2 pwd (module-pwd.html)\n---\n## 8.1.2 Module Contents\nModule posix defines the following data item:", "python_version": "2.3", "length": 336, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.1 posix (module-posix.html)\nUp:\n8.1 posix (module-posix.html)\nNext:\n8.1.2 Module Contents (posix-contents.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.3", "length": 1367, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/posix-large-files.html"} {"title": "10.7 Calibration", "text": "profile-limits.html | profile.html | node390.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.6 Limitations (profile-limits.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.8 Extensions (node390.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 (#foot40211)\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.3", "length": 1863, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/profile-calibration.html"} {"title": "10.3 Instant Users Manual", "text": "node383.html | profile.html | node385.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n10.2 How Is This (node383.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.4 What Is Deterministic (node385.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.3", "length": 4029, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n10.5.1 The Stats Class (profile-stats.html)\nUp:\n10. The Python Profiler (profile.html)\nNext:\n10.7 Calibration (profile-calibration.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.3", "length": 2457, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/profile-limits.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\nPrevious:\n10.5 Reference Manual (module-profile.html)\nUp:\n10.5 Reference Manual (module-profile.html)\nNext:\n10.6 Limitations (profile-limits.html)\n---\n## 10.5.1 The Stats Class\nStats objects have the following methods:", "python_version": "2.3", "length": 357, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/profile-stats.html"} {"title": "10. The Python Profiler", "text": "debugger-hooks.html | lib.html | node382.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n9.2 How It Works (debugger-hooks.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n10.1 Introduction to the (node382.html)\n---\n# 10. The Python Profiler\nCopyright © 1994, by InfoSeek Corporation, all rights reserved.\nWritten by James Roskind.10.1 (#foot39983)\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\n... Roskind.10.1 (profile.html#tex2html49): Updated and converted to LATEX by Guido van Rossum. The references to\nthe old profiler are left in the text, although it no longer exists.", "python_version": "2.3", "length": 2314, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/profile.html"} {"title": "11.20.6 ProtocolError Objects", "text": "fault-objects.html | module-xmlrpclib.html | node474.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.20.5 Fault Objects (fault-objects.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.20.7 Convenience Functions (node474.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.3", "length": 512, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.8 HTTPBasicAuthHandler Objects (http-basic-auth-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.10 AbstractDigestAuthHandler Objects (abstract-digest-auth-handler.html)\n---\n## 11.5.9 ProxyBasicAuthHandler Objects", "python_version": "2.3", "length": 405, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.11 HTTPDigestAuthHandler Objects (http-digest-auth-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.13 HTTPHandler Objects (http-handler-objects.html)\n---\n## 11.5.12 ProxyDigestAuthHandler Objects", "python_version": "2.3", "length": 381, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5.4 HTTPRedirectHandler Objects (http-redirect-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.6 HTTPPasswordMgr Objects (http-password-mgr.html)\n---\n## 11.5.5 ProxyHandler Objects", "python_version": "2.3", "length": 358, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n18.7 pyclbr (module-pyclbr.html)\nUp:\n18.7 pyclbr (module-pyclbr.html)\nNext:\n18.8 py_compile (module-pycompile.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.3", "length": 426, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pyclbr-class-objects.html"} {"title": "3. Python Runtime Services", "text": "node33.html | lib.html | module-sys.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n2.4 Built-in Constants (node33.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n3.1 sys (module-sys.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.3", "length": 434, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/python.html"} {"title": "7.18.2 PyZipFile Objects", "text": "zipfile-objects.html | module-zipfile.html | zipinfo-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.18.1 ZipFile Objects (zipfile-objects.html)\nUp:\n7.18 zipfile (module-zipfile.html)\nNext:\n7.18.3 ZipInfo Objects (zipinfo-objects.html)\n---\n## 7.18.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.3", "length": 466, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/pyzipfile-objects.html"} {"title": "7.8.1 Queue Objects", "text": "module-Queue.html | module-Queue.html | module-mmap.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.8 Queue (module-Queue.html)\nUp:\n7.8 Queue (module-Queue.html)\nNext:\n7.9 mmap (module-mmap.html)\n---\n## 7.8.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.3", "length": 542, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/QueueObjects.html"} {"title": "5.14.1 RawConfigParser Objects", "text": "module-ConfigParser.html | module-ConfigParser.html | ConfigParser-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.14 ConfigParser (module-ConfigParser.html)\nUp:\n5.14 ConfigParser (module-ConfigParser.html)\nNext:\n5.14.2 ConfigParser Objects (ConfigParser-objects.html)\n---\n## 5.14.1 RawConfigParser Objects\nRawConfigParser instances have the following methods:", "python_version": "2.3", "length": 412, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/RawConfigParser-objects.html"} {"title": "4.2.4 Regular Expression Objects", "text": "node105.html | module-re.html | match-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.2.3 Module Contents (node105.html)\nUp:\n4.2 re (module-re.html)\nNext:\n4.2.5 Match Objects (match-objects.html)\n---\n## 4.2.4 Regular Expression Objects\nCompiled regular expression objects support the following methods and\nattributes:", "python_version": "2.3", "length": 369, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.2 re (module-re.html)\nUp:\n4.2 re (module-re.html)\nNext:\n4.2.2 Matching vs Searching (matching-searching.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 above, 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 \"$\".\nMost of the standard escapes supported by Python string literals are\nalso accepted by the regular expression parser:\n```text\n\n\\a \\b \\f \\n\n\\r \\t \\v \\x\n\\\\\n```\nOctal escapes are included in a limited form: If the first digit is a\n0, or if there are three octal digits, it is considered an octal\nescape. Otherwise, it is a group reference.", "python_version": "2.3", "length": 2542, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/re-syntax.html"} {"title": "7.20.1 Example", "text": "module-readline.html | module-readline.html | module-rlcompleter.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.20 readline (module-readline.html)\nUp:\n7.20 readline (module-readline.html)\nNext:\n7.21 rlcompleter (module-rlcompleter.html)\n---\n## 7.20.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.3", "length": 621, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/readline-example.html"} {"title": "5.4.3 Running tests Using regrtest.py", "text": "writing-tests.html | module-test.html | module-math.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.4.2 Writing Unit Tests (writing-tests.html)\nUp:\n5.4 test (module-test.html)\nNext:\n5.5 math (module-math.html)\n---\n## 5.4.3 Running tests Using regrtest.py\nregrtest.py is the script used to drive Python's regression test\nsuite.\nRunning the script by itself automatically starts running all\nregression tests in the test package.\nIt does this by finding all modules in the package whose name starts with\n`test_`, importing them, and executing the function test_main\nif present.\nThe names of tests to execute may also be passed to the script.\nSpecifying a single regression test (`python regrtest.py test_spam.py`)\nwill minimize output and only print whether the test passed or failed and thus\nminimize output.\nRunning regrtest.py directly allows what resources are\navailable for tests to use to be set.\nYou do this by using the `-u` command-line option.\nRun `python regrtest.py -uall` to turn on all resources;\nspecifying `all` as an option for `-u` enables all possible\nresources.\nIf all but one resource is desired (a more common case), a\ncomma-separated list of resources that are not desired may be listed after\n`all`.\nThe command `python regrtest.py -uall,-audio,-largefile` will run\nregrtest.py with all resources except the audio and largefile\nresources.\nFor a list of all resources and more command-line options, run\n`python regrtest.py -h`.", "python_version": "2.3", "length": 1490, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/regrtest.html"} {"title": "B. Reporting Bugs", "text": "node749.html | lib.html | node751.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\nA.6 SGI-specific Extension modules (node749.html)\nUp:\nPython Library Reference (lib.html)\nNext:\nC. History and License (node751.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.\nBefore submitting a report, you will be required to log into SourceForge;\nthis will make it possible for the developers to contact you\nfor additional information if needed. It is not possible to submit a\nbug report anonymously.\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.\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. You will\nreceive an update each time action is taken on the bug.\nSee Also:", "python_version": "2.3", "length": 2566, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/reporting-bugs.html"} {"title": "3.26.1 Repr Objects", "text": "module-repr.html | module-repr.html | subclassing-reprs.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.26 repr (module-repr.html)\nUp:\n3.26 repr (module-repr.html)\nNext:\n3.26.2 Subclassing Repr Objects (subclassing-reprs.html)\n---\n## 3.26.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.3", "length": 476, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.5 urllib2 (module-urllib2.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.2 OpenerDirector Objects (opener-director-objects.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.3", "length": 439, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n16.6 Other Graphical User (other-gui-packages.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n17.1 rexec (module-rexec.html)\n---\n# 17. Restricted Execution\nWarning:\nIn Python 2.3 these modules have been disabled due to various known\nand not readily fixable security holes. The modules are still\ndocumented here to help in reading old code that uses the\nrexec and Bastion modules.\nRestricted execution is the basic framework in Python that allows\nfor the segregation of trusted and untrusted code. The framework 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.3", "length": 3265, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/restricted.html"} {"title": "17.1.2 Defining restricted environments", "text": "rexec-objects.html | module-rexec.html | node678.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n17.1.1 RExec Objects (rexec-objects.html)\nUp:\n17.1 rexec (module-rexec.html)\nNext:\n17.1.3 An example (node678.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.3", "length": 646, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n17.1 rexec (module-rexec.html)\nUp:\n17.1 rexec (module-rexec.html)\nNext:\n17.1.2 Defining restricted environments (rexec-extension.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.3", "length": 880, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.1 Lock Objects (lock-objects.html)\nUp:\n7.5 threading (module-threading.html)\nNext:\n7.5.3 Condition Objects (condition-objects.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.3", "length": 1004, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.10.3 EntityResolver Objects (entity-resolver-objects.html)\nUp:\n13.10 xml.sax.handler (module-xml.sax.handler.html)\nNext:\n13.11 xml.sax.saxutils (module-xml.sax.saxutils.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.3", "length": 938, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.9 xml.sax (module-xml.sax.html)\nUp:\n13.9 xml.sax (module-xml.sax.html)\nNext:\n13.10 xml.sax.handler (module-xml.sax.handler.html)\n---\n## 13.9.1 SAXException Objects\nThe SAXException exception class supports the following\nmethods:", "python_version": "2.3", "length": 388, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/sax-exception-objects.html"} {"title": "6.11.1 Scheduler Objects", "text": "module-sched.html | module-sched.html | module-mutex.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.11 sched (module-sched.html)\nUp:\n6.11 sched (module-sched.html)\nNext:\n6.12 mutex (module-mutex.html)\n---\n## 6.11.1 Scheduler Objects\nscheduler instances have the following methods:", "python_version": "2.3", "length": 325, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.4 Semaphore Objects (semaphore-objects.html)\nUp:\n7.5.4 Semaphore Objects (semaphore-objects.html)\nNext:\n7.5.5 Event Objects (event-objects.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.3", "length": 1095, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.3 Condition Objects (condition-objects.html)\nUp:\n7.5 threading (module-threading.html)\nNext:\n7.5.4.1 Semaphore Example (semaphore-examples.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.3", "length": 809, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.4 difflib (module-difflib.html)\nUp:\n4.4 difflib (module-difflib.html)\nNext:\n4.4.2 SequenceMatcher Examples (sequencematcher-examples.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.3", "length": 1067, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n4.4.1 SequenceMatcher Objects (sequence-matcher.html)\nUp:\n4.4 difflib (module-difflib.html)\nNext:\n4.4.3 Differ Objects (differ-objects.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.3", "length": 1711, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/sequencematcher-examples.html"} {"title": "11.20.1 ServerProxy Objects", "text": "module-xmlrpclib.html | module-xmlrpclib.html | boolean-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.20 xmlrpclib (module-xmlrpclib.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.20.2 Boolean Objects (boolean-objects.html)\n---\n## 11.20.1 ServerProxy Objects\nA ServerProxy instance 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.3", "length": 1133, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/serverproxy-objects.html"} {"title": "5.12.2 Example", "text": "set-objects.html | module-sets.html | immutable-transforms.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.12.1 Set Objects (set-objects.html)\nUp:\n5.12 sets (module-sets.html)\nNext:\n5.12.3 Protocol for automatic (immutable-transforms.html)\n---\n## 5.12.2 Example\n```text\n\n>>> from sets import Set\n>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])\n>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])\n>>> management = Set(['Jane', 'Jack', 'Susan', 'Zack'])\n>>> employees = engineers | programmers | management # union\n>>> engineering_management = engineers & programmers # intersection\n>>> fulltime_management = management - engineers - programmers # difference\n>>> engineers.add('Marvin') # add element\n>>> print engineers\nSet(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])\n>>> employees.issuperset(engineers) # superset test\nFalse\n>>> employees.update(engineers) # update from another set\n>>> employees.issuperset(engineers)\nTrue\n>>> for group in [engineers, programmers, management, employees]:\n... group.discard('Susan') # unconditionally remove element\n... print group\n...\nSet(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])\nSet(['Janice', 'Jack', 'Sam'])\nSet(['Jane', 'Zack', 'Jack'])\nSet(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])\n```", "python_version": "2.3", "length": 1309, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/set-example.html"} {"title": "5.12.1 Set Objects", "text": "module-sets.html | module-sets.html | set-example.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.12 sets (module-sets.html)\nUp:\n5.12 sets (module-sets.html)\nNext:\n5.12.2 Example (set-example.html)\n---\n## 5.12.1 Set Objects\nInstances of Set and ImmutableSet both provide\nthe following operations:\nIn addition, both Set and ImmutableSet\nsupport set to set comparisons. Two sets are equal if and only if\nevery element of each set is contained in the other (each is a subset\nof the other).\nA set is less than another set if and only if the first set is a proper\nsubset of the second set (is a subset, but is not equal).\nA set is greater than another set if and only if the first set is a proper\nsuperset of the second set (is a superset, but is not equal).\nThe subset and equality comparisons do not generalize to a complete\nordering function. For example, any two disjoint sets are not equal and\nare not subsets of each other, so none of the following are true:\n`a < b`, `a == b`, or `a > b`.\nAccordingly, sets do not implement the __cmp__ method.\nSince sets only define partial ordering (subset relationships), the output\nof the list.sort() method is undefined for lists of sets.\nThe following table lists operations available in ImmutableSet\nbut not found in Set:\nThe following table lists operations available in Set\nbut not found in ImmutableSet:", "python_version": "2.3", "length": 1392, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/set-objects.html"} {"title": "20. SGI IRIX Specific Services", "text": "node710.html | lib.html | module-al.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n19.5 Bytecode Generation (node710.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n20.1 al (module-al.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.3", "length": 409, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/sgi.html"} {"title": "5.19.2 shlex Objects", "text": "node180.html | module-shlex.html | shlex-parsing-rules.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.19.1 Module Contents (node180.html)\nUp:\n5.19 shlex (module-shlex.html)\nNext:\n5.19.3 Parsing Rules (shlex-parsing-rules.html)\n---\n## 5.19.2 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:", "python_version": "2.3", "length": 477, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/shlex-objects.html"} {"title": "5.19.3 Parsing Rules", "text": "shlex-objects.html | module-shlex.html | allos.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.19.2 shlex Objects (shlex-objects.html)\nUp:\n5.19 shlex (module-shlex.html)\nNext:\n6. Generic Operating System (allos.html)\n---\n## 5.19.3 Parsing Rules\nWhen operating in non-POSIX mode, shlex will try to obey to\nthe following rules.\n- Quote characters are not recognized within words\n(`Do\"Not\"Separate` is parsed as the single word\n`Do\"Not\"Separate`);\n- Escape characters are not recognized;\n- Enclosing characters in quotes preserve the literal value of\nall characters within the quotes;\n- Closing quotes separate words (`\"Do\"Separate` is parsed\nas `\"Do\"` and `Separate`);\n- If whitespace_split is `False`, any character not\ndeclared to be a word character, whitespace, or a quote will be\nreturned as a single-character token. If it is `True`,\nshlex will only split words in whitespaces;\n- EOF is signaled with an empty string (`''`);\n- It's not possible to parse empty strings, even if quoted.\nWhen operating in POSIX mode, shlex will try to obey to the\nfollowing parsing rules.\n- Quotes are stripped out, and do not separate words\n(`\"Do\"Not\"Separate\"` is parsed as the single word\n`DoNotSeparate`);\n- Non-quoted escape characters (e.g. \"\\\")\npreserve the literal value of the next character that follows;\n- Enclosing characters in quotes which are not part of\nescapedquotes (e.g. \"'\") preserve the literal\nvalue of all characters within the quotes;\n- Enclosing characters in quotes which are part of\nescapedquotes (e.g. \"\"\") preserves the literal\nvalue of all characters within the quotes, with the exception of\nthe characters mentioned in escape. The escape characters\nretain its special meaning only when followed by the quote in use,\nor the escape character itself. Otherwise the escape character\nwill be considered a normal character.\n- EOF is signaled with a `None` value;\n- Quoted empty strings (`''`) are allowed;", "python_version": "2.3", "length": 1959, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/shlex-parsing-rules.html"} {"title": "6.25.1 Example", "text": "module-shutil.html | module-shutil.html | module-locale.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.25 shutil (module-shutil.html)\nUp:\n6.25 shutil (module-shutil.html)\nNext:\n6.26 locale (module-locale.html)\n---\n## 6.25.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.3", "length": 453, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/shutil-example.html"} {"title": "11.21.1 SimpleXMLRPCServer Objects", "text": "module-SimpleXMLRPCServer.html | module-SimpleXMLRPCServer.html | node478.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.21 SimpleXMLRPCServer (module-SimpleXMLRPCServer.html)\nUp:\n11.21 SimpleXMLRPCServer (module-SimpleXMLRPCServer.html)\nNext:\n11.21.2 CGIXMLRPCRequestHandler (node478.html)\n---\n## 11.21.1 SimpleXMLRPCServer Objects\nThe SimpleXMLRPCServer class is based on\nSocketServer.TCPServer and provides a means of creating\nsimple, stand alone XML-RPC servers.\nExample:\n```text\n\nclass MyFuncs:\ndef div(self, x, y) : return div(x,y)\n\nserver = SimpleXMLRPCServer((\"localhost\", 8000))\nserver.register_function(pow)\nserver.register_function(lambda x,y: x+y, 'add')\nserver.register_introspection_functions()\nserver.register_instance(MyFuncs())\nserver.serve_forever()\n```", "python_version": "2.3", "length": 817, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.12.1 SMTP Objects (SMTP-objects.html)\nUp:\n11.12 smtplib (module-smtplib.html)\nNext:\n11.13 telnetlib (module-telnetlib.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.3", "length": 737, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.12 smtplib (module-smtplib.html)\nUp:\n11.12 smtplib (module-smtplib.html)\nNext:\n11.12.2 SMTP Example (SMTP-example.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.3", "length": 601, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.2.2 SSL Objects (ssl-objects.html)\nUp:\n7.2 socket (module-socket.html)\nNext:\n7.3 select (module-select.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.3", "length": 2603, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.2 socket (module-socket.html)\nUp:\n7.2 socket (module-socket.html)\nNext:\n7.2.2 SSL Objects (ssl-objects.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.\nSome notes on socket blocking and timeouts: A socket object can be in\none of three modes: blocking, non-blocking, or timeout. Sockets are\nalways created in blocking mode. In blocking mode, operations block\nuntil complete. In non-blocking mode, operations fail (with an error\nthat is unfortunately system-dependent) if they cannot be completed\nimmediately. In timeout mode, operations fail if they cannot be\ncompleted within the timeout specified for the socket. The\nsetblocking() method is simply a shorthand for certain\nsettimeout() calls.\nTimeout mode internally sets the socket in non-blocking mode. The\nblocking and timeout modes are shared between file descriptors and\nsocket objects that refer to the same network endpoint. A consequence\nof this is that file objects returned by the makefile()\nmethod should only be used when the socket is in blocking mode; in\ntimeout or non-blocking mode file operations that cannot be completed\nimmediately will fail.\nNote that there are no methods read() or write();\nuse recv() and send() without flags argument\ninstead.", "python_version": "2.3", "length": 1472, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/socket-objects.html"} {"title": "7. Optional Operating System Services", "text": "node301.html | lib.html | module-signal.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n6.28.8.1 Basic example - (node301.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n7.1 signal (module-signal.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.3", "length": 595, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9.10 Internal Objects (typesinternal.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.3 Built-in Exceptions (module-exceptions.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.3", "length": 421, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.2.1 Socket Objects (socket-objects.html)\nUp:\n7.2 socket (module-socket.html)\nNext:\n7.2.3 Example (socket-example.html)\n---\n## 7.2.2 SSL Objects\nSSL objects have the following methods.", "python_version": "2.3", "length": 333, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/ssl-objects.html"} {"title": "4.9.1.3 StreamReader Objects", "text": "stream-writer-objects.html | node120.html | stream-reader-writer.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.1.2 StreamWriter Objects (stream-writer-objects.html)\nUp:\n4.9.1 Codec Base Classes (node120.html)\nNext:\n4.9.1.4 StreamReaderWriter Objects (stream-reader-writer.html)\n---\n### 4.9.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.3", "length": 800, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/stream-reader-objects.html"} {"title": "4.9.1.4 StreamReaderWriter Objects", "text": "stream-reader-objects.html | node120.html | stream-recoder-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.1.3 StreamReader Objects (stream-reader-objects.html)\nUp:\n4.9.1 Codec Base Classes (node120.html)\nNext:\n4.9.1.5 StreamRecoder Objects (stream-recoder-objects.html)\n---\n### 4.9.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.3", "length": 749, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/stream-reader-writer.html"} {"title": "4.9.1.5 StreamRecoder Objects", "text": "stream-reader-writer.html | node120.html | node126.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.1.4 StreamReaderWriter Objects (stream-reader-writer.html)\nUp:\n4.9.1 Codec Base Classes (node120.html)\nNext:\n4.9.2 Standard Encodings (node126.html)\n---\n### 4.9.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.\nStreamRecoder instances define the combined interfaces of\nStreamReader and StreamWriter classes. They inherit\nall other methods and attribute from the underlying stream.", "python_version": "2.3", "length": 766, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/stream-recoder-objects.html"} {"title": "4.9.1.2 StreamWriter Objects", "text": "codec-objects.html | node120.html | stream-reader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n4.9.1.1 Codec Objects (codec-objects.html)\nUp:\n4.9.1 Codec Base Classes (node120.html)\nNext:\n4.9.1.3 StreamReader Objects (stream-reader-objects.html)\n---\n### 4.9.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.3", "length": 638, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.6 Sequence Types (typesseq.html)\nUp:\n2.2.6 Sequence Types (typesseq.html)\nNext:\n2.2.6.2 String Formatting Operations (typesseq-strings.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.3", "length": 397, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/string-methods.html"} {"title": "4. String Services", "text": "module-future.html | lib.html | module-string.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.32 __future__ (module-future.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n4.1 string (module-string.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.\ntextwrap (module-textwrap.html) | Text wrapping and filling\ncodecs (module-codecs.html) | Encode and decode data and streams.\nencodings.idna (module-encodings.idna.html) | Internationalized Domain Names implementation\nunicodedata (module-unicodedata.html) | Access the Unicode Database.\nstringprep (module-stringprep.html) | String preparation, as per RFC 3453", "python_version": "2.3", "length": 1311, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/strings.html"} {"title": "3.26.2 Subclassing Repr Objects", "text": "Repr-objects.html | module-repr.html | module-new.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n3.26.1 Repr Objects (Repr-objects.html)\nUp:\n3.26 repr (module-repr.html)\nNext:\n3.27 new (module-new.html)\n---\n## 3.26.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.3", "length": 535, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n20.12 jpeg (module-jpeg.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n21.1 sunaudiodev (module-sunaudiodev.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.3", "length": 473, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/sunos.html"} {"title": "7.19.3 Examples", "text": "tarinfo-objects.html | module-tarfile.html | module-readline.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.19.2 TarInfo Objects (tarinfo-objects.html)\nUp:\n7.19 tarfile (module-tarfile.html)\nNext:\n7.20 readline (module-readline.html)\n---\n## 7.19.3 Examples\nHow to create an uncompressed tar archive from a list of filenames:\n```text\n\nimport tarfile\ntar = tarfile.open(\"sample.tar\", \"w\")\nfor name in [\"foo\", \"bar\", \"quux\"]:\ntar.add(name)\ntar.close()\n```\nHow to read a gzip compressed tar archive and display some member information:\n```text\n\nimport tarfile\ntar = tarfile.open(\"sample.tar.gz\", \"r:gz\")\nfor tarinfo in tar:\nprint tarinfo.name, \"is\", tarinfo.size, \"bytes in size and is\",\nif tarinfo.isreg():\nprint \"a regular file.\"\nelif tarinfo.isdir():\nprint \"a directory.\"\nelse:\nprint \"something else.\"\ntar.close()\n```\nHow to create a tar archive with faked information:\n```text\n\nimport tarfile\ntar = tarfile.open(\"sample.tar.gz\", \"w:gz\")\nfor name in namelist:\ntarinfo = tar.gettarinfo(name, \"fakeproj-1.0/\" + name)\ntarinfo.uid = 123\ntarinfo.gid = 456\ntarinfo.uname = \"johndoe\"\ntarinfo.gname = \"fake\"\ntar.addfile(tarinfo, file(name))\ntar.close()\n```", "python_version": "2.3", "length": 1192, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/tar-examples.html"} {"title": "7.19.1 TarFile Objects", "text": "module-tarfile.html | module-tarfile.html | tarinfo-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.19 tarfile (module-tarfile.html)\nUp:\n7.19 tarfile (module-tarfile.html)\nNext:\n7.19.2 TarInfo Objects (tarinfo-objects.html)\n---\n## 7.19.1 TarFile Objects\nThe TarFile object provides an interface to a tar archive. A tar\narchive is a sequence of blocks. An archive member (a stored file) is made up\nof a header block followed by data blocks. It is possible, to store a file in a\ntar archive several times. Each archive member is represented by a\nTarInfo object, see TarInfo Objects (section\n7.19.2 (tarinfo-objects.html#tarinfo-objects)) for details.", "python_version": "2.3", "length": 700, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/tarfile-objects.html"} {"title": "7.19.2 TarInfo Objects", "text": "tarfile-objects.html | module-tarfile.html | tar-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.19.1 TarFile Objects (tarfile-objects.html)\nUp:\n7.19 tarfile (module-tarfile.html)\nNext:\n7.19.3 Examples (tar-examples.html)\n---\n## 7.19.2 TarInfo Objects\nA TarInfo object represents one member in a TarFile. Aside from\nstoring all required attributes of a file (like file type, size, time,\npermissions, owner etc.), it provides some useful methods to determine its\ntype. It does not contain the file's data itself.\nTarInfo objects are returned by `TarFile`'s methods\n`getmember()`, `getmembers()` and `gettarinfo()`.\nA `TarInfo` object has the following public data attributes:\nA TarInfo object also provides some convenient query methods:", "python_version": "2.3", "length": 789, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/tarinfo-objects.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\nPrevious:\n11.13.1 Telnet Objects (telnet-objects.html)\nUp:\n11.13 telnetlib (module-telnetlib.html)\nNext:\n11.14 urlparse (module-urlparse.html)\n---\n## 11.13.2 Telnet Example\nA simple example illustrating typical use:", "python_version": "2.3", "length": 357, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n11.13 telnetlib (module-telnetlib.html)\nUp:\n11.13 telnetlib (module-telnetlib.html)\nNext:\n11.13.2 Telnet Example (telnet-example.html)\n---\n## 11.13.1 Telnet Objects\nTelnet instances have the following methods:", "python_version": "2.3", "length": 362, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.13 pipes (module-pipes.html)\nUp:\n8.13 pipes (module-pipes.html)\nNext:\n8.14 posixfile (module-posixfile.html)\n---\n## 8.13.1 Template Objects\nTemplate objects following methods:", "python_version": "2.3", "length": 324, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/template-objects.html"} {"title": "5.3.5 TestCase Objects", "text": "unittest-contents.html | module-unittest.html | testsuite-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.4 Classes and functions (unittest-contents.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.6 TestSuite Objects (testsuite-objects.html)\n---\n## 5.3.5 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.3", "length": 1011, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/testcase-objects.html"} {"title": "5.3.8 TestLoader Objects", "text": "testresult-objects.html | module-unittest.html | unittest-error-info.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.7 TestResult Objects (testresult-objects.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.9 Getting Extended Error (unittest-error-info.html)\n---\n## 5.3.8 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.3", "length": 858, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/testloader-objects.html"} {"title": "5.3.7 TestResult Objects", "text": "testsuite-objects.html | module-unittest.html | testloader-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.6 TestSuite Objects (testsuite-objects.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.8 TestLoader Objects (testloader-objects.html)\n---\n## 5.3.7 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 , traceback )`, where traceback is a string containing a\nformatted version of the traceback for the exception.\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.3", "length": 1552, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/testresult-objects.html"} {"title": "5.3.6 TestSuite Objects", "text": "testcase-objects.html | module-unittest.html | testresult-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.5 TestCase Objects (testcase-objects.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.7 TestResult Objects (testresult-objects.html)\n---\n## 5.3.6 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.3", "length": 762, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n7.5.5 Event Objects (event-objects.html)\nUp:\n7.5 threading (module-threading.html)\nNext:\n7.5.7 Timer Objects (timer-objects.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.3", "length": 2386, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/thread-objects.html"} {"title": "7.5.7 Timer Objects", "text": "thread-objects.html | module-threading.html | module-dummythread.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.5.6 Thread Objects (thread-objects.html)\nUp:\n7.5 threading (module-threading.html)\nNext:\n7.6 dummy_thread (module-dummythread.html)\n---\n## 7.5.7 Timer Objects\nThis class represents an action that should be run only after a\ncertain amount of time has passed -- a timer. Timer is a\nsubclass of Thread and as such also functions as an example of\ncreating custom threads.\nTimers are started, as with threads, by calling their start()\nmethod. The timer can be stopped (before its action has begun) by\ncalling the cancel() method. The interval the timer will\nwait before executing its action may not be exactly the same as the\ninterval specified by the user.\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.3", "length": 954, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/timer-objects.html"} {"title": "16.1.4 Mapping Basic Tk into Tkinter", "text": "node634.html | module-Tkinter.html | node636.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.3 A (Very) Quick (node634.html)\nUp:\n16.1 Tkinter (module-Tkinter.html)\nNext:\n16.1.5 How Tk and (node636.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.3", "length": 2000, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/tkinter-basic-mapping.html"} {"title": "16.1.6.1 Setting Options", "text": "node637.html | node637.html | node639.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n16.1.6 Handy Reference (node637.html)\nUp:\n16.1.6 Handy Reference (node637.html)\nNext:\n16.1.6.2 The Packer (node639.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 without arguments, or by calling the\nkeys() method on that widget. The return value of these\ncalls is a dictionary whose key is the name of the option as a string\n(for example, `'relief'`) and whose values are 5-tuples.\nSome options, like `bg` are synonyms for common options with long\nnames (`bg` is shorthand for \"background\"). Passing the\n`config()` method the name of a shorthand option will return a\n2-tuple, not 5-tuple. The 2-tuple passed back will contain the name of\nthe synonym and the ``real'' option (such as `('bg',\n'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.3", "length": 2361, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n15.5 rotor (module-rotor.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n16.1 Tkinter (module-Tkinter.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.3", "length": 1514, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.12 traceback (module-traceback.html)\nUp:\n3.12 traceback (module-traceback.html)\nNext:\n3.13 linecache (module-linecache.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.3", "length": 563, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2 Built-in Types (types.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.2 Boolean Operations (boolean.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- `False`\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 the integer zero or bool value\n`False`.2.5 (#foot3003)\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` or `False` for false and `1` or `True`\nfor true, unless otherwise stated. (Important exception: the Boolean\noperations \"or\" and \"and\" always\nreturn one of their operands.)", "python_version": "2.3", "length": 1123, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.4.1 Bit-string Operations on (bitstring-ops.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.6 Sequence Types (typesseq.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.\nThe intention of the protocol is that once an iterator's\nnext() method raises StopIteration, it will\ncontinue to do so on subsequent calls. Implementations that\ndo not obey this property are deemed broken. (This constraint\nwas added in Python 2.3; in Python 2.2, various iterators are\nbroken according to this rule.)\nPython's generators provide a convenient way to implement the\niterator protocol. If a container object's __iter__()\nmethod is implemented as a generator, it will automatically\nreturn an iterator object (technically, a generator object)\nsupplying the __iter__() and next() methods.", "python_version": "2.3", "length": 1614, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.1 Built-in Functions (built-in-funcs.html)\nUp:\n2. Built-In Objects (builtin.html)\nNext:\n2.2.1 Truth Value Testing (truth.html)\n---\n# 2.2 Built-in Types\nThe following sections describe the standard types that are built into\nthe interpreter. Historically, Python's built-in types have differed\nfrom user-defined types because it was not possible to use the built-in\ntypes as the basis for object-oriented inheritance. With the 2.2\nrelease this situation has started to change, although the intended\nunification of user-defined and built-in types is as yet far from\ncomplete.\nThe principal built-in types are numerics, sequences, mappings, files\nclasses, instances and exceptions.\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\nprint statement.\n(Information on print statement (../ref/print.html)\nand other language statements can be found in the\nPython Reference Manual (../ref/ref.html) and the\nPython Tutorial (../tut/tut.html).)", "python_version": "2.3", "length": 1270, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9.2 Classes and Class (typesobjects.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.4 Methods (typesmethods.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.3", "length": 1593, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/typesfunctions.html"} {"title": "2.2.9.10 Internal Objects", "text": "node29.html | typesother.html | specialattrs.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n2.2.9.9 Boolean Values (node29.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.10 Special Attributes (specialattrs.html)\n---\n### 2.2.9.10 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.3", "length": 450, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.6.4 Mutable Sequence Types (typesseq-mutable.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.8 File Objects (bltin-file-objects.html)\n---\n## 2.2.7 Mapping Types\nA mapping object maps immutable values 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. Only values containing lists, dictionaries\nor other mutable types (that are compared by value rather than by\nobject identity) may not be used as keys.\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\nitems(), keys(), values(),\niteritems(), iterkeys(), and itervalues()\nare called with no intervening modifications to the dictionary, the\nlists will directly correspond. This allows the creation of\n`( value , key )` pairs using zip():\n\"pairs = zip(a.values(), a.keys())\". The same\nrelationship holds for the iterkeys() and\nitervalues() methods: \"pairs = zip(a.itervalues(),\na.iterkeys())\" provides the same value for `pairs`.\nAnother way to create the same list is \"pairs = [(v, k) for (k,\nv) in a.iteritems()]\".\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.\n(7): fromkeys() is a class method that returns a\nnew dictionary. value defaults to `None`.\nNew in version 2.3.\n(8): pop() raises a KeyError when no default\nvalue is given and the key is not found.\nNew in version 2.3.", "python_version": "2.3", "length": 2441, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9.3 Functions (typesfunctions.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.5 Code Objects (bltin-code-objects.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.3", "length": 1903, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9 Other Built-in Types (typesother.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.2 Classes and Class (typesobjects.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.3", "length": 1272, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.3 Comparisons (comparisons.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.4.1 Bit-string Operations on (bitstring-ops.html)\n---\n## 2.2.4 Numeric Types\nThere are four distinct numeric types: plain integers,\nlong integers,\nfloating point numbers, and complex numbers.\nIn addition, Booleans are a subtype of plain integers.\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 each\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 unless the value they denote\nis too large to be represented as a plain integer, in which case\nthey yield a long integer. 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 with a\nzero real part. A complex numeric literal is the sum of a real and\nan imaginary part.\nPython fully supports mixed arithmetic: when a binary arithmetic\noperator has operands of different numeric types, the operand with the\n``narrower'' type is widened to that of the other, where plain\ninteger is narrower than long integer is narrower than floating point is\nnarrower than complex.\nComparisons between numbers of mixed type use the same rule.2.6 (#foot3022) The constructors int(), long(), float(),\nand complex() can be used\nto produce numbers of a specific type.\nAll numeric types (except complex) support the following operations,\nsorted by ascending 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(4): Complex floor division operator, modulo operator, and divmod().\nDeprecated since release 2.3.\nInstead convert to float using abs()\nif appropriate.\n---\n#### Footnotes\n... rule.2.6 (typesnumeric.html#tex2html7): As a consequence, the list `[1, 2]` is considered equal\nto `[1.0, 2.0]`, and similarly for tuples.", "python_version": "2.3", "length": 3241, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.9.1 Modules (typesmodules.html)\nUp:\n2.2.9 Other Built-in Types (typesother.html)\nNext:\n2.2.9.3 Functions (typesfunctions.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.3", "length": 398, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.8 File Objects (bltin-file-objects.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.9.1 Modules (typesmodules.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.3", "length": 405, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.6.3 XRange Type (typesseq-xrange.html)\nUp:\n2.2.6 Sequence Types (typesseq.html)\nNext:\n2.2.7 Mapping Types (typesmapping.html)\n---\n### 2.2.6.4 Mutable Sequence Types\nList objects support additional operations that allow in-place\nmodification of the object.\nOther mutable sequence types (when added to the language) should\nalso support these operations.\nStrings and tuples are immutable sequence types: 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): t must have the same length as the slice it is\nreplacing.\n(2): 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(3): 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(4): Raises ValueError when x is not found in\ns. When a negative index is passed as the second or third parameter\nto the index() method, the list length is added, as for slice\nindices. If it is still negative, it is truncated to zero, as for\nslice indices.\nChanged in version 2.3:\nPreviously, index() didn't\nhave arguments for specifying start and stop positions.\n(5): When a negative index is passed as the first parameter to\nthe insert() method, the list length is added, as for slice\nindices. If it is still negative, it is truncated to zero, as for\nslice indices.\nChanged in version 2.3:\nPreviously, all negative indices\nwere truncated to zero.\n(6): 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(7): 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(8): 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; for example to sort a list in reverse order it is much\nfaster to call sort() followed by reverse()\nthan to use sort() with a comparison function that\nreverses the ordering of the elements. Passing None as the\ncomparison function is semantically equivalent to calling\nsort() with no comparison function.\nChanged in version 2.3:\nSupport for `None` as an equivalent to omitting\ncmpfunc was added.\nAs an example of using the cmpfunc argument to the\nsort() method, consider sorting a list of sequences by the\nsecond element of that list:\n```text\n\ndef mycmp(a, b):\nreturn cmp(a[1], b[1])\n\nmylist.sort(mycmp)\n```\nA more time-efficient approach for reasonably-sized data structures can\noften be used:\n```text\n\ntmplist = [(x[1], x) for x in mylist]\ntmplist.sort()\nmylist = [x for (key, x) in tmplist]\n```\n(9): Whether the sort() method is stable is not defined by\nthe language (a sort is stable if it guarantees not to change the\nrelative order of elements that compare equal). In the C\nimplementation of Python, sorts were stable only by accident through\nPython 2.2. The C implementation of Python 2.3 introduced a stable\nsort() method, but code that intends to be portable across\nimplementations and versions must not rely on stability.\n(10): While a list is being sorted, the effect of attempting to\nmutate, or even inspect, the list is undefined. The C implementation\nof Python 2.3 makes the list appear empty for the duration, and raises\nValueError if it can detect that the list has been\nmutated during a sort.", "python_version": "2.3", "length": 4019, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.6.1 String Methods (string-methods.html)\nUp:\n2.2.6 Sequence Types (typesseq.html)\nNext:\n2.2.6.3 XRange Type (typesseq-xrange.html)\n---\n### 2.2.6.2 String Formatting Operations\nString and Unicode objects have one unique built-in operation: the\n`%` operator (modulo). This is also known as the string\nformatting or interpolation operator. Given\n`format % values` (where format is a string or\nUnicode object), `%` conversion specifications in format\nare replaced with zero or more elements of values. The effect\nis similar to the using sprintf() in the C language. If\nformat is a Unicode object, or if any of the objects being\nconverted using the `%s` conversion are Unicode objects, the\nresult will also be a Unicode object.\nIf format requires a single argument, values may be a\nsingle non-tuple object. 2.8 (#foot2196) 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 (optional), consisting of a parenthesised sequence\nof characters (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.\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string must include a parenthesised mapping key into\nthat dictionary inserted immediately after the \"%\"\ncharacter. The mapping key selects the value to be formatted from the\nmapping. For example:\n```text\n\n>>> print '%(language)s has %(#)03d quote types.' % \\\n{'language': \"Python\", \"#\": 2}\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:\nNotes:\n(1): The alternate form causes a leading zero (\"0\") to be\ninserted between left-hand padding and the formatting of the\nnumber if the leading character of the result is not already a\nzero.\n(2): The alternate form causes a leading `'0x'` or `'0X'`\n(depending on whether the \"x\" or \"X\" format\nwas used) to be inserted between left-hand padding and the\nformatting of the number if the leading character of the result is\nnot already a zero.\n(3): The `%r` conversion was added in Python 2.0.\n(4): If the object or format provided is a unicode string,\nthe resulting string will also be unicode.\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 (#foot2303) 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.3", "length": 3729, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.6.2 String Formatting Operations (typesseq-strings.html)\nUp:\n2.2.6 Sequence Types (typesseq.html)\nNext:\n2.2.6.4 Mutable Sequence Types (typesseq-mutable.html)\n---\n### 2.2.6.3 XRange Type\nThe xrange type 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,\niteration, and the len() function.", "python_version": "2.3", "length": 716, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2.5 Iterator Types (typeiter.html)\nUp:\n2.2 Built-in Types (types.html)\nNext:\n2.2.6.1 String Methods (string-methods.html)\n---\n## 2.2.6 Sequence Types\nThere are six sequence types: strings, Unicode strings, lists,\ntuples, buffers, and xrange objects.\nString 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 (#foot1788)\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): When s is a string or Unicode string object the\n`in` and `not in` operations act like a substring test. In\nPython versions before 2.3, x had to be a string of length 1.\nIn Python 2.3 and beyond, x may be a string of any length.\n(2): 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(3): 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(4): 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(5): The slice of s from i to j with step\nk is defined as the sequence of items with index\n`x = i + n * k` such that `0`\n`<=` n `<` `abs(i-j)`. If i or j\nis greater than `len( s )`, use `len( s )`. If\ni or j are ommitted then they become ``end'' values\n(which end depends on the sign of k).\n---\n#### Footnotes\n... operations.2.7 (typesseq.html#tex2html8): They must\nhave since the parser can't tell the type of the operands.", "python_version": "2.3", "length": 3723, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/typesseq.html"} {"title": "A. Undocumented Modules", "text": "module-winsound.html | lib.html | node744.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n22.3 winsound (module-winsound.html)\nUp:\nPython Library Reference (lib.html)\nNext:\nA.1 Frameworks (node744.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.3", "length": 627, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/undoc.html"} {"title": "5.3.4 Classes and functions", "text": "legacy-unit-tests.html | module-unittest.html | testcase-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.3 Re-using old test (legacy-unit-tests.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.3.5 TestCase Objects (testcase-objects.html)\n---\n## 5.3.4 Classes and functions", "python_version": "2.3", "length": 331, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/unittest-contents.html"} {"title": "5.3.9 Getting Extended Error Information", "text": "testloader-objects.html | module-unittest.html | module-test.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.3.8 TestLoader Objects (testloader-objects.html)\nUp:\n5.3 unittest (module-unittest.html)\nNext:\n5.4 test (module-test.html)\n---\n## 5.3.9 Getting Extended Error Information\nSome applications can make use of more error information (for example,\nan integrated development environment, or IDE). Such an application\ncan retrieve supplemental information about errors and failures by\nusing an alternate TestResult implementation, and extending\nthe defaultTestResult() method of the TestCase class\nto provide it.\nHere is a brief example of a TestResult subclass which stores\nthe actual exception and traceback objects. (Be aware that storing\ntraceback objects can cause a great deal of memory not to be reclaimed\nwhen it otherwise would be, which can have effects that affect the\nbehavior of the tests.)\n```text\n\nimport unittest\n\nclass MyTestCase(unittest.TestCase):\ndef defaultTestResult(self):\nreturn MyTestResult()\n\nclass MyTestResult(unittest.TestResult):\ndef __init__(self):\nself.errors_tb = []\nself.failures_tb = []\n\ndef addError(self, test, err):\nself.errors_tb.append((test, err))\nunittest.TestResult.addError(self, test, err)\n\ndef addFailure(self, test, err):\nself.failures_tb.append((test, err))\nunittest.TestResult.addFailure(self, test, err)\n```", "python_version": "2.3", "length": 1402, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/unittest-error-info.html"} {"title": "8. Unix Specific Services", "text": "completer-objects.html | lib.html | module-posix.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.21.1 Completer Objects (completer-objects.html)\nUp:\nPython Library Reference (lib.html)\nNext:\n8.1 posix (module-posix.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.3", "length": 480, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/unix.html"} {"title": "11.5.19 UnknownHandler Objects", "text": "gopher-handler.html | module-urllib2.html | urllib2-examples.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.5.18 GopherHandler Objects (gopher-handler.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.5.20 Examples (urllib2-examples.html)\n---\n## 11.5.19 UnknownHandler Objects", "python_version": "2.3", "length": 326, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/unknown-handler-objects.html"} {"title": "11.5.20 Examples", "text": "unknown-handler-objects.html | module-urllib2.html | module-httplib.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.5.19 UnknownHandler Objects (unknown-handler-objects.html)\nUp:\n11.5 urllib2 (module-urllib2.html)\nNext:\n11.6 httplib (module-httplib.html)\n---\n## 11.5.20 Examples\nThis example gets the python.org main page and displays the first 100\nbytes of it:\n```text\n\n>>> import urllib2\n>>> f = urllib2.urlopen('http://www.python.org/')\n>>> print f.read(100)\n\n>> import urllib2\n>>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',\n... data='This data is passed to stdin of the CGI')\n>>> f = urllib2.urlopen(req)\n>>> print f.read()\nGot Data: \"This data is passed to stdin of the CGI\"\n```\nThe code for the sample CGI used in the above example is:", "python_version": "2.3", "length": 1016, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/urllib2-examples.html"} {"title": "11.4.1 URLopener Objects", "text": "module-urllib.html | module-urllib.html | node415.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.4 urllib (module-urllib.html)\nUp:\n11.4 urllib (module-urllib.html)\nNext:\n11.4.2 Examples (node415.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.3", "length": 463, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/urlopener-objs.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\nPrevious:\n3.20 warnings (module-warnings.html)\nUp:\n3.20 warnings (module-warnings.html)\nNext:\n3.20.2 The Warnings Filter (warning-filter.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.3", "length": 839, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.20.1 Warning Categories (warning-categories.html)\nUp:\n3.20 warnings (module-warnings.html)\nNext:\n3.20.3 Available Functions (warning-functions.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 string containing a regular expression that\nthe warning message must match (the match is compiled to always be\ncase-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 string containing a regular expression that the module\nname must match (the match is compiled to be case-sensitive)\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.3", "length": 1802, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.20.2 The Warnings Filter (warning-filter.html)\nUp:\n3.20 warnings (module-warnings.html)\nNext:\n3.21 imp (module-imp.html)\n---\n## 3.20.3 Available Functions", "python_version": "2.3", "length": 302, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.5 wave (module-wave.html)\nUp:\n14.5 wave (module-wave.html)\nNext:\n14.5.2 Wave_write Objects (Wave-write-objects.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.3", "length": 630, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n14.5.1 Wave_read Objects (Wave-read-objects.html)\nUp:\n14.5 wave (module-wave.html)\nNext:\n14.6 chunk (module-chunk.html)\n---\n## 14.5.2 Wave_write Objects\nWave_write objects, as returned by open(), have the\nfollowing methods:", "python_version": "2.3", "length": 370, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.3.1 Weak Reference Objects (weakref-objects.html)\nUp:\n3.3 weakref (module-weakref.html)\nNext:\n3.3.3 Weak References in (weakref-extension.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.3", "length": 782, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.3.2 Example (weakref-example.html)\nUp:\n3.3 weakref (module-weakref.html)\nNext:\n3.4 fpectl (module-fpectl.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.\nAlso, it needs to add Py_TPFLAGS_HAVE_WEAKREFS to the\ntp_flags slot. For example, the instance type is defined with the\nfollowing 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\nPy_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_WEAKREFS /* tp_flags */\n0, /* tp_doc */\n0, /* tp_traverse */\n0, /* tp_clear */\n0, /* tp_richcompare */\noffsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */\n};\n```\nThe type constructor is responsible for initializing the weak reference\nlist to NULL:\n```text\n\nstatic PyObject *\ninstance_new() {\n/* Other initialization stuff omitted for brevity */\n\nself->in_weakreflist = NULL;\n\nreturn (PyObject *) self;\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.3", "length": 2126, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3.3 weakref (module-weakref.html)\nUp:\n3.3 weakref (module-weakref.html)\nNext:\n3.3.2 Example (weakref-example.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.3", "length": 1390, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.1.3 The Writer Interface (writer-interface.html)\nUp:\n12.1 formatter (module-formatter.html)\nNext:\n12.2 email (module-email.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.3", "length": 497, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.1.2 Formatter Implementations (formatter-impls.html)\nUp:\n12.1 formatter (module-formatter.html)\nNext:\n12.1.4 Writer Implementations (writer-impls.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.3", "length": 683, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/writer-interface.html"} {"title": "5.4.2 Writing Unit Tests for the test package", "text": "module-test.testsupport.html | module-test.html | regrtest.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n5.4.1 [test.testsupport]test.test_support (module-test.testsupport.html)\nUp:\n5.4 test (module-test.html)\nNext:\n5.4.3 Running tests Using (regrtest.html)\n---\n## 5.4.2 Writing Unit Tests for the test package\nIt is preferred that tests for the test package use the\nunittest (module-unittest.html) module and follow a few guidelines.\nOne is to have the name of all the test methods start with `\"test_\"` as\nwell as the module's name.\nThis is needed so that the methods are recognized by the test driver as\ntest methods.\nAlso, no documentation string for the method should be included.\nA comment (such as\n`# Tests function returns only True or False`) should be used to provide\ndocumentation for test methods.\nThis is done because documentation strings get printed out if they exist and\nthus what test is being run is not stated.\nA basic boilerplate is often used:\n```text\n\nimport unittest\nfrom test import test_support\n\nclass MyTestCase1(unittest.TestCase):\n\n# Only use setUp() and tearDown() if necessary\n\ndef setUp(self):\n... code to execute in preparation for tests ...\n\ndef tearDown(self):\n... code to execute to clean up after tests ...\n\ndef test_feature_one(self):\n# Test feature one.\n... testing code ...\n\ndef test_feature_two(self):\n# Test feature two.\n... testing code ...\n\n... more test methods ...\n\nclass MyTestCase2(unittest.TestCase):\n... same structure as MyTestCase1 ...\n\n... more test classes ...\n\ndef test_main():\ntest_support.run_unittest(MyTestCase1,\nMyTestCase2,\n... list other tests ...\n)\n\nif __name__ == '__main__':\ntest_main()\n```\nThis boilerplate code allows the testing suite to be run by regrtest.py\nas well as on its own as a script.\nThe goal for regression testing is to try to break code.\nThis leads to a few guidelines to be followed:\n- The testing suite should exercise all classes, functions, and\nconstants.\nThis includes not just the external API that is to be presented to the\noutside world but also \"private\" code.\n- Whitebox testing (examining the code being tested when the tests are\nbeing written) is preferred.\nBlackbox testing (testing only the published user interface) is not\ncomplete enough to make sure all boundary and edge cases are tested.\n- Make sure all possible values are tested including invalid ones.\nThis makes sure that not only all valid values are acceptable but also\nthat improper values are handled correctly.\n- Exhaust as many code paths as possible.\nTest where branching occurs and thus tailor input to make sure as many\ndifferent paths through the code are taken.\n- Add an explicit test for any bugs discovered for the tested code.\nThis will make sure that the error does not crop up again if the code is\nchanged in the future.\n- Make sure to clean up after your tests (such as close and remove all\ntemporary files).\n- Import as few modules as possible and do it as soon as possible.\nThis minimizes external dependencies of tests and also minimizes possible\nanomalous behavior from side-effects of importing a module.\n- Try to maximize code reuse.\nOn occasion tests will vary by something as small as what type of input\nthey take.\nMinimize code duplication by subclassing a basic test class with a class\nthat specifies the input:\n```text\n\nclass TestFuncAcceptsSequences(unittest.TestCase):\n\nfunc = mySuperWhammyFunction\n\ndef test_func(self):\nself.func(self.arg)\n\nclass AcceptLists(TestFuncAcceptsSequences):\narg = [1,2,3]\n\nclass AcceptStrings(TestFuncAcceptsSequences):\narg = 'abc'\n\nclass AcceptTuples(TestFuncAcceptsSequences):\narg = (1,2,3)\n```\nSee Also:", "python_version": "2.3", "length": 3662, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/writing-tests.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\nPrevious:\n12.17.2 Unpacker Objects (xdr-unpacker-objects.html)\nUp:\n12.17 xdrlib (module-xdrlib.html)\nNext:\n12.18 netrc (module-netrc.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.3", "length": 591, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.17 xdrlib (module-xdrlib.html)\nUp:\n12.17 xdrlib (module-xdrlib.html)\nNext:\n12.17.2 Unpacker Objects (xdr-unpacker-objects.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.3", "length": 801, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n12.17.1 Packer Objects (xdr-packer-objects.html)\nUp:\n12.17 xdrlib (module-xdrlib.html)\nNext:\n12.17.3 Exceptions (xdr-exceptions.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.3", "length": 705, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.13 xmllib (module-xmllib.html)\nUp:\n13.13 xmllib (module-xmllib.html)\nNext:\n14. Multimedia Services (mmedia.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.3", "length": 1097, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.5 xml.parsers.expat (module-xml.parsers.expat.html)\nUp:\n13.5 xml.parsers.expat (module-xml.parsers.expat.html)\nNext:\n13.5.2 ExpatError Exceptions (expaterror-objects.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.3", "length": 1013, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)\nUp:\n13.12 xml.sax.xmlreader (module-xml.sax.xmlreader.html)\nNext:\n13.12.2 IncrementalParser Objects (incremental-parser-objects.html)\n---\n## 13.12.1 XMLReader Objects\nThe XMLReader interface supports the following methods:", "python_version": "2.3", "length": 459, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/xmlreader-objects.html"} {"title": "11.20.8 Example of Client Usage", "text": "node474.html | module-xmlrpclib.html | module-SimpleXMLRPCServer.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n11.20.7 Convenience Functions (node474.html)\nUp:\n11.20 xmlrpclib (module-xmlrpclib.html)\nNext:\n11.21 SimpleXMLRPCServer (module-SimpleXMLRPCServer.html)\n---\n## 11.20.8 Example of Client Usage", "python_version": "2.3", "length": 346, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/xmlrpc-client-example.html"} {"title": "7.18.1 ZipFile Objects", "text": "module-zipfile.html | module-zipfile.html | pyzipfile-objects.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.18 zipfile (module-zipfile.html)\nUp:\n7.18 zipfile (module-zipfile.html)\nNext:\n7.18.2 PyZipFile Objects (pyzipfile-objects.html)\n---\n## 7.18.1 ZipFile Objects\nThe following data attribute is also available:", "python_version": "2.3", "length": 359, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/zipfile-objects.html"} {"title": "7.18.3 ZipInfo Objects", "text": "pyzipfile-objects.html | module-zipfile.html | module-tarfile.html | Python Library Reference | contents.html | modindex.html | genindex.html\nPrevious:\n7.18.2 PyZipFile Objects (pyzipfile-objects.html)\nUp:\n7.18 zipfile (module-zipfile.html)\nNext:\n7.19 tarfile (module-tarfile.html)\n---\n## 7.18.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.3", "length": 529, "url": "https://docs.python.org/2.3/Python-Docs-2.3/lib/zipinfo-objects.html"} {"title": "About this document ...", "text": "genindex.html | mac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\nUp:\nMacintosh Library Modules (mac.html)\n---\n# About this document ...\nMacintosh Library Modules,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1667, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/about.html"} {"title": "3.5.1 AEServer Objects", "text": "module-MiniAEFrame.html | module-MiniAEFrame.html | toolbox.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n3.5 MiniAEFrame (module-MiniAEFrame.html)\nUp:\n3.5 MiniAEFrame (module-MiniAEFrame.html)\nNext:\n4. MacOS Toolbox Modules (toolbox.html)\n---\n## 3.5.1 AEServer Objects\nNote that there are some serious problems with the current\ndesign. AppleEvents which have non-identifier 4-character designators\nfor arguments are not implementable, and it is not possible to return\nan error to the originator. This will be addressed in a future\nrelease.", "python_version": "2.3", "length": 585, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/aeserver-objects.html"} {"title": "2.3.2 Alias Objects", "text": "fsspec-objects.html | module-macfs.html | finfo-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.3.1 FSSpec Objects (fsspec-objects.html)\nUp:\n2.3 macfs (module-macfs.html)\nNext:\n2.3.3 FInfo Objects (finfo-objects.html)\n---\n## 2.3.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.3", "length": 587, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/alias-objects.html"} {"title": "2.9.1 Application Objects", "text": "module-FrameWork.html | module-FrameWork.html | window-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.9 FrameWork (module-FrameWork.html)\nUp:\n2.9 FrameWork (module-FrameWork.html)\nNext:\n2.9.2 Window Objects (window-objects.html)\n---\n## 2.9.1 Application Objects\nApplication objects have the following methods, among others:", "python_version": "2.3", "length": 377, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/application-objects.html"} {"title": "1.2.3 Simulating command line arguments", "text": "creator-code.html | getting.html | node14.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.2.2 Set Creator and (creator-code.html)\nUp:\n1.2 Getting and Installing (getting.html)\nNext:\n1.2.4 Creating a Python (node14.html)\n---\n## 1.2.3 Simulating command line arguments\nThere are two ways to simulate command-line arguments with MacPython-OS9.\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.3.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.3", "length": 1157, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/argv.html"} {"title": "1.2.5 Configuration", "text": "scripting-with-BBedit.html | getting.html | EditPythonPrefs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.4.3 BBedit (scripting-with-BBedit.html)\nUp:\n1.2 Getting and Installing (getting.html)\nNext:\n1.2.5.1 EditPythonPrefs (EditPythonPrefs.html)\n---\n## 1.2.5 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.3", "length": 469, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/configuration.html"} {"title": "Contents", "text": "front.html | mac.html | using.html | Macintosh Library Modules | modindex.html | genindex.html\nPrevious:\nFront Matter (front.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\n1. Using Python on (using.html)\n---\n## Contents\nTable of Contents\n- Front Matter (front.html)\n 1. Using Python on a Mac OS 9 Macintosh (using.html)\n - 1.1 Getting and Installing MacPython-OSX (getting-OSX.html)\n - 1.1.1 How to run a Python script (node5.html)\n 1.1.2 Running scripts with a GUI (osx-gui-scripts.html)\n 1.1.3 configuration (node7.html)\n 1.2 Getting and Installing MacPython-OS9 (getting.html)\n - 1.2.1 Entering the interactive Interpreter (interpreter.html)\n 1.2.2 How to run a Python script (node10.html)\n 1.2.3 Simulating command line arguments (argv.html)\n 1.2.4 Creating a Python script (node14.html)\n 1.2.5 Configuration (configuration.html)\n 1.3 The IDE (IDE.html)\n - 1.3.1 Using the ``Python Interactive'' window (node23.html)\n 1.3.2 Writing a Python Script (IDEwrite.html)\n 1.3.3 Executing a script from within the IDE (IDEexecution.html)\n 1.3.4 ``Save as'' versus ``Save as Applet'' (IDEapplet.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 macfs -- Various file system services (module-macfs.html)\n - 2.3.1 FSSpec Objects (fsspec-objects.html)\n 2.3.2 Alias Objects (alias-objects.html)\n 2.3.3 FInfo Objects (finfo-objects.html)\n 2.4 ic -- Access to Internet Config (module-ic.html)\n - 2.4.1 IC Objects (node35.html)\n 2.5 MacOS -- Access to Mac OS interpreter features (module-MacOS.html)\n 2.6 macostools -- Convenience routines for file manipulation (module-macostools.html)\n 2.7 findertools -- The finder's Apple Events interface (module-findertools.html)\n 2.8 EasyDialogs -- Basic Macintosh dialogs (module-EasyDialogs.html)\n - 2.8.1 ProgressBar Objects (progressbar-objects.html)\n 2.9 FrameWork -- Interactive application framework (module-FrameWork.html)\n - 2.9.1 Application Objects (application-objects.html)\n 2.9.2 Window Objects (window-objects.html)\n 2.9.3 ControlsWindow Object (controlswindow-object.html)\n 2.9.4 ScrolledWindow Object (scrolledwindow-object.html)\n 2.9.5 DialogWindow Objects (dialogwindow-objects.html)\n 2.10 autoGIL -- Global Interpreter Lock handling in event loops (module-autoGIL.html)\n 3. MacPython OSA Modules (scripting.html)\n - 3.1 gensuitemodule -- Generate OSA stub packages (module-gensuitemodule.html)\n 3.2 aetools -- OSA client support (module-aetools.html)\n 3.3 aepack -- Conversion between Python variables and AppleEvent data containers (module-aepack.html)\n 3.4 aetypes -- AppleEvent objects (module-aetypes.html)\n 3.5 MiniAEFrame -- Open Scripting Architecture server support (module-MiniAEFrame.html)\n - 3.5.1 AEServer Objects (aeserver-objects.html)\n 4. MacOS Toolbox Modules (toolbox.html)\n - 4.1 Carbon.AE -- Apple Events (module-Carbon.AE.html)\n 4.2 Carbon.AH -- Apple Help (module-Carbon.AH.html)\n 4.3 Carbon.App -- Appearance Manager (module-Carbon.App.html)\n 4.4 Carbon.CF -- Core Foundation (module-Carbon.CF.html)\n 4.5 Carbon.CG -- Core Graphics (module-Carbon.CG.html)\n 4.6 Carbon.CarbonEvt -- Carbon Event Manager (module-Carbon.CaronEvt.html)\n 4.7 Carbon.Cm -- Component Manager (module-Carbon.Cm.html)\n 4.8 Carbon.Ctl -- Control Manager (module-Carbon.Ctl.html)\n 4.9 Carbon.Dlg -- Dialog Manager (module-Carbon.Dlg.html)\n 4.10 Carbon.Evt -- Event Manager (module-Carbon.Evt.html)\n 4.11 Carbon.Fm -- Font Manager (module-Carbon.Fm.html)\n 4.12 Carbon.Folder -- Folder Manager (module-Carbon.Folder.html)\n 4.13 Carbon.Help -- Help Manager (module-Carbon.Help.html)\n 4.14 Carbon.List -- List Manager (module-Carbon.List.html)\n 4.15 Carbon.Menu -- Menu Manager (module-Carbon.Menu.html)\n 4.16 Carbon.Mlte -- MultiLingual Text Editor (module-Carbon.Mlte.html)\n 4.17 Carbon.Qd -- QuickDraw (module-Carbon.Qd.html)\n 4.18 Carbon.Qdoffs -- QuickDraw Offscreen (module-Carbon.Qdoffs.html)\n 4.19 Carbon.Qt -- QuickTime (module-Carbon.Qt.html)\n 4.20 Carbon.Res -- Resource Manager and Handles (module-Carbon.Res.html)\n 4.21 Carbon.Scrap -- Scrap Manager (module-Carbon.Scrap.html)\n 4.22 Carbon.Snd -- Sound Manager (module-Carbon.Snd.html)\n 4.23 Carbon.TE -- TextEdit (module-Carbon.TE.html)\n 4.24 Carbon.Win -- Window Manager (module-Carbon.Win.html)\n 4.25 ColorPicker -- Color selection dialog (module-ColorPicker.html)\n 5. Undocumented Modules (undocumented-modules.html)\n - 5.1 applesingle -- AppleSingle decoder (module-applesingle.html)\n 5.2 buildtools -- Helper module for BuildApplet and Friends (module-buildtools.html)\n 5.3 py_resource -- Resources from Python code (module-pyresource.html)\n 5.4 cfmfile -- Code Fragment Resource module (module-cfmfile.html)\n 5.5 icopen -- Internet Config replacement for open() (module-icopen.html)\n 5.6 macerrors -- Mac OS Errors (module-macerrors.html)\n 5.7 macresource -- Locate script resources (module-macresource.html)\n 5.8 Nav -- NavServices calls (module-Nac.html)\n 5.9 mkcwproject -- Create CodeWarrior projects (module-mkcwproject.html)\n 5.10 nsremote -- Wrapper around Netscape OSA modules (module-nsremote.html)\n 5.11 PixMapWrapper -- Wrapper for PixMap objects (module-PixMapWrapper.html)\n 5.12 preferences -- Application preferences manager (module-preferences.html)\n 5.13 pythonprefs -- Preferences manager for Python (module-pythonprefs.html)\n 5.14 quietconsole -- Non-visible standard output (module-quietconsole.html)\n 5.15 videoreader -- Read QuickTime movies (module-videoreader.html)\n 5.16 W -- Widgets built on FrameWork (module-W.html)\n 5.17 waste -- non-Apple TextEdit replacement (module-waste.html)\n A. History and License (node99.html)\n - A.1 History of the software (node100.html)\n A.2 Terms and conditions for accessing or otherwise using Python (node101.html)\n Module Index (modindex.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.3", "length": 6019, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/contents.html"} {"title": "2.9.3 ControlsWindow Object", "text": "window-objects.html | module-FrameWork.html | scrolledwindow-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.9.2 Window Objects (window-objects.html)\nUp:\n2.9 FrameWork (module-FrameWork.html)\nNext:\n2.9.4 ScrolledWindow Object (scrolledwindow-object.html)\n---\n## 2.9.3 ControlsWindow Object\nControlsWindow objects have the following methods besides those of\n`Window` objects:", "python_version": "2.3", "length": 426, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/controlswindow-object.html"} {"title": "1.2.2.2 Set Creator and Double Click", "text": "node11.html | node10.html | argv.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.2.1 Drag and drop (node11.html)\nUp:\n1.2.2 How to run (node10.html)\nNext:\n1.2.3 Simulating command line (argv.html)\n---\n### 1.2.2.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.3.2 (IDEwrite.html#IDEwrite) and 1.3.4 (IDEapplet.html#IDEapplet)), with an editor with a\nPython mode (BBEdit) - see section\n1.2.4 (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.3", "length": 1413, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/creator-code.html"} {"title": "1.2.5.3 Default startup options", "text": "search-path.html | configuration.html | IDE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.5.2 Adding modules to (search-path.html)\nUp:\n1.2.5 Configuration (configuration.html)\nNext:\n1.3 The IDE (IDE.html)\n---\n### 1.2.5.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.3", "length": 665, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/defaults.html"} {"title": "2.9.5 DialogWindow Objects", "text": "scrolledwindow-object.html | module-FrameWork.html | module-autoGIL.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.9.4 ScrolledWindow Object (scrolledwindow-object.html)\nUp:\n2.9 FrameWork (module-FrameWork.html)\nNext:\n2.10 autoGIL (module-autoGIL.html)\n---\n## 2.9.5 DialogWindow Objects\nDialogWindow objects have the following methods besides those of\n`Window` objects:", "python_version": "2.3", "length": 415, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/dialogwindow-objects.html"} {"title": "1.2.5.1 EditPythonPrefs", "text": "configuration.html | configuration.html | search-path.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.5 Configuration (configuration.html)\nUp:\n1.2.5 Configuration (configuration.html)\nNext:\n1.2.5.2 Adding modules to (search-path.html)\n---\n### 1.2.5.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.3.4 (IDEapplet.html#IDEapplet).", "python_version": "2.3", "length": 1140, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/EditPythonPrefs.html"} {"title": "2.3.3 FInfo Objects", "text": "alias-objects.html | module-macfs.html | module-ic.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.3.2 Alias Objects (alias-objects.html)\nUp:\n2.3 macfs (module-macfs.html)\nNext:\n2.4 ic (module-ic.html)\n---\n## 2.3.3 FInfo Objects\nSee Inside Macintosh: Files for a complete description of what\nthe various fields mean.", "python_version": "2.3", "length": 361, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/finfo-objects.html"} {"title": "Front Matter", "text": "mac.html | mac.html | contents.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\nMacintosh Library Modules (mac.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\n---\n# Front Matter\nCopyright © 2001, 2002, 2003 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.3", "length": 1274, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/front.html"} {"title": "2.3.1 FSSpec Objects", "text": "module-macfs.html | module-macfs.html | alias-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.3 macfs (module-macfs.html)\nUp:\n2.3 macfs (module-macfs.html)\nNext:\n2.3.2 Alias Objects (alias-objects.html)\n---\n## 2.3.1 FSSpec Objects", "python_version": "2.3", "length": 283, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/fsspec-objects.html"} {"title": "Index", "text": "modindex.html | mac.html | about.html | Macintosh Library Modules | contents.html | modindex.html\nPrevious:\nModule Index (modindex.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\nAbout this document ... (about.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)\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", "python_version": "2.3", "length": 823, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/genindex.html"} {"title": "1.1 Getting and Installing MacPython-OSX", "text": "using.html | using.html | node5.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1. Using Python on (using.html)\nUp:\n1. Using Python on (using.html)\nNext:\n1.1.1 How to run (node5.html)\n---\n# 1.1 Getting and Installing MacPython-OSX\nAs of Python 2.3a2 the only sure way of getting MacPython-OSX on your machine\nis getting a source distribution and building what is called a \"framework Python\".\nThe details are in the file Mac/OSX/README.\nAs binary installers become available the details will be posted to\nhttp://www.cwi.nl/~jack/macpython.html.\nWhat you get after installing is a number of things:\n- A MacPython-2.3 folder in your Applications\nfolder. In here you find the PythonIDE Integrated Development Environment;\nPythonLauncher, which handles double-clicking Python scripts from\nthe Finder; and the Package Manager.\n- A fairly standard Unix commandline Python interpreter in\n/usr/local/bin/python, but without the usual\n/usr/local/lib/python.\n- A framework /Library/Frameworks/Python.framework, where\nall the action really is, but which you usually do not have to be aware of.\nTo uninstall MacPython you can simply remove these three things.\nPythonIDE contains an Apple Help Viewer book called \"MacPython Help\"\nwhich you can access through its help menu. If you are completely new to\nPython you should start reading the IDE introduction in that document.\nIf you are familiar with Python on other Unix platforms you should\nread the section on running Python scripts from the Unix shell.", "python_version": "2.3", "length": 1533, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/getting-OSX.html"} {"title": "1.2 Getting and Installing MacPython-OS9", "text": "node7.html | using.html | interpreter.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.1.3 configuration (node7.html)\nUp:\n1. Using Python on (using.html)\nNext:\n1.2.1 Entering the interactive (interpreter.html)\n---\n# 1.2 Getting and Installing MacPython-OS9\nThe most recent release version as well as possible newer experimental\nversions are best found at the MacPython page maintained by Jack\nJansen: http://homepages.cwi.nl/~jack/macpython.html.\nPlease refer to the README included with your distribution for\nthe most up-to-date instructions.\nNote that MacPython-OS9 runs fine on Mac OS X, and it runs in native\nmode, not in the Classic environment. Unless you have specific\nrequirements for a CFM-based Python there is no reason not to\nuse MacPython-OSX, though.", "python_version": "2.3", "length": 808, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/getting.html"} {"title": "1.3 The IDE", "text": "defaults.html | using.html | node23.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.5.3 Default startup options (defaults.html)\nUp:\n1. Using Python on (using.html)\nNext:\n1.3.1 Using the ``Python (node23.html)\n---\n# 1.3 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.3", "length": 449, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/IDE.html"} {"title": "1.3.4 ``Save as'' versus ``Save as Applet''", "text": "IDEexecution.html | IDE.html | macpython-modules.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.3.3 Executing a script (IDEexecution.html)\nUp:\n1.3 The IDE (IDE.html)\nNext:\n2. MacPython Modules (macpython-modules.html)\n---\n## 1.3.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.3", "length": 1098, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/IDEapplet.html"} {"title": "1.3.3 Executing a script from within the IDE", "text": "IDEwrite.html | IDE.html | IDEapplet.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.3.2 Writing a Python (IDEwrite.html)\nUp:\n1.3 The IDE (IDE.html)\nNext:\n1.3.4 ``Save as'' versus (IDEapplet.html)\n---\n## 1.3.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.3", "length": 836, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/IDEexecution.html"} {"title": "1.3.2 Writing a Python Script", "text": "node23.html | IDE.html | IDEexecution.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.3.1 Using the ``Python (node23.html)\nUp:\n1.3 The IDE (IDE.html)\nNext:\n1.3.3 Executing a script (IDEexecution.html)\n---\n## 1.3.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.2.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.3", "length": 1508, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/IDEwrite.html"} {"title": "Macintosh Library Modules", "text": "../index.html | front.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Macintosh Library Modules\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 324, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/index.html"} {"title": "1.2.1 Entering the interactive Interpreter", "text": "getting.html | getting.html | node10.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2 Getting and Installing (getting.html)\nUp:\n1.2 Getting and Installing (getting.html)\nNext:\n1.2.2 How to run (node10.html)\n---\n## 1.2.1 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.3", "length": 600, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/interpreter.html"} {"title": "Macintosh Library Modules", "text": "../index.html | front.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Macintosh Library Modules\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 324, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/mac.html"} {"title": "2. MacPython Modules", "text": "IDEapplet.html | mac.html | module-mac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.3.4 ``Save as'' versus (IDEapplet.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\n2.1 mac (module-mac.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.\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.\nEasyDialogs (module-EasyDialogs.html) | Basic Macintosh dialogs.\nFrameWork (module-FrameWork.html) | Interactive application framework.\nautoGIL (module-autoGIL.html) | Global Interpreter Lock handling in event loops.", "python_version": "2.3", "length": 1112, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/macpython-modules.html"} {"title": "Module Index", "text": "node101.html | mac.html | genindex.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\nA.2 Terms and conditions (node101.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\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.3", "length": 490, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/modindex.html"} {"title": "3.3 aepack -- Conversion between Python variables and AppleEvent data containers", "text": "module-aetools.html | scripting.html | module-aetypes.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n3.2 aetools (module-aetools.html)\nUp:\n3. MacPython OSA Modules (scripting.html)\nNext:\n3.4 aetypes (module-aetypes.html)\n---\n# 3.3 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.3", "length": 686, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-aepack.html"} {"title": "3.2 aetools -- OSA client support", "text": "module-gensuitemodule.html | scripting.html | module-aepack.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n3.1 gensuitemodule (module-gensuitemodule.html)\nUp:\n3. MacPython OSA Modules (scripting.html)\nNext:\n3.3 aepack (module-aepack.html)\n---\n# 3.2 aetools --\nOSA client support\nAvailability: Macintosh.\nThe aetools module contains the basic functionality\non which Python AppleScript client support is built. It also\nimports and re-exports the core functionality of the\naetypes and aepack modules. The stub packages\ngenerated by gensuitemodule import the relevant\nportions of aetools, so usually you do not need to\nimport it yourself. The exception to this is when you\ncannot use a generated suite package and need lower-level\naccess to scripting.\nThe aetools module itself uses the AppleEvent support\nprovided by the Carbon.AE module. This has one drawback:\nyou need access to the window manager, see section 1.1.2 (osx-gui-scripts.html#osx-gui-scripts)\nfor details. This restriction may be lifted in future releases.\nThe aetools module defines the following functions:\nThe aetools module defines the following class:", "python_version": "2.3", "length": 1162, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-aetools.html"} {"title": "3.4 aetypes -- AppleEvent objects", "text": "module-aepack.html | scripting.html | module-MiniAEFrame.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n3.3 aepack (module-aepack.html)\nUp:\n3. MacPython OSA Modules (scripting.html)\nNext:\n3.5 MiniAEFrame (module-MiniAEFrame.html)\n---\n# 3.4 aetypes --\nAppleEvent objects\nAvailability: Macintosh.\nThe aetypes defines classes used to represent Apple Event data\ndescriptors and Apple Event object specifiers.\nApple Event data is is contained in descriptors, and these descriptors\nare typed. For many descriptors the Python representation is simply the\ncorresponding Python type: `typeText` in OSA is a Python string,\n`typeFloat` is a float, etc. For OSA types that have no direct\nPython counterpart this module declares classes. Packing and unpacking\ninstances of these classes is handled automatically by aepack.\nAn object specifier is essentially an address of an object implemented\nin a Apple Event server. An Apple Event specifier is used as the direct\nobject for an Apple Event or as the argument of an optional parameter.\nThe aetypes module contains the base classes for OSA classes\nand properties, which are used by the packages generated by\ngensuitemodule to populate the classes and properties in a\ngiven suite.\nFor reasons of backward compatibility, and for cases where you need to\nscript an application for which you have not generated the stub package\nthis module also contains object specifiers for a number of common OSA\nclasses such as `Document`, `Window`, `Character`, etc.\nThe AEObjects module defines the following classes to represent\nApple Event descriptor data:\nThe following classes are used as base classes by the generated stub\npackages to represent AppleScript classes and properties in Python:", "python_version": "2.3", "length": 1760, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-aetypes.html"} {"title": "5.1 applesingle -- AppleSingle decoder", "text": "undocumented-modules.html | undocumented-modules.html | module-buildtools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5. Undocumented Modules (undocumented-modules.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.2 buildtools (module-buildtools.html)\n---\n# 5.1 applesingle -- AppleSingle decoder\nAvailability: Macintosh.", "python_version": "2.3", "length": 388, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-applesingle.html"} {"title": "2.10 autoGIL -- Global Interpreter Lock handling in event loops", "text": "dialogwindow-objects.html | macpython-modules.html | scripting.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.9.5 DialogWindow Objects (dialogwindow-objects.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n3. MacPython OSA Modules (scripting.html)\n---\n# 2.10 autoGIL --\nGlobal Interpreter Lock handling in event loops\nAvailability: Macintosh.\nThe autoGIL module provides a function installAutoGIL that\nautomatically locks and unlocks Python's Global Interpreter Lock\nwhen running an event loop.", "python_version": "2.3", "length": 553, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-autoGIL.html"} {"title": "5.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\nPrevious:\n5.1 applesingle (module-applesingle.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.3 py_resource (module-pyresource.html)\n---\n# 5.2 buildtools -- Helper module for BuildApplet and Friends\nAvailability: Macintosh.", "python_version": "2.3", "length": 398, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-buildtools.html"} {"title": "4.1 Carbon.AE -- Apple Events", "text": "toolbox.html | toolbox.html | module-Carbon.AH.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4. MacOS Toolbox Modules (toolbox.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.2 Carbon.AH (module-Carbon.AH.html)\n---\n# 4.1 Carbon.AE -- Apple Events\nAvailability: Macintosh.", "python_version": "2.3", "length": 326, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.AE.html"} {"title": "4.2 Carbon.AH -- Apple Help", "text": "module-Carbon.AE.html | toolbox.html | module-Carbon.App.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.1 Carbon.AE (module-Carbon.AE.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.3 Carbon.App (module-Carbon.App.html)\n---\n# 4.2 Carbon.AH -- Apple Help\nAvailability: Macintosh.", "python_version": "2.3", "length": 334, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.AH.html"} {"title": "4.3 Carbon.App -- Appearance Manager", "text": "module-Carbon.AH.html | toolbox.html | module-Carbon.CF.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.2 Carbon.AH (module-Carbon.AH.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.4 Carbon.CF (module-Carbon.CF.html)\n---\n# 4.3 Carbon.App -- Appearance Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 340, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.App.html"} {"title": "4.6 Carbon.CarbonEvt -- Carbon Event Manager", "text": "module-Carbon.CG.html | toolbox.html | module-Carbon.Cm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.5 Carbon.CG (module-Carbon.CG.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.7 Carbon.Cm (module-Carbon.Cm.html)\n---\n# 4.6 Carbon.CarbonEvt -- Carbon Event Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 348, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.CaronEvt.html"} {"title": "4.4 Carbon.CF -- Core Foundation", "text": "module-Carbon.App.html | toolbox.html | module-Carbon.CG.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.3 Carbon.App (module-Carbon.App.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.5 Carbon.CG (module-Carbon.CG.html)\n---\n# 4.4 Carbon.CF -- Core Foundation\nAvailability: Macintosh.\nThe\n`CFBase`, `CFArray`, `CFData`, `CFDictionary`,\n`CFString` and `CFURL` objects are supported, some\nonly partially.", "python_version": "2.3", "length": 457, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.CF.html"} {"title": "4.5 Carbon.CG -- Core Graphics", "text": "module-Carbon.CF.html | toolbox.html | module-Carbon.CaronEvt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.4 Carbon.CF (module-Carbon.CF.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.6 Carbon.CarbonEvt (module-Carbon.CaronEvt.html)\n---\n# 4.5 Carbon.CG -- Core Graphics\nAvailability: Macintosh.", "python_version": "2.3", "length": 353, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.CG.html"} {"title": "4.7 Carbon.Cm -- Component Manager", "text": "module-Carbon.CaronEvt.html | toolbox.html | module-Carbon.Ctl.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.6 Carbon.CarbonEvt (module-Carbon.CaronEvt.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.8 Carbon.Ctl (module-Carbon.Ctl.html)\n---\n# 4.7 Carbon.Cm -- Component Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 360, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Cm.html"} {"title": "4.8 Carbon.Ctl -- Control Manager", "text": "module-Carbon.Cm.html | toolbox.html | module-Carbon.Dlg.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.7 Carbon.Cm (module-Carbon.Cm.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.9 Carbon.Dlg (module-Carbon.Dlg.html)\n---\n# 4.8 Carbon.Ctl -- Control Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 340, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Ctl.html"} {"title": "4.9 Carbon.Dlg -- Dialog Manager", "text": "module-Carbon.Ctl.html | toolbox.html | module-Carbon.Evt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.8 Carbon.Ctl (module-Carbon.Ctl.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.10 Carbon.Evt (module-Carbon.Evt.html)\n---\n# 4.9 Carbon.Dlg -- Dialog Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 343, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Dlg.html"} {"title": "4.10 Carbon.Evt -- Event Manager", "text": "module-Carbon.Dlg.html | toolbox.html | module-Carbon.Fm.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.9 Carbon.Dlg (module-Carbon.Dlg.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.11 Carbon.Fm (module-Carbon.Fm.html)\n---\n# 4.10 Carbon.Evt -- Event Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 340, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Evt.html"} {"title": "4.11 Carbon.Fm -- Font Manager", "text": "module-Carbon.Evt.html | toolbox.html | module-Carbon.Folder.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.10 Carbon.Evt (module-Carbon.Evt.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.12 Carbon.Folder (module-Carbon.Folder.html)\n---\n# 4.11 Carbon.Fm -- Font Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 351, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Fm.html"} {"title": "4.12 Carbon.Folder -- Folder Manager", "text": "module-Carbon.Fm.html | toolbox.html | module-Carbon.Help.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.11 Carbon.Fm (module-Carbon.Fm.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.13 Carbon.Help (module-Carbon.Help.html)\n---\n# 4.12 Carbon.Folder -- Folder Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 348, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Folder.html"} {"title": "4.13 Carbon.Help -- Help Manager", "text": "module-Carbon.Folder.html | toolbox.html | module-Carbon.List.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.12 Carbon.Folder (module-Carbon.Folder.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.14 Carbon.List (module-Carbon.List.html)\n---\n# 4.13 Carbon.Help -- Help Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 356, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Help.html"} {"title": "4.14 Carbon.List -- List Manager", "text": "module-Carbon.Help.html | toolbox.html | module-Carbon.Menu.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.13 Carbon.Help (module-Carbon.Help.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.15 Carbon.Menu (module-Carbon.Menu.html)\n---\n# 4.14 Carbon.List -- List Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 350, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.List.html"} {"title": "4.15 Carbon.Menu -- Menu Manager", "text": "module-Carbon.List.html | toolbox.html | module-Carbon.Mlte.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.14 Carbon.List (module-Carbon.List.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.16 Carbon.Mlte (module-Carbon.Mlte.html)\n---\n# 4.15 Carbon.Menu -- Menu Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 350, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Menu.html"} {"title": "4.16 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\nPrevious:\n4.15 Carbon.Menu (module-Carbon.Menu.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.17 Carbon.Qd (module-Carbon.Qd.html)\n---\n# 4.16 Carbon.Mlte -- MultiLingual Text Editor\nAvailability: Macintosh.", "python_version": "2.3", "length": 356, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Mlte.html"} {"title": "4.17 Carbon.Qd -- QuickDraw", "text": "module-Carbon.Mlte.html | toolbox.html | module-Carbon.Qdoffs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.16 Carbon.Mlte (module-Carbon.Mlte.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.18 Carbon.Qdoffs (module-Carbon.Qdoffs.html)\n---\n# 4.17 Carbon.Qd -- QuickDraw\nAvailability: Macintosh.", "python_version": "2.3", "length": 351, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Qd.html"} {"title": "4.18 Carbon.Qdoffs -- QuickDraw Offscreen", "text": "module-Carbon.Qd.html | toolbox.html | module-Carbon.Qt.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.17 Carbon.Qd (module-Carbon.Qd.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.19 Carbon.Qt (module-Carbon.Qt.html)\n---\n# 4.18 Carbon.Qdoffs -- QuickDraw Offscreen\nAvailability: Macintosh.", "python_version": "2.3", "length": 347, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Qdoffs.html"} {"title": "4.19 Carbon.Qt -- QuickTime", "text": "module-Carbon.Qdoffs.html | toolbox.html | module-Carbon.Res.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.18 Carbon.Qdoffs (module-Carbon.Qdoffs.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.20 Carbon.Res (module-Carbon.Res.html)\n---\n# 4.19 Carbon.Qt -- QuickTime\nAvailability: Macintosh.", "python_version": "2.3", "length": 348, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Qt.html"} {"title": "4.20 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\nPrevious:\n4.19 Carbon.Qt (module-Carbon.Qt.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.21 Carbon.Scrap (module-Carbon.Scrap.html)\n---\n# 4.20 Carbon.Res -- Resource Manager and Handles\nAvailability: Macintosh.", "python_version": "2.3", "length": 362, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Res.html"} {"title": "4.21 Carbon.Scrap -- Scrap Manager", "text": "module-Carbon.Res.html | toolbox.html | module-Carbon.Snd.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.20 Carbon.Res (module-Carbon.Res.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.22 Carbon.Snd (module-Carbon.Snd.html)\n---\n# 4.21 Carbon.Scrap -- Scrap Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 346, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Scrap.html"} {"title": "4.22 Carbon.Snd -- Sound Manager", "text": "module-Carbon.Scrap.html | toolbox.html | module-Carbon.TE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.21 Carbon.Scrap (module-Carbon.Scrap.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.23 Carbon.TE (module-Carbon.TE.html)\n---\n# 4.22 Carbon.Snd -- Sound Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 347, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Snd.html"} {"title": "4.23 Carbon.TE -- TextEdit", "text": "module-Carbon.Snd.html | toolbox.html | module-Carbon.Win.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.22 Carbon.Snd (module-Carbon.Snd.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.24 Carbon.Win (module-Carbon.Win.html)\n---\n# 4.23 Carbon.TE -- TextEdit\nAvailability: Macintosh.", "python_version": "2.3", "length": 338, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.TE.html"} {"title": "4.24 Carbon.Win -- Window Manager", "text": "module-Carbon.TE.html | toolbox.html | module-ColorPicker.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.23 Carbon.TE (module-Carbon.TE.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n4.25 ColorPicker (module-ColorPicker.html)\n---\n# 4.24 Carbon.Win -- Window Manager\nAvailability: Macintosh.", "python_version": "2.3", "length": 345, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Carbon.Win.html"} {"title": "5.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\nPrevious:\n5.3 py_resource (module-pyresource.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.5 icopen (module-icopen.html)\n---\n# 5.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.3", "length": 581, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-cfmfile.html"} {"title": "4.25 ColorPicker -- Color selection dialog", "text": "module-Carbon.Win.html | toolbox.html | undocumented-modules.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.24 Carbon.Win (module-Carbon.Win.html)\nUp:\n4. MacOS Toolbox Modules (toolbox.html)\nNext:\n5. Undocumented Modules (undocumented-modules.html)\n---\n# 4.25 ColorPicker --\nColor selection dialog\nAvailability: Macintosh.\nThe ColorPicker module provides access to the standard color\npicker dialog.", "python_version": "2.3", "length": 444, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-ColorPicker.html"} {"title": "2.8 EasyDialogs -- Basic Macintosh dialogs", "text": "module-findertools.html | macpython-modules.html | progressbar-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.7 findertools (module-findertools.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.8.1 ProgressBar Objects (progressbar-objects.html)\n---\n# 2.8 EasyDialogs --\nBasic Macintosh dialogs\nAvailability: Macintosh.\nThe EasyDialogs module contains some simple dialogs for the\nMacintosh. All routines take an optional resource ID parameter id\nwith which one can override the DLOG resource used for the\ndialog, provided that the dialog items correspond (both type and item\nnumber) to those in the default DLOG resource. See source\ncode for details.\nThe EasyDialogs module defines the following functions:", "python_version": "2.3", "length": 773, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-EasyDialogs.html"} {"title": "2.7 findertools -- The finder's Apple Events interface", "text": "module-macostools.html | macpython-modules.html | module-EasyDialogs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.6 macostools (module-macostools.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.8 EasyDialogs (module-EasyDialogs.html)\n---\n# 2.7 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 FSRef or FSSpec objects.\nThe findertools module defines the following functions:", "python_version": "2.3", "length": 732, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-findertools.html"} {"title": "2.9 FrameWork -- Interactive application framework", "text": "progressbar-objects.html | macpython-modules.html | application-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.8.1 ProgressBar Objects (progressbar-objects.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.9.1 Application Objects (application-objects.html)\n---\n# 2.9 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.3", "length": 1722, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-FrameWork.html"} {"title": "3.1 gensuitemodule -- Generate OSA stub packages", "text": "scripting.html | scripting.html | module-aetools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n3. MacPython OSA Modules (scripting.html)\nUp:\n3. MacPython OSA Modules (scripting.html)\nNext:\n3.2 aetools (module-aetools.html)\n---\n# 3.1 gensuitemodule --\nGenerate OSA stub packages\nAvailability: Macintosh.\nThe gensuitemodule module creates a Python package implementing\nstub code for the AppleScript suites that are implemented by a specific\napplication, according to its AppleScript dictionary.\nIt is usually invoked by the user through the PythonIDE, but\nit can also be run as a script from the command line (pass `-help`\nfor help on the options) or imported from Python code. For an example of\nits use see Mac/scripts/genallsuites.py in a source distribution,\nwhich generates the stub packages that are included in the standard\nlibrary.\nIt defines the following public functions:", "python_version": "2.3", "length": 924, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-gensuitemodule.html"} {"title": "2.4 ic -- Access to Internet Config", "text": "finfo-objects.html | macpython-modules.html | node35.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.3.3 FInfo Objects (finfo-objects.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.4.1 IC Objects (node35.html)\n---\n# 2.4 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.3", "length": 1314, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-ic.html"} {"title": "5.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\nPrevious:\n5.4 cfmfile (module-cfmfile.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.6 macerrors (module-macerrors.html)\n---\n# 5.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.3", "length": 509, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-icopen.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\nPrevious:\n2. MacPython Modules (macpython-modules.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.2 macpath (module-macpath.html)\n---\n# 2.1 mac --\nImplementations for the os module\nAvailability: Macintosh.\nThis module implements the Mac OS 9 operating system dependent functionality\nprovided by the standard module os. It is\nbest accessed through the os module. This module is only available in\nMacPython-OS9, on MacPython-OSX posix is used.\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-OS9.", "python_version": "2.3", "length": 938, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-mac.html"} {"title": "5.6 macerrors -- Mac OS Errors", "text": "module-icopen.html | undocumented-modules.html | module-macresource.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.5 icopen (module-icopen.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.7 macresource (module-macresource.html)\n---\n# 5.6 macerrors -- Mac OS Errors\nAvailability: Macintosh.\nmacerrors cotains constant definitions for many Mac OS error\ncodes.", "python_version": "2.3", "length": 424, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-macerrors.html"} {"title": "2.3 macfs -- Various file system services", "text": "module-macpath.html | macpython-modules.html | fsspec-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.2 macpath (module-macpath.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.3.1 FSSpec Objects (fsspec-objects.html)\n---\n# 2.3 macfs --\nVarious file system services\nAvailability: Macintosh.\nDeprecated since release 2.3.\nThe macfs module should be considered obsolete. For\nFSSpec, FSRef and Alias handling use the\nCarbon.File or Carbon.Folder module. For file dialogs use the\nEasyDialogs module.\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. An FSSpec can point to\na non-existing file, as long as the folder containing the file exists.\nUnder MacPython the same is true for a pathname, but not under unix-Pyton\nbecause of the way pathnames and FSRefs works. See Apple's documentation\nfor details.\nA description of aliases and the\nStandard File package can also be found there.", "python_version": "2.3", "length": 1268, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-macfs.html"} {"title": "2.5 MacOS -- Access to Mac OS interpreter features", "text": "node35.html | macpython-modules.html | module-macostools.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.4.1 IC Objects (node35.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.6 macostools (module-macostools.html)\n---\n# 2.5 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.3", "length": 595, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-MacOS.html"} {"title": "2.6 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\nPrevious:\n2.5 MacOS (module-MacOS.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.7 findertools (module-findertools.html)\n---\n# 2.6 macostools --\nConvenience routines for file manipulation\nAvailability: Macintosh.\nThis module contains some convenience routines for file-manipulation\non the Macintosh. All file parameters can be specified as\npathnames, FSRef or FSSpec objects.\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.3", "length": 785, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-macostools.html"} {"title": "2.2 macpath -- MacOS path manipulation functions", "text": "module-mac.html | macpython-modules.html | module-macfs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.1 mac (module-mac.html)\nUp:\n2. MacPython Modules (macpython-modules.html)\nNext:\n2.3 macfs (module-macfs.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.3", "length": 507, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-macpath.html"} {"title": "5.7 macresource -- Locate script resources", "text": "module-macerrors.html | undocumented-modules.html | module-Nac.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.6 macerrors (module-macerrors.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.8 Nav (module-Nac.html)\n---\n# 5.7 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.3", "length": 554, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-macresource.html"} {"title": "3.5 MiniAEFrame -- Open Scripting Architecture server support", "text": "module-aetypes.html | scripting.html | aeserver-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n3.4 aetypes (module-aetypes.html)\nUp:\n3. MacPython OSA Modules (scripting.html)\nNext:\n3.5.1 AEServer Objects (aeserver-objects.html)\n---\n# 3.5 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.3", "length": 721, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-MiniAEFrame.html"} {"title": "5.9 mkcwproject -- Create CodeWarrior projects", "text": "module-Nac.html | undocumented-modules.html | module-nsremote.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.8 Nav (module-Nac.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.10 nsremote (module-nsremote.html)\n---\n# 5.9 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.3", "length": 549, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-mkcwproject.html"} {"title": "5.8 Nav -- NavServices calls", "text": "module-macresource.html | undocumented-modules.html | module-mkcwproject.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.7 macresource (module-macresource.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.9 mkcwproject (module-mkcwproject.html)\n---\n# 5.8 Nav -- NavServices calls\nAvailability: Macintosh.\nA low-level interface to Navigation Services.", "python_version": "2.3", "length": 415, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-Nac.html"} {"title": "5.10 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\nPrevious:\n5.9 mkcwproject (module-mkcwproject.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.11 PixMapWrapper (module-PixMapWrapper.html)\n---\n# 5.10 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.3", "length": 643, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-nsremote.html"} {"title": "5.11 PixMapWrapper -- Wrapper for PixMap objects", "text": "module-nsremote.html | undocumented-modules.html | module-preferences.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.10 nsremote (module-nsremote.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.12 preferences (module-preferences.html)\n---\n# 5.11 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.3", "length": 536, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-PixMapWrapper.html"} {"title": "5.12 preferences -- Application preferences manager", "text": "module-PixMapWrapper.html | undocumented-modules.html | module-pythonprefs.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.11 PixMapWrapper (module-PixMapWrapper.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.13 pythonprefs (module-pythonprefs.html)\n---\n# 5.12 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.3", "length": 615, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-preferences.html"} {"title": "5.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\nPrevious:\n5.2 buildtools (module-buildtools.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.4 cfmfile (module-cfmfile.html)\n---\n# 5.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.3", "length": 528, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-pyresource.html"} {"title": "5.13 pythonprefs -- Preferences manager for Python", "text": "module-preferences.html | undocumented-modules.html | module-quietconsole.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.12 preferences (module-preferences.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.14 quietconsole (module-quietconsole.html)\n---\n# 5.13 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.3", "length": 559, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-pythonprefs.html"} {"title": "5.14 quietconsole -- Non-visible standard output", "text": "module-pythonprefs.html | undocumented-modules.html | module-videoreader.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.13 pythonprefs (module-pythonprefs.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.15 videoreader (module-videoreader.html)\n---\n# 5.14 quietconsole -- Non-visible standard 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.3", "length": 768, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-quietconsole.html"} {"title": "5.15 videoreader -- Read QuickTime movies", "text": "module-quietconsole.html | undocumented-modules.html | module-W.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.14 quietconsole (module-quietconsole.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.16 W (module-W.html)\n---\n# 5.15 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.3", "length": 499, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-videoreader.html"} {"title": "5.16 W -- Widgets built on FrameWork", "text": "module-videoreader.html | undocumented-modules.html | module-waste.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.15 videoreader (module-videoreader.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\n5.17 waste (module-waste.html)\n---\n# 5.16 W -- Widgets built on FrameWork\nAvailability: Macintosh.\nThe W widgets are used extensively in the IDE.", "python_version": "2.3", "length": 408, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-W.html"} {"title": "5.17 waste -- non-Apple TextEdit replacement", "text": "module-W.html | undocumented-modules.html | node99.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.16 W (module-W.html)\nUp:\n5. Undocumented Modules (undocumented-modules.html)\nNext:\nA. History and License (node99.html)\n---\n# 5.17 waste -- non-Apple TextEdit replacement\nAvailability: Macintosh.\nSee Also:", "python_version": "2.3", "length": 349, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/module-waste.html"} {"title": "1.2.2 How to run a Python script", "text": "interpreter.html | getting.html | node11.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.1 Entering the interactive (interpreter.html)\nUp:\n1.2 Getting and Installing (getting.html)\nNext:\n1.2.2.1 Drag and drop (node11.html)\n---\n## 1.2.2 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.3 (IDE.html#IDE)), or launching via AppleScript.", "python_version": "2.3", "length": 566, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node10.html"} {"title": "A.1 History of the software", "text": "node99.html | node99.html | node101.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\nA. History and License (node99.html)\nUp:\nA. History and License (node99.html)\nNext:\nA.2 Terms and conditions (node101.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 Digital Creations (now Zope\nCorporation; 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. Zope Corporation 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.3", "length": 1913, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node100.html"} {"title": "A.2 Terms and conditions for accessing or otherwise using Python", "text": "node100.html | node99.html | modindex.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\nA.1 History of the (node100.html)\nUp:\nA. History and License (node99.html)\nNext:\nModule Index (modindex.html)\n---\n# A.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.3\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.3 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.3 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001-2003 Python Software Foundation; All\nRights Reserved'' are retained in Python 2.3 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.3 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.3.\n4. PSF is making Python 2.3 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.3 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.3, 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.3, 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.3", "length": 9913, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node101.html"} {"title": "1.2.2.1 Drag and drop", "text": "node10.html | node10.html | creator-code.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.2 How to run (node10.html)\nUp:\n1.2.2 How to run (node10.html)\nNext:\n1.2.2.2 Set Creator and (creator-code.html)\n---\n### 1.2.2.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.2.5 (defaults.html#defaults).\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.2.2 (creator-code.html#creator-code) for more details.", "python_version": "2.3", "length": 1349, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node11.html"} {"title": "1.2.4 Creating a Python script", "text": "argv.html | getting.html | node15.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.3 Simulating command line (argv.html)\nUp:\n1.2 Getting and Installing (getting.html)\nNext:\n1.2.4.1 In an editor (node15.html)\n---\n## 1.2.4 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.3", "length": 453, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node14.html"} {"title": "1.2.4.1 In an editor", "text": "node14.html | node14.html | node16.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.4 Creating a Python (node14.html)\nUp:\n1.2.4 Creating a Python (node14.html)\nNext:\n1.2.4.2 Editors with Python (node16.html)\n---\n### 1.2.4.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.3", "length": 452, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node15.html"} {"title": "1.2.4.2 Editors with Python modes", "text": "node15.html | node14.html | scripting-with-BBedit.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.4.1 In an editor (node15.html)\nUp:\n1.2.4 Creating a Python (node14.html)\nNext:\n1.2.4.3 BBedit (scripting-with-BBedit.html)\n---\n### 1.2.4.2 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.3 (IDE.html#IDE)).", "python_version": "2.3", "length": 628, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node16.html"} {"title": "1.3.1 Using the ``Python Interactive'' window", "text": "IDE.html | IDE.html | IDEwrite.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.3 The IDE (IDE.html)\nUp:\n1.3 The IDE (IDE.html)\nNext:\n1.3.2 Writing a Python (IDEwrite.html)\n---\n## 1.3.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.3.3 (IDEexecution.html#IDEexecution)).", "python_version": "2.3", "length": 577, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node23.html"} {"title": "2.4.1 IC Objects", "text": "module-ic.html | module-ic.html | module-MacOS.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.4 ic (module-ic.html)\nUp:\n2.4 ic (module-ic.html)\nNext:\n2.5 MacOS (module-MacOS.html)\n---\n## 2.4.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.3", "length": 989, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node35.html"} {"title": "1.1.1 How to run a Python script", "text": "getting-OSX.html | getting-OSX.html | osx-gui-scripts.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.1 Getting and Installing (getting-OSX.html)\nUp:\n1.1 Getting and Installing (getting-OSX.html)\nNext:\n1.1.2 Running scripts with (osx-gui-scripts.html)\n---\n## 1.1.1 How to run a Python script\nYour best way to get started with Python on Mac OS X is through the PythonIDE\nintegrated development environment, see section 1.3 (IDE.html#IDE) and use the Help\nmenu when the IDE is running.\nIf you want to run Python scripts from the Terminal window command line\nor from the Finder you first need an editor to create your script.\nMac OS X comes with a number of standard Unix command line editors,\nvi and emacs among them. If you want a more Mac-like\neditor BBEdit or TextWrangler from Bare Bones Software\n(see http://www.barebones.com/products/bbedit/index.shtml) are\ngood choices. Their freeware BBEdit Lite is officially\ndiscontinued but still available. AppleWorks or any other\nword processor that can save files in ASCII is also a possibility, but\nTextEdit is not: it saves in .rtf format only.\nTo run your script from the Terminal window you must make sure that\n/usr/local/bin is in your shell search path before /usr/bin,\nwhere the Apple-supplied Python lives (which is version 2.2, as of Mac OS X\n10.2.4).\nTo run your script from the Finder you have two options:\n- Drag it to PythonLauncher\n- Select PythonLauncher as the default application\nto open your script (or any .py script) through the finder Info window\nand double-click it.\nPythonLauncher has various preferences to control how your script is launched.\nOption-dragging allows you to change these for one invocation, or use its\nPreferences menu to change things globally.", "python_version": "2.3", "length": 1776, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node5.html"} {"title": "1.1.3 configuration", "text": "osx-gui-scripts.html | getting-OSX.html | getting.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.1.2 Running scripts with (osx-gui-scripts.html)\nUp:\n1.1 Getting and Installing (getting-OSX.html)\nNext:\n1.2 Getting and Installing (getting.html)\n---\n## 1.1.3 configuration\nMacPython honours all standard Unix environment variables such as\nPYTHONPATH, but setting these variables for programs started\nfrom the Finder is non-standard\nas the Finder does not read your .profile or .cshrc at startup.\nYou need to create a file ~/.MacOSX/environment.plist.\nSee Apple's Technical Document QA1067 for details.\nInstalling additional Python packages is most easily done through the\nPackage Manager, see the MacPython Help Book for details.", "python_version": "2.3", "length": 772, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node7.html"} {"title": "A. History and License", "text": "module-waste.html | mac.html | node100.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n5.17 waste (module-waste.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\nA.1 History of the (node100.html)\n---\n# A. History and License", "python_version": "2.3", "length": 270, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/node99.html"} {"title": "1.1.2 Running scripts with a GUI", "text": "node5.html | getting-OSX.html | node7.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.1.1 How to run (node5.html)\nUp:\n1.1 Getting and Installing (getting-OSX.html)\nNext:\n1.1.3 configuration (node7.html)\n---\n## 1.1.2 Running scripts with a GUI\nThere is one Mac OS X quirk that you need to be aware of: programs\nthat talk to the Aqua window manager (in other words, anything that has a GUI)\nneed to be run in a special way. Use pythonw in stead of python\nto start such scripts.", "python_version": "2.3", "length": 520, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/osx-gui-scripts.html"} {"title": "2.8.1 ProgressBar Objects", "text": "module-EasyDialogs.html | module-EasyDialogs.html | module-FrameWork.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.8 EasyDialogs (module-EasyDialogs.html)\nUp:\n2.8 EasyDialogs (module-EasyDialogs.html)\nNext:\n2.9 FrameWork (module-FrameWork.html)\n---\n## 2.8.1 ProgressBar Objects\nProgressBar objects provide support for modeless progress-bar\ndialogs. Both determinate (thermometer style) and indeterminate\n(barber-pole style) progress bars are supported. The bar will be\ndeterminate if its maximum value is greater than zero; otherwise it\nwill be indeterminate.\nChanged in version 2.2:\nSupport for indeterminate-style progress bars was\nadded.\nThe dialog is displayed immediately after creation. If the dialog's\n``Cancel'' button is pressed, or if Cmd-. or ESC is typed,\nthe dialog window is hidden and KeyboardInterrupt is\nraised (but note that this response does not occur until the progress\nbar is next updated, typically via a call to inc() or\nset()). Otherwise, the bar remains visible until the\nProgressBar object is discarded.\nProgressBar objects possess the following attributes and\nmethods:", "python_version": "2.3", "length": 1143, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/progressbar-objects.html"} {"title": "1.2.4.3 BBedit", "text": "node16.html | node14.html | configuration.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.4.2 Editors with Python (node16.html)\nUp:\n1.2.4 Creating a Python (node14.html)\nNext:\n1.2.5 Configuration (configuration.html)\n---\n### 1.2.4.3 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.3", "length": 758, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/scripting-with-BBedit.html"} {"title": "3. MacPython OSA Modules", "text": "module-autoGIL.html | mac.html | module-gensuitemodule.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.10 autoGIL (module-autoGIL.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\n3.1 gensuitemodule (module-gensuitemodule.html)\n---\n# 3. MacPython OSA Modules\nPython has a fairly complete implementation of the Open Scripting\nArchitecure (OSA, also commonly referred to as AppleScript), allowing\nyou to control scriptable applications from your Python program,\nand with a fairly pythonic interface.\nFor a description of the various components of AppleScript and OSA, and\nto get an understanding of the architecture and terminology, you should\nread Apple's documentation. The \"Applescript Language Guide\" explains\nthe conceptual model and the terminology, and documents the standard\nsuite. The \"Open Scripting Architecture\" document explains how to use\nOSA from an application programmers point of view. In the Apple Help\nViewer these book sare located in the Developer Documentation, Core\nTechnologies section.\nAs an example of scripting an application, the following piece of\nAppleScript will get the name of the frontmost Finder window\nand print it:\n```text\n\ntell application \"Finder\"\nget name of window 1\nend tell\n```\nIn Python, the following code fragment will do the same:\n```text\n\nimport Finder\n\nf = Finder.Finder()\nprint f.get(f.window(1).name)\n```\nAs distributed the Python library includes packages that implement the\nstandard suites, plus packages that interface to a small number of\ncommon applications.\nTo send AppleEvents to an application you must first create the Python\npackage interfacing to the terminology of the application (what\nScript Editor calls the \"Dictionary\"). This can be done from\nwithin the PythonIDE or by running the\ngensuitemodule.py module as a standalone program from the command\nline.\nThe generated output is a package with a number of modules, one for\nevery suite used in the program plus an __init__ module to glue\nit all together. The Python inheritance graph follows the AppleScript\ninheritance graph, so if a programs dictionary specifies that it\nincludes support for the Standard Suite, but extends one or two verbs\nwith extra arguments then the output suite will contain a module\nStandard_Suite that imports and re-exports everything from\nStdSuites.Standard_Suite but overrides the methods that have\nextra functionality. The output of gensuitemodule is pretty\nreadable, and contains the documentation that was in the original\nAppleScript dictionary in Python docstrings, so reading it is a good\nsource of documentation.\nThe output package implements a main class with the same name as the\npackage which contains all the AppleScript verbs as methods, with the\ndirect object as the first argument and all optional parameters as\nkeyword arguments. AppleScript classes are also implemented as Python\nclasses, as are comparisons and all the other thingies.\nThe main\nPython class implementing the verbs also allows access to the properties\nand elements declared in the AppleScript class \"application\". In the\ncurrent release that is as far as the object orientation goes, so\nin the example above we need to use\n`f.get(f.window(1).name)` in stead of the more Pythonic\n`f.window(1).name.get()`.\nIf an AppleScript identifier is not a Python identifier the name is\nmangled according to a small number of rules:\n- spaces are replaced with underscores\n- other non-alphanumeric characters are replaced with\n`_xx_` where `xx` is the hexadecimal character value\n- any Python reserved word gets an underscore appended\nPython also has support for creating scriptable applications\nin Python, but\nThe following modules are relevant to MacPython AppleScript support:\ngensuitemodule (module-gensuitemodule.html) | Create a stub package from an OSA dictionary\naetools (module-aetools.html) | Basic support for sending 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.\nMiniAEFrame (module-MiniAEFrame.html) | Support to act as an Open Scripting Architecture (OSA) server\n(``Apple Events'').\nIn addition, support modules have been pre-generated for\nFinder, Terminal, Explorer,\nNetscape, CodeWarrior, SystemEvents and\nStdSuites.", "python_version": "2.3", "length": 4342, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/scripting.html"} {"title": "2.9.4 ScrolledWindow Object", "text": "controlswindow-object.html | module-FrameWork.html | dialogwindow-objects.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.9.3 ControlsWindow Object (controlswindow-object.html)\nUp:\n2.9 FrameWork (module-FrameWork.html)\nNext:\n2.9.5 DialogWindow Objects (dialogwindow-objects.html)\n---\n## 2.9.4 ScrolledWindow Object\nScrolledWindow objects are ControlsWindow objects with the following\nextra methods:", "python_version": "2.3", "length": 443, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/scrolledwindow-object.html"} {"title": "1.2.5.2 Adding modules to the Module Search Path", "text": "EditPythonPrefs.html | configuration.html | defaults.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n1.2.5.1 EditPythonPrefs (EditPythonPrefs.html)\nUp:\n1.2.5 Configuration (configuration.html)\nNext:\n1.2.5.3 Default startup options (defaults.html)\n---\n### 1.2.5.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.3", "length": 928, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/search-path.html"} {"title": "4. MacOS Toolbox Modules", "text": "aeserver-objects.html | mac.html | module-Carbon.AE.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n3.5.1 AEServer Objects (aeserver-objects.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\n4.1 Carbon.AE (module-Carbon.AE.html)\n---\n# 4. 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/documentation/macos8/mac8.html) or similar works.\nThese modules all live in a package called Carbon. Despite that name\nthey are not all part of the Carbon framework: CF is really in the CoreFoundation\nframework and Qt is in the QuickTime framework.\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.AH (module-Carbon.AH.html) | Interface to the Apple Help manager.\nCarbon.App (module-Carbon.App.html) | Interface to the Appearance Manager.\nCarbon.CF (module-Carbon.CF.html) | Interface to the Core Foundation.\nCarbon.CG (module-Carbon.CG.html) | Interface to the Component Manager.\nCarbon.CaronEvt (module-Carbon.CaronEvt.html) | Interface to the Carbon Event Manager.\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 classic Event Manager.\nCarbon.Fm (module-Carbon.Fm.html) | Interface to the Font Manager.\nCarbon.Folder (module-Carbon.Folder.html) | Interface to the Folder Manager.\nCarbon.Help (module-Carbon.Help.html) | Interface to the Carbon 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) | Interface to the Carbon Scrap Manager.\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.3", "length": 3360, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/toolbox.html"} {"title": "5. Undocumented Modules", "text": "module-ColorPicker.html | mac.html | module-applesingle.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n4.25 ColorPicker (module-ColorPicker.html)\nUp:\nMacintosh Library Modules (mac.html)\nNext:\n5.1 applesingle (module-applesingle.html)\n---\n# 5. 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.\nmacresource (module-macresource.html) | Locate script resources.\nNac (module-Nac.html) | Interface to Navigation Services.\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 standard 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 (module-FrameWork.html).\nwaste (module-waste.html) | Interface to the ``WorldScript-Aware Styled Text Engine.''", "python_version": "2.3", "length": 1927, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/undocumented-modules.html"} {"title": "1. Using Python on a Mac OS 9 Macintosh", "text": "contents.html | mac.html | getting-OSX.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\nUp:\nMacintosh Library Modules (mac.html)\nNext:\n1.1 Getting and Installing (getting-OSX.html)\n---\n# 1. Using Python on a Mac OS 9 Macintosh\nUsing Python on a Macintosh, especially on Mac OS 9 (MacPython-OSX\nincludes a complete Unix Python) 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 published\nbooks, describe only how Python is used on these systems, causing\nconfusion for the new user of MacPython-OS9. This chapter gives a brief\nintroduction to the specifics of using Python on a Macintosh.\nThe section on the IDE (see Section 1.3 (IDE.html#IDE)) is relevant to MacPython-OSX\ntoo.", "python_version": "2.3", "length": 835, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/using.html"} {"title": "2.9.2 Window Objects", "text": "application-objects.html | module-FrameWork.html | controlswindow-object.html | Macintosh Library Modules | contents.html | modindex.html | genindex.html\nPrevious:\n2.9.1 Application Objects (application-objects.html)\nUp:\n2.9 FrameWork (module-FrameWork.html)\nNext:\n2.9.3 ControlsWindow Object (controlswindow-object.html)\n---\n## 2.9.2 Window Objects\nWindow objects have the following methods, among others:", "python_version": "2.3", "length": 406, "url": "https://docs.python.org/2.3/Python-Docs-2.3/mac/window-objects.html"} {"title": "Global Module Index", "text": "index.html | 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.3", "length": 155, "url": "https://docs.python.org/2.3/Python-Docs-2.3/modindex.html"} {"title": "About this document ...", "text": "genindex.html | ref.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\nUp:\nPython Reference Manual (ref.html)\n---\n# About this document ...\nPython Reference Manual,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1645, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/about.html"} {"title": "6.2 Assert statements", "text": "exprstmts.html | simple.html | assignment.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.1 Expression statements (exprstmts.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.3 Assignment statements (assignment.html)\n---\n# 6.2 Assert statements\nAssert statements are a convenient way to insert\ndebugging assertions into a program:\n`assert_stmt` | ::= | `\"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\nAssertionError refer 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.3", "length": 1400, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/assert.html"} {"title": "6.3 Assignment statements", "text": "assert.html | simple.html | augassign.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.2 Assert statements (assert.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.3.1 Augmented assignment statements (augassign.html)\n---\n# 6.3 Assignment statements\nAssignment statements are 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`\n`| \"(\" target_list \")\"`\n`| \"[\" target_list \"]\"`\n`| attributeref`\n`| subscription`\n`| 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.3", "length": 5735, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/assignment.html"} {"title": "5.2.1 Identifiers (Names)", "text": "atoms.html | atoms.html | atom-literals.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.2 Atoms (atoms.html)\nUp:\n5.2 Atoms (atoms.html)\nNext:\n5.2.2 Literals (atom-literals.html)\n---\n## 5.2.1 Identifiers (Names)\nAn identifier occurring as an atom is a name. See Section 4.1 for\ndocumentation of naming and binding.\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.3", "length": 1361, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/atom-identifiers.html"} {"title": "5.2.2 Literals", "text": "atom-identifiers.html | atoms.html | parenthesized.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.2.1 Identifiers (Names) (atom-identifiers.html)\nUp:\n5.2 Atoms (atoms.html)\nNext:\n5.2.3 Parenthesized forms (parenthesized.html)\n---\n## 5.2.2 Literals\nPython supports string literals and various numeric literals:\n`literal` | ::= | `stringliteral | integer | longinteger`\n`| 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.3", "length": 1084, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/atom-literals.html"} {"title": "5.2 Atoms", "text": "conversions.html | expressions.html | atom-identifiers.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.1 Arithmetic conversions (conversions.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.2.1 Identifiers (Names) (atom-identifiers.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`\n`| dict_display | string_conversion`\nDownload entire grammar as text. (grammar.txt)", "python_version": "2.3", "length": 706, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/atoms.html"} {"title": "3.3.2 Customizing attribute access", "text": "customization.html | specialnames.html | new-style-attribute-access.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.1 Basic customization (customization.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n3.3.2.1 More attribute access (new-style-attribute-access.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.", "python_version": "2.3", "length": 500, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/attribute-access.html"} {"title": "5.3.1 Attribute references", "text": "primaries.html | primaries.html | subscriptions.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.3 Primaries (primaries.html)\nUp:\n5.3 Primaries (primaries.html)\nNext:\n5.3.2 Subscriptions (subscriptions.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\nAttributeError is 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.3", "length": 875, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n6.3 Assignment statements (assignment.html)\nUp:\n6.3 Assignment statements (assignment.html)\nNext:\n6.4 The pass statement (pass.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`| \"»=\" | \"«=\" | \"&=\" | \"^=\" | \"|=\"`\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.\nFor targets which are attribute references, the initial value is\nretrieved with a getattr() and the result is assigned with a\nsetattr(). Notice that the two methods do not necessarily\nrefer to the same variable. When getattr() refers to a class\nvariable, setattr() still writes to an instance variable.\nFor example:\n```text\n\nclass A:\nx = 3 # class variable\na = A()\na.x += 1 # writes a.x as 4 leaving A.x as 3\n```", "python_version": "2.3", "length": 2158, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/augassign.html"} {"title": "5.6 Binary arithmetic operations", "text": "unary.html | expressions.html | shifting.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.5 Unary arithmetic operations (unary.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.7 Shifting operations (shifting.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`| m_expr \"%\" u_expr`\n`a_expr` | ::= | `m_expr | a_expr \"+\" m_expr | a_expr \"-\" 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) and `//` (floor division) operators yield\nthe quotient of their arguments. The numeric arguments are first\nconverted to a common type. Plain or long integer division yields an\ninteger of the same type; the result is that of mathematical division\nwith the `floor' function applied to the result. Division by zero\nraises 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 absolute\nvalue of the second operand5.1 (#foot4387).\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 numbers; there similar identities hold\napproximately where `x/y` is replaced by `floor(x/y)` or\n`floor(x/y) - 1`5.2 (#foot4453).\nDeprecated since release 2.3.\nThe floor division operator, the modulo operator,\nand the divmod() function are no longer defined for complex\nnumbers. Instead, convert to a floating point number using the\nabs() function if appropriate.\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.3", "length": 3135, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/binary.html"} {"title": "5.8 Binary bit-wise operations", "text": "shifting.html | expressions.html | comparisons.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.7 Shifting operations (shifting.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.9 Comparisons (comparisons.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.3", "length": 1007, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/bitwise.html"} {"title": "2.1.7 Blank lines", "text": "implicit-joining.html | line-structure.html | indentation.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.6 Implicit line joining (implicit-joining.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.8 Indentation (indentation.html)\n---\n## 2.1.7 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.3", "length": 717, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/blank-lines.html"} {"title": "5.10 Boolean operations", "text": "comparisons.html | expressions.html | lambdas.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.9 Comparisons (comparisons.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.11 Lambdas (lambdas.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 `''`.)", "python_version": "2.3", "length": 1755, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/Booleans.html"} {"title": "6.10 The break statement", "text": "raise.html | simple.html | continue.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.9 The raise statement (raise.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.11 The continue statement (continue.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.3", "length": 796, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/break.html"} {"title": "3.3.4 Emulating callable objects", "text": "metaclasses.html | specialnames.html | sequence-types.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.3 Customizing class creation (metaclasses.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n3.3.5 Emulating container types (sequence-types.html)\n---\n## 3.3.4 Emulating callable objects", "python_version": "2.3", "length": 327, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/callable-types.html"} {"title": "5.3.4 Calls", "text": "slicings.html | primaries.html | power.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.3.3 Slicings (slicings.html)\nUp:\n5.3 Primaries (primaries.html)\nNext:\n5.4 The power operator (power.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 ]`\n`[\",\" \"*\" expression ]`\n`[\",\" \"**\" expression ]`\n`| keyword_arguments [\",\" \"*\" expression ]`\n`[\",\" \"**\" 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.3", "length": 6155, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/calls.html"} {"title": "7.6 Class definitions", "text": "function.html | compound.html | top-level.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n7.5 Function definitions (function.html)\nUp:\n7. Compound statements (compound.html)\nNext:\n8. Top-level components (top-level.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 (naming.html#naming)), 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.3", "length": 1276, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/class.html"} {"title": "3.3.8 Coercion rules", "text": "numeric-types.html | specialnames.html | execmodel.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.7 Emulating numeric types (numeric-types.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n4. Execution model (execmodel.html)\n---\n## 3.3.8 Coercion rules\nThis section used to document the rules for coercion. As the language\nhas evolved, the coercion rules have become hard to document\nprecisely; documenting what one version of one particular\nimplementation does is undesirable. Instead, here are some informal\nguidelines regarding coercion. In Python 3.0, coercion will not be\nsupported.", "python_version": "2.3", "length": 628, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/coercion-rules.html"} {"title": "2.1.3 Comments", "text": "physical.html | line-structure.html | encodings.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.2 Physical lines (physical.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.4 Encoding declarations (encodings.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.3", "length": 557, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/comments.html"} {"title": "5.9 Comparisons", "text": "bitwise.html | expressions.html | Booleans.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.8 Binary bit-wise operations (bitwise.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.10 Boolean operations (Booleans.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 boolean values: `True` or `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 converted 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 elements. This means that to compare equal, each\nelement must compare equal and the two sequences must be of the same\ntype and have the same length.\nIf not equal, the sequences are ordered the same as their first\ndiffering elements. For example, `cmp([1,2,x], [1,2,y])` returns\nthe same as `cmp(x,y)`. If the corresponding element does not\nexist, the shorter sequence is ordered first (for example,\n`[1,2] < [1,2,3]`).\n- Mappings (dictionaries) compare equal if and only if their sorted\n(key, value) lists compare equal.5.3 (#foot4090)Outcomes other than equality are resolved consistently, but are not\notherwise defined.5.4 (#foot4400)\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 x is a substring of y. An equivalent test is\n`y.find(x) != -1`. Note, x and y need not be the\nsame type; consequently, `u'ab' in 'abc'` will return `True`.\nEmpty strings are always considered to be a substring of any other string,\nso `\"\" in \"abc\"` will return `True`.\nChanged in version 2.3:\nPreviously, x was required to be a string of\nlength `1`.\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.3", "length": 5119, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/comparisons.html"} {"title": "7. Compound statements", "text": "exec.html | ref.html | if.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.14 The exec statement (exec.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n7.1 The if statement (if.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`\n`| while_stmt`\n`| for_stmt`\n`| try_stmt`\n`| funcdef`\n`| 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.3", "length": 2499, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/compound.html"} {"title": "Contents", "text": "front.html | ref.html | introduction.html | Python Reference Manual | genindex.html\nPrevious:\nFront Matter (front.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n1. Introduction (introduction.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 Encoding declarations (encodings.html)\n 2.1.5 Explicit line joining (explicit-joining.html)\n 2.1.6 Implicit line joining (implicit-joining.html)\n 2.1.7 Blank lines (blank-lines.html)\n 2.1.8 Indentation (indentation.html)\n 2.1.9 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 Customizing class creation (metaclasses.html)\n 3.3.4 Emulating callable objects (callable-types.html)\n 3.3.5 Emulating container types (sequence-types.html)\n 3.3.6 Additional methods for emulation of sequence types (sequence-methods.html)\n 3.3.7 Emulating numeric types (numeric-types.html)\n 3.3.8 Coercion rules (coercion-rules.html)\n 4. Execution model (execmodel.html)\n - 4.1 Naming and binding (naming.html)\n - 4.1.1 Interaction with dynamic features (dynamic-features.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 (Booleans.html)\n 5.11 Lambdas (lambdas.html)\n 5.12 Expression lists (exprlists.html)\n 5.13 Evaluation order (evalorder.html)\n 5.14 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.12.1 Future statements (future.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. History and License (node103.html)\n - A.1 History of the software (node104.html)\n A.2 Terms and conditions for accessing or otherwise using Python (node105.html)\n About this document ... (about.html)\nEnd of Table of Contents", "python_version": "2.3", "length": 4646, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/contents.html"} {"title": "6.11 The continue statement", "text": "break.html | simple.html | import.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.10 The break statement (break.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.12 The import statement (import.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 (#foot5622)It continues with the next cycle of the nearest enclosing loop.", "python_version": "2.3", "length": 578, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/continue.html"} {"title": "5.1 Arithmetic conversions", "text": "expressions.html | expressions.html | atoms.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5. Expressions (expressions.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.2 Atoms (atoms.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.3", "length": 1056, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/conversions.html"} {"title": "3.3.1 Basic customization", "text": "specialnames.html | specialnames.html | attribute-access.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3 Special method names (specialnames.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n3.3.2 Customizing attribute access (attribute-access.html)\n---\n## 3.3.1 Basic customization", "python_version": "2.3", "length": 321, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/customization.html"} {"title": "3. Data model", "text": "delimiters.html | ref.html | objects.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.6 Delimiters (delimiters.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n3.1 Objects, values and (objects.html)\n---\n# 3. Data model", "python_version": "2.3", "length": 246, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/datamodel.html"} {"title": "6.5 The del statement", "text": "pass.html | simple.html | print.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.4 The pass statement (pass.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.6 The print statement (print.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\nfrom the local or global namespace, depending on whether the name\noccurs in a global statement in the same code block. If the\nname is unbound, a NameError exception will be raised.\nIt is illegal to delete a name from the local namespace if it occurs\nas a free variable in a nested 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.3", "length": 1151, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/del.html"} {"title": "2.6 Delimiters", "text": "operators.html | lexical.html | datamodel.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.5 Operators (operators.html)\nUp:\n2. Lexical analysis (lexical.html)\nNext:\n3. Data model (datamodel.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.3", "length": 952, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/delimiters.html"} {"title": "3.3.2.3 Invoking Descriptors", "text": "descriptors.html | attribute-access.html | slots.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.2.2 Implementing Descriptors (descriptors.html)\nUp:\n3.3.2 Customizing attribute access (attribute-access.html)\nNext:\n3.3.2.4 __slots__ (slots.html)\n---\n### 3.3.2.3 Invoking Descriptors\nIn general, a descriptor is an object attribute with ``binding behavior'',\none whose attribute access has been overridden by methods in the descriptor\nprotocol: __get__(), __set__(), and __delete__().\nIf any of those methods are defined for an object, it is said to be a\ndescriptor.\nThe default behavior for attribute access is to get, set, or delete the\nattribute from an object's dictionary. For instance, `a.x` has a\nlookup chain starting with `a.__dict__['x']`, then\n`type(a).__dict__['x']`, and continuing\nthrough the base classes of `type(a)` excluding metaclasses.\nHowever, if the looked-up value is an object defining one of the descriptor\nmethods, then Python may override the default behavior and invoke the\ndescriptor method instead. Where this occurs in the precedence chain depends\non which descriptor methods were defined and how they were called. Note that\ndescriptors are only invoked for new style objects or classes\n(ones that subclass object() or type()).\nThe starting point for descriptor invocation is a binding, `a.x`.\nHow the arguments are assembled depends on `a`:\nDirect Call: The simplest and least common call is when user code\ndirectly invokes a descriptor method: `x.__get__(a)`.\nInstance Binding: If binding to a new-style object instance,\n`a.x` is transformed into the call:\n`type(a).__dict__['x'].__get__(a, type(a))`.\nClass Binding: If binding to a new-style class, `A.x`\nis transformed into the call: `A.__dict__['x'].__get__(None, A)`.\nSuper Binding: If `a` is an instance of super,\nthen the binding `super(B, obj).m()` searches\n`obj.__class__.__mro__` for the base class `A` immediately\npreceding `B` and then invokes the descriptor with the call:\n`A.__dict__['m'].__get__(obj, A)`.\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. Data descriptors define\nboth __get__() and __set__(). Non-data descriptors have\njust the __get__() method. Data descriptors always override\na redefinition in an instance dictionary. In contrast, non-data\ndescriptors can be overridden by instances.\nPython methods (including staticmethod() and classmethod())\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to acquire\nbehaviors that differ from other instances of the same class.\nThe property() function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.", "python_version": "2.3", "length": 2786, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/descriptor-invocation.html"} {"title": "3.3.2.2 Implementing Descriptors", "text": "new-style-attribute-access.html | attribute-access.html | descriptor-invocation.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.2.1 More attribute access (new-style-attribute-access.html)\nUp:\n3.3.2 Customizing attribute access (attribute-access.html)\nNext:\n3.3.2.3 Invoking Descriptors (descriptor-invocation.html)\n---\n### 3.3.2.2 Implementing Descriptors\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called descriptor class) appears in\nthe class dictionary of another new-style class, known as the\nowner class. In the examples below, ``the attribute'' refers to\nthe attribute whose name is the key of the property in the owner\nclass' `__dict__`.", "python_version": "2.3", "length": 721, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/descriptors.html"} {"title": "5.2.5 Dictionary displays", "text": "lists.html | atoms.html | string-conversions.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.2.4 List displays (lists.html)\nUp:\n5.2 Atoms (atoms.html)\nNext:\n5.2.6 String conversions (string-conversions.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.3", "length": 1124, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/dict.html"} {"title": "4.1.1 Interaction with dynamic features", "text": "naming.html | naming.html | exceptions.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n4.1 Naming and binding (naming.html)\nUp:\n4.1 Naming and binding (naming.html)\nNext:\n4.2 Exceptions (exceptions.html)\n---\n## 4.1.1 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\nis a nested block with free variables, the compiler will raise a\nSyntaxError unless the exec explicitly specifies the local\nnamespace for the exec. (In other words, \"exec obj\"would be illegal, but \"exec obj in ns\" would be legal.)\nThe eval(), execfile(), and input()\nfunctions and the exec statement do not have access to the\nfull environment for resolving names. Names may be resolved in the\nlocal and global namespaces of the caller. Free variables are not\nresolved in the nearest enclosing namespace, but in the global\nnamespace.4.1 (#foot3394)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.", "python_version": "2.3", "length": 1504, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/dynamic-features.html"} {"title": "2.1.4 Encoding declarations", "text": "comments.html | line-structure.html | explicit-joining.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.3 Comments (comments.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.5 Explicit line joining (explicit-joining.html)\n---\n## 2.1.4 Encoding declarations\nIf a comment in the first or second line of the Python script matches\nthe regular expression coding[=:]\\s*([\\w-_.]+), this comment is\nprocessed as an encoding declaration; the first group of this\nexpression names the encoding of the source code file. The recommended\nforms of this expression are\n```text\n\n# -*- coding: -*-\n```\nwhich is recognized also by GNU Emacs, and\n```text\n\n# vim:fileencoding=\n```\nwhich is recognized by Bram Moolenar's VIM. In addition, if the first\nbytes of the file are the UTF-8 byte-order mark\n(`'\\xef\\xbb\\xbf'`), the declared file encoding is UTF-8\n(this is supported, among others, by Microsoft's notepad).\nIf an encoding is declared, the encoding name must be recognized by\nPython. The encoding is used for all lexical analysis, in particular to find\nthe end of a string, and to interpret the contents of Unicode literals.\nString literals are converted to Unicode for syntactical analysis,\nthen converted back to their original encoding before interpretation\nstarts. The encoding declaration must appear on a line of its own.", "python_version": "2.3", "length": 1383, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/encodings.html"} {"title": "5.13 Evaluation order", "text": "exprlists.html | expressions.html | summary.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.12 Expression lists (exprlists.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.14 Summary (summary.html)\n---\n# 5.13 Evaluation order\nPython evaluates expressions from left to right. Notice that while\nevaluating an assignment, the right-hand side is evaluated before\nthe left-hand side.\nIn the following lines, expressions will be evaluated in the\narithmetic order of their suffixes:\n```text\n\nexpr1, expr2, expr3, expr4\n(expr1, expr2, expr3, expr4)\n{expr1: expr2, expr3: expr4}\nexpr1 + expr2 * (expr3 - expr4)\nfunc(expr1, expr2, *expr3, **expr4)\nexpr3, expr4 = expr1, expr2\n```", "python_version": "2.3", "length": 699, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/evalorder.html"} {"title": "4.2 Exceptions", "text": "dynamic-features.html | execmodel.html | expressions.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n4.1.1 Interaction with dynamic (dynamic-features.html)\nUp:\n4. Execution model (execmodel.html)\nNext:\n5. Expressions (expressions.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''model 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 class instances.\nSelection of a matching except clause is based on object identity.\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 value; this object does not affect the\nselection of an exception handler, but is passed to the selected\nexception handler as additional information. For class exceptions,\nthis object must be an instance of the exception class being raised.\nWarning:\nMessages to exceptions are not part of the Python API. Their contents may\nchange from one version of Python to the next without warning and should not\nbe relied on by code which will run under multiple versions of the\ninterpreter.", "python_version": "2.3", "length": 2310, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/exceptions.html"} {"title": "6.14 The exec statement", "text": "global.html | simple.html | compound.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.13 The global statement (global.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n7. Compound statements (compound.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.", "python_version": "2.3", "length": 1709, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/exec.html"} {"title": "4. Execution model", "text": "coercion-rules.html | ref.html | naming.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.8 Coercion rules (coercion-rules.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n4.1 Naming and binding (naming.html)\n---\n# 4. Execution model", "python_version": "2.3", "length": 262, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/execmodel.html"} {"title": "2.1.5 Explicit line joining", "text": "encodings.html | line-structure.html | implicit-joining.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.4 Encoding declarations (encodings.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.6 Implicit line joining (implicit-joining.html)\n---\n## 2.1.5 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.3", "length": 1150, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/explicit-joining.html"} {"title": "8.4 Expression input", "text": "interactive.html | top-level.html | node103.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n8.3 Interactive input (interactive.html)\nUp:\n8. Top-level components (top-level.html)\nNext:\nA. History and License (node103.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.3", "length": 800, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/expression-input.html"} {"title": "5. Expressions", "text": "exceptions.html | ref.html | conversions.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n4.2 Exceptions (exceptions.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n5.1 Arithmetic conversions (conversions.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.3", "length": 638, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/expressions.html"} {"title": "5.12 Expression lists", "text": "lambdas.html | expressions.html | evalorder.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.11 Lambdas (lambdas.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.13 Evaluation order (evalorder.html)\n---\n# 5.12 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.3", "length": 851, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/exprlists.html"} {"title": "6.1 Expression statements", "text": "simple.html | simple.html | assert.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6. Simple statements (simple.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.2 Assert statements (assert.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.3", "length": 1094, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/exprstmts.html"} {"title": "8.2 File input", "text": "programs.html | top-level.html | interactive.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n8.1 Complete Python programs (programs.html)\nUp:\n8. Top-level components (top-level.html)\nNext:\n8.3 Interactive input (interactive.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.3", "length": 631, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.4.4 Integer and long (integers.html)\nUp:\n2.4 Literals (literals.html)\nNext:\n2.4.6 Imaginary literals (imaginary.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.3", "length": 1190, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/floating.html"} {"title": "7.3 The for statement", "text": "while.html | compound.html | try.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n7.2 The while statement (while.html)\nUp:\n7. Compound statements (compound.html)\nNext:\n7.4 The try statement (try.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`\n`[\"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.3", "length": 2512, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/for.html"} {"title": "Front Matter", "text": "ref.html | ref.html | contents.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\nPython Reference Manual (ref.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n---\n# Front Matter\nCopyright © 2001, 2002, 2003 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.3", "length": 2007, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/front.html"} {"title": "7.5 Function definitions", "text": "try.html | compound.html | class.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n7.4 The try statement (try.html)\nUp:\n7. Compound statements (compound.html)\nNext:\n7.6 Class definitions (class.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\nsection 5.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.11 (lambdas.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: Functions are first-class objects. A\n```def`'' form executed inside a function definition defines a\nlocal function that can be returned or passed around. Free variables\nused in the nested function can access the local variables of the\nfunction containing the def. See section 4.1 (naming.html#naming) for details.", "python_version": "2.3", "length": 3857, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/function.html"} {"title": "6.12.1 Future statements", "text": "import.html | import.html | global.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.12 The import statement (import.html)\nUp:\n6.12 The import statement (import.html)\nNext:\n6.13 The global statement (global.html)\n---\n## 6.12.1 Future statements\nA future statement is 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`future_statement` | ::= | `\"from\" \"__future__\" \"import\" feature [\"as\" name]`\n`(\",\" feature [\"as\" name])*`\n`feature` | ::= | `identifier`\n`name` | ::= | `identifier`\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.3 are \"generators\",\n\"division\" and \"nested_scopes\". \"generators\" and\n\"nested_scopes\" are redundant in 2.3 because they are always\nenabled.\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.3", "length": 3082, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/future.html"} {"title": "Index", "text": "node105.html | ref.html | about.html | Python Reference Manual | contents.html\nPrevious:\nA.2 Terms and conditions (node105.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\nAbout this document ... (about.html)\n---\n## Index\n---\nSymbols (#letter-Symbols) |\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## Symbols\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.3", "length": 956, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/genindex.html"} {"title": "6.13 The global statement", "text": "future.html | simple.html | exec.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.12.1 Future statements (future.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.14 The exec statement (exec.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. It would be impossible to assign to a global\nvariable without global, although free variables may refer\nto globals without being declared 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.3", "length": 1611, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.3.1 Keywords (keywords.html)\nUp:\n2.3 Identifiers and keywords (identifiers.html)\nNext:\n2.4 Literals (literals.html)\n---\n## 2.3.2 Reserved classes of identifiers\nCertain classes of identifiers (besides keywords) have special\nmeanings. These are:\nSee sections: 6.12 (import.html#import), ``The import statement'';\n3.3 (specialnames.html#specialnames), ``Special method names'';\n5.2.1 (atom-identifiers.html#atom-identifiers), ``Identifiers (Names)''.\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.3", "length": 805, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.2 Other tokens (other-tokens.html)\nUp:\n2. Lexical analysis (lexical.html)\nNext:\n2.3.1 Keywords (keywords.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.3", "length": 657, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/identifiers.html"} {"title": "7.1 The if statement", "text": "compound.html | compound.html | while.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n7. Compound statements (compound.html)\nUp:\n7. Compound statements (compound.html)\nNext:\n7.2 The while statement (while.html)\n---\n# 7.1 The if statement\nThe if statement is used for conditional execution:\n`if_stmt` | ::= | `\"if\" expression \":\" suite`\n`( \"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 (Booleans.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.3", "length": 833, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/if.html"} {"title": "2.4.6 Imaginary literals", "text": "floating.html | literals.html | operators.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.4.5 Floating point literals (floating.html)\nUp:\n2.4 Literals (literals.html)\nNext:\n2.5 Operators (operators.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.3", "length": 818, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/imaginary.html"} {"title": "2.1.6 Implicit line joining", "text": "explicit-joining.html | line-structure.html | blank-lines.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.5 Explicit line joining (explicit-joining.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.7 Blank lines (blank-lines.html)\n---\n## 2.1.6 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.3", "length": 997, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/implicit-joining.html"} {"title": "6.12 The import statement", "text": "continue.html | simple.html | future.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.11 The continue statement (continue.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.12.1 Future statements (future.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.\nIn this context, to ``initialize'' a built-in or extension module means to\ncall an initialization function that the module must provide for the purpose\n(in the reference implementation, the function's name is obtained by\nprepending string ``init'' to the module's name); to ``initialize'' a\nPython-coded module means to execute the module's body.\nThe system maintains a table of modules that have been or are being\ninitialized,\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\nbuilt-in initialization code is executed and step (1) is finished. If\nno matching file is found,\nImportError is raised.\nIf a file is found, it is parsed,\nyielding an executable code block. If a syntax error occurs,\nSyntaxError is raised. Otherwise, an\nempty module of the given name is created and inserted in the module\ntable, and then the code block is executed in the context of this\nmodule. Exceptions during this 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.\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(\"_\"). `__all__` should contain the entire public API.\nIt is intended to avoid accidentally exporting items that are not part\nof the API (such as library modules which were imported and used within\nthe module).\nThe from form with \"*\" may only occur in a module\nscope. If the wild card form of import -- \"import *\" -- is\nused in a function and the function contains or is a nested block with\nfree variables, the compiler will raise a SyntaxError.\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.3", "length": 4853, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/import.html"} {"title": "2.1.8 Indentation", "text": "blank-lines.html | line-structure.html | whitespace.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.7 Blank lines (blank-lines.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.9 Whitespace between tokens (whitespace.html)\n---\n## 2.1.8 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. It\nshould also be noted that different platforms may explicitly limit the\nmaximum indentation level.\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.3", "length": 3145, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/indentation.html"} {"title": "Python Reference Manual", "text": "../index.html | front.html | Python Reference Manual | contents.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Python Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 304, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.4.3 Numeric literals (numbers.html)\nUp:\n2.4 Literals (literals.html)\nNext:\n2.4.5 Floating point literals (floating.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\nallowed as suffix for long integers, it is strongly recommended to always\nuse \"L\", since the letter \"l\" looks too much like the\ndigit \"1\".\nPlain integer decimal literals that are above the largest representable\nplain integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted\nas if they were long integers instead. Octal and hexadecimal literals\nbehave similarly, but when in the range just above the largest representable\nplain integer but below the largest unsigned 32-bit number (on a machine\nusing 32-bit arithmetic), 4294967296, they are taken as the negative plain\ninteger obtained by subtracting 4294967296 from their unsigned value. There\nis no limit for long integer literals apart from what can be stored in\navailable memory. For example, 0xdeadbeef is taken, on a 32-bit machine,\nas the value -559038737, while 0xdeadbeeffeed is taken as the value\n244837814107885L.\nSome examples of plain integer literals (first row) and long integer\nliterals (second and third rows):\n```text\n\n7 2147483647 0177 0x80000000\n3L 79228162514264337593543950336L 0377L 0x100000000L\n79228162514264337593543950336 0xdeadbeeffeed\n```", "python_version": "2.3", "length": 1961, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8.2 File input (file-input.html)\nUp:\n8. Top-level components (top-level.html)\nNext:\n8.4 Expression input (expression-input.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.3", "length": 629, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/interactive.html"} {"title": "1. Introduction", "text": "contents.html | ref.html | notation.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\nUp:\nPython Reference Manual (ref.html)\nNext:\n1.1 Notation (notation.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.3", "length": 1915, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/introduction.html"} {"title": "2.3.1 Keywords", "text": "identifiers.html | identifiers.html | id-classes.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.3 Identifiers and keywords (identifiers.html)\nUp:\n2.3 Identifiers and keywords (identifiers.html)\nNext:\n2.3.2 Reserved classes of (id-classes.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```\nNote that although the identifier `as` can be used as part of the\nsyntax of import statements, it is not currently a reserved\nword.\nIn some future version of Python, the identifiers `as` and\n`None` will both become keywords.", "python_version": "2.3", "length": 860, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/keywords.html"} {"title": "5.11 Lambdas", "text": "Booleans.html | expressions.html | exprlists.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.10 Boolean operations (Booleans.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.12 Expression lists (exprlists.html)\n---\n# 5.11 Lambdas\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. The unnamed object behaves like a function\nobject defined 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.", "python_version": "2.3", "length": 731, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/lambdas.html"} {"title": "2. Lexical analysis", "text": "notation.html | ref.html | line-structure.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n1.1 Notation (notation.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n2.1 Line structure (line-structure.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.\nNew in version 2.3:\nAn encoding declaration can be used to indicate that\nstring literals and comments use an encoding different from ASCII..\nFor compatibility with older versions, Python only warns if it finds\n8-bit characters; those warnings should be corrected by either declaring\nan explicit encoding, or using escape sequences if those bytes are binary\ndata, instead of characters.\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.3", "length": 1670, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/lexical.html"} {"title": "2.1 Line structure", "text": "lexical.html | lexical.html | logical.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2. Lexical analysis (lexical.html)\nUp:\n2. Lexical analysis (lexical.html)\nNext:\n2.1.1 Logical lines (logical.html)\n---\n# 2.1 Line structure\nA Python program is divided into a number of logical lines.", "python_version": "2.3", "length": 310, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/line-structure.html"} {"title": "5.2.4 List displays", "text": "parenthesized.html | atoms.html | dict.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.2.3 Parenthesized forms (parenthesized.html)\nUp:\n5.2 Atoms (atoms.html)\nNext:\n5.2.5 Dictionary displays (dict.html)\n---\n## 5.2.4 List displays\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n`test` | ::= | `and_test ( \"or\" and_test )*\n| lambda_form`\n`testlist` | ::= | `test ( \",\" test )* [ \",\" ]`\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.3", "length": 1459, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/lists.html"} {"title": "2.4 Literals", "text": "id-classes.html | lexical.html | strings.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.3.2 Reserved classes of (id-classes.html)\nUp:\n2. Lexical analysis (lexical.html)\nNext:\n2.4.1 String literals (strings.html)\n---\n# 2.4 Literals\nLiterals are notations for constant values of some built-in types.", "python_version": "2.3", "length": 325, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.1 Line structure (line-structure.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.2 Physical lines (physical.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.3", "length": 609, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/logical.html"} {"title": "3.3.3 Customizing class creation", "text": "slots.html | specialnames.html | callable-types.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.2.4 __slots__ (slots.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n3.3.4 Emulating callable objects (callable-types.html)\n---\n## 3.3.3 Customizing class creation\nBy default, new-style classes are constructed using type().\nA class definition is read into a separate namespace and the value\nof class name is bound to the result of `type(name, bases, dict)`.\nWhen the class definition is read, if __metaclass__ is defined\nthen the callable assigned to it will be called instead of type().\nThe allows classes or functions to be written which monitor or alter the class\ncreation process:\n- Modifying the class dictionary prior to the class being created.\n- Returning an instance of another class - essentially performing\nthe role of a factory function.\nThe appropriate metaclass is determined by the following precedence rules:\n- If `dict['__metaclass__']` exists, it is used.\n- Otherwise, if there is at least one base class, its metaclass is used\n(this looks for a __class__ attribute first and if not found, uses its\ntype).\n- Otherwise, if a global variable named __metaclass__ exists, it is used.\n- Otherwise, the old-style, classic metaclass (types.ClassType) is used.\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic delegation,\nautomatic property creation, proxies, frameworks, and automatic resource\nlocking/synchronization.", "python_version": "2.3", "length": 1552, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/metaclasses.html"} {"title": "4.1 Naming and binding", "text": "execmodel.html | execmodel.html | dynamic-features.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n4. Execution model (execmodel.html)\nUp:\n4. Execution model (execmodel.html)\nNext:\n4.1.1 Interaction with dynamic (dynamic-features.html)\n---\n# 4.1 Naming and binding\nNamesrefer to objects. Names are introduced by\nname binding operations. Each occurrence of a name in the program\ntext refers to the binding of that name\nestablished in the innermost function block containing the use.\nA blockis a piece of Python program text that is\nexecuted as a unit. The following are blocks: a module, a function\nbody, and a class definition. Each command typed interactively is a\nblock. A script file (a file given as standard input to the\ninterpreter or specified on the interpreter command line the first\nargument) is a code block. A script command (a command specified on\nthe interpreter command line with the `-c' option) is a code\nblock. The file read by the built-in function execfile()\nis a code block. The string argument passed to the built-in function\neval() and to the exec statement is a code block.\nThe expression read and evaluated by the built-in function\ninput() is a code block.\nA code block is executed in an execution\nframe. A frame contains some\nadministrative information (used for debugging) and determines where\nand how execution continues after the code block's execution has\ncompleted.\nA scopedefines the visibility of a name within a\nblock. If a local variable is defined in a block, its scope includes\nthat block. If the definition occurs in a function block, the scope\nextends to any blocks contained within the defining one, unless a\ncontained block introduces a different binding for the name. The\nscope of names defined in a class block is limited to the class block;\nit does not extend 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.\nWhen a name is not found at all, a\nNameError exception is raised. If the name\nrefers to a local variable that has not been bound, a\nUnboundLocalErrorexception is\nraised. UnboundLocalError is a subclass of\nNameError.\nThe following 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. The import statement of the form ``\"from\n...import *\"'' binds all names defined in the\nimported module, except those beginning with an underscore. This form\nmay only be used at the module level.\nA target occurring in a del statement is also considered bound\nfor this purpose (though the actual semantics are to unbind the\nname). It is illegal to unbind a name that is referenced by an\nenclosing scope; the compiler will report a SyntaxError.\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 built-in namespace associated with the execution of a code block\nis actually found by looking up the name `__builtins__` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used). Normally, the\n`__builtins__` namespace is the dictionary of the built-in module\n__builtin__ (note: no `s'). If it isn't, restricted\nexecution mode is in effect.\nThe namespace for a module is automatically created the first time a\nmodule is imported. The main module for a script is always called\n__main__.\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.3", "length": 5497, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/naming.html"} {"title": "3.3.2.1 More attribute access for new-style classes", "text": "attribute-access.html | attribute-access.html | descriptors.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.2 Customizing attribute access (attribute-access.html)\nUp:\n3.3.2 Customizing attribute access (attribute-access.html)\nNext:\n3.3.2.2 Implementing Descriptors (descriptors.html)\n---\n### 3.3.2.1 More attribute access for new-style classes\nThe following methods only apply to new-style classes.", "python_version": "2.3", "length": 427, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/new-style-attribute-access.html"} {"title": "A. History and License", "text": "expression-input.html | ref.html | node104.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n8.4 Expression input (expression-input.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\nA.1 History of the (node104.html)\n---\n# A. History and License", "python_version": "2.3", "length": 268, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/node103.html"} {"title": "A.1 History of the software", "text": "node103.html | node103.html | node105.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\nA. History and License (node103.html)\nUp:\nA. History and License (node103.html)\nNext:\nA.2 Terms and conditions (node105.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 Digital Creations (now Zope\nCorporation; 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. Zope Corporation 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.3", "length": 1899, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/node104.html"} {"title": "A.2 Terms and conditions for accessing or otherwise using Python", "text": "node104.html | node103.html | genindex.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\nA.1 History of the (node104.html)\nUp:\nA. History and License (node103.html)\nNext:\n---\n# A.2 Terms and conditions for accessing or otherwise using Python\nPSF LICENSE AGREEMENT FOR PYTHON 2.3\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.3 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.3 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001-2003 Python Software Foundation; All\nRights Reserved'' are retained in Python 2.3 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.3 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.3.\n4. PSF is making Python 2.3 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.3 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.3, 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.3, 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.3", "length": 9868, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/node105.html"} {"title": "1.1 Notation", "text": "introduction.html | introduction.html | lexical.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n1. Introduction (introduction.html)\nUp:\n1. Introduction (introduction.html)\nNext:\n2. Lexical analysis (lexical.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.3", "length": 1935, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/notation.html"} {"title": "2.4.3 Numeric literals", "text": "string-catenation.html | literals.html | integers.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.4.2 String literal concatenation (string-catenation.html)\nUp:\n2.4 Literals (literals.html)\nNext:\n2.4.4 Integer and long (integers.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.3", "length": 674, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/numbers.html"} {"title": "3.3.7 Emulating numeric types", "text": "sequence-methods.html | specialnames.html | coercion-rules.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.6 Additional methods for (sequence-methods.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n3.3.8 Coercion rules (coercion-rules.html)\n---\n## 3.3.7 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.", "python_version": "2.3", "length": 566, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n3. Data model (datamodel.html)\nUp:\n3. Data model (datamodel.html)\nNext:\n3.2 The standard type (types.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.3.1 (#foot2276)An object's type determines the operations that the 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\ncyclically 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.3", "length": 4449, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/objects.html"} {"title": "2.5 Operators", "text": "imaginary.html | lexical.html | delimiters.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.4.6 Imaginary literals (imaginary.html)\nUp:\n2. Lexical analysis (lexical.html)\nNext:\n2.6 Delimiters (delimiters.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.3", "length": 491, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/operators.html"} {"title": "2.2 Other tokens", "text": "whitespace.html | lexical.html | identifiers.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.9 Whitespace between tokens (whitespace.html)\nUp:\n2. Lexical analysis (lexical.html)\nNext:\n2.3 Identifiers and keywords (identifiers.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.3", "length": 663, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n5.2.2 Literals (atom-literals.html)\nUp:\n5.2 Atoms (atoms.html)\nNext:\n5.2.4 List displays (lists.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.3", "length": 1118, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/parenthesized.html"} {"title": "6.4 The pass statement", "text": "augassign.html | simple.html | del.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.3.1 Augmented assignment statements (augassign.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.5 The del statement (del.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.3", "length": 646, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/pass.html"} {"title": "2.1.2 Physical lines", "text": "logical.html | line-structure.html | comments.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.1 Logical lines (logical.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.1.3 Comments (comments.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 Windows, it is the ASCII sequence CR LF (return\nfollowed by linefeed). On Macintosh, it is the ASCII CR (return)\ncharacter.", "python_version": "2.3", "length": 535, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/physical.html"} {"title": "5.4 The power operator", "text": "calls.html | expressions.html | unary.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.3.4 Calls (calls.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.5 Unary arithmetic operations (unary.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.\nWith mixed operand types, the coercion rules for binary arithmetic\noperators apply. For int and long int operands, the result has the\nsame type as the operands (after coercion) unless the second argument\nis negative; in that case, all arguments are converted to float and a\nfloat result is delivered. For example, `10**2` returns `100`,\nbut `10**-2` returns `0.01`. (This last feature was added in\nPython 2.2. In Python 2.1 and before, if both arguments were of integer\ntypes and the second argument was negative, an exception was raised).\nRaising `0.0` to a negative power results in a\nZeroDivisionError. Raising a negative number to a\nfractional power results in a ValueError.", "python_version": "2.3", "length": 1637, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/power.html"} {"title": "5.3 Primaries", "text": "string-conversions.html | expressions.html | attribute-references.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.2.6 String conversions (string-conversions.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.3.1 Attribute references (attribute-references.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.3", "length": 515, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/primaries.html"} {"title": "6.6 The print statement", "text": "del.html | simple.html | return.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.5 The del statement (del.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.7 The return statement (return.html)\n---\n# 6.6 The print statement\n`print_stmt` | ::= | `\"print\" ( [ expression (\",\" expression )* [ \",\" ] ]`\n`| \"> > \" 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.3", "length": 2198, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n8. Top-level components (top-level.html)\nUp:\n8. Top-level components (top-level.html)\nNext:\n8.2 File input (file-input.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.3", "length": 1545, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/programs.html"} {"title": "6.9 The raise statement", "text": "yield.html | simple.html | break.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.8 The yield statement (yield.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.10 The break statement (break.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 active in the current scope. If no exception is\nactive in the current scope, an exception is raised indicating this error.\nOtherwise, raise evaluates the expressions to get three\nobjects, using `None` as the value of omitted expressions. The\nfirst two objects are used to determine the type and\nvalue of the exception.\nIf the first object is an instance, the type of the exception is the\nclass of the instance, the instance itself is the value, and the\nsecond object must be `None`.\nIf the first object is a class, it becomes the type of the exception.\nThe second object is used to determine the exception value: If it is\nan instance of the class, the instance becomes the exception value.\nIf the second object is a tuple, it is used as the argument list for\nthe class constructor; if it is `None`, an empty argument list is\nused, and any other object is treated as a single argument to the\nconstructor. The instance so created by calling the constructor is\nused as the exception value.\nIf a third object is present and not `None`, it must be a\ntraceback object (see section 3.2 (types.html#traceback)), and\nit is substituted instead of the current location as the place where\nthe exception occurred. If the third object is present and not a\ntraceback object or `None`, a TypeError exception is\nraised. The three-expression form of raise is useful to\nre-raise an exception transparently in an except clause, but\nraise with no expressions should be preferred if the\nexception to be re-raised was the most recently active exception in\nthe current scope.\nAdditional information on exceptions can be found in\nsection 4.2 (exceptions.html#exceptions), and information about handling exceptions is\nin section 7.4 (try.html#try).", "python_version": "2.3", "length": 2181, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/raise.html"} {"title": "Python Reference Manual", "text": "../index.html | front.html | Python Reference Manual | contents.html | genindex.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (front.html)\n---\n# Python Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 304, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/ref.html"} {"title": "6.7 The return statement", "text": "print.html | simple.html | yield.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.6 The print statement (print.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.8 The yield statement (yield.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.3", "length": 1016, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/return.html"} {"title": "3.3.6 Additional methods for emulation of sequence types", "text": "sequence-types.html | specialnames.html | numeric-types.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.5 Emulating container types (sequence-types.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n3.3.7 Emulating numeric types (numeric-types.html)\n---\n## 3.3.6 Additional methods for emulation of sequence types\nThe following optional methods can be defined to further emulate sequence\nobjects. Immutable sequences methods should at most only define\n__getslice__(); mutable sequences might 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 necessary because of\nthe 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.3", "length": 2352, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/sequence-methods.html"} {"title": "3.3.5 Emulating container types", "text": "callable-types.html | specialnames.html | sequence-methods.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.4 Emulating callable objects (callable-types.html)\nUp:\n3.3 Special method names (specialnames.html)\nNext:\n3.3.6 Additional methods for (sequence-methods.html)\n---\n## 3.3.5 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(),\nsetdefault(), iterkeys(), itervalues(),\niteritems(), pop(), popitem(),\ncopy(), and update() behaving similar to those for\nPython's standard dictionary objects. The UserDict module\nprovides a DictMixin class to help create those methods\nfrom a base set of __getitem__(), __setitem__(),\n__delitem__(), and keys().\nMutable sequences should provide\nmethods append(), count(), index(),\nextend(),\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. It is further recommended that both mappings and sequences\nimplement the __iter__() method to allow efficient iteration\nthrough the container; for mappings, __iter__() should be\nthe same as iterkeys(); for sequences, it should iterate\nthrough the values.\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.3", "length": 2589, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/sequence-types.html"} {"title": "5.7 Shifting operations", "text": "binary.html | expressions.html | bitwise.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.6 Binary arithmetic operations (binary.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.8 Binary bit-wise operations (bitwise.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.3", "length": 1031, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/shifting.html"} {"title": "6. Simple statements", "text": "summary.html | ref.html | exprstmts.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.14 Summary (summary.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n6.1 Expression statements (exprstmts.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`\n`| assert_stmt`\n`| assignment_stmt`\n`| augmented_assignment_stmt`\n`| pass_stmt`\n`| del_stmt`\n`| print_stmt`\n`| return_stmt`\n`| yield_stmt`\n`| raise_stmt`\n`| break_stmt`\n`| continue_stmt`\n`| import_stmt`\n`| global_stmt`\n`| exec_stmt`\nDownload entire grammar as text. (grammar.txt)", "python_version": "2.3", "length": 748, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/simple.html"} {"title": "5.3.3 Slicings", "text": "subscriptions.html | primaries.html | calls.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.3.2 Subscriptions (subscriptions.html)\nUp:\n5.3 Primaries (primaries.html)\nNext:\n5.3.4 Calls (calls.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.3", "length": 3015, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/slicings.html"} {"title": "3.3.2.4 __slots__", "text": "descriptor-invocation.html | attribute-access.html | metaclasses.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.3.2.3 Invoking Descriptors (descriptor-invocation.html)\nUp:\n3.3.2 Customizing attribute access (attribute-access.html)\nNext:\n3.3.3 Customizing class creation (metaclasses.html)\n---\n### 3.3.2.4 __slots__\nBy default, instances of both old and new-style classes have a dictionary\nfor attribute storage. This wastes space for objects having very few instance\nvariables. The space consumption can become acute when creating large numbers\nof instances.\nThe default can be overridden by defining __slots__ in a new-style class\ndefinition. The __slots__ declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a value\nfor each variable. Space is saved because __dict__ is not created for\neach instance.\nNotes on using __slots__\n- Without a __dict__ variable, instances cannot be assigned new\nvariables not listed in the __slots__ definition. Attempts to assign\nto an unlisted variable name raises AttributeError. If dynamic\nassignment of new variables is desired, then add `'__dict__'` to the\nsequence of strings in the __slots__ declaration.\nChanged in version 2.3:\nPreviously, adding `'__dict__'` to the __slots__\ndeclaration would not enable the assignment of new attributes not\nspecifically listed in the sequence of instance variable names.\n- Without a __weakref__ variable for each instance, classes\ndefining __slots__ do not support weak references to its instances.\nIf weak reference support is needed, then add `'__weakref__'` to the\nsequence of strings in the __slots__ declaration.\nChanged in version 2.3:\nPreviously, adding `'__weakref__'` to the __slots__\ndeclaration would not enable support for weak references.\n- __slots__ are implemented at the class level by creating\ndescriptors (3.3.2 (descriptors.html#descriptors)) for each variable name. As a result,\nclass attributes cannot be used to set default values for instance\nvariables defined by __slots__; otherwise, the class attribute would\noverwrite the descriptor assignment.\n- If a class defines a slot also defined in a base class, the instance\nvariable defined by the base class slot is inaccessible (except by retrieving\nits descriptor directly from the base class). This renders the meaning of the\nprogram undefined. In the future, a check may be added to prevent this.\n- The action of a __slots__ declaration is limited to the class\nwhere it is defined. As a result, subclasses will have a __dict__\nunless they also define __slots__.\n- __slots__ do not work for classes derived from ``variable-length''\nbuilt-in types such as long, str and tuple.\n- Any non-string iterable may be assigned to __slots__.\nMappings may also be used; however, in the future, special meaning may\nbe assigned to the values corresponding to each key.", "python_version": "2.3", "length": 2886, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/slots.html"} {"title": "3.3 Special method names", "text": "types.html | datamodel.html | customization.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.2 The standard type (types.html)\nUp:\n3. Data model (datamodel.html)\nNext:\n3.3.1 Basic customization (customization.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.This is Python's approach to operator overloading, allowing\nclasses to define their own behavior with respect to language\noperators. 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)`. Except where mentioned, attempts to execute\nan operation 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.3", "length": 1230, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/specialnames.html"} {"title": "2.4.2 String literal concatenation", "text": "strings.html | literals.html | numbers.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.4.1 String literals (strings.html)\nUp:\n2.4 Literals (literals.html)\nNext:\n2.4.3 Numeric literals (numbers.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.3", "length": 1098, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/string-catenation.html"} {"title": "5.2.6 String conversions", "text": "dict.html | atoms.html | primaries.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.2.5 Dictionary displays (dict.html)\nUp:\n5.2 Atoms (atoms.html)\nNext:\n5.3 Primaries (primaries.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.)\nRecursive objects (for example, lists or dictionaries that contain a\nreference to themselves, directly or indirectly) use \"...\" to\nindicate a recursive reference, and the result cannot be passed to\neval() to get an equal value (SyntaxError will\nbe raised instead).\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.3", "length": 1537, "url": "https://docs.python.org/2.3/Python-Docs-2.3/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\nPrevious:\n2.4 Literals (literals.html)\nUp:\n2.4 Literals (literals.html)\nNext:\n2.4.2 String literal concatenation (string-catenation.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\nraw stringsand use different rules for interpreting\nbackslash escape sequences. A prefix of \"u\" or \"U\"\nmakes the string a Unicode string. Unicode strings use the Unicode character\nset as defined 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\nsequences in strings are interpreted according to rules similar\nto those used by Standard C. The recognized escape sequences are:\nNotes:\n(1): Individual code units which form parts of a surrogate pair can be\nencoded using this escape sequence.\n(2): Any Unicode character can be encoded this way, but characters\noutside the Basic Multilingual Plane (BMP) will be encoded using a\nsurrogate pair if Python is compiled to use 16-bit code units (the\ndefault). Individual code units which form parts of a surrogate\npair can be encoded using this escape sequence.\n(3): As in Standard C, up to three octal digits are accepted.\n(4): Unlike in Standard C, at most two hex digits are accepted.\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\nfollowing a backslash 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\nbackslash remains 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.\nWhen an \"r\" or \"R\" prefix is used in conjunction\nwith a \"u\" or \"U\" prefix, then the `\\uXXXX`\nescape sequence is processed while all other backslashes are\nleft in the string. For example, the string literal\n`ur\"\\u0062\\n\"` consists of three Unicode characters: `LATIN\nSMALL LETTER B', `REVERSE SOLIDUS', and `LATIN SMALL LETTER N'.\nBackslashes can be escaped with a preceding backslash; however, both\nremain in the string. As a result, `\\uXXXX` escape sequences\nare only recognized when there are an odd number of backslashes.", "python_version": "2.3", "length": 4859, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/strings.html"} {"title": "5.3.2 Subscriptions", "text": "attribute-references.html | primaries.html | slicings.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.3.1 Attribute references (attribute-references.html)\nUp:\n5.3 Primaries (primaries.html)\nNext:\n5.3.3 Slicings (slicings.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.3", "length": 1335, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/subscriptions.html"} {"title": "5.14 Summary", "text": "evalorder.html | expressions.html | simple.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.13 Evaluation order (evalorder.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n6. Simple statements (simple.html)\n---\n# 5.14 Summary\nThe following table summarizes the operator\nprecedences in 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.3", "length": 679, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/summary.html"} {"title": "8. Top-level components", "text": "class.html | ref.html | programs.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n7.6 Class definitions (class.html)\nUp:\nPython Reference Manual (ref.html)\nNext:\n8.1 Complete Python programs (programs.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.3", "length": 503, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/top-level.html"} {"title": "7.4 The try statement", "text": "for.html | compound.html | function.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n7.3 The for statement (for.html)\nUp:\n7. Compound statements (compound.html)\nNext:\n7.5 Function definitions (function.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`\n`(\"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 (#foot6465) 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 - this 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).\nAdditional information on exceptions can be found in\nsection 4.2 (exceptions.html#exceptions), and information on using the raise\nstatement to generate exceptions may be found in section 6.9 (raise.html#raise).", "python_version": "2.3", "length": 4871, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/try.html"} {"title": "3.2 The standard type hierarchy", "text": "objects.html | datamodel.html | specialnames.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n3.1 Objects, values and (objects.html)\nUp:\n3. Data model (datamodel.html)\nNext:\n3.3 Special method names (specialnames.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, Java, or other languages, depending on\nthe implementation) 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 three 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\nresult is normally returned as a long integer (in some cases, the\nexception OverflowError is raised instead).\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.\nBooleans: These represent the truth values False and True. The two objects\nrepresenting the values False and True are the only Boolean objects.\nThe Boolean type is a subtype of plain integers, and Boolean values\nbehave like the values 0 and 1, respectively, in almost all contexts,\nthe exception being that when converted to a string, the strings\n`\"False\"` or `\"True\"` are returned, respectively.\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. Any operation except left shift,\nif it yields a result in the plain integer domain without causing\noverflow, 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 or Java 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 parts of a complex\nnumber `z` can be retrieved through the read-only attributes\n`z.real` and `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.\nSome sequences also support ``extended slicing'' with a third ``step''\nparameter: `a [ i : j : k ]` selects all items\nof a with index x where `x = i + n * k`, n `>=` `0` and i `<=`\nx `<` j.\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 code units. A Unicode code\nunit is represented by a Unicode object of one item and can hold\neither a 16-bit or 32-bit value representing a Unicode ordinal (the\nmaximum value for the ordinal is given in `sys.maxunicode`, and\ndepends on how Python is configured at compile time). Surrogate pairs\nmay be present in the Unicode object, and will be reported as two\nseparate items. The built-in functions\nunichr() and\nord() convert between code units 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 intrinsic 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: These represent 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 can be 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: These are 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;\n__module__ is the name of the module the function was defined\nin, or `None` if unavailable;\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\nbindings for the function's free variables.\nOf these, func_code, func_defaults,\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.\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__`); __module__ is the name of the\nmodule the method was defined in, or `None` if unavailable.\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 may be created when getting an attribute\nof a class (perhaps via an instance of that class), if that attribute\nis a user-defined function object, an unbound user-defined method object,\nor a class method object.\nWhen the attribute is a user-defined method object, a new\nmethod object is only created if the class from which it is being\nretrieved is the same as, or a derived class of, the class stored\nin the original method object; otherwise, the original method object\nis used as it is.\nWhen a user-defined method object is created by retrieving\na user-defined function object from a class, its im_self\nattribute is `None` and the method object is said to be unbound.\nWhen one is created by retrieving a user-defined function object\nfrom a class via one of its instances, its im_self attribute\nis the instance, and the method object is said to be bound.\nIn either case, the new method's im_class attribute\nis the class from which the retrieval takes place, and\nits im_func attribute is the original function object.\nWhen a user-defined method object is created by retrieving another\nmethod object from a class or instance, the behaviour is the same\nas for a function object, except that the im_func attribute\nof the new instance is not the original method object but its\nim_func attribute.\nWhen a user-defined method object is created by retrieving a\nclass method object from a class or instance, its im_self\nattribute is the class itself (the same as the im_class\nattribute), and its im_func attribute is the function\nobject underlying the class method.\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)`.\nWhen a user-defined method object is derived from a class method object,\nthe ``class instance'' stored in im_self will actually be the\nclass itself, so that calling either `x.f(1)` or `C.f(1)` is\nequivalent to calling `f(C,1)` where `f` is the underlying\nfunction.\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); __module__ is the name of the module the\nfunction was defined in or `None` if unavailable.\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`alist .append()`, assuming\nalist is a list object.\nIn this case, the special read-only attribute __self__ is set\nto the object denoted by list.\nClass Types: Class types, or ``new-style classes,'' are callable. These objects\nnormally act as factories for new instances of themselves, but\nvariations are possible for class types that override\n__new__(). The arguments of the call are passed to\n__new__() and, in the typical case, to __init__() to\ninitialize the new instance.\nClassic Classes: 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\nsection 6.12 (import.html#import), ``The import statement'').A 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\nsection 7.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 (for class C, say)\nwould yield a user-defined function object or\nan unbound user-defined method object whose associated class is either\nC or one of its base classes, it is transformed into an unbound\nuser-defined method object whose im_class attribute is C.\nWhen it would yield a class method object, it is transformed into\na bound user-defined method object whose im_class and\nim_self attributes are both C. When it would yield\na static method object, it is transformed into the object wrapped\nby the static method object. See section 3.3.2 (descriptors.html#descriptors) for another\nway in which attributes retrieved from a class may differ from those\nactually contained in its __dict__.\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 or an unbound\nuser-defined method object whose associated class is the class\n(call it C) of the instance for which the attribute reference\nwas initiated or one of its bases,\nit is transformed into a bound user-defined method object whose\nim_class attribute is C whose im_self attribute\nis the instance. Static method and class method objects are also\ntransformed, as if they had been retrieved from class C;\nsee above under ``Classes''. See section 3.3.2 (descriptors.html#descriptors) for\nanother way in which attributes of a class retrieved via its\ninstances may differ from the objects actually stored in the\nclass's __dict__.\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 file object 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 free variables; co_code is a string representing the\nsequence 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 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; bit `0x20` is set if the\nfunction is a generator.\nFuture feature declarations (\"from __future__ import division\")\nalso use bits in co_flags to indicate whether a code object\nwas compiled with a particular feature enabled: bit `0x2000` is\nset if the function was compiled with future division enabled; bits\n`0x10` and `0x1000` were used in earlier versions of Python.\nOther bits in co_flags are reserved for internal use.\nIfa code object represents a function,\nthe 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; 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; f_lineno is the current line number of the frame\n-- writing to this from within a trace function jumps to the given line\n(only for the bottom-most frame). A debugger can implement a Jump\ncommand (aka Set Next Statement) by writing to f_lineno.\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.\nSlice objects support one method:\nStatic method objects: Static method objects provide a way of defeating the transformation\nof function objects to method objects described above. A static method\nobject is a wrapper around any other object, usually a user-defined\nmethod object. When a static method object is retrieved from a class\nor a class instance, the object actually returned is the wrapped object,\nwhich is not subject to any further transformation. Static method\nobjects are not themselves callable, although the objects they\nwrap usually are. Static method objects are created by the built-in\nstaticmethod() constructor.\nClass method objects: A class method object, like a static method object, is a wrapper\naround another object that alters the way in which that object\nis retrieved from classes and class instances. The behaviour of\nclass method objects upon such retrieval is described above,\nunder ``User-defined methods''. Class method objects are created\nby the built-in classmethod() constructor.", "python_version": "2.3", "length": 29272, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/types.html"} {"title": "5.5 Unary arithmetic operations", "text": "power.html | expressions.html | binary.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n5.4 The power operator (power.html)\nUp:\n5. Expressions (expressions.html)\nNext:\n5.6 Binary arithmetic operations (binary.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.3", "length": 895, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/unary.html"} {"title": "7.2 The while statement", "text": "if.html | compound.html | for.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n7.1 The if statement (if.html)\nUp:\n7. Compound statements (compound.html)\nNext:\n7.3 The for statement (for.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`\n`[\"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.3", "length": 910, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/while.html"} {"title": "2.1.9 Whitespace between tokens", "text": "indentation.html | line-structure.html | other-tokens.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n2.1.8 Indentation (indentation.html)\nUp:\n2.1 Line structure (line-structure.html)\nNext:\n2.2 Other tokens (other-tokens.html)\n---\n## 2.1.9 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.3", "length": 621, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/whitespace.html"} {"title": "6.8 The yield statement", "text": "return.html | simple.html | raise.html | Python Reference Manual | contents.html | genindex.html\nPrevious:\n6.7 The return statement (return.html)\nUp:\n6. Simple statements (simple.html)\nNext:\n6.9 The raise statement (raise.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.3", "length": 1882, "url": "https://docs.python.org/2.3/Python-Docs-2.3/ref/yield.html"} {"title": "About this document ...", "text": "node15.html | tut.html | Python Tutorial | node2.html\nPrevious:\nC. History and License (node15.html)\nUp:\nPython Tutorial (tut.html)\n---\n# About this document ...\nPython Tutorial,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1637, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/about.html"} {"title": "Python Tutorial", "text": "../index.html | node1.html | Python Tutorial | node2.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (node1.html)\n---\n# Python Tutorial\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 269, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/index.html"} {"title": "Front Matter", "text": "tut.html | tut.html | node2.html | Python Tutorial | node2.html\nPrevious:\nPython Tutorial (tut.html)\nUp:\nPython Tutorial (tut.html)\nNext:\nContents (node2.html)\n---\n# Front Matter\nCopyright © 2001, 2002, 2003 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.3", "length": 2651, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node1.html"} {"title": "8. Errors and Exceptions", "text": "node9.html | tut.html | node11.html | Python Tutorial | node2.html\nPrevious:\n7. Input and Output (node9.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n9. Classes (node11.html)\n---\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---\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 True print 'Hello world'\nFile \"\", line 1, in ?\nwhile True 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 by zero\n>>> 4 + spam*3\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nNameError: name 'spam' is not defined\n>>> '2' + 2\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nTypeError: cannot concatenate 'str' and 'int' objects\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 True:\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.\nThe except clause may specify a variable after the exception name (or list).\nThe variable is bound to an exception instance with the arguments stored\nin `instance.args`. For convenience, the exception instance\ndefines __getitem__ and __str__ so the arguments can\nbe accessed or printed directly without having to reference `.args`.\n```text\n\n>>> try:\n... raise Exception('spam', 'eggs')\n... except Exception, inst:\n... print type(inst) # the exception instance\n... print inst.args # arguments stored in .args\n... print inst # __str__ allows args to printed directly\n... x, y = inst # __getitem__ allows args to be unpacked directly\n... print 'x =', x\n... print 'y =', y\n...\n\n('spam', 'eggs')\n('spam', 'eggs')\nx = spam\ny = eggs\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 repr(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.3", "length": 11616, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node10.html"} {"title": "9. Classes", "text": "node10.html | tut.html | node12.html | Python Tutorial | node2.html\nPrevious:\n8. Errors and Exceptions (node10.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n10. What Now? (node12.html)\n---\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.8 Exceptions Are Classes Too (node11.html#SECTION0011800000000000000000)\n 9.9 Iterators (node11.html#SECTION0011900000000000000000)\n 9.10 Generators (node11.html#SECTION00111000000000000000000)\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\neliminates 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 (#foot1513)\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, there are at least three nested scopes whose\nnamespaces are directly accessible: the innermost scope, which is searched\nfirst, contains the local names; the namespaces of any enclosing\nfunctions, which are searched starting with the nearest enclosing scope;\nthe middle scope, searched next, contains the current module's global names;\nand the outermost scope (searched last) is the namespace containing built-in\nnames.\nIf a name is declared global, then all references and assignments go\ndirectly to the middle scope containing the module's global names.\nOtherwise, all variables found outside of the innermost scope are read-only.\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 True:\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.\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.8 Exceptions Are Classes Too\nUser-defined exceptions are identified by classes as well. Using this\nmechanism it is 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```\nA class in 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().\n# 9.9 Iterators\nBy now, you've probably noticed that most container objects can looped over\nusing a `for` statement:\n```text\n\nfor element in [1, 2, 3]:\nprint element\nfor element in (1, 2, 3):\nprint element\nfor key in {'one':1, 'two':2}:\nprint key\nfor char in \"123\":\nprint char\nfor line in open(\"myfile.txt\"):\nprint line\n```\nThis style of access is clear, concise, and convenient. The use of iterators\npervades and unifies Python. Behind the scenes, the `for` statement calls\niter() on the container object. The function returns an iterator\nobject that defines the method next() which accesses elements in the\ncontainer one at a time. When there are no more elements, next()\nraises a StopIteration exception which tells the `for` loop\nto terminate. This example shows how it all works:\n```text\n\n>>> s = 'abc'\n>>> it = iter(s)\n>>> it\n\n>>> it.next()\n'a'\n>>> it.next()\n'b'\n>>> it.next()\n'c'\n>>> it.next()\n\nTraceback (most recent call last):\nFile \"\", line 1, in -toplevel-\nit.next()\nStopIteration\n```\nHaving seen the mechanics behind the iterator protocol, it is easy to add\niterator behavior to your classes. Define a __iter__() method\nwhich returns an object with a next() method. If the class defines\nnext(), then __iter__() can just return `self`:\n```text\n\n>>> class Reverse:\n\"Iterator for looping over a sequence backwards\"\ndef __init__(self, data):\nself.data = data\nself.index = len(data)\ndef __iter__(self):\nreturn self\ndef next(self):\nif self.index == 0:\nraise StopIteration\nself.index = self.index - 1\nreturn self.data[self.index]\n\n>>> for char in Reverse('spam'):\nprint char\n\nm\na\np\ns\n```\n# 9.10 Generators\nGenerators are a simple and powerful tool for creating iterators. They are\nwritten like regular functions but use the yield statement whenever\nthey want to return data. Each time the next() is called, the\ngenerator resumes where it left-off (it remembers all the data values and\nwhich statement was last executed). An example shows that generators can\nbe trivially easy to create:\n```text\n\n>>> def reverse(data):\nfor index in range(len(data)-1, -1, -1):\nyield data[index]\n\n>>> for char in reverse('golf'):\nprint char\n\nf\nl\no\ng\n```\nAnything that can be done with generators can also be done with class based\niterators as described in the previous section. What makes generators so\ncompact is that the __iter__() and next() methods are\ncreated automatically.\nAnother key feature is that the local variables and execution state\nare automatically saved between calls. This made the function easier to write\nand much more clear than an approach using class variables like\n`self.index` and `self.data`.\nIn addition to automatic method creation and saving program state, when\ngenerators terminate, they automatically raise StopIteration.\nIn combination, these features make it easy to create iterators with no\nmore effort than writing a regular function.", "python_version": "2.3", "length": 30723, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node11.html"} {"title": "10. What Now?", "text": "node11.html | tut.html | node13.html | Python Tutorial | node2.html\nPrevious:\n9. Classes (node11.html)\nUp:\nPython Tutorial (tut.html)\nNext:\nA. Interactive Input Editing (node13.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. Many more user-created Python modules\ncan be found in a third-party repository at\nhttp://www.vex.net/parnassus.\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 (with peaks\nup to several hundred),\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.3", "length": 2413, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node12.html"} {"title": "A. Interactive Input Editing and History Substitution", "text": "node12.html | tut.html | node14.html | Python Tutorial | node2.html\nPrevious:\n10. What Now? (node12.html)\nUp:\nPython Tutorial (tut.html)\nNext:\nB. Floating Point Arithmetic: (node14.html)\n---\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---\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 (#foot1534)\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: \"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.3", "length": 5929, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node13.html"} {"title": "B. Floating Point Arithmetic: Issues and Limitations", "text": "node13.html | tut.html | node15.html | Python Tutorial | node2.html\nPrevious:\nA. Interactive Input Editing (node13.html)\nUp:\nPython Tutorial (tut.html)\nNext:\nC. History and License (node15.html)\n---\n- B.1 Representation Error (node14.html#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.3", "length": 8098, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node14.html"} {"title": "C. History and License", "text": "node14.html | tut.html | node16.html | Python Tutorial | node2.html\nPrevious:\nB. Floating Point Arithmetic: (node14.html)\nUp:\nPython Tutorial (tut.html)\nNext:\nAbout this document ... (node16.html)\n---\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---\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 Digital Creations (now Zope\nCorporation; 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. Zope Corporation 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.3\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(``PSF''), and the Individual or Organization (``Licensee'') accessing\nand otherwise using Python 2.3 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.3 alone or in any derivative version, provided, however, that\nPSF's License Agreement and PSF's notice of copyright, i.e.,\n``Copyright © 2001-2003 Python Software Foundation; All\nRights Reserved'' are retained in Python 2.3 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.3 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.3.\n4. PSF is making Python 2.3 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.3 WILL\nNOT INFRINGE ANY THIRD PARTY RIGHTS.\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR\nLOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON\n2.3, 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.3, 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.3", "length": 11744, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node15.html"} {"title": "About this document ...", "text": "node15.html | tut.html | Python Tutorial | node2.html\nPrevious:\nC. History and License (node15.html)\nUp:\nPython Tutorial (tut.html)\n---\n# About this document ...\nPython Tutorial,\nJuly 29, 2003, Release 2.3\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, either in the content or the presentation, please\nreport 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.", "python_version": "2.3", "length": 1637, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node16.html"} {"title": "Contents", "text": "node1.html | tut.html | node3.html | Python Tutorial\nPrevious:\nFront Matter (node1.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n1. Whetting Your Appetite (node3.html)\n---\n## Contents\nTable of Contents\n- Front Matter (node1.html)\n 1. Whetting Your Appetite (node3.html)\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 Source Code Encoding (node4.html#SECTION004230000000000000000)\n 2.2.4 The Interactive Startup File (node4.html#SECTION004240000000000000000)\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 Looping Techniques (node7.html#SECTION007500000000000000000)\n 5.6 More on Conditions (node7.html#SECTION007600000000000000000)\n 5.7 Comparing Sequences and Other Types (node7.html#SECTION007700000000000000000)\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 6.4.3 Packages in Multiple Directories (node8.html#SECTION008430000000000000000)\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.8 Exceptions Are Classes Too (node11.html#SECTION0011800000000000000000)\n 9.9 Iterators (node11.html#SECTION0011900000000000000000)\n 9.10 Generators (node11.html#SECTION00111000000000000000000)\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.3", "length": 6384, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node2.html"} {"title": "1. Whetting Your Appetite", "text": "node2.html | tut.html | node4.html | Python Tutorial | node2.html\nPrevious:\nContents (node2.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n2. Using the Python (node4.html)\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!\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.3", "length": 4273, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node3.html"} {"title": "2. Using the Python Interpreter", "text": "node3.html | tut.html | node5.html | Python Tutorial | node2.html\nPrevious:\n1. Whetting Your Appetite (node3.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n3. An Informal Introduction (node5.html)\n---\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 Source Code Encoding (node4.html#SECTION004230000000000000000)\n 2.2.4 The Interactive Startup File (node4.html#SECTION004240000000000000000)\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 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\ntry 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 (#foot107)Typing an interrupt while a command is executing raises the\nKeyboardInterrupt exception, which may be handled by a\ntry 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. On some\nplatforms, this first line must end with a Unix-style line ending\n(\"\\n\"), not a Mac OS (\"\\r\") or Windows\n(\"\\r\\n\") line ending. Note that\nthe hash, or pound, character, \"#\", is used to start a\ncomment in Python.\nThe script can be given a executable mode, or permission, using the\nchmod command:\n```text\n\n$ chmod +x myscript.py\n```\n## 2.2.3 Source Code Encoding\nIt is possible to use encodings different than ASCII in Python source\nfiles. The best way to do it is to put one more special comment line\nright after the `#!` line to define the source file encoding:\n```text\n\n# -*- coding: iso-8859-1 -*-\n```\nWith that declaration, all characters in the source file will be treated as\n`iso-8859-1`, and it will be\npossible to directly write Unicode string literals in the selected\nencoding. The list of possible encodings can be found in the\nPython Library Reference (../lib/lib.html), in the section\non codecs.\nIf your editor supports saving files as `UTF-8` with an UTF-8\nsignature (aka BOM - Byte Order Mark), you can use that instead of an\nencoding declaration. IDLE supports this capability if\n`Options/General/Default Source Encoding/UTF-8` is set. Notice\nthat this signature is not understood in older Python releases (2.2\nand earlier), and also not understood by the operating system for\n`#!` files.\nBy using UTF-8 (either through the signature or an encoding\ndeclaration), characters of most languages in the world can be used\nsimultaneously in string literals and comments. Using non-ASCII\ncharacters in identifiers is not supported. To display all these\ncharacters properly, your editor must recognize that the file is\nUTF-8, and it must use a font that supports all the characters in the\nfile.\n## 2.2.4 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.3", "length": 9401, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node4.html"} {"title": "3. An Informal Introduction to Python", "text": "node4.html | tut.html | node6.html | Python Tutorial | node2.html\nPrevious:\n2. Using the Python (node4.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n4. More Control Flow (node6.html)\n---\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---\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```\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```\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```\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 ?\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: 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.3", "length": 18966, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node5.html"} {"title": "4. More Control Flow Tools", "text": "node5.html | tut.html | node7.html | Python Tutorial | node2.html\nPrevious:\n3. An Informal Introduction (node5.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n5. Data Structures (node7.html)\n---\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\n 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---\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 for statement 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\nfor statement 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 True:\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 (#foot1448) 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 True:\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, dictionary, or instances of most classes. For example, the\nfollowing function accumulates the arguments passed to it on\nsubsequent 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: function() got multiple values for keyword argument 'a'\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\nkeys = keywords.keys()\nkeys.sort()\nfor kw in 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```\nNote that the sort() method of the list of keyword argument\nnames is called before printing the contents of the `keywords`\ndictionary; if this is not done, the order in which the arguments are\nprinted is undefined.\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.3", "length": 16556, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node6.html"} {"title": "5. Data Structures", "text": "node6.html | tut.html | node8.html | Python Tutorial | node2.html\nPrevious:\n4. More Control Flow (node6.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n6. Modules (node8.html)\n---\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 Looping Techniques (node7.html#SECTION007500000000000000000)\n 5.6 More on Conditions (node7.html#SECTION007600000000000000000)\n 5.7 Comparing Sequences and Other Types (node7.html#SECTION007700000000000000000)\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:\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```\nDon't use this example's definition of sum(): since summing\nnumbers is such a common need, a built-in function\n`sum( sequence )` is already provided, and works exactly like\nthis.\nNew in version 2.3.\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\nfollowed 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] # 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```\nTo make list comprehensions match the behavior of for\nloops, assignments to the loop variable remain visible outside\nof the comprehension:\n```text\n\n>>> x = 100 # this gets overwritten\n>>> [x**3 for x in range(5)]\n[0, 1, 8, 27, 64]\n>>> x # the final value for range(5)\n4\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 = [-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')\nTrue\n```\nThe dict() contructor builds dictionaries directly from\nlists of key-value pairs stored as tuples. When the pairs form a\npattern, list comprehensions can compactly specify the key-value list.\n```text\n\n>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])\n{'sape': 4139, 'jack': 4098, 'guido': 4127}\n>>> dict([(x, x**2) for x in vec]) # use a list comprehension\n{2: 4, 4: 16, 6: 36}\n```\n# 5.5 Looping Techniques\nWhen looping through dictionaries, the key and corresponding value can\nbe retrieved at the same time using the items() method.\n```text\n\n>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}\n>>> for k, v in knights.items():\n... print k, v\n...\ngallahad the pure\nrobin the brave\n```\nWhen looping through a sequence, the position index and corresponding\nvalue can be retrieved at the same time using the\nenumerate() function.\n```text\n\n>>> for i, v in enumerate(['tic', 'tac', 'toe']):\n... print i, v\n...\n0 tic\n1 tac\n2 toe\n```\nTo loop over two or more sequences at the same time, the entries\ncan be paired with the zip() function.\n```text\n\n>>> questions = ['name', 'quest', 'favorite color']\n>>> answers = ['lancelot', 'the holy grail', 'blue']\n>>> for q, a in zip(questions, answers):\n... print 'What is your %s? It is %s.' % (q, a)\n...\nWhat is your name? It is lancelot.\nWhat is your quest? It is the holy grail.\nWhat is your favorite color? It is blue.\n```\n# 5.6 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\nshort-circuit operators: their arguments are evaluated from\nleft to right, and evaluation stops as soon as the outcome is\ndetermined. For example, if `A` and `C` are true but\n`B` is false, `A and B and C` does not evaluate the\nexpression `C`. In general, the return value of a short-circuit\noperator, when used as a general value and not as a Boolean, is the\nlast 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.7 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 (#foot677)", "python_version": "2.3", "length": 16449, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node7.html"} {"title": "6. Modules", "text": "node7.html | tut.html | node9.html | Python Tutorial | node2.html\nPrevious:\n5. Data Structures (node7.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n7. Input and Output (node9.html)\n---\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 6.4.3 Packages in Multiple Directories (node8.html#SECTION008430000000000000000)\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 (#foot698)\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. The\noptimizer currently doesn't help much; it only removes\nassert statements. When -O is used, all\nbytecode is optimized; `.pyc` files are ignored and `.py`\nfiles are compiled to optimized 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', 'api_version', 'argv',\n'builtin_module_names', 'byteorder', 'callstats', 'copyright',\n'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',\n'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',\n'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',\n'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',\n'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',\n'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',\n'version', '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', 'False', 'FloatingPointError', 'IOError', 'ImportError',\n'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',\n'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',\n'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',\n'PendingDeprecationWarning', 'ReferenceError',\n'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',\n'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',\n'True', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning',\n'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__',\n'__import__', '__name__', 'abs', 'apply', 'bool', 'buffer',\n'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex',\n'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',\n'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',\n'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',\n'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',\n'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',\n'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit',\n'range', 'raw_input', 'reduce', 'reload', 'repr', 'round',\n'setattr', 'slice', 'staticmethod', 'str', 'string', 'sum', 'super',\n'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', '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```\nWhen importing the package, Python searchs through the directories\non `sys.path` looking for the package subdirectory.\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 practice 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`.\n## 6.4.3 Packages in Multiple Directories\nPackages support one more special attribute, __path__. This\nis initialized to be a list containing the name of the directory\nholding the package's __init__.py before the code in that file\nis executed. This variable can be modified; doing so affects future\nsearches for modules and subpackages contained in the package.\nWhile this feature is not often needed, it can be used to extend the\nset of modules found in a package.", "python_version": "2.3", "length": 20544, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node8.html"} {"title": "7. Input and Output", "text": "node8.html | tut.html | node10.html | Python Tutorial | node2.html\nPrevious:\n6. Modules (node8.html)\nUp:\nPython Tutorial (tut.html)\nNext:\n8. Errors and Exceptions (node10.html)\n---\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---\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. Reverse quotes\n(````) are equivalent to repr(), but their use is\ndiscouraged.\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>>> repr(s)\n\"'Hello, world.'\"\n>>> str(0.1)\n'0.1'\n>>> repr(0.1)\n'0.10000000000000001'\n>>> x = 10 * 3.25\n>>> y = 200 * 200\n>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'\n>>> print s\nThe value of x is 32.5, and y is 40000...\n>>> # The repr() of a string adds string quotes and backslashes:\n... hello = 'hello, world\\n'\n>>> hellos = repr(hello)\n>>> print hellos\n'hello, world\\n'\n>>> # The argument to repr() may be any Python object:\n... repr((x, y, ('spam', 'eggs')))\n\"(32.5, 40000, ('spam', 'eggs'))\"\n>>> # reverse quotes are convenient in interactive sessions:\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(repr(x), 2), string.rjust(repr(x*x), 3),\n... # Note trailing comma on previous line\n... print string.rjust(repr(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.3", "length": 12675, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/node9.html"} {"title": "Python Tutorial", "text": "../index.html | node1.html | Python Tutorial | node2.html\nUp:\nPython Documentation Index (../index.html)\nNext:\nFront Matter (node1.html)\n---\n# Python Tutorial\nGuido van Rossum\nFred L. Drake, Jr., editor\nPythonLabs\nEmail: python-docs@python.org\nRelease 2.3\nJuly 29, 2003", "python_version": "2.3", "length": 269, "url": "https://docs.python.org/2.3/Python-Docs-2.3/tut/tut.html"} {"title": "About this document ...", "text": "acks.html | whatsnew23.html | What's New in Python 2.3 | contents.html\nPrevious:\n22 Acknowledgements (acks.html)\nUp:\nWhat's New in Python (whatsnew23.html)\n---\n# About this document ...\nWhat's New in Python 2.3\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, either in the content or the presentation, please\nreport 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---\nacks.html | whatsnew23.html | What's New in Python 2.3 | contents.html\nPrevious:\n22 Acknowledgements (acks.html)\nUp:\nWhat's New in Python (whatsnew23.html)\n---\nRelease 1.00.", "python_version": "2.3", "length": 1820, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/about.html"} {"title": "22 Acknowledgements", "text": "node22.html | whatsnew23.html | about.html | What's New in Python 2.3 | contents.html\nPrevious:\n21 Porting to Python (node22.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\nAbout this document ... (about.html)\n---\n# 22 Acknowledgements\nThe author would like to thank the following people for offering\nsuggestions, corrections and assistance with various drafts of this\narticle: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside,\nAndrew Dalke, Scott David Daniels, Fred L. Drake, Jr., Kelly Gerber,\nRaymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert,\nMartin von Löwis, Andrew MacIntyre, Lalo Martins, Chad Netzer,\nGustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco\nRicciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler,\nJust van Rossum.", "python_version": "2.3", "length": 796, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/acks.html"} {"title": "Contents", "text": "whatsnew23.html | whatsnew23.html | node2.html | What's New in Python 2.3\nPrevious:\nWhat's New in Python (whatsnew23.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n1 PEP 218: A (node2.html)\n---\n## Contents\nTable of Contents\n- 1 PEP 218: A Standard Set Datatype (node2.html)\n 2 PEP 255: Simple Generators (section-generators.html)\n 3 PEP 263: Source Code Encodings (section-encodings.html)\n 4 PEP 273: Importing Modules from Zip Archives (node5.html)\n 5 PEP 277: Unicode file name support for Windows NT (node6.html)\n 6 PEP 278: Universal Newline Support (node7.html)\n 7 PEP 279: enumerate() (section-enumerate.html)\n 8 PEP 282: The logging Package (node9.html)\n 9 PEP 285: A Boolean Type (section-bool.html)\n 10 PEP 293: Codec Error Handling Callbacks (node11.html)\n 11 PEP 301: Package Index and Metadata for\n Distutils (section-pep301.html)\n 12 PEP 302: New Import Hooks (section-pep302.html)\n 13 PEP 305: Comma-separated Files (node14.html)\n 14 PEP 307: Pickle Enhancements (section-pep305.html)\n 15 Extended Slices (section-slices.html)\n 16 Other Language Changes (node17.html)\n - 16.1 String Changes (node17.html#SECTION0001710000000000000000)\n 16.2 Optimizations (node17.html#SECTION0001720000000000000000)\n 17 New, Improved, and Deprecated Modules (node18.html)\n - 17.1 Date/Time Type (node18.html#SECTION0001810000000000000000)\n 17.2 The optparse Module (node18.html#SECTION0001820000000000000000)\n 18 Pymalloc: A Specialized Object Allocator (section-pymalloc.html)\n 19 Build and C API Changes (node20.html)\n - 19.1 Port-Specific Changes (node20.html#SECTION0002010000000000000000)\n 20 Other Changes and Fixes (section-other.html)\n 21 Porting to Python 2.3 (node22.html)\n 22 Acknowledgements (acks.html)\n About this document ... (about.html)\nEnd of Table of Contents\nThis article explains the new features in Python 2.3. Python 2.3 was\nreleased on July 29, 2003.\nThe main themes for Python 2.3 are polishing some of the features\nadded in 2.2, adding various small but useful enhancements to the core\nlanguage, and expanding the standard library. The new object model\nintroduced in the previous version has benefited from 18 months of\nbugfixes and from optimization efforts that have improved the\nperformance of new-style classes. A few new built-in functions have\nbeen added such as sum() and enumerate(). The\nin operator can now be used for substring searches (e.g.\n`\"ab\" in \"abc\"` returns True).\nSome of the many new library features include Boolean, set, heap, and\ndate/time data types, the ability to import modules from ZIP-format\narchives, metadata support for the long-awaited Python catalog, an\nupdated version of IDLE, and modules for logging messages, wrapping\ntext, parsing CSV files, processing command-line options, using BerkeleyDB\ndatabases... the list of new and enhanced modules is lengthy.\nThis article doesn't attempt to provide a complete specification of\nthe new features, but instead provides a convenient overview. For\nfull details, you should refer to the documentation for Python 2.3,\nsuch as the Python Library Reference (../lib/lib.html) and\nthe Python Reference Manual (../ref/ref.html). If you want\nto understand the complete implementation and design rationale,\nrefer to the PEP for a particular new feature.", "python_version": "2.3", "length": 3283, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/contents.html"} {"title": "What's New in Python 2.3", "text": "../index.html | contents.html | What's New in Python 2.3 | contents.html\nUp:\nPython Documentation Index (../index.html)\nNext:\n---\n# What's New in Python 2.3\nA.M. Kuchling\namk@amk.ca", "python_version": "2.3", "length": 181, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/index.html"} {"title": "10 PEP 293: Codec Error Handling Callbacks", "text": "section-bool.html | whatsnew23.html | section-pep301.html | What's New in Python 2.3 | contents.html\nPrevious:\n9 PEP 285: A (section-bool.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n11 PEP 301: Package (section-pep301.html)\n---\n# 10 PEP 293: Codec Error Handling Callbacks\nWhen encoding a Unicode string into a byte string, unencodable\ncharacters may be encountered. So far, Python has allowed specifying\nthe error processing as either ``strict'' (raising\nUnicodeError), ``ignore'' (skipping the character), or\n``replace'' (using a question mark in the output string), with\n``strict'' being the default behavior. It may be desirable to specify\nalternative processing of such errors, such as inserting an XML\ncharacter reference or HTML entity reference into the converted\nstring.\nPython now has a flexible framework to add different processing\nstrategies. New error handlers can be added with\ncodecs.register_error, and codecs then can access the error\nhandler with codecs.lookup_error. An equivalent C API has\nbeen added for codecs written in C. The error handler gets the\nnecessary state information such as the string being converted, the\nposition in the string where the error was detected, and the target\nencoding. The handler can then either raise an exception or return a\nreplacement string.\nTwo additional error handlers have been implemented using this\nframework: ``backslashreplace'' uses Python backslash quoting to\nrepresent unencodable characters and ``xmlcharrefreplace'' emits\nXML character references.\nSee Also:", "python_version": "2.3", "length": 1538, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node11.html"} {"title": "13 PEP 305: Comma-separated Files", "text": "section-pep302.html | whatsnew23.html | section-pep305.html | What's New in Python 2.3 | contents.html\nPrevious:\n12 PEP 302: New (section-pep302.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n14 PEP 307: Pickle (section-pep305.html)\n---\n# 13 PEP 305: Comma-separated Files\nComma-separated files are a format frequently used for exporting data\nfrom databases and spreadsheets. Python 2.3 adds a parser for\ncomma-separated files.\nComma-separated format is deceptively simple at first glance:\n```text\n\nCosts,150,200,3.95\n```\nRead a line and call `line.split(',')`: what could be simpler?\nBut toss in string data that can contain commas, and things get more\ncomplicated:\n```text\n\n\"Costs\",150,200,3.95,\"Includes taxes, shipping, and sundry items\"\n```\nA big ugly regular expression can parse this, but using the new\ncsv package is much simpler:\n```text\n\nimport csv\n\ninput = open('datafile', 'rb')\nreader = csv.reader(input)\nfor line in reader:\nprint line\n```\nThe reader function takes a number of different options.\nThe field separator isn't limited to the comma and can be changed to\nany character, and so can the quoting and line-ending characters.\nDifferent dialects of comma-separated files can be defined and\nregistered; currently there are two dialects, both used by Microsoft Excel.\nA separate csv.writer class will generate comma-separated files\nfrom a succession of tuples or lists, quoting strings that contain the\ndelimiter.\nSee Also:", "python_version": "2.3", "length": 1447, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node14.html"} {"title": "16 Other Language Changes", "text": "section-slices.html | whatsnew23.html | node18.html | What's New in Python 2.3 | contents.html\nPrevious:\n15 Extended Slices (section-slices.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n17 New, Improved, and (node18.html)\n---\n- 16.1 String Changes (node17.html#SECTION0001710000000000000000)\n 16.2 Optimizations (node17.html#SECTION0001720000000000000000)\n---\n# 16 Other Language Changes\nHere are all of the changes that Python 2.3 makes to the core Python\nlanguage.\n- The yield statement is now always a keyword, as\ndescribed in section 2 (section-generators.html#section-generators) of this document.\n- A new built-in function enumerate()\nwas added, as described in section 7 (section-enumerate.html#section-enumerate) of this\ndocument.\n- Two new constants, True and False were\nadded along with the built-in bool type, as described in\nsection 9 (section-bool.html#section-bool) of this document.\n- The int() type constructor will now return a long\ninteger instead of raising an OverflowError when a string\nor floating-point number is too large to fit into an integer. This\ncan lead to the paradoxical result that\n`isinstance(int( expression ), int)` is false, but that seems\nunlikely to cause problems in practice.\n- Built-in types now support the extended slicing syntax,\nas described in section 15 (section-slices.html#section-slices) of this document.\n- A new built-in function, sum(iterable, start=0),\nadds up the numeric items in the iterable object and returns their sum.\nsum() only accepts numbers, meaning that you can't use it\nto concatenate a bunch of strings. (Contributed by Alex\nMartelli.)\n- `list.insert( pos , value )` used to\ninsert value at the front of the list when pos was\nnegative. The behaviour has now been changed to be consistent with\nslice indexing, so when pos is -1 the value will be inserted\nbefore the last element, and so forth.\n- `list.index( value )`, which searches for value\nwithin the list and returns its index, now takes optional\nstart and stop arguments to limit the search to\nonly part of the list.\n- Dictionaries have a new method, pop(key[,\ndefault]), that returns the value corresponding to key\nand removes that key/value pair from the dictionary. If the requested\nkey isn't present in the dictionary, default is returned if it's\nspecified and KeyError raised if it isn't.\n```text\n\n>>> d = {1:2}\n>>> d\n{1: 2}\n>>> d.pop(4)\nTraceback (most recent call last):\nFile \"stdin\", line 1, in ?\nKeyError: 4\n>>> d.pop(1)\n2\n>>> d.pop(1)\nTraceback (most recent call last):\nFile \"stdin\", line 1, in ?\nKeyError: 'pop(): dictionary is empty'\n>>> d\n{}\n>>>\n```\nThere's also a new class method,\ndict.fromkeys(iterable, value), that\ncreates a dictionary with keys taken from the supplied iterator\niterable and all values set to value, defaulting to\n`None`.\n(Patches contributed by Raymond Hettinger.)\nAlso, the dict() constructor now accepts keyword arguments to\nsimplify creating small dictionaries:\n```text\n\n>>> dict(red=1, blue=2, green=3, black=4)\n{'blue': 2, 'black': 4, 'green': 3, 'red': 1}\n```\n(Contributed by Just van Rossum.)\n- The assert statement no longer checks the `__debug__`\nflag, so you can no longer disable assertions by assigning to `__debug__`.\nRunning Python with the -O switch will still generate\ncode that doesn't execute any assertions.\n- Most type objects are now callable, so you can use them\nto create new objects such as functions, classes, and modules. (This\nmeans that the new module can be deprecated in a future\nPython version, because you can now use the type objects available in\nthe types module.)\nFor example, you can create a new module object with the following code:\n```text\n\n>>> import types\n>>> m = types.ModuleType('abc','docstring')\n>>> m\n\n>>> m.__doc__\n'docstring'\n```\n- A new warning, PendingDeprecationWarning was added to\nindicate features which are in the process of being\ndeprecated. The warning will not be printed by default. To\ncheck for use of features that will be deprecated in the future,\nsupply -Walways::PendingDeprecationWarning:: on the\ncommand line or use warnings.filterwarnings().\n- The process of deprecating string-based exceptions, as\nin `raise \"Error occurred\"`, has begun. Raising a string will\nnow trigger PendingDeprecationWarning.\n- Using `None` as a variable name will now result in a\nSyntaxWarning warning. In a future version of Python,\n`None` may finally become a keyword.\n- The xreadlines() method of file objects, introduced in\nPython 2.1, is no longer necessary because files now behave as their\nown iterator. xreadlines() was originally introduced as a\nfaster way to loop over all the lines in a file, but now you can\nsimply write `for line in file_obj`. File objects also have a\nnew read-only encoding attribute that gives the encoding used\nby the file; Unicode strings written to the file will be automatically\nconverted to bytes using the given encoding.\n- The method resolution order used by new-style classes has\nchanged, though you'll only notice the difference if you have a really\ncomplicated inheritance hierarchy. Classic classes are unaffected by\nthis change. Python 2.2 originally used a topological sort of a\nclass's ancestors, but 2.3 now uses the C3 algorithm as described in\nthe paper ``A Monotonic Superclass Linearization for\nDylan'' (http://www.webcom.com/haahr/dylan/linearization-oopsla96.html).\nTo understand the motivation for this change,\nread Michele Simionato's article\n``Python 2.3 Method Resolution Order'' (http://www.python.org/2.3/mro.html), or\nread the thread on python-dev starting with the message at\nhttp://mail.python.org/pipermail/python-dev/2002-October/029035.html.\nSamuele Pedroni first pointed out the problem and also implemented the\nfix by coding the C3 algorithm.\n- Python runs multithreaded programs by switching between threads\nafter executing N bytecodes. The default value for N has been\nincreased from 10 to 100 bytecodes, speeding up single-threaded\napplications by reducing the switching overhead. Some multithreaded\napplications may suffer slower response time, but that's easily fixed\nby setting the limit back to a lower number using\nsys.setcheckinterval(N).\nThe limit can be retrieved with the new\nsys.getcheckinterval() function.\n- One minor but far-reaching change is that the names of extension\ntypes defined by the modules included with Python now contain the\nmodule and a \".\" in front of the type name. For example, in\nPython 2.2, if you created a socket and printed its\n__class__, you'd get this output:\n```text\n\n>>> s = socket.socket()\n>>> s.__class__\n\n```\nIn 2.3, you get this:\n```text\n\n>>> s.__class__\n\n```\n- One of the noted incompatibilities between old- and new-style\nclasses has been removed: you can now assign to the\n__name__ and __bases__ attributes of new-style\nclasses. There are some restrictions on what can be assigned to\n__bases__ along the lines of those relating to assigning to\nan instance's __class__ attribute.\n## 16.1 String Changes\n- The in operator now works differently for strings.\nPreviously, when evaluating `X in Y` where X\nand Y are strings, X could only be a single character.\nThat's now changed; X can be a string of any length, and\n`X in Y` will return True if X is a\nsubstring of Y. If X is the empty string, the result is\nalways True.\n```text\n\n>>> 'ab' in 'abcd'\nTrue\n>>> 'ad' in 'abcd'\nFalse\n>>> '' in 'abcd'\nTrue\n```\nNote that this doesn't tell you where the substring starts; if you\nneed that information, use the find() string method.\n- The strip(), lstrip(), and rstrip()\nstring methods now have an optional argument for specifying the\ncharacters to strip. The default is still to remove all whitespace\ncharacters:\n```text\n\n>>> ' abc '.strip()\n'abc'\n>>> '><><><>'.strip('<>')\n'abc'\n>>> '><><><>\\n'.strip('<>')\n'abc<><><>\\n'\n>>> u'\\u4000\\u4001abc\\u4000'.strip(u'\\u4000')\nu'\\u4001abc'\n>>>\n```\n(Suggested by Simon Brunning and implemented by Walter Dörwald.)\n- The startswith() and endswith()\nstring methods now accept negative numbers for the start and end\nparameters.\n- Another new string method is zfill(), originally a\nfunction in the string module. zfill() pads a\nnumeric string with zeros on the left until it's the specified width.\nNote that the `%` operator is still more flexible and powerful\nthan zfill().\n```text\n\n>>> '45'.zfill(4)\n'0045'\n>>> '12345'.zfill(4)\n'12345'\n>>> 'goofy'.zfill(6)\n'0goofy'\n```\n(Contributed by Walter Dörwald.)\n- A new type object, basestring, has been added.\nBoth 8-bit strings and Unicode strings inherit from this type, so\n`isinstance(obj, basestring)` will return True for\neither kind of string. It's a completely abstract type, so you\ncan't create basestring instances.\n- Interned strings are no longer immortal and will now be\ngarbage-collected in the usual way when the only reference to them is\nfrom the internal dictionary of interned strings. (Implemented by\nOren Tirosh.)\n## 16.2 Optimizations\n- The creation of new-style class instances has been made much\nfaster; they're now faster than classic classes!\n- The sort() method of list objects has been extensively\nrewritten by Tim Peters, and the implementation is significantly\nfaster.\n- Multiplication of large long integers is now much faster thanks\nto an implementation of Karatsuba multiplication, an algorithm that\nscales better than the O(n*n) required for the grade-school\nmultiplication algorithm. (Original patch by Christopher A. Craig,\nand significantly reworked by Tim Peters.)\n- The `SET_LINENO` opcode is now gone. This may provide a\nsmall speed increase, depending on your compiler's idiosyncrasies.\nSee section 20 (section-other.html#section-other) for a longer explanation.\n(Removed by Michael Hudson.)\n- xrange() objects now have their own iterator, making\n`for i in xrange(n)` slightly faster than\n`for i in range(n)`. (Patch by Raymond Hettinger.)\n- A number of small rearrangements have been made in various\nhotspots to improve performance, such as inlining a function or removing\nsome code. (Implemented mostly by GvR, but lots of people have\ncontributed single changes.)\nThe net result of the 2.3 optimizations is that Python 2.3 runs the\npystone benchmark around 25% faster than Python 2.2.", "python_version": "2.3", "length": 10198, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node17.html"} {"title": "17 New, Improved, and Deprecated Modules", "text": "node17.html | whatsnew23.html | section-pymalloc.html | What's New in Python 2.3 | contents.html\nPrevious:\n16 Other Language Changes (node17.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n18 Pymalloc: A Specialized (section-pymalloc.html)\n---\n- 17.1 Date/Time Type (node18.html#SECTION0001810000000000000000)\n 17.2 The optparse Module (node18.html#SECTION0001820000000000000000)\n---\n# 17 New, Improved, and Deprecated Modules\nAs usual, Python's standard library received a number of enhancements and\nbug fixes. Here's a partial list of the most notable changes, sorted\nalphabetically by module name. Consult the\nMisc/NEWS file in the source tree for a more\ncomplete list of changes, or look through the CVS logs for all the\ndetails.\n- The array module now supports arrays of Unicode\ncharacters using the \"u\" format character. Arrays also now\nsupport using the `+=` assignment operator to add another array's\ncontents, and the `*=` assignment operator to repeat an array.\n(Contributed by Jason Orendorff.)\n- The bsddb module has been replaced by version 4.1.1\nof the PyBSDDB (http://pybsddb.sourceforge.net) package,\nproviding a more complete interface to the transactional features of\nthe BerkeleyDB library.\nThe old version of the module has been renamed to\nbsddb185 and is no longer built automatically; you'll\nhave to edit Modules/Setup to enable it. Note that the new\nbsddb package is intended to be compatible with the\nold module, so be sure to file bugs if you discover any\nincompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled\nwith a new version of\nthe underlying BerkeleyDB library, you will almost certainly have to\nconvert your database files to the new version. You can do this\nfairly easily with the new scripts db2pickle.py and\npickle2db.py which you will find in the distribution's\nTools/scripts directory. If you've already been using the PyBSDDB\npackage and importing it as bsddb3, you will have to change your\n`import` statements to import it as bsddb.\n- The new bz2 module is an interface to the bz2 data\ncompression library. bz2-compressed data is usually smaller than\ncorresponding zlib-compressed data. (Contributed by Gustavo Niemeyer.)\n- A set of standard date/type types has been added in the new datetime\nmodule. See the following section for more details.\n- The Distutils Extension class now supports\nan extra constructor argument named depends for listing\nadditional source files that an extension depends on. This lets\nDistutils recompile the module if any of the dependency files are\nmodified. For example, if sampmodule.c includes the header\nfile sample.h, you would create the Extension object like\nthis:\n```text\n\next = Extension(\"samp\",\nsources=[\"sampmodule.c\"],\ndepends=[\"sample.h\"])\n```\nModifying sample.h would then cause the module to be recompiled.\n(Contributed by Jeremy Hylton.)\n- Other minor changes to Distutils:\nit now checks for the CC, CFLAGS, CPP,\nLDFLAGS, and CPPFLAGS environment variables, using\nthem to override the settings in Python's configuration (contributed\nby Robert Weber).\n- Previously the doctest module would only search the\ndocstrings of public methods and functions for test cases, but it now\nalso examines private ones as well. The DocTestSuite(\nfunction creates a unittest.TestSuite object from a set of\ndoctest tests.\n- The new gc.get_referents(object) function returns a\nlist of all the objects referenced by object.\n- The getopt module gained a new function,\ngnu_getopt(), that supports the same arguments as the existing\ngetopt() function but uses GNU-style scanning mode.\nThe existing getopt() stops processing options as soon as a\nnon-option argument is encountered, but in GNU-style mode processing\ncontinues, meaning that options and arguments can be mixed. For\nexample:\n```text\n\n>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')\n([('-f', 'filename')], ['output', '-v'])\n>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')\n([('-f', 'filename'), ('-v', '')], ['output'])\n```\n(Contributed by Peter Åstrand.)\n- The grp, pwd, and resource modules\nnow return enhanced tuples:\n```text\n\n>>> import grp\n>>> g = grp.getgrnam('amk')\n>>> g.gr_name, g.gr_gid\n('amk', 500)\n```\n- The gzip module can now handle files exceeding 2 Gb.\n- The new heapq module contains an implementation of a\nheap queue algorithm. A heap is an array-like data structure that\nkeeps items in a partially sorted order such that, for every index\nk, `heap[ k ] <= heap[2* k +1]` and\n`heap[ k ] <= heap[2* k +2]`. This makes it quick to\nremove the smallest item, and inserting a new item while maintaining\nthe heap property is O(lg n). (See\nhttp://www.nist.gov/dads/HTML/priorityque.html for more\ninformation about the priority queue data structure.)\nThe heapq module provides heappush() and\nheappop() functions for adding and removing items while\nmaintaining the heap property on top of some other mutable Python\nsequence type. Here's an example that uses a Python list:\n```text\n\n>>> import heapq\n>>> heap = []\n>>> for item in [3, 7, 5, 11, 1]:\n... heapq.heappush(heap, item)\n...\n>>> heap\n[1, 3, 5, 11, 7]\n>>> heapq.heappop(heap)\n1\n>>> heapq.heappop(heap)\n3\n>>> heap\n[5, 7, 11]\n```\n(Contributed by Kevin O'Connor.)\n- The IDLE integrated development environment has been updated\nusing the code from the IDLEfork project\n(http://idlefork.sf.net). The most notable feature is that the\ncode being developed is now executed in a subprocess, meaning that\nthere's no longer any need for manual `reload()` operations.\nIDLE's core code has been incorporated into the standard library as the\nidlelib package.\n- The imaplib module now supports IMAP over SSL.\n(Contributed by Piers Lauder and Tino Lange.)\n- The itertools contains a number of useful functions for\nuse with iterators, inspired by various functions provided by the ML\nand Haskell languages. For example,\n`itertools.ifilter(predicate, iterator)` returns all elements in\nthe iterator for which the function predicate() returns\nTrue, and `itertools.repeat(obj, N )` returns\n`obj` N times. There are a number of other functions in\nthe module; see the package's reference\ndocumentation (../lib/module-itertools.html) for details.\n(Contributed by Raymond Hettinger.)\n- Two new functions in the math module,\ndegrees(rads) and radians(degs),\nconvert between radians and degrees. Other functions in the\nmath module such as math.sin() and\nmath.cos() have always required input values measured in\nradians. Also, an optional base argument was added to\nmath.log() to make it easier to compute logarithms for\nbases other than `e` and `10`. (Contributed by Raymond\nHettinger.)\n- Several new POSIX functions (getpgid(), killpg(),\nlchown(), loadavg(), major(), makedev(),\nminor(), and mknod()) were added to the\nposix module that underlies the os module.\n(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)\n- In the os module, the *stat() family of\nfunctions can now report fractions of a second in a timestamp. Such\ntime stamps are represented as floats, similar to\nthe value returned by time.time().\nDuring testing, it was found that some applications will break if time\nstamps are floats. For compatibility, when using the tuple interface\nof the stat_result time stamps will be represented as integers.\nWhen using named fields (a feature first introduced in Python 2.2),\ntime stamps are still represented as integers, unless\nos.stat_float_times() is invoked to enable float return\nvalues:\n```text\n\n>>> os.stat(\"/tmp\").st_mtime\n1034791200\n>>> os.stat_float_times(True)\n>>> os.stat(\"/tmp\").st_mtime\n1034791200.6335014\n```\nIn Python 2.4, the default will change to always returning floats.\nApplication developers should enable this feature only if all their\nlibraries work properly when confronted with floating point time\nstamps, or if they use the tuple API. If used, the feature should be\nactivated on an application level instead of trying to enable it on a\nper-use basis.\n- The optparse module contains a new parser for command-line arguments\nthat can convert option values to a particular Python type\nand will automatically generate a usage message. See the following section for\nmore details.\n- The old and never-documented linuxaudiodev module has\nbeen deprecated, and a new version named ossaudiodev has been\nadded. The module was renamed because the OSS sound drivers can be\nused on platforms other than Linux, and the interface has also been\ntidied and brought up to date in various ways. (Contributed by Greg\nWard and Nicholas FitzRoy-Dale.)\n- The new platform module contains a number of functions\nthat try to determine various properties of the platform you're\nrunning on. There are functions for getting the architecture, CPU\ntype, the Windows OS version, and even the Linux distribution version.\n(Contributed by Marc-André Lemburg.)\n- The parser objects provided by the pyexpat module\ncan now optionally buffer character data, resulting in fewer calls to\nyour character data handler and therefore faster performance. Setting\nthe parser object's buffer_text attribute to True\nwill enable buffering.\n- The sample(population, k) function was\nadded to the random module. population is a sequence or\nxrange object containing the elements of a population, and\nsample() chooses k elements from the population without\nreplacing chosen elements. k can be any value up to\n`len( population )`. For example:\n```text\n\n>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']\n>>> random.sample(days, 3) # Choose 3 elements\n['St', 'Sn', 'Th']\n>>> random.sample(days, 7) # Choose 7 elements\n['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']\n>>> random.sample(days, 7) # Choose 7 again\n['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']\n>>> random.sample(days, 8) # Can't choose eight\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nFile \"random.py\", line 414, in sample\nraise ValueError, \"sample larger than population\"\nValueError: sample larger than population\n>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000\n[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]\n```\nThe random module now uses a new algorithm, the Mersenne\nTwister, implemented in C. It's faster and more extensively studied\nthan the previous algorithm.\n(All changes contributed by Raymond Hettinger.)\n- The readline module also gained a number of new\nfunctions: get_history_item(),\nget_current_history_length(), and redisplay().\n- The rexec and Bastion modules have been\ndeclared dead, and attempts to import them will fail with a\nRuntimeError. New-style classes provide new ways to break\nout of the restricted execution environment provided by\nrexec, and no one has interest in fixing them or time to do\nso. If you have applications using rexec, rewrite them to\nuse something else.\n(Sticking with Python 2.2 or 2.1 will not make your applications any\nsafer because there are known bugs in the rexec module in\nthose versions. To repeat: if you're using rexec, stop using\nit immediately.)\n- The rotor module has been deprecated because the\nalgorithm it uses for encryption is not believed to be secure. If\nyou need encryption, use one of the several AES Python modules\nthat are available separately.\n- The shutil module gained a move(src,\ndest) function that recursively moves a file or directory to a new\nlocation.\n- Support for more advanced POSIX signal handling was added\nto the signal but then removed again as it proved impossible\nto make it work reliably across platforms.\n- The socket module now supports timeouts. You\ncan call the settimeout(t) method on a socket object to\nset a timeout of t seconds. Subsequent socket operations that\ntake longer than t seconds to complete will abort and raise a\nsocket.timeout exception.\nThe original timeout implementation was by Tim O'Malley. Michael\nGilfix integrated it into the Python socket module and\nshepherded it through a lengthy review. After the code was checked\nin, Guido van Rossum rewrote parts of it. (This is a good example of\na collaborative development process in action.)\n- On Windows, the socket module now ships with Secure\nSockets Layer (SSL) support.\n- The value of the C PYTHON_API_VERSION macro is now\nexposed at the Python level as `sys.api_version`. The current\nexception can be cleared by calling the new sys.exc_clear()\nfunction.\n- The new tarfile module\nallows reading from and writing to tar-format archive files.\n(Contributed by Lars Gustäbel.)\n- The new textwrap module contains functions for wrapping\nstrings containing paragraphs of text. The wrap(text,\nwidth) function takes a string and returns a list containing\nthe text split into lines of no more than the chosen width. The\nfill(text, width) function returns a single\nstring, reformatted to fit into lines no longer than the chosen width.\n(As you can guess, fill() is built on top of\nwrap(). For example:\n```text\n\n>>> import textwrap\n>>> paragraph = \"Not a whit, we defy augury: ... more text ...\"\n>>> textwrap.wrap(paragraph, 60)\n[\"Not a whit, we defy augury: there's a special providence in\",\n\"the fall of a sparrow. If it be now, 'tis not to come; if it\",\n...]\n>>> print textwrap.fill(paragraph, 35)\nNot a whit, we defy augury: there's\na special providence in the fall of\na sparrow. If it be now, 'tis not\nto come; if it be not to come, it\nwill be now; if it be not now, yet\nit will come: the readiness is all.\n>>>\n```\nThe module also contains a TextWrapper class that actually\nimplements the text wrapping strategy. Both the\nTextWrapper class and the wrap() and\nfill() functions support a number of additional keyword\narguments for fine-tuning the formatting; consult the module's\ndocumentation (../lib/module-textwrap.html) for details.\n(Contributed by Greg Ward.)\n- The thread and threading modules now have\ncompanion modules, dummy_thread and dummy_threading,\nthat provide a do-nothing implementation of the thread\nmodule's interface for platforms where threads are not supported. The\nintention is to simplify thread-aware modules (ones that don't\nrely on threads to run) by putting the following code at the top:\n```text\n\ntry:\nimport threading as _threading\nexcept ImportError:\nimport dummy_threading as _threading\n```\nIn this example, _threading is used as the module name to make\nit clear that the module being used is not necessarily the actual\nthreading module. Code can call functions and use classes in\n_threading whether or not threads are supported, avoiding an\nif statement and making the code slightly clearer. This\nmodule will not magically make multithreaded code run without threads;\ncode that waits for another thread to return or to do something will\nsimply hang forever.\n- The time module's strptime() function has\nlong been an annoyance because it uses the platform C library's\nstrptime() implementation, and different platforms\nsometimes have odd bugs. Brett Cannon contributed a portable\nimplementation that's written in pure Python and should behave\nidentically on all platforms.\n- The new timeit module helps measure how long snippets\nof Python code take to execute. The timeit.py file can be run\ndirectly from the command line, or the module's Timer class\ncan be imported and used directly. Here's a short example that\nfigures out whether it's faster to convert an 8-bit string to Unicode\nby appending an empty Unicode string to it or by using the\nunicode() function:\n```text\n\nimport timeit\n\ntimer1 = timeit.Timer('unicode(\"abc\")')\ntimer2 = timeit.Timer('\"abc\" + u\"\"')\n\n# Run three trials\nprint timer1.repeat(repeat=3, number=100000)\nprint timer2.repeat(repeat=3, number=100000)\n\n# On my laptop this outputs:\n# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]\n# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]\n```\n- The Tix module has received various bug fixes and\nupdates for the current version of the Tix package.\n- The Tkinter module now works with a thread-enabled\nversion of Tcl. Tcl's threading model requires that widgets only be\naccessed from the thread in which they're created; accesses from\nanother thread can cause Tcl to panic. For certain Tcl interfaces,\nTkinter will now automatically avoid this\nwhen a widget is accessed from a different thread by marshalling a\ncommand, passing it to the correct thread, and waiting for the\nresults. Other interfaces can't be handled automatically but\nTkinter will now raise an exception on such an access so that\nyou can at least find out about the problem. See\nhttp://mail.python.org/pipermail/python-dev/2002-December/031107.html for a more detailed explanation of this change. (Implemented by\nMartin von Löwis.)\n- Calling Tcl methods through _tkinter no longer\nreturns only strings. Instead, if Tcl returns other objects those\nobjects are converted to their Python equivalent, if one exists, or\nwrapped with a _tkinter.Tcl_Obj object if no Python equivalent\nexists. This behavior can be controlled through the\nwantobjects() method of tkapp objects.\nWhen using _tkinter through the Tkinter module (as\nmost Tkinter applications will), this feature is always activated. It\nshould not cause compatibility problems, since Tkinter would always\nconvert string results to Python types where possible.\nIf any incompatibilities are found, the old behavior can be restored\nby setting the wantobjects variable in the Tkinter\nmodule to false before creating the first tkapp object.\n```text\n\nimport Tkinter\nTkinter.wantobjects = 0\n```\nAny breakage caused by this change should be reported as a bug.\n- The UserDict module has a new DictMixin class which\ndefines all dictionary methods for classes that already have a minimum\nmapping interface. This greatly simplifies writing classes that need\nto be substitutable for dictionaries, such as the classes in\nthe shelve module.\nAdding the mix-in as a superclass provides the full dictionary\ninterface whenever the class defines __getitem__,\n__setitem__, __delitem__, and keys.\nFor example:\n```text\n\n>>> import UserDict\n>>> class SeqDict(UserDict.DictMixin):\n... \"\"\"Dictionary lookalike implemented with lists.\"\"\"\n... def __init__(self):\n... self.keylist = []\n... self.valuelist = []\n... def __getitem__(self, key):\n... try:\n... i = self.keylist.index(key)\n... except ValueError:\n... raise KeyError\n... return self.valuelist[i]\n... def __setitem__(self, key, value):\n... try:\n... i = self.keylist.index(key)\n... self.valuelist[i] = value\n... except ValueError:\n... self.keylist.append(key)\n... self.valuelist.append(value)\n... def __delitem__(self, key):\n... try:\n... i = self.keylist.index(key)\n... except ValueError:\n... raise KeyError\n... self.keylist.pop(i)\n... self.valuelist.pop(i)\n... def keys(self):\n... return list(self.keylist)\n...\n>>> s = SeqDict()\n>>> dir(s) # See that other dictionary methods are implemented\n['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',\n'__init__', '__iter__', '__len__', '__module__', '__repr__',\n'__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',\n'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',\n'setdefault', 'update', 'valuelist', 'values']\n```\n(Contributed by Raymond Hettinger.)\n- The DOM implementation\nin xml.dom.minidom can now generate XML output in a\nparticular encoding by providing an optional encoding argument to\nthe toxml() and toprettyxml() methods of DOM nodes.\n- The xmlrpclib module now supports an XML-RPC extension\nfor handling nil data values such as Python's `None`. Nil values\nare always supported on unmarshalling an XML-RPC response. To\ngenerate requests containing `None`, you must supply a true value\nfor the allow_none parameter when creating a Marshaller\ninstance.\n- The new DocXMLRPCServer module allows writing\nself-documenting XML-RPC servers. Run it in demo mode (as a program)\nto see it in action. Pointing the Web browser to the RPC server\nproduces pydoc-style documentation; pointing xmlrpclib to the\nserver allows invoking the actual methods.\n(Contributed by Brian Quinlan.)\n- Support for internationalized domain names (RFCs 3454, 3490,\n3491, and 3492) has been added. The ``idna'' encoding can be used\nto convert between a Unicode domain name and the ASCII-compatible\nencoding (ACE) of that name.\n```text\n\n>>> u\"www.Alliancefran¸ caise.nu\".encode(\"idna\")\n\n'www.xn-alliancefranaise-npb.nu'\n```\nThe socket module has also been extended to transparently\nconvert Unicode hostnames to the ACE version before passing them to\nthe C library. Modules that deal with hostnames such as\nhttplib and ftplib) also support Unicode host names;\nhttplib also sends HTTP \"Host\" headers using the ACE\nversion of the domain name. urllib supports Unicode URLs\nwith non-ASCII host names as long as the `path` part of the URL\nis ASCII only.\nTo implement this change, the stringprep module, the\n`mkstringprep` tool and the `punycode` encoding have been added.\n## 17.1 Date/Time Type\nDate and time types suitable for expressing timestamps were added as\nthe datetime module. The types don't support different\ncalendars or many fancy features, and just stick to the basics of\nrepresenting time.\nThe three primary types are: date, representing a day, month,\nand year; time, consisting of hour, minute, and second; and\ndatetime, which contains all the attributes of both\ndate and time. There's also a\ntimedelta class representing differences between two points\nin time, and time zone logic is implemented by classes inheriting from\nthe abstract tzinfo class.\nYou can create instances of date and time by either\nsupplying keyword arguments to the appropriate constructor,\ne.g. `datetime.date(year=1972, month=10, day=15)`, or by using\none of a number of class methods. For example, the date.today()\nclass method returns the current local date.\nOnce created, instances of the date/time classes are all immutable.\nThere are a number of methods for producing formatted strings from\nobjects:\n```text\n\n>>> import datetime\n>>> now = datetime.datetime.now()\n>>> now.isoformat()\n'2002-12-30T21:27:03.994956'\n>>> now.ctime() # Only available on date, datetime\n'Mon Dec 30 21:27:03 2002'\n>>> now.strftime('%Y %d %b')\n'2002 30 Dec'\n```\nThe replace() method allows modifying one or more fields\nof a date or datetime instance, returning a new instance:\n```text\n\n>>> d = datetime.datetime.now()\n>>> d\ndatetime.datetime(2002, 12, 30, 22, 15, 38, 827738)\n>>> d.replace(year=2001, hour = 12)\ndatetime.datetime(2001, 12, 30, 12, 15, 38, 827738)\n>>>\n```\nInstances can be compared, hashed, and converted to strings (the\nresult is the same as that of isoformat()). date and\ndatetime instances can be subtracted from each other, and\nadded to timedelta instances. The largest missing feature is\nthat there's no standard library support for parsing strings and getting back a\ndate or datetime.\nFor more information, refer to the module's reference\ndocumentation (../lib/module-datetime.html).\n(Contributed by Tim Peters.)\n## 17.2 The optparse Module\nThe getopt module provides simple parsing of command-line\narguments. The new optparse module (originally named Optik)\nprovides more elaborate command-line parsing that follows the Unix\nconventions, automatically creates the output for --help,\nand can perform different actions for different options.\nYou start by creating an instance of OptionParser and telling\nit what your program's options are.\n```text\n\nimport sys\nfrom optparse import OptionParser\n\nop = OptionParser()\nop.add_option('-i', '--input',\naction='store', type='string', dest='input',\nhelp='set input filename')\nop.add_option('-l', '--length',\naction='store', type='int', dest='length',\nhelp='set maximum length of output')\n```\nParsing a command line is then done by calling the parse_args()\nmethod.\n```text\n\noptions, args = op.parse_args(sys.argv[1:])\nprint options\nprint args\n```\nThis returns an object containing all of the option values,\nand a list of strings containing the remaining arguments.\nInvoking the script with the various arguments now works as you'd\nexpect it to. Note that the length argument is automatically\nconverted to an integer.\n```text\n\n$ ./python opt.py -i data arg1\n\n['arg1']\n$ ./python opt.py --input=data --length=4\n\n[]\n$\n```\nThe help message is automatically generated for you:\n```text\n\n$ ./python opt.py --help\nusage: opt.py [options]\n\noptions:\n-h, --help show this help message and exit\n-iINPUT, --input=INPUT\nset input filename\n-lLENGTH, --length=LENGTH\nset maximum length of output\n$\n```\nSee the module's documentation (../lib/module-optparse.html)\nfor more details.\nOptik was written by Greg Ward, with suggestions from the readers of\nthe Getopt SIG.", "python_version": "2.3", "length": 24511, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node18.html"} {"title": "1 PEP 218: A Standard Set Datatype", "text": "contents.html | whatsnew23.html | section-generators.html | What's New in Python 2.3 | contents.html\nPrevious:\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n2 PEP 255: Simple (section-generators.html)\n---\n# 1 PEP 218: A Standard Set Datatype\nThe new sets module contains an implementation of a set\ndatatype. The Set class is for mutable sets, sets that can\nhave members added and removed. The ImmutableSet class is for\nsets that can't be modified, and instances of ImmutableSet can\ntherefore be used as dictionary keys. Sets are built on top of\ndictionaries, so the elements within a set must be hashable.\nHere's a simple example:\n```text\n\n>>> import sets\n>>> S = sets.Set([1,2,3])\n>>> S\nSet([1, 2, 3])\n>>> 1 in S\nTrue\n>>> 0 in S\nFalse\n>>> S.add(5)\n>>> S.remove(3)\n>>> S\nSet([1, 2, 5])\n>>>\n```\nThe union and intersection of sets can be computed with the\nunion() and intersection() methods; an alternative\nnotation uses the bitwise operators `&` and `|`.\nMutable sets also have in-place versions of these methods,\nunion_update() and intersection_update().\n```text\n\n>>> S1 = sets.Set([1,2,3])\n>>> S2 = sets.Set([4,5,6])\n>>> S1.union(S2)\nSet([1, 2, 3, 4, 5, 6])\n>>> S1 | S2 # Alternative notation\nSet([1, 2, 3, 4, 5, 6])\n>>> S1.intersection(S2)\nSet([])\n>>> S1 & S2 # Alternative notation\nSet([])\n>>> S1.union_update(S2)\n>>> S1\nSet([1, 2, 3, 4, 5, 6])\n>>>\n```\nIt's also possible to take the symmetric difference of two sets. This\nis the set of all elements in the union that aren't in the\nintersection. Another way of putting it is that the symmetric\ndifference contains all elements that are in exactly one\nset. Again, there's an alternative notation (`^`), and an\nin-place version with the ungainly name\nsymmetric_difference_update().\n```text\n\n>>> S1 = sets.Set([1,2,3,4])\n>>> S2 = sets.Set([3,4,5,6])\n>>> S1.symmetric_difference(S2)\nSet([1, 2, 5, 6])\n>>> S1 ^ S2\nSet([1, 2, 5, 6])\n>>>\n```\nThere are also issubset() and issuperset() methods\nfor checking whether one set is a subset or superset of another:\n```text\n\n>>> S1 = sets.Set([1,2,3])\n>>> S2 = sets.Set([2,3])\n>>> S2.issubset(S1)\nTrue\n>>> S1.issubset(S2)\nFalse\n>>> S1.issuperset(S2)\nTrue\n>>>\n```\nSee Also:", "python_version": "2.3", "length": 2163, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node2.html"} {"title": "19 Build and C API Changes", "text": "section-pymalloc.html | whatsnew23.html | section-other.html | What's New in Python 2.3 | contents.html\nPrevious:\n18 Pymalloc: A Specialized (section-pymalloc.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n20 Other Changes and (section-other.html)\n---\n- 19.1 Port-Specific Changes (node20.html#SECTION0002010000000000000000)\n---\n# 19 Build and C API Changes\nChanges to Python's build process and to the C API include:\n- The C-level interface to the garbage collector has been changed\nto make it easier to write extension types that support garbage\ncollection and to debug misuses of the functions.\nVarious functions have slightly different semantics, so a bunch of\nfunctions had to be renamed. Extensions that use the old API will\nstill compile but will not participate in garbage collection,\nso updating them for 2.3 should be considered fairly high priority.\nTo upgrade an extension module to the new API, perform the following\nsteps:\n- Rename Py_TPFLAGS_GC to PyTPFLAGS_HAVE_GC.\n- Use PyObject_GC_New or PyObject_GC_NewVar to\nallocate objects, and PyObject_GC_Del to deallocate them.\n- Rename PyObject_GC_Init to PyObject_GC_Track and\nPyObject_GC_Fini to PyObject_GC_UnTrack.\n- Remove PyGC_HEAD_SIZE from object size calculations.\n- Remove calls to PyObject_AS_GC and PyObject_FROM_GC.\n- The cycle detection implementation used by the garbage collection\nhas proven to be stable, so it's now been made mandatory. You can no\nlonger compile Python without it, and the\n--with-cycle-gc switch to configure has been removed.\n- Python can now optionally be built as a shared library\n(libpython2.3.so) by supplying --enable-shared\nwhen running Python's configure script. (Contributed by Ondrej\nPalkovsky.)\n- The DL_EXPORT and DL_IMPORT macros\nare now deprecated. Initialization functions for Python extension\nmodules should now be declared using the new macro\nPyMODINIT_FUNC, while the Python core will generally\nuse the PyAPI_FUNC and PyAPI_DATA\nmacros.\n- The interpreter can be compiled without any docstrings for\nthe built-in functions and modules by supplying\n--without-doc-strings to the configure script.\nThis makes the Python executable about 10% smaller, but will also\nmean that you can't get help for Python's built-ins. (Contributed by\nGustavo Niemeyer.)\n- The PyArg_NoArgs() macro is now deprecated, and code\nthat uses it should be changed. For Python 2.2 and later, the method\ndefinition table can specify the\nMETH_NOARGS flag, signalling that there are no arguments, and\nthe argument checking can then be removed. If compatibility with\npre-2.2 versions of Python is important, the code could use\n`PyArg_ParseTuple( args , \"\")` instead, but this will be slower\nthan using METH_NOARGS.\n- A new function, PyObject_DelItemString(mapping,\nchar *key) was added as shorthand for\n`PyObject_DelItem( mapping , PyString_New( key ))`.\n- File objects now manage their internal string buffer\ndifferently, increasing it exponentially when needed. This results in\nthe benchmark tests in Lib/test/test_bufio.py speeding up\nconsiderably (from 57 seconds to 1.7 seconds, according to one\nmeasurement).\n- It's now possible to define class and static methods for a C\nextension type by setting either the METH_CLASS or\nMETH_STATIC flags in a method's PyMethodDef\nstructure.\n- Python now includes a copy of the Expat XML parser's source code,\nremoving any dependence on a system version or local installation of\nExpat.\n- If you dynamically allocate type objects in your extension, you\nshould be aware of a change in the rules relating to the\n__module__ and __name__ attributes. In summary,\nyou will want to ensure the type's dictionary contains a\n`'__module__'` key; making the module name the part of the type\nname leading up to the final period will no longer have the desired\neffect. For more detail, read the API reference documentation or the\nsource.\n## 19.1 Port-Specific Changes\nSupport for a port to IBM's OS/2 using the EMX runtime environment was\nmerged into the main Python source tree. EMX is a POSIX emulation\nlayer over the OS/2 system APIs. The Python port for EMX tries to\nsupport all the POSIX-like capability exposed by the EMX runtime, and\nmostly succeeds; fork() and fcntl() are\nrestricted by the limitations of the underlying emulation layer. The\nstandard OS/2 port, which uses IBM's Visual Age compiler, also gained\nsupport for case-sensitive import semantics as part of the integration\nof the EMX port into CVS. (Contributed by Andrew MacIntyre.)\nOn MacOS, most toolbox modules have been weaklinked to improve\nbackward compatibility. This means that modules will no longer fail\nto load if a single routine is missing on the curent OS version.\nInstead calling the missing routine will raise an exception.\n(Contributed by Jack Jansen.)\nThe RPM spec files, found in the Misc/RPM/ directory in the\nPython source distribution, were updated for 2.3. (Contributed by\nSean Reifschneider.)\nOther new platforms now supported by Python include AtheOS\n(http://www.atheos.cx/), GNU/Hurd, and OpenVMS.", "python_version": "2.3", "length": 5004, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node20.html"} {"title": "21 Porting to Python 2.3", "text": "section-other.html | whatsnew23.html | acks.html | What's New in Python 2.3 | contents.html\nPrevious:\n20 Other Changes and (section-other.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n22 Acknowledgements (acks.html)\n---\n# 21 Porting to Python 2.3\nThis section lists previously described changes that may require\nchanges to your code:\n- yield is now always a keyword; if it's used as a\nvariable name in your code, a different name must be chosen.\n- For strings X and Y, `X in Y` now works\nif X is more than one character long.\n- The int() type constructor will now return a long\ninteger instead of raising an OverflowError when a string\nor floating-point number is too large to fit into an integer.\n- If you have Unicode strings that contain 8-bit characters, you\nmust declare the file's encoding (UTF-8, Latin-1, or whatever) by\nadding a comment to the top of the file. See\nsection 3 (section-encodings.html#section-encodings) for more information.\n- Calling Tcl methods through _tkinter no longer\nreturns only strings. Instead, if Tcl returns other objects those\nobjects are converted to their Python equivalent, if one exists, or\nwrapped with a _tkinter.Tcl_Obj object if no Python equivalent\nexists.\n- Large octal and hex literals such as\n`0xffffffff` now trigger a FutureWarning. Currently\nthey're stored as 32-bit numbers and result in a negative value, but\nin Python 2.4 they'll become positive long integers.\nThere are a few ways to fix this warning. If you really need a\npositive number, just add an \"L\" to the end of the literal. If\nyou're trying to get a 32-bit integer with low bits set and have\npreviously used an expression such as `(1 « 31)`, it's probably\nclearest to start with all bits set and clear the desired upper bits.\nFor example, to clear just the top bit (bit 31), you could write\n`0xffffffffL &~(1L«31)`.\n- You can no longer disable assertions by assigning to `__debug__`.\n- The Distutils setup() function has gained various new\nkeyword arguments such as depends. Old versions of the\nDistutils will abort if passed unknown keywords. A solution is to check\nfor the presence of the new get_distutil_options() function\nin your setup.py and only uses the new keywords\nwith a version of the Distutils that supports them:\n```text\n\nfrom distutils import core\n\nkw = {'sources': 'foo.c', ...}\nif hasattr(core, 'get_distutil_options'):\nkw['depends'] = ['foo.h']\next = Extension(**kw)\n```\n- Using `None` as a variable name will now result in a\nSyntaxWarning warning.\n- Names of extension types defined by the modules included with\nPython now contain the module and a \".\" in front of the type\nname.", "python_version": "2.3", "length": 2621, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node22.html"} {"title": "4 PEP 273: Importing Modules from Zip Archives", "text": "section-encodings.html | whatsnew23.html | node6.html | What's New in Python 2.3 | contents.html\nPrevious:\n3 PEP 263: Source (section-encodings.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n5 PEP 277: Unicode (node6.html)\n---\n# 4 PEP 273: Importing Modules from Zip Archives\nThe new zipimport module adds support for importing\nmodules from a ZIP-format archive. You don't need to import the\nmodule explicitly; it will be automatically imported if a ZIP\narchive's filename is added to `sys.path`. For example:\n```text\n\namk@nyman:~/src/python$ unzip -l /tmp/example.zip\nArchive: /tmp/example.zip\nLength Date Time Name\n-------- ---- ---- ----\n8467 11-26-02 22:30 jwzthreading.py\n-------- -------\n8467 1 file\namk@nyman:~/src/python$ ./python\nPython 2.3 (#1, Aug 1 2003, 19:54:32)\n>>> import sys\n>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path\n>>> import jwzthreading\n>>> jwzthreading.__file__\n'/tmp/example.zip/jwzthreading.py'\n>>>\n```\nAn entry in `sys.path` can now be the filename of a ZIP archive.\nThe ZIP archive can contain any kind of files, but only files named\n*.py, *.pyc, or *.pyo can be imported. If an\narchive only contains *.py files, Python will not attempt to\nmodify the archive by adding the corresponding *.pyc file, meaning\nthat if a ZIP archive doesn't contain *.pyc files, importing may be\nrather slow.\nA path within the archive can also be specified to only import from a\nsubdirectory; for example, the path /tmp/example.zip/lib/\nwould only import from the lib/ subdirectory within the\narchive.\nSee Also:", "python_version": "2.3", "length": 1558, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node5.html"} {"title": "5 PEP 277: Unicode file name support for Windows NT", "text": "node5.html | whatsnew23.html | node7.html | What's New in Python 2.3 | contents.html\nPrevious:\n4 PEP 273: Importing (node5.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n6 PEP 278: Universal (node7.html)\n---\n# 5 PEP 277: Unicode file name support for Windows NT\nOn Windows NT, 2000, and XP, the system stores file names as Unicode\nstrings. Traditionally, Python has represented file names as byte\nstrings, which is inadequate because it renders some file names\ninaccessible.\nPython now allows using arbitrary Unicode strings (within the\nlimitations of the file system) for all functions that expect file\nnames, most notably the open() built-in function. If a Unicode\nstring is passed to os.listdir(), Python now returns a list\nof Unicode strings. A new function, os.getcwdu(), returns\nthe current directory as a Unicode string.\nByte strings still work as file names, and on Windows Python will\ntransparently convert them to Unicode using the `mbcs` encoding.\nOther systems also allow Unicode strings as file names but convert\nthem to byte strings before passing them to the system, which can\ncause a UnicodeError to be raised. Applications can test\nwhether arbitrary Unicode strings are supported as file names by\nchecking os.path.supports_unicode_filenames, a Boolean value.\nUnder MacOS, os.listdir() may now return Unicode filenames.\nSee Also:", "python_version": "2.3", "length": 1353, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node6.html"} {"title": "6 PEP 278: Universal Newline Support", "text": "node6.html | whatsnew23.html | section-enumerate.html | What's New in Python 2.3 | contents.html\nPrevious:\n5 PEP 277: Unicode (node6.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n7 PEP 279: enumerate() (section-enumerate.html)\n---\n# 6 PEP 278: Universal Newline Support\nThe three major operating systems used today are Microsoft Windows,\nApple's Macintosh OS, and the various Unix derivatives. A minor\nirritation of cross-platform work\nis that these three platforms all use different characters\nto mark the ends of lines in text files. Unix uses the linefeed\n(ASCII character 10), MacOS uses the carriage return (ASCII\ncharacter 13), and Windows uses a two-character sequence of a\ncarriage return plus a newline.\nPython's file objects can now support end of line conventions other\nthan the one followed by the platform on which Python is running.\nOpening a file with the mode `'U'` or `'rU'` will open a file\nfor reading in universal newline mode. All three line ending\nconventions will be translated to a \"\\n\" in the strings\nreturned by the various file methods such as read() and\nreadline().\nUniversal newline support is also used when importing modules and when\nexecuting a file with the execfile() function. This means\nthat Python modules can be shared between all three operating systems\nwithout needing to convert the line-endings.\nThis feature can be disabled when compiling Python by specifying\nthe --without-universal-newlines switch when running Python's\nconfigure script.\nSee Also:", "python_version": "2.3", "length": 1501, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node7.html"} {"title": "8 PEP 282: The logging Package", "text": "section-enumerate.html | whatsnew23.html | section-bool.html | What's New in Python 2.3 | contents.html\nPrevious:\n7 PEP 279: enumerate() (section-enumerate.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n9 PEP 285: A (section-bool.html)\n---\n# 8 PEP 282: The logging Package\nA standard package for writing logs, logging, has been added\nto Python 2.3. It provides a powerful and flexible mechanism for\ngenerating logging output which can then be filtered and processed in\nvarious ways. A configuration file written in a standard format can\nbe used to control the logging behavior of a program. Python\nincludes handlers that will write log records to\nstandard error or to a file or socket, send them to the system log, or\neven e-mail them to a particular address; of course, it's also\npossible to write your own handler classes.\nThe Logger class is the primary class.\nMost application code will deal with one or more Logger\nobjects, each one used by a particular subsystem of the application.\nEach Logger is identified by a name, and names are organized\ninto a hierarchy using \".\" as the component separator. For\nexample, you might have Logger instances named \"server\",\n\"server.auth\" and \"server.network\". The latter two\ninstances are below \"server\" in the hierarchy. This means that\nif you turn up the verbosity for \"server\" or direct \"server\"messages to a different handler, the changes will also apply to\nrecords logged to \"server.auth\" and \"server.network\".\nThere's also a root Logger that's the parent of all other\nloggers.\nFor simple uses, the logging package contains some\nconvenience functions that always use the root log:\n```text\n\nimport logging\n\nlogging.debug('Debugging information')\nlogging.info('Informational message')\nlogging.warning('Warning:config file %s not found', 'server.conf')\nlogging.error('Error occurred')\nlogging.critical('Critical error -- shutting down')\n```\nThis produces the following output:\n```text\n\nWARNING:root:Warning:config file server.conf not found\nERROR:root:Error occurred\nCRITICAL:root:Critical error -- shutting down\n```\nIn the default configuration, informational and debugging messages are\nsuppressed and the output is sent to standard error. You can enable\nthe display of informational and debugging messages by calling the\nsetLevel() method on the root logger.\nNotice the warning() call's use of string formatting\noperators; all of the functions for logging messages take the\narguments `( msg , arg1 , arg2 , ...)` and log the\nstring resulting from `msg % ( arg1 , arg2 ,\n...)`.\nThere's also an exception() function that records the most\nrecent traceback. Any of the other functions will also record the\ntraceback if you specify a true value for the keyword argument\nexc_info.\n```text\n\ndef f():\ntry: 1/0\nexcept: logging.exception('Problem recorded')\n\nf()\n```\nThis produces the following output:\n```text\n\nERROR:root:Problem recorded\nTraceback (most recent call last):\nFile \"t.py\", line 6, in f\n1/0\nZeroDivisionError: integer division or modulo by zero\n```\nSlightly more advanced programs will use a logger other than the root\nlogger. The getLogger(name) function is used to get\na particular log, creating it if it doesn't exist yet.\ngetLogger(None) returns the root logger.\n```text\n\nlog = logging.getLogger('server')\n...\nlog.info('Listening on port %i', port)\n...\nlog.critical('Disk full')\n...\n```\nLog records are usually propagated up the hierarchy, so a message\nlogged to \"server.auth\" is also seen by \"server\" and\n\"root\", but a Logger can prevent this by setting its\npropagate attribute to False.\nThere are more classes provided by the logging package that\ncan be customized. When a Logger instance is told to log a\nmessage, it creates a LogRecord instance that is sent to any\nnumber of different Handler instances. Loggers and handlers\ncan also have an attached list of filters, and each filter can cause\nthe LogRecord to be ignored or can modify the record before\npassing it along. When they're finally output, LogRecord\ninstances are converted to text by a Formatter class. All of\nthese classes can be replaced by your own specially-written classes.\nWith all of these features the logging package should provide\nenough flexibility for even the most complicated applications. This\nis only an incomplete overview of its features, so please see the\npackage's reference documentation (../lib/module-logging.html)\nfor all of the details. Reading PEP 282 (http://www.python.org/peps/pep-0282.html) will also be helpful.\nSee Also:", "python_version": "2.3", "length": 4480, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/node9.html"} {"title": "9 PEP 285: A Boolean Type", "text": "node9.html | whatsnew23.html | node11.html | What's New in Python 2.3 | contents.html\nPrevious:\n8 PEP 282: The (node9.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n10 PEP 293: Codec (node11.html)\n---\n# 9 PEP 285: A Boolean Type\nA Boolean type was added to Python 2.3. Two new constants were added\nto the __builtin__ module, True and\nFalse. (True and\nFalse constants were added to the built-ins\nin Python 2.2.1, but the 2.2.1 versions are simply set to integer values of\n1 and 0 and aren't a different type.)\nThe type object for this new type is named\nbool; the constructor for it takes any Python value and\nconverts it to True or False.\n```text\n\n>>> bool(1)\nTrue\n>>> bool(0)\nFalse\n>>> bool([])\nFalse\n>>> bool( (1,) )\nTrue\n```\nMost of the standard library modules and built-in functions have been\nchanged to return Booleans.\n```text\n\n>>> obj = []\n>>> hasattr(obj, 'append')\nTrue\n>>> isinstance(obj, list)\nTrue\n>>> isinstance(obj, tuple)\nFalse\n```\nPython's Booleans were added with the primary goal of making code\nclearer. For example, if you're reading a function and encounter the\nstatement `return 1`, you might wonder whether the `1`\nrepresents a Boolean truth value, an index, or a\ncoefficient that multiplies some other quantity. If the statement is\n`return True`, however, the meaning of the return value is quite\nclear.\nPython's Booleans were not added for the sake of strict\ntype-checking. A very strict language such as Pascal would also\nprevent you performing arithmetic with Booleans, and would require\nthat the expression in an if statement always evaluate to a\nBoolean result. Python is not this strict and never will be, as\nPEP 285 (http://www.python.org/peps/pep-0285.html) explicitly says. This means you can still use any\nexpression in an if statement, even ones that evaluate to a\nlist or tuple or some random object. The Boolean type is a\nsubclass of the int class so that arithmetic using a Boolean\nstill works.\n```text\n\n>>> True + 1\n2\n>>> False + 1\n1\n>>> False * 75\n0\n>>> True * 75\n75\n```\nTo sum up True and False in a sentence: they're\nalternative ways to spell the integer values 1 and 0, with the single\ndifference that str() and repr() return the\nstrings `'True'` and `'False'` instead of `'1'` and\n`'0'`.\nSee Also:", "python_version": "2.3", "length": 2248, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-bool.html"} {"title": "3 PEP 263: Source Code Encodings", "text": "section-generators.html | whatsnew23.html | node5.html | What's New in Python 2.3 | contents.html\nPrevious:\n2 PEP 255: Simple (section-generators.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n4 PEP 273: Importing (node5.html)\n---\n# 3 PEP 263: Source Code Encodings\nPython source files can now be declared as being in different\ncharacter set encodings. Encodings are declared by including a\nspecially formatted comment in the first or second line of the source\nfile. For example, a UTF-8 file can be declared with:\n```text\n\n#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n```\nWithout such an encoding declaration, the default encoding used is\n7-bit ASCII. Executing or importing modules that contain string\nliterals with 8-bit characters and have no encoding declaration will result\nin a DeprecationWarning being signalled by Python 2.3; in\n2.4 this will be a syntax error.\nThe encoding declaration only affects Unicode string literals, which\nwill be converted to Unicode using the specified encoding. Note that\nPython identifiers are still restricted to ASCII characters, so you\ncan't have variable names that use characters outside of the usual\nalphanumerics.\nSee Also:", "python_version": "2.3", "length": 1177, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-encodings.html"} {"title": "7 PEP 279: enumerate()", "text": "node7.html | whatsnew23.html | node9.html | What's New in Python 2.3 | contents.html\nPrevious:\n6 PEP 278: Universal (node7.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n8 PEP 282: The (node9.html)\n---\n# 7 PEP 279: enumerate()\nA new built-in function, enumerate(), will make\ncertain loops a bit clearer. `enumerate(thing)`, where\nthing is either an iterator or a sequence, returns a iterator\nthat will return `(0, thing [0])`, `(1, thing [1])`, `(2, thing [2])`, and so forth.\nA common idiom to change every element of a list looks like this:\n```text\n\nfor i in range(len(L)):\nitem = L[i]\n# ... compute some result based on item ...\nL[i] = result\n```\nThis can be rewritten using enumerate() as:\n```text\n\nfor i, item in enumerate(L):\n# ... compute some result based on item ...\nL[i] = result\n```\nSee Also:", "python_version": "2.3", "length": 811, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-enumerate.html"} {"title": "2 PEP 255: Simple Generators", "text": "node2.html | whatsnew23.html | section-encodings.html | What's New in Python 2.3 | contents.html\nPrevious:\n1 PEP 218: A (node2.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n3 PEP 263: Source (section-encodings.html)\n---\n# 2 PEP 255: Simple Generators\nIn Python 2.2, generators were added as an optional feature, to be\nenabled by a `from __future__ import generators` directive. In\n2.3 generators no longer need to be specially enabled, and are now\nalways present; this means that yield is now always a\nkeyword. The rest of this section is a copy of the description of\ngenerators from the ``What's New in Python 2.2'' document; if you read\nit back when Python 2.2 came out, you can skip the rest of this section.\nYou're doubtless familiar with how function calls work in Python or C.\nWhen you call a function, it gets a private namespace where its local\nvariables are created. When the function reaches a return\nstatement, the local variables are destroyed and the resulting value\nis returned to the caller. A later call to the same function will get\na fresh new set of local variables. But, what if the local variables\nweren't thrown away on exiting a function? What if you could later\nresume the function where it left off? This is what generators\nprovide; they can be thought of as resumable functions.\nHere's the simplest example of a generator function:\n```text\n\ndef generate_ints(N):\nfor i in range(N):\nyield i\n```\nA new keyword, yield, was introduced for generators. Any\nfunction containing a yield statement is a generator\nfunction; this is detected by Python's bytecode compiler which\ncompiles the function specially as a result.\nWhen you call a generator function, it doesn't return a single value;\ninstead it returns a generator object that supports the iterator\nprotocol. On executing the yield statement, the generator\noutputs the value of `i`, similar to a return\nstatement. The big difference between yield and a\nreturn statement is that on reaching a yield the\ngenerator's state of execution is suspended and local variables are\npreserved. On the next call to the generator's `.next()` method,\nthe function will resume executing immediately after the\nyield statement. (For complicated reasons, the\nyield statement isn't allowed inside the try block\nof a try...finally statement; read PEP 255 (http://www.python.org/peps/pep-0255.html) for a full\nexplanation of the interaction between yield and\nexceptions.)\nHere's a sample usage of the generate_ints() generator:\n```text\n\n>>> gen = generate_ints(3)\n>>> gen\n\n>>> gen.next()\n0\n>>> gen.next()\n1\n>>> gen.next()\n2\n>>> gen.next()\nTraceback (most recent call last):\nFile \"stdin\", line 1, in ?\nFile \"stdin\", line 2, in generate_ints\nStopIteration\n```\nYou could equally write `for i in generate_ints(5)`, or\n`a,b,c = generate_ints(3)`.\nInside a generator function, the return statement can only\nbe used without a value, and signals the end of the procession of\nvalues; afterwards the generator cannot return any further values.\nreturn with a value, such as `return 5`, is a syntax\nerror inside a generator function. The end of the generator's results\ncan also be indicated by raising StopIteration manually,\nor by just letting the flow of execution fall off the bottom of the\nfunction.\nYou could achieve the effect of generators manually by writing your\nown class and storing all the local variables of the generator as\ninstance variables. For example, returning a list of integers could\nbe done by setting `self.count` to 0, and having the\nnext() method increment `self.count` and return it.\nHowever, for a moderately complicated generator, writing a\ncorresponding class would be much messier.\nLib/test/test_generators.py contains a number of more\ninteresting examples. The simplest one implements an in-order\ntraversal of a tree using generators recursively.\n```text\n\n# A recursive generator that generates Tree leaves in in-order.\ndef inorder(t):\nif t:\nfor x in inorder(t.left):\nyield x\nyield t.label\nfor x in inorder(t.right):\nyield x\n```\nTwo other examples in Lib/test/test_generators.py produce\nsolutions for the N-Queens problem (placing queens on an\nchess board so that no queen threatens another) and the Knight's Tour\n(a route that takes a knight to every square of an chessboard\nwithout visiting any square twice).\nThe idea of generators comes from other programming languages,\nespecially Icon (http://www.cs.arizona.edu/icon/), where the\nidea of generators is central. In Icon, every\nexpression and function call behaves like a generator. One example\nfrom ``An Overview of the Icon Programming Language'' at\nhttp://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of\nwhat this looks like:\n```text\n\nsentence := \"Store it in the neighboring harbor\"\nif (i := find(\"or\", sentence)) > 5 then write(i)\n```\nIn Icon the find() function returns the indexes at which the\nsubstring ``or'' is found: 3, 23, 33. In the if statement,\n`i` is first assigned a value of 3, but 3 is less than 5, so the\ncomparison fails, and Icon retries it with the second value of 23. 23\nis greater than 5, so the comparison now succeeds, and the code prints\nthe value 23 to the screen.\nPython doesn't go nearly as far as Icon in adopting generators as a\ncentral concept. Generators are considered part of the core\nPython language, but learning or using them isn't compulsory; if they\ndon't solve any problems that you have, feel free to ignore them.\nOne novel feature of Python's interface as compared to\nIcon's is that a generator's state is represented as a concrete object\n(the iterator) that can be passed around to other functions or stored\nin a data structure.\nSee Also:", "python_version": "2.3", "length": 5658, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-generators.html"} {"title": "20 Other Changes and Fixes", "text": "node20.html | whatsnew23.html | node22.html | What's New in Python 2.3 | contents.html\nPrevious:\n19 Build and C (node20.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n21 Porting to Python (node22.html)\n---\n# 20 Other Changes and Fixes\nAs usual, there were a bunch of other improvements and bugfixes\nscattered throughout the source tree. A search through the CVS change\nlogs finds there were 523 patches applied and 514 bugs fixed between\nPython 2.2 and 2.3. Both figures are likely to be underestimates.\nSome of the more notable changes are:\n- If the PYTHONINSPECT environment variable is set, the\nPython interpreter will enter the interactive prompt after running a\nPython program, as if Python had been invoked with the -i\noption. The environment variable can be set before running the Python\ninterpreter, or it can be set by the Python program as part of its\nexecution.\n- The regrtest.py script now provides a way to allow ``all\nresources except foo.'' A resource name passed to the\n-u option can now be prefixed with a hyphen\n(\"-\") to mean ``remove this resource.'' For example, the\noption ``-u all,-bsddb`' could be used to enable the\nuse of all resources except `bsddb`.\n- The tools used to build the documentation now work under Cygwin\nas well as Unix.\n- The `SET_LINENO` opcode has been removed. Back in the\nmists of time, this opcode was needed to produce line numbers in\ntracebacks and support trace functions (for, e.g., pdb).\nSince Python 1.5, the line numbers in tracebacks have been computed\nusing a different mechanism that works with ``python -O''. For Python\n2.3 Michael Hudson implemented a similar scheme to determine when to\ncall the trace function, removing the need for `SET_LINENO`\nentirely.\nIt would be difficult to detect any resulting difference from Python\ncode, apart from a slight speed up when Python is run without\n-O.\nC extensions that access the f_lineno field of frame objects\nshould instead call `PyCode_Addr2Line(f->f_code, f->f_lasti)`.\nThis will have the added effect of making the code work as desired\nunder ``python -O'' in earlier versions of Python.\nA nifty new feature is that trace functions can now assign to the\nf_lineno attribute of frame objects, changing the line that\nwill be executed next. A \"jump\" command has been added to the\npdb debugger taking advantage of this new feature.\n(Implemented by Richie Hindle.)", "python_version": "2.3", "length": 2370, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-other.html"} {"title": "11 PEP 301: Package Index and Metadata for\nDistutils", "text": "node11.html | whatsnew23.html | section-pep302.html | What's New in Python 2.3 | contents.html\nPrevious:\n10 PEP 293: Codec (node11.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n12 PEP 302: New (section-pep302.html)\n---\n# 11 PEP 301: Package Index and Metadata for\nDistutils\nSupport for the long-requested Python catalog makes its first\nappearance in 2.3.\nThe heart of the catalog is the new Distutils `register` command.\nRunning `python setup.py register` will collect the metadata\ndescribing a package, such as its name, version, maintainer,\ndescription, &c., and send it to a central catalog server. The\nresulting catalog is available from http://www.python.org/pypi.\nTo make the catalog a bit more useful, a new optional\nclassifiers keyword argument has been added to the Distutils\nsetup() function. A list of\nTrove (http://catb.org/~esr/trove/)-style\nstrings can be supplied to help classify the software.\nHere's an example setup.py with classifiers, written to be compatible\nwith older versions of the Distutils:\n```text\n\nfrom distutils import core\nkw = {'name': \"Quixote\",\n'version': \"0.5.1\",\n'description': \"A highly Pythonic Web application framework\",\n# ...\n}\n\nif (hasattr(core, 'setup_keywords') and\n'classifiers' in core.setup_keywords):\nkw['classifiers'] = \\\n['Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n'Environment :: No Input/Output (Daemon)',\n'Intended Audience :: Developers'],\n\ncore.setup(**kw)\n```\nThe full list of classifiers can be obtained by running\n`python setup.py register --list-classifiers`.\nSee Also:", "python_version": "2.3", "length": 1546, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-pep301.html"} {"title": "12 PEP 302: New Import Hooks", "text": "section-pep301.html | whatsnew23.html | node14.html | What's New in Python 2.3 | contents.html\nPrevious:\n11 PEP 301: Package (section-pep301.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n13 PEP 305: Comma-separated (node14.html)\n---\n# 12 PEP 302: New Import Hooks\nWhile it's been possible to write custom import hooks ever since the\nihooks module was introduced in Python 1.3, no one has ever\nbeen really happy with it because writing new import hooks is\ndifficult and messy. There have been various proposed alternatives\nsuch as the imputil and iu modules, but none of them\nhas ever gained much acceptance, and none of them were easily usable\nfrom C code.\nPEP 302 (http://www.python.org/peps/pep-0302.html) borrows ideas from its predecessors, especially from\nGordon McMillan's iu module. Three new items\nare added to the sys module:\n- `sys.path_hooks` is a list of callable objects; most\noften they'll be classes. Each callable takes a string containing a\npath and either returns an importer object that will handle imports\nfrom this path or raises an ImportError exception if it\ncan't handle this path.\n- `sys.path_importer_cache` caches importer objects for\neach path, so `sys.path_hooks` will only need to be traversed\nonce for each path.\n- `sys.meta_path` is a list of importer objects that will\nbe traversed before `sys.path` is checked. This list is\ninitially empty, but user code can add objects to it. Additional\nbuilt-in and frozen modules can be imported by an object added to\nthis list.\nImporter objects must have a single method,\nfind_module(fullname, path=None). fullname\nwill be a module or package name, e.g. \"string\" or\n\"distutils.core\". find_module() must return a loader object\nthat has a single method, load_module(fullname), that\ncreates and returns the corresponding module object.\nPseudo-code for Python's new import logic, therefore, looks something\nlike this (simplified a bit; see PEP 302 (http://www.python.org/peps/pep-0302.html) for the full details):\n```text\n\nfor mp in sys.meta_path:\nloader = mp(fullname)\nif loader is not None:\n = loader.load_module(fullname)\n\nfor path in sys.path:\nfor hook in sys.path_hooks:\ntry:\nimporter = hook(path)\nexcept ImportError:\n# ImportError, so try the other path hooks\npass\nelse:\nloader = importer.find_module(fullname)\n = loader.load_module(fullname)\n\n# Not found!\nraise ImportError\n```\nSee Also:", "python_version": "2.3", "length": 2387, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-pep302.html"} {"title": "14 PEP 307: Pickle Enhancements", "text": "node14.html | whatsnew23.html | section-slices.html | What's New in Python 2.3 | contents.html\nPrevious:\n13 PEP 305: Comma-separated (node14.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n15 Extended Slices (section-slices.html)\n---\n# 14 PEP 307: Pickle Enhancements\nThe pickle and cPickle modules received some\nattention during the 2.3 development cycle. In 2.2, new-style classes\ncould be pickled without difficulty, but they weren't pickled very\ncompactly; PEP 307 (http://www.python.org/peps/pep-0307.html) quotes a trivial example where a new-style class\nresults in a pickled string three times longer than that for a classic\nclass.\nThe solution was to invent a new pickle protocol. The\npickle.dumps() function has supported a text-or-binary flag\nfor a long time. In 2.3, this flag is redefined from a Boolean to an\ninteger: 0 is the old text-mode pickle format, 1 is the old binary\nformat, and now 2 is a new 2.3-specific format. A new constant,\npickle.HIGHEST_PROTOCOL, can be used to select the fanciest\nprotocol available.\nUnpickling is no longer considered a safe operation. 2.2's\npickle provided hooks for trying to prevent unsafe classes\nfrom being unpickled (specifically, a\n__safe_for_unpickling__ attribute), but none of this code\nwas ever audited and therefore it's all been ripped out in 2.3. You\nshould not unpickle untrusted data in any version of Python.\nTo reduce the pickling overhead for new-style classes, a new interface\nfor customizing pickling was added using three special methods:\n__getstate__, __setstate__, and\n__getnewargs__. Consult PEP 307 (http://www.python.org/peps/pep-0307.html) for the full semantics\nof these methods.\nAs a way to compress pickles yet further, it's now possible to use\ninteger codes instead of long strings to identify pickled classes.\nThe Python Software Foundation will maintain a list of standardized\ncodes; there's also a range of codes for private use. Currently no\ncodes have been specified.\nSee Also:", "python_version": "2.3", "length": 1971, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-pep305.html"} {"title": "18 Pymalloc: A Specialized Object Allocator", "text": "node18.html | whatsnew23.html | node20.html | What's New in Python 2.3 | contents.html\nPrevious:\n17 New, Improved, and (node18.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n19 Build and C (node20.html)\n---\n# 18 Pymalloc: A Specialized Object Allocator\nPymalloc, a specialized object allocator written by Vladimir\nMarangozov, was a feature added to Python 2.1. Pymalloc is intended\nto be faster than the system malloc() and to have less\nmemory overhead for allocation patterns typical of Python programs.\nThe allocator uses C's malloc() function to get large\npools of memory and then fulfills smaller memory requests from these\npools.\nIn 2.1 and 2.2, pymalloc was an experimental feature and wasn't\nenabled by default; you had to explicitly enable it when compiling\nPython by providing the\n--with-pymalloc option to the configure\nscript. In 2.3, pymalloc has had further enhancements and is now\nenabled by default; you'll have to supply\n--without-pymalloc to disable it.\nThis change is transparent to code written in Python; however,\npymalloc may expose bugs in C extensions. Authors of C extension\nmodules should test their code with pymalloc enabled,\nbecause some incorrect code may cause core dumps at runtime.\nThere's one particularly common error that causes problems. There are\na number of memory allocation functions in Python's C API that have\npreviously just been aliases for the C library's malloc()\nand free(), meaning that if you accidentally called\nmismatched functions the error wouldn't be noticeable. When the\nobject allocator is enabled, these functions aren't aliases of\nmalloc() and free() any more, and calling the\nwrong function to free memory may get you a core dump. For example,\nif memory was allocated using PyObject_Malloc(), it has to\nbe freed using PyObject_Free(), not free(). A\nfew modules included with Python fell afoul of this and had to be\nfixed; doubtless there are more third-party modules that will have the\nsame problem.\nAs part of this change, the confusing multiple interfaces for\nallocating memory have been consolidated down into two API families.\nMemory allocated with one family must not be manipulated with\nfunctions from the other family. There is one family for allocating\nchunks of memory and another family of functions specifically for\nallocating Python objects.\n- To allocate and free an undistinguished chunk of memory use\nthe ``raw memory'' family: PyMem_Malloc(),\nPyMem_Realloc(), and PyMem_Free().\n- The ``object memory'' family is the interface to the pymalloc\nfacility described above and is biased towards a large number of\n``small'' allocations: PyObject_Malloc,\nPyObject_Realloc, and PyObject_Free.\n- To allocate and free Python objects, use the ``object'' family\nPyObject_New(), PyObject_NewVar(), and\nPyObject_Del().\nThanks to lots of work by Tim Peters, pymalloc in 2.3 also provides\ndebugging features to catch memory overwrites and doubled frees in\nboth extension modules and in the interpreter itself. To enable this\nsupport, compile a debugging version of the Python interpreter by\nrunning configure with --with-pydebug.\nTo aid extension writers, a header file Misc/pymemcompat.h is\ndistributed with the source to Python 2.3 that allows Python\nextensions to use the 2.3 interfaces to memory allocation while\ncompiling against any version of Python since 1.5.2. You would copy\nthe file from Python's source distribution and bundle it with the\nsource of your extension.\nSee Also:", "python_version": "2.3", "length": 3452, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-pymalloc.html"} {"title": "15 Extended Slices", "text": "section-pep305.html | whatsnew23.html | node17.html | What's New in Python 2.3 | contents.html\nPrevious:\n14 PEP 307: Pickle (section-pep305.html)\nUp:\nWhat's New in Python (whatsnew23.html)\nNext:\n16 Other Language Changes (node17.html)\n---\n# 15 Extended Slices\nEver since Python 1.4, the slicing syntax has supported an optional\nthird ``step'' or ``stride'' argument. For example, these are all\nlegal Python syntax: `L[1:10:2]`, `L[:-1:1]`,\n`L[::-1]`. This was added to Python at the request of\nthe developers of Numerical Python, which uses the third argument\nextensively. However, Python's built-in list, tuple, and string\nsequence types have never supported this feature, raising a\nTypeError if you tried it. Michael Hudson contributed a\npatch to fix this shortcoming.\nFor example, you can now easily extract the elements of a list that\nhave even indexes:\n```text\n\n>>> L = range(10)\n>>> L[::2]\n[0, 2, 4, 6, 8]\n```\nNegative values also work to make a copy of the same list in reverse\norder:\n```text\n\n>>> L[::-1]\n[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n```\nThis also works for tuples, arrays, and strings:\n```text\n\n>>> s='abcd'\n>>> s[::2]\n'ac'\n>>> s[::-1]\n'dcba'\n```\nIf you have a mutable sequence such as a list or an array you can\nassign to or delete an extended slice, but there are some differences\nbetween assignment to extended and regular slices. Assignment to a\nregular slice can be used to change the length of the sequence:\n```text\n\n>>> a = range(3)\n>>> a\n[0, 1, 2]\n>>> a[1:3] = [4, 5, 6]\n>>> a\n[0, 4, 5, 6]\n```\nExtended slices aren't this flexible. When assigning to an extended\nslice, the list on the right hand side of the statement must contain\nthe same number of items as the slice it is replacing:\n```text\n\n>>> a = range(4)\n>>> a\n[0, 1, 2, 3]\n>>> a[::2]\n[0, 2]\n>>> a[::2] = [0, -1]\n>>> a\n[0, 1, -1, 3]\n>>> a[::2] = [0,1,2]\nTraceback (most recent call last):\nFile \"\", line 1, in ?\nValueError: attempt to assign sequence of size 3 to extended slice of size 2\n```\nDeletion is more straightforward:\n```text\n\n>>> a = range(4)\n>>> a\n[0, 1, 2, 3]\n>>> a[::2]\n[0, 2]\n>>> del a[::2]\n>>> a\n[1, 3]\n```\nOne can also now pass slice objects to the\n__getitem__ methods of the built-in sequences:\n```text\n\n>>> range(10).__getitem__(slice(0, 5, 2))\n[0, 2, 4]\n```\nOr use slice objects directly in subscripts:\n```text\n\n>>> range(10)[slice(0, 5, 2)]\n[0, 2, 4]\n```\nTo simplify implementing sequences that support extended slicing,\nslice objects now have a method indices(length) which,\ngiven the length of a sequence, returns a `( start , stop , step )` tuple that can be passed directly to\nrange().\nindices() handles omitted and out-of-bounds indices in a\nmanner consistent with regular slices (and this innocuous phrase hides\na welter of confusing details!). The method is intended to be used\nlike this:\n```text\n\nclass FakeSeq:\n...\ndef calc_item(self, i):\n...\ndef __getitem__(self, item):\nif isinstance(item, slice):\nindices = item.indices(len(self))\nreturn FakeSeq([self.calc_item(i) in range(*indices)])\nelse:\nreturn self.calc_item(i)\n```\nFrom this example you can also see that the built-in slice\nobject is now the type object for the slice type, and is no longer a\nfunction. This is consistent with Python 2.2, where int,\nstr, etc., underwent the same change.", "python_version": "2.3", "length": 3257, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/section-slices.html"} {"title": "What's New in Python 2.3", "text": "../index.html | contents.html | What's New in Python 2.3 | contents.html\nUp:\nPython Documentation Index (../index.html)\nNext:\n---\n# What's New in Python 2.3\nA.M. Kuchling\namk@amk.ca", "python_version": "2.3", "length": 181, "url": "https://docs.python.org/2.3/Python-Docs-2.3/whatsnew/whatsnew23.html"}