{"title": "About the Python Documentation", "text": "./ | About the Python Documentation\nUp:\nPython Documentation Index (./)\n---\n## About the Python Documentation\nThe Python documentation was originally written by Guido van\nRossum, but has increasingly become a community effort over the\npast several years. This growing collection of documents is\navailable in several formats, including typeset versions in PDF\nand PostScript for printing, from the Python Web site (http://www.pythonlabs.com/).\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": "1.6", "length": 1156, "url": "https://docs.python.org/1.6/about.html"} {"title": "About this document ...", "text": "genindex.html | api.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# About this document ...\nPython/C API Reference Manual,\nSeptember 18, 2000, Release 1.6\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | api.html | Python/C API Reference Manual | contents.html | genindex.html\n---", "python_version": "1.6", "length": 1667, "url": "https://docs.python.org/1.6/api/about.html"} {"title": "6. Abstract Objects Layer", "text": "importing.html | api.html | object.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6. Abstract Objects Layer\nThe functions in this chapter interact with Python objects regardless\nof their type, or with wide classes of object types (e.g. all\nnumerical types, or all sequence types). When used on object types\nfor which they do not apply, they will raise a Python exception.", "python_version": "1.6", "length": 399, "url": "https://docs.python.org/1.6/api/abstract.html"} {"title": "Python/C API Reference Manual", "text": "../index.html | front.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 250, "url": "https://docs.python.org/1.6/api/api.html"} {"title": "10.5 Buffer Object Structures", "text": "sequence-structs.html | newTypes.html | genindex.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.5 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: It is very important that your\nPyTypeObject structure uses `Py_TPFLAGS_DEFAULT` for the\nvalue of the tp_flags member rather than `0`. This\ntells the Python runtime that your PyBufferProcs structure\ncontains the bf_getcharbuffer slot. Older versions of Python\ndid not have this member, so a new Python interpreter using an old\nextension needs to be able to test for its presence before using it.", "python_version": "1.6", "length": 997, "url": "https://docs.python.org/1.6/api/buffer-structs.html"} {"title": "7.2.3 Buffer Objects", "text": "unicodeMethodsAndSlots.html | sequenceObjects.html | tupleObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.3 Buffer Objects\nPython objects implemented in C can export a group of functions called\nthe ``buffer interface.'' 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 PyArgs_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.5 (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": "1.6", "length": 2211, "url": "https://docs.python.org/1.6/api/bufferObjects.html"} {"title": "7.2.2.1 Builtin Codecs", "text": "unicodeObjects.html | unicodeObjects.html | unicodeMethodsAndSlots.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.2.2.1 Builtin 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 which\nis UTF-8.\nError handling is set by errors which may also be set to NULL meaning\nto use the default handling defined for the codec. Default error\nhandling for all builtin codecs is ``strict'' (ValueErrors are 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:\nOnly 7-bit ASCII data is excepted. 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\nWindows and use the Win32 MBCS converters to implement the\nconversions.\nNote that MBCS (or DBCS) is a class of encodings, not just one. The\ntarget encoding is defined by the user settings on the machine running\nthe codec.", "python_version": "1.6", "length": 2737, "url": "https://docs.python.org/1.6/api/builtinCodecs.html"} {"title": "7.5.3 CObjects", "text": "moduleObjects.html | otherObjects.html | initialization.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.3 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": "1.6", "length": 310, "url": "https://docs.python.org/1.6/api/cObjects.html"} {"title": "10.1 Common Object Structures", "text": "newTypes.html | newTypes.html | mapping-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.1 Common Object Structures\nPyObject, PyVarObject\nPyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD\nTypedefs:\nunaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,\nintintargfunc, intobjargproc, intintobjargproc, objobjargproc,\ndestructor, printfunc, getattrfunc, getattrofunc, setattrfunc,\nsetattrofunc, cmpfunc, reprfunc, hashfunc", "python_version": "1.6", "length": 472, "url": "https://docs.python.org/1.6/api/common-structs.html"} {"title": "7.4.4 Complex Number Objects", "text": "floatObjects.html | numericObjects.html | node44.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.4.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": "1.6", "length": 435, "url": "https://docs.python.org/1.6/api/complexObjects.html"} {"title": "7. Concrete Objects Layer", "text": "mapping.html | api.html | fundamental.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7. Concrete Objects Layer\nThe functions in this chapter are specific to certain Python object\ntypes. Passing them an object of the wrong type is not a good idea;\nif you receive an object from a Python program and you are not sure\nthat it has the right type, you must perform a type check first;\nfor example. to check that an object is a dictionary, use\nPyDict_Check(). The chapter is structured like the\n``family tree'' of Python object types.", "python_version": "1.6", "length": 556, "url": "https://docs.python.org/1.6/api/concrete.html"} {"title": "Contents", "text": "front.html | api.html | intro.html | Python/C API Reference Manual | genindex.html\n---\n## Contents", "python_version": "1.6", "length": 98, "url": "https://docs.python.org/1.6/api/contents.html"} {"title": "3. Reference Counting", "text": "veryhigh.html | api.html | exceptionHandling.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 3. Reference Counting\nThe macros in this section are used for managing reference counts\nof Python objects.\nThe following functions or macros are only for use within the\ninterpreter core: _Py_Dealloc(),\n_Py_ForgetReference(), _Py_NewReference(), as\nwell as the global variable _Py_RefTotal.", "python_version": "1.6", "length": 409, "url": "https://docs.python.org/1.6/api/countingRefs.html"} {"title": "7.3.1 Dictionary Objects", "text": "mapObjects.html | mapObjects.html | numericObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.3.1 Dictionary Objects", "python_version": "1.6", "length": 151, "url": "https://docs.python.org/1.6/api/dictObjects.html"} {"title": "1.4 Embedding Python", "text": "exceptions.html | intro.html | veryhigh.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.4 Embedding Python\nThe one important task that only embedders (as opposed to extension\nwriters) of the Python interpreter have to worry about is the\ninitialization, and possibly the finalization, of the Python\ninterpreter. Most functionality of the interpreter can only be used\nafter the interpreter has been initialized.\nThe basic initialization function is\nPy_Initialize().\nThis initializes the table of loaded modules, and creates the\nfundamental modules __builtin__,\n__main__ and\nsys. It also initializes the module\nsearch 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/python1.5 (replacing 1.5 with the current\ninterpreter version) relative to the parent directory where the\nexecutable named python is found on the shell command search\npath (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/python1.5. (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).\nSometimes, it is desirable to ``uninitialize'' Python. For instance,\nthe application may want to start over (make another call to\nPy_Initialize()) or the application is simply done with its\nuse of Python and wants to free all memory allocated by Python. This\ncan be accomplished by calling Py_Finalize(). The function\nPy_IsInitialized() returns\ntrue if Python is currently in the initialized state. More\ninformation about these functions is given in a later chapter.", "python_version": "1.6", "length": 2859, "url": "https://docs.python.org/1.6/api/embedding.html"} {"title": "4. Exception Handling", "text": "countingRefs.html | api.html | standardExceptions.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 4. Exception Handling\nThe functions described in this chapter will let you handle and raise Python\nexceptions. It is important to understand some of the basics of\nPython exception handling. It works somewhat like the\nUnix errno variable: there is a global indicator (per\nthread) of the last error that occurred. Most functions don't clear\nthis on success, but will set it to indicate the cause of the error on\nfailure. Most functions also return an error indicator, usually\nNULL if they are supposed to return a pointer, or `-1` if they\nreturn an integer (exception: the PyArg_Parse*() functions\nreturn `1` for success and `0` for failure). When a\nfunction must fail because some function it called failed, it\ngenerally doesn't set the error indicator; the function it called\nalready set it.\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": "1.6", "length": 1191, "url": "https://docs.python.org/1.6/api/exceptionHandling.html"} {"title": "1.3 Exceptions", "text": "types.html | intro.html | embedding.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.3 Exceptions\nThe Python programmer only needs to deal with exceptions if specific\nerror handling is required; unhandled exceptions are automatically\npropagated to the caller, then to the caller's caller, and so on, until\nthey reach the top-level interpreter, where they are reported to the\nuser accompanied by a stack traceback.\nFor C programmers, however, error checking always has to be explicit.\nAll functions in the Python/C API can raise exceptions, unless an\nexplicit claim is made otherwise in a function's documentation. In\ngeneral, when a function encounters an error, it sets an exception,\ndiscards any object references that it owns, and returns an\nerror indicator -- usually NULL or `-1`. A few functions\nreturn a Boolean true/false result, with false indicating an error.\nVery few functions return no explicit error indicator or have an\nambiguous return value, and require explicit testing for errors with\nPyErr_Occurred().\nException state is maintained in per-thread storage (this is\nequivalent to using global storage in an unthreaded application). A\nthread can be in one of two states: an exception has occurred, or not.\nThe function PyErr_Occurred() can be used to check for\nthis: it returns a borrowed reference to the exception type object\nwhen an exception has occurred, and NULL otherwise. There are a\nnumber of functions to set the exception state:\nPyErr_SetString() is the most\ncommon (though not the most general) function to set the exception\nstate, and PyErr_Clear() clears the\nexception state.\nThe full exception state consists of three objects (all of which can\nbe NULL): the exception type, the corresponding exception\nvalue, and the traceback. These have the same meanings as the Python\nobjects `sys.exc_type`, `sys.exc_value`, and\n`sys.exc_traceback`; however, they are not the same: the Python\nobjects represent the last exception being handled by a Python\ntry ... except statement, while the C level\nexception state only exists while an exception is being passed on\nbetween C functions until it reaches the Python bytecode interpreter's\nmain loop, which takes care of transferring it to `sys.exc_type`and 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\nreturn item + 1\n```\nHere is the corresponding C code, in all its glory:\n```text\n\nint incr_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)) goto error;\n\n/* Clear the error and use zero: */\nPyErr_Clear();\nitem = PyInt_FromLong(0L);\nif (item == NULL) goto error;\n}\n\nconst_one = PyInt_FromLong(1L);\nif (const_one == NULL) goto error;\n\nincremented_item = PyNumber_Add(item, const_one);\nif (incremented_item == NULL) goto error;\n\nif (PyObject_SetItem(dict, key, incremented_item) < 0) goto 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": "1.6", "length": 5497, "url": "https://docs.python.org/1.6/api/exceptions.html"} {"title": "7.5.1 File Objects", "text": "otherObjects.html | otherObjects.html | moduleObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.1 File Objects\nPython's built-in file objects are implemented entirely on the\nFILE* support from the C standard library. This is an\nimplementation detail and may change in future releases of Python.", "python_version": "1.6", "length": 332, "url": "https://docs.python.org/1.6/api/fileObjects.html"} {"title": "7.4.3 Floating Point Objects", "text": "longObjects.html | numericObjects.html | complexObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.4.3 Floating Point Objects", "python_version": "1.6", "length": 160, "url": "https://docs.python.org/1.6/api/floatObjects.html"} {"title": "Front Matter", "text": "api.html | api.html | contents.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# Front Matter\nBEOPEN.COM TERMS AND CONDITIONS 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 OPEN SOURCE LICENSE AGREEMENT\nPython 1.6 is made available subject to the terms and conditions in\nCNRI's License Agreement. This Agreement together with Python 1.6 may\nbe located on the Internet using the following unique, persistent\nidentifier (known as a handle): 1895.22/1012. This Agreement may also\nbe obtained from a proxy server on the Internet using the following\nURL: http://hdl.handle.net/1895.22/1012.\nCWI PERMISSIONS STATEMENT AND DISCLAIMER\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.\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: The current version of this document is incomplete.\nI hope that it is nevertheless useful. I will continue to work on it,\nand release new versions from time to time, independent from Python\nsource code releases.", "python_version": "1.6", "length": 4601, "url": "https://docs.python.org/1.6/api/front.html"} {"title": "7.1 Fundamental Objects", "text": "concrete.html | concrete.html | typeObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.1 Fundamental Objects\nThis section describes Python type objects and the singleton object\n`None`.", "python_version": "1.6", "length": 218, "url": "https://docs.python.org/1.6/api/fundamental.html"} {"title": "Index", "text": "buffer-structs.html | api.html | about.html | Python/C API Reference Manual | contents.html\n---\n## Index\n---\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\nk (#letter-k) |\nl (#letter-l) |\nm (#letter-m) |\nn (#letter-n) |\no (#letter-o) |\np (#letter-p) |\nr (#letter-r) |\ns (#letter-s) |\nt (#letter-t) |\nu (#letter-u) |\nv (#letter-v)\n---\n## _ (underscore)\n---\n## A\n---\n## B\n---\n## C\n---\n## D\n---\n## E\n---\n## F\n---\n## G\n---\n## H\n---\n## I\n---\n## K\n---\n## L\n---\n## M\n---\n## N\n---\n## O\n---\n## P\n---\n## R\n---\n## S\n---\n## T\n---\n## U\n---\n## V", "python_version": "1.6", "length": 644, "url": "https://docs.python.org/1.6/api/genindex.html"} {"title": "5.3 Importing Modules", "text": "processControl.html | utilities.html | abstract.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.3 Importing Modules", "python_version": "1.6", "length": 144, "url": "https://docs.python.org/1.6/api/importing.html"} {"title": "1.1 Include Files", "text": "intro.html | intro.html | objects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.1 Include Files\nAll function, type and macro definitions needed to use the Python/C\nAPI are included in your code by the following line:\n```text\n\n#include \"Python.h\"\n```\nThis implies inclusion of the following standard headers:\n``, ``, ``, and\n`` (if available).\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\n$prefix/include/pythonversion/ and\n$exec_prefix/include/pythonversion/, where\n$prefix 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\n$prefix include the platform specific headers from\n$exec_prefix.", "python_version": "1.6", "length": 1777, "url": "https://docs.python.org/1.6/api/includes.html"} {"title": "Python/C API Reference Manual", "text": "../index.html | front.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 250, "url": "https://docs.python.org/1.6/api/index.html"} {"title": "8. Initialization, Finalization, and Threads", "text": "cObjects.html | api.html | threads.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 8. Initialization, Finalization, and Threads", "python_version": "1.6", "length": 154, "url": "https://docs.python.org/1.6/api/initialization.html"} {"title": "7.4.1 Plain Integer Objects", "text": "numericObjects.html | numericObjects.html | longObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.4.1 Plain Integer Objects", "python_version": "1.6", "length": 159, "url": "https://docs.python.org/1.6/api/intObjects.html"} {"title": "1. Introduction", "text": "contents.html | api.html | includes.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1. Introduction\nThe Application Programmer's Interface to Python gives C and\nC++ programmers access to the Python interpreter at a variety of\nlevels. The API is equally usable from C++, but for brevity it is\ngenerally referred to as the Python/C API. There are two\nfundamentally different reasons for using the Python/C API. The first\nreason is to write extension modules for specific purposes;\nthese are C modules that extend the Python interpreter. This is\nprobably the most common use. The second reason is to use Python as a\ncomponent in a larger application; this technique is generally\nreferred to as embedding Python in an application.\nWriting an extension module is a relatively well-understood process,\nwhere a ``cookbook'' approach works well. There are several tools\nthat automate the process to some extent. While people have embedded\nPython in other applications since its early existence, the process of\nembedding Python is less straightforward that 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": "1.6", "length": 1413, "url": "https://docs.python.org/1.6/api/intro.html"} {"title": "7.2.5 List Objects", "text": "tupleObjects.html | sequenceObjects.html | mapObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.5 List Objects", "python_version": "1.6", "length": 148, "url": "https://docs.python.org/1.6/api/listObjects.html"} {"title": "7.4.2 Long Integer Objects", "text": "intObjects.html | numericObjects.html | floatObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.4.2 Long Integer Objects", "python_version": "1.6", "length": 155, "url": "https://docs.python.org/1.6/api/longObjects.html"} {"title": "7.3 Mapping Objects", "text": "listObjects.html | concrete.html | dictObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.3 Mapping Objects", "python_version": "1.6", "length": 141, "url": "https://docs.python.org/1.6/api/mapObjects.html"} {"title": "10.2 Mapping Object Structures", "text": "common-structs.html | newTypes.html | number-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.2 Mapping Object Structures", "python_version": "1.6", "length": 158, "url": "https://docs.python.org/1.6/api/mapping-structs.html"} {"title": "6.4 Mapping Protocol", "text": "sequence.html | abstract.html | concrete.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.4 Mapping Protocol", "python_version": "1.6", "length": 136, "url": "https://docs.python.org/1.6/api/mapping.html"} {"title": "9. Memory Management", "text": "threads.html | api.html | memoryOverview.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9. Memory Management", "python_version": "1.6", "length": 136, "url": "https://docs.python.org/1.6/api/memory.html"} {"title": "9.3 Examples", "text": "memoryInterface.html | memory.html | newTypes.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9.3 Examples\nHere is the example from section 9.1 (memoryOverview.html#memoryOverview), rewritten so\nthat the I/O buffer is allocated from the Python heap by using the\nfirst function set:\n```text\n\nPyObject *res;\nchar *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */\n\nif (buf == NULL)\nreturn PyErr_NoMemory();\n/* ...Do some I/O operation involving buf... */\nres = PyString_FromString(buf);\nPyMem_Free(buf); /* allocated with PyMem_Malloc */\nreturn res;\n```\nWith the second function set, the need to call\nPyErr_NoMemory() is obviated:\n```text\n\nPyObject *res;\nchar *buf = (char *) Py_Malloc(BUFSIZ); /* for I/O */\n\nif (buf == NULL)\nreturn NULL;\n/* ...Do some I/O operation involving buf... */\nres = PyString_FromString(buf);\nPy_Free(buf); /* allocated with Py_Malloc */\nreturn res;\n```\nThe same code using the macro 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 three examples above, the buffer is always\nmanipulated via functions/macros 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\n_PyObject_New() and\n_PyObject_NewVar(), or with\ntheir corresponding macros\nPyObject_NEW() and\nPyObject_NEW_VAR().", "python_version": "1.6", "length": 2174, "url": "https://docs.python.org/1.6/api/memoryExamples.html"} {"title": "9.2 Memory Interface", "text": "memoryOverview.html | memory.html | memoryExamples.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9.2 Memory Interface\nThe following function sets, modeled after the ANSI C standard, are\navailable for allocating and releasing memory from the Python heap:\nThe following type-oriented macros are provided for convenience. Note\nthat TYPE refers to any C type.", "python_version": "1.6", "length": 384, "url": "https://docs.python.org/1.6/api/memoryInterface.html"} {"title": "9.1 Overview", "text": "memory.html | memory.html | memoryInterface.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 9.1 Overview\nMemory management in Python involves a private heap containing all\nPython objects and data structures. The management of this private\nheap is ensured internally by the Python memory manager. The\nPython memory manager has different components which deal with various\ndynamic storage management aspects, like sharing, segmentation,\npreallocation or caching.\nAt the lowest level, a raw memory allocator ensures that there is\nenough room in the private heap for storing all Python-related data\nby interacting with the memory manager of the operating system. On top\nof the raw memory allocator, several object-specific allocators\noperate on the same heap and implement distinct memory management\npolicies adapted to the peculiarities of every object type. For\nexample, integer objects are managed differently within the heap than\nstrings, tuples or dictionaries because integers imply different\nstorage requirements and speed/space tradeoffs. The Python memory\nmanager thus delegates some of the work to the object-specific\nallocators, but ensures that the latter operate within the bounds of\nthe private heap.\nIt is important to understand that the management of the Python heap\nis performed by the interpreter itself and that the user has no\ncontrol on it, even if she regularly manipulates object pointers to\nmemory blocks inside that heap. The allocation of heap space for\nPython objects and other internal buffers is performed on demand by\nthe Python memory manager through the Python/C API functions listed in\nthis document.\nTo avoid memory corruption, extension writers should never try to\noperate on Python objects with the functions exported by the C\nlibrary: malloc(),\ncalloc(),\nrealloc() and\nfree(). This will result in\nmixed calls between the C allocator and the Python memory manager\nwith fatal consequences, because they implement different algorithms\nand operate on different heaps. However, one may safely allocate and\nrelease memory blocks with the C library allocator for individual\npurposes, as shown in the following example:\n```text\n\nPyObject *res;\nchar *buf = (char *) malloc(BUFSIZ); /* for I/O */\n\nif (buf == NULL)\nreturn PyErr_NoMemory();\n...Do some I/O operation involving buf...\nres = PyString_FromString(buf);\nfree(buf); /* malloc'ed */\nreturn res;\n```\nIn this example, the memory request for the I/O buffer is handled by\nthe C library allocator. The Python memory manager is involved only\nin the allocation of the string object returned as a result.\nIn most situations, however, it is recommended to allocate memory from\nthe Python heap specifically because the latter is under control of\nthe Python memory manager. For example, this is required when the\ninterpreter is extended with new object types written in C. Another\nreason for using the Python heap is the desire to inform the\nPython memory manager about the memory needs of the extension module.\nEven when the requested memory is used exclusively for internal,\nhighly-specific purposes, delegating all memory requests to the Python\nmemory manager causes the interpreter to have a more accurate image of\nits memory footprint as a whole. Consequently, under certain\ncircumstances, the Python memory manager may or may not trigger\nappropriate actions, like garbage collection, memory compaction or\nother preventive procedures. Note that by using the C library\nallocator as shown in the previous example, the allocated memory for\nthe I/O buffer escapes completely the Python memory manager.", "python_version": "1.6", "length": 3600, "url": "https://docs.python.org/1.6/api/memoryOverview.html"} {"title": "7.5.2 Module Objects", "text": "fileObjects.html | otherObjects.html | cObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.5.2 Module Objects\nThere are only a few functions special to module objects.", "python_version": "1.6", "length": 202, "url": "https://docs.python.org/1.6/api/moduleObjects.html"} {"title": "10. Defining New Object Types", "text": "memoryExamples.html | api.html | common-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10. Defining New Object Types\nPy_InitModule (!!!)\nPyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse\nPy_BuildValue\nDL_IMPORT\nPy*_Check\n_Py_NoneStruct", "python_version": "1.6", "length": 280, "url": "https://docs.python.org/1.6/api/newTypes.html"} {"title": "4.2 Deprecation of String Exceptions", "text": "standardExceptions.html | exceptionHandling.html | utilities.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 4.2 Deprecation of String Exceptions\nThe `-X` command-line option will be removed in Python 1.6. All\nexceptions built into Python or provided in the standard library will\nbe classes derived from Exception.\nString exceptions will still be supported in the interpreter to allow\nexisting code to run unmodified, but this will also change in a future\nrelease.", "python_version": "1.6", "length": 491, "url": "https://docs.python.org/1.6/api/node15.html"} {"title": "7.4.4.1 Complex Numbers as C Structures", "text": "complexObjects.html | complexObjects.html | node45.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.4.4.1 Complex Numbers as C Structures\nNote that the functions which accept these structures as parameters\nand return them as results do so by value rather than\ndereferencing them through pointers. This is consistent throughout\nthe API.", "python_version": "1.6", "length": 365, "url": "https://docs.python.org/1.6/api/node44.html"} {"title": "7.4.4.2 Complex Numbers as Python Objects", "text": "node44.html | complexObjects.html | otherObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.4.4.2 Complex Numbers as Python Objects", "python_version": "1.6", "length": 167, "url": "https://docs.python.org/1.6/api/node45.html"} {"title": "7.1.2 The None Object", "text": "typeObjects.html | fundamental.html | sequenceObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.1.2 The None Object\nNote that the PyTypeObject for `None` is not directly\nexposed in the Python/C API. Since `None` is a singleton,\ntesting for object identity (using \"==\" in C) is sufficient.\nThere is no PyNone_Check() function for the same reason.", "python_version": "1.6", "length": 381, "url": "https://docs.python.org/1.6/api/noneObject.html"} {"title": "10.3 Number Object Structures", "text": "mapping-structs.html | newTypes.html | sequence-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.3 Number Object Structures", "python_version": "1.6", "length": 160, "url": "https://docs.python.org/1.6/api/number-structs.html"} {"title": "6.2 Number Protocol", "text": "object.html | abstract.html | sequence.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.2 Number Protocol", "python_version": "1.6", "length": 133, "url": "https://docs.python.org/1.6/api/number.html"} {"title": "7.4 Numeric Objects", "text": "dictObjects.html | concrete.html | intObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.4 Numeric Objects", "python_version": "1.6", "length": 140, "url": "https://docs.python.org/1.6/api/numericObjects.html"} {"title": "6.1 Object Protocol", "text": "abstract.html | abstract.html | number.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.1 Object Protocol", "python_version": "1.6", "length": 133, "url": "https://docs.python.org/1.6/api/object.html"} {"title": "1.2 Objects, Types and Reference Counts", "text": "includes.html | intro.html | refcounts.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 1.2 Objects, Types and Reference Counts\nMost Python/C API functions have one or more arguments as well as a\nreturn value of type PyObject*. This type is a pointer\nto an opaque data type representing an arbitrary Python\nobject. Since all Python object types are treated the same way by the\nPython language in most situations (e.g., assignments, scope rules,\nand argument passing), it is only fitting that they should be\nrepresented by a single C type. Almost all Python objects live on the\nheap: you never declare an automatic or static variable of type\nPyObject, only pointer variables of type PyObject* can\nbe declared. The sole exception are the type objects;\nsince these must never be deallocated, they are typically static\nPyTypeObject objects.\nAll Python objects (even Python integers) have a type and a\nreference count. An object's type determines what kind of object\nit is (e.g., an integer, a list, or a user-defined function; there are\nmany more as explained in the Python\nReference Manual (../ref/ref.html)). For each of the well-known types there is a macro\nto check whether an object is of that type; for instance,\n\"PyList_Check(a)\" is true if (and only if) the object\npointed to by a is a Python list.", "python_version": "1.6", "length": 1328, "url": "https://docs.python.org/1.6/api/objects.html"} {"title": "5.1 OS Utilities", "text": "utilities.html | utilities.html | processControl.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.1 OS Utilities", "python_version": "1.6", "length": 140, "url": "https://docs.python.org/1.6/api/os.html"} {"title": "7.5 Other Objects", "text": "node45.html | concrete.html | fileObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.5 Other Objects", "python_version": "1.6", "length": 134, "url": "https://docs.python.org/1.6/api/otherObjects.html"} {"title": "5.2 Process Control", "text": "os.html | utilities.html | importing.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5.2 Process Control", "python_version": "1.6", "length": 131, "url": "https://docs.python.org/1.6/api/processControl.html"} {"title": "1.2.1.1 Reference Count Details", "text": "refcounts.html | refcounts.html | types.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 1.2.1.1 Reference Count Details\nThe reference count behavior of functions in the Python/C API is best\nexplained in terms of ownership of references. Note that we\ntalk of owning references, never of owning objects; objects are always\nshared! When a function owns a reference, it has to dispose of it\nproperly -- either by passing ownership on (usually to its caller) or\nby calling Py_DECREF() or Py_XDECREF(). When\na function passes ownership of a reference on to its caller, the\ncaller is said to receive a new reference. When no ownership\nis transferred, the caller is said to borrow the reference.\nNothing needs to be done for a borrowed reference.\nConversely, when calling a 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 set_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 (i.e.,\nthe caller 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 (i.e., 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 sum_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 sum_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": "1.6", "length": 5631, "url": "https://docs.python.org/1.6/api/refcountDetails.html"} {"title": "1.2.1 Reference Counts", "text": "objects.html | objects.html | refcountDetails.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 1.2.1 Reference Counts\nThe reference count is important because today's computers have a\nfinite (and often severely limited) memory size; it counts how many\ndifferent places there are that have a reference to an object. Such a\nplace could be another object, or a global (or static) C variable, or\na local variable in some C function. When an object's reference count\nbecomes zero, the object is deallocated. If it contains references to\nother objects, their reference count is decremented. Those other\nobjects may be deallocated in turn, if this decrement makes their\nreference count become zero, and so on. (There's an obvious problem\nwith objects that reference each other here; for now, the solution is\n``don't do that.'')\nReference counts are always manipulated explicitly. The normal way is\nto use the macro Py_INCREF() to\nincrement an object's reference count by one, and\nPy_DECREF() to decrement it by\none. The Py_DECREF() macro is considerably more complex\nthan the incref one, since it must check whether the reference count\nbecomes zero and then cause the object's deallocator to be called.\nThe deallocator is a function pointer contained in the object's type\nstructure. The type-specific deallocator takes care of decrementing\nthe reference counts for other objects contained in the object if this\nis a compound object type, such as a list, as well as performing any\nadditional finalization that's needed. There's no chance that the\nreference count can overflow; at least as many bits are used to hold\nthe reference count as there are distinct memory locations in virtual\nmemory (assuming `sizeof(long) >= sizeof(char*)`). Thus, the\nreference count increment is a simple operation.\nIt is not necessary to increment an object's reference count for every\nlocal variable that contains a pointer to an object. In theory, the\nobject's reference count goes up by one when the variable is made to\npoint to it and it goes down by one when the variable goes out of\nscope. However, these two cancel each other out, so at the end the\nreference count hasn't changed. The only real reason to use the\nreference count is to prevent the object from being deallocated as\nlong as our variable is pointing to it. If we know that there is at\nleast one other reference to the object that lives at least as long as\nour variable, there is no need to increment the reference count\ntemporarily. An important situation where this arises is in objects\nthat are passed as arguments to C functions in an extension module\nthat are called from Python; the call mechanism guarantees to hold a\nreference to every argument for the duration of the call.\nHowever, a common pitfall is to extract an object from a list and\nhold on to it for a while without incrementing its reference count.\nSome other operation might conceivably remove the object from the\nlist, decrementing its reference count and possible deallocating it.\nThe real danger is that innocent-looking operations may invoke\narbitrary Python code which could do this; there is a code path which\nallows control to flow back to the user from a Py_DECREF(),\nso almost any operation is potentially dangerous.\nA safe approach is to always use the generic operations (functions\nwhose name begins with \"PyObject_\", \"PyNumber_\",\n\"PySequence_\" or \"PyMapping_\"). These operations always\nincrement the reference count of the object they return. This leaves\nthe caller with the responsibility to call\nPy_DECREF() when they are done with the result; this soon\nbecomes second nature.", "python_version": "1.6", "length": 3628, "url": "https://docs.python.org/1.6/api/refcounts.html"} {"title": "10.4 Sequence Object Structures", "text": "number-structs.html | newTypes.html | buffer-structs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 10.4 Sequence Object Structures", "python_version": "1.6", "length": 159, "url": "https://docs.python.org/1.6/api/sequence-structs.html"} {"title": "6.3 Sequence Protocol", "text": "number.html | abstract.html | mapping.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 6.3 Sequence Protocol", "python_version": "1.6", "length": 134, "url": "https://docs.python.org/1.6/api/sequence.html"} {"title": "7.2 Sequence Objects", "text": "noneObject.html | concrete.html | stringObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 7.2 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": "1.6", "length": 328, "url": "https://docs.python.org/1.6/api/sequenceObjects.html"} {"title": "4.1 Standard Exceptions", "text": "exceptionHandling.html | exceptionHandling.html | node15.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 4.1 Standard Exceptions\nAll standard Python exceptions are available as global variables whose\nnames are \"PyExc_\" followed by the Python exception name. These\nhave the type PyObject*; they are all class objects. For\ncompleteness, here are all the variables:\nNote:\n(1): This is a base class for other standard exceptions. If the\n`-X` interpreter option is used, these will be tuples\ncontaining the string exceptions which would have otherwise been\nsubclasses.", "python_version": "1.6", "length": 590, "url": "https://docs.python.org/1.6/api/standardExceptions.html"} {"title": "7.2.1 String Objects", "text": "sequenceObjects.html | sequenceObjects.html | unicodeObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.1 String Objects", "python_version": "1.6", "length": 157, "url": "https://docs.python.org/1.6/api/stringObjects.html"} {"title": "8.1 Thread State and the Global Interpreter Lock", "text": "initialization.html | initialization.html | memory.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 8.1 Thread State and the Global Interpreter Lock\nThe Python interpreter is not fully thread safe. In order to support\nmulti-threaded Python programs, there's a global lock that must be\nheld by the current thread before it can safely access Python objects.\nWithout the lock, even the simplest operations could cause problems in\na multi-threaded program: for example, when two threads simultaneously\nincrement the reference count of the same object, the reference count\ncould end up being incremented only once instead of twice.\nTherefore, the rule exists that only the thread that has acquired the\nglobal interpreter lock may operate on Python objects or call Python/C\nAPI functions. In order to support multi-threaded Python programs,\nthe interpreter regularly releases and reacquires the lock -- by\ndefault, every ten bytecode instructions (this can be changed with\nsys.setcheckinterval()). The lock is also released and\nreacquired around potentially blocking I/O operations like reading or\nwriting a file, so that other threads can run while the thread that\nrequests the I/O is waiting for the I/O operation to complete.\nThe Python interpreter needs to keep some bookkeeping information\nseparate per thread -- for this it uses a data structure called\nPyThreadState. This is new in Python\n1.5; in earlier versions, such state was stored in global variables,\nand switching threads could cause problems. In particular, exception\nhandling is now thread safe, when the application uses\nsys.exc_info() to access the exception last raised in the\ncurrent thread.\nThere's one global variable left, however: the pointer to the current\nPyThreadState structure. While most\nthread packages have a way to store ``per-thread global data,''\nPython's internal platform independent thread abstraction doesn't\nsupport this yet. Therefore, the current thread state must be\nmanipulated explicitly.\nThis is easy enough in most cases. Most code manipulating the global\ninterpreter lock has the following simple structure:\n```text\n\nSave the thread state in a local variable.\nRelease the interpreter lock.\n...Do some blocking I/O operation...\nReacquire the interpreter lock.\nRestore the thread state from the local variable.\n```\nThis is so common that a pair of macros exists to simplify it:\n```text\n\nPy_BEGIN_ALLOW_THREADS\n...Do some blocking I/O operation...\nPy_END_ALLOW_THREADS\n```\nThe `Py_BEGIN_ALLOW_THREADS` macro\nopens a new block and declares a hidden local variable; the\n`Py_END_ALLOW_THREADS` macro closes\nthe block. Another advantage of using these two macros is that when\nPython is compiled without thread support, they are defined empty,\nthus saving the thread state and lock manipulations.\nWhen thread support is enabled, the block above expands to the\nfollowing code:\n```text\n\nPyThreadState *_save;\n\n_save = PyEval_SaveThread();\n...Do some blocking I/O operation...\nPyEval_RestoreThread(_save);\n```\nUsing even lower level primitives, we can get roughly the same effect\nas follows:\n```text\n\nPyThreadState *_save;\n\n_save = PyThreadState_Swap(NULL);\nPyEval_ReleaseLock();\n...Do some blocking I/O operation...\nPyEval_AcquireLock();\nPyThreadState_Swap(_save);\n```\nThere are some subtle differences; in particular,\nPyEval_RestoreThread() saves\nand restores the value of the global variable\nerrno, since the lock manipulation does not\nguarantee that errno is left alone. Also, when thread support\nis disabled,\nPyEval_SaveThread() and\nPyEval_RestoreThread() don't manipulate the lock; in this\ncase, PyEval_ReleaseLock() and\nPyEval_AcquireLock() are not\navailable. This is done so that dynamically loaded extensions\ncompiled with thread support enabled can be loaded by an interpreter\nthat was compiled with disabled thread support.\nThe global interpreter lock is used to protect the pointer to the\ncurrent thread state. When releasing the lock and saving the thread\nstate, the current thread state pointer must be retrieved before the\nlock is released (since another thread could immediately acquire the\nlock and store its own thread state in the global variable).\nReversely, when acquiring the lock and restoring the thread state, the\nlock must be acquired before storing the thread state pointer.\nWhy am I going on with so much detail about this? Because when\nthreads are created from C, they don't have the global interpreter\nlock, nor is there a thread state data structure for them. Such\nthreads must bootstrap themselves into existence, by first creating a\nthread state data structure, then acquiring the lock, and finally\nstoring their thread state pointer, before they can start using the\nPython/C API. When they are done, they should reset the thread state\npointer, release the lock, and finally free their thread state data\nstructure.\nWhen creating a thread data structure, you need to provide an\ninterpreter state data structure. The interpreter state data\nstructure hold global data that is shared by all threads in an\ninterpreter, for example the module administration\n(`sys.modules`). Depending on your needs, you can either create\na new interpreter state data structure, or share the interpreter state\ndata structure used by the Python main thread (to access the latter,\nyou must obtain the thread state and access its interp member;\nthis must be done by a thread that is created by Python or by the main\nthread after Python is initialized).\nThe following macros are normally used without a trailing semicolon;\nlook for example usage in the Python source distribution.\nAll of the following functions are only available when thread support\nis enabled at compile time, and must be called only when the\ninterpreter lock has been created.", "python_version": "1.6", "length": 5760, "url": "https://docs.python.org/1.6/api/threads.html"} {"title": "7.2.4 Tuple Objects", "text": "bufferObjects.html | sequenceObjects.html | listObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.4 Tuple Objects", "python_version": "1.6", "length": 151, "url": "https://docs.python.org/1.6/api/tupleObjects.html"} {"title": "7.1.1 Type Objects", "text": "fundamental.html | fundamental.html | noneObject.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.1.1 Type Objects", "python_version": "1.6", "length": 143, "url": "https://docs.python.org/1.6/api/typeObjects.html"} {"title": "1.2.2 Types", "text": "refcountDetails.html | objects.html | exceptions.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 1.2.2 Types\nThere are few other data types that play a significant role in\nthe Python/C API; most are simple C types such as int,\nlong, double and char*. A few structure types\nare used to describe static tables used to list the functions exported\nby a module or the data attributes of a new object type, and another\nis used to describe the value of a complex number. These will\nbe discussed together with the functions that use them.", "python_version": "1.6", "length": 558, "url": "https://docs.python.org/1.6/api/types.html"} {"title": "7.2.2.2 Methods and Slot Functions", "text": "builtinCodecs.html | unicodeObjects.html | bufferObjects.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n### 7.2.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 in case an exception occurrs.", "python_version": "1.6", "length": 410, "url": "https://docs.python.org/1.6/api/unicodeMethodsAndSlots.html"} {"title": "7.2.2 Unicode Objects", "text": "stringObjects.html | sequenceObjects.html | builtinCodecs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n## 7.2.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": "1.6", "length": 943, "url": "https://docs.python.org/1.6/api/unicodeObjects.html"} {"title": "5. Utilities", "text": "node15.html | api.html | os.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 5. Utilities\nThe functions in this chapter perform various utility tasks, such as\nparsing function arguments and constructing Python values from C\nvalues.", "python_version": "1.6", "length": 257, "url": "https://docs.python.org/1.6/api/utilities.html"} {"title": "2. The Very High Level Layer", "text": "embedding.html | api.html | countingRefs.html | Python/C API Reference Manual | contents.html | genindex.html\n---\n# 2. The Very High Level Layer\nThe functions in this chapter will let you execute Python source code\ngiven in a file or a buffer, but they will not let you interact in a\nmore detailed way with the interpreter.\nSeveral of these functions accept a start symbol from the grammar as a\nparameter. The available start symbols are Py_eval_input,\nPy_file_input, and Py_single_input. These are\ndescribed following the functions which accept them as parameters.", "python_version": "1.6", "length": 565, "url": "https://docs.python.org/1.6/api/veryhigh.html"} {"title": "About this document ...", "text": "node45.html | dist.html | Distributing Python Modules | contents.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, 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---\nnode45.html | dist.html | Distributing Python Modules | contents.html\n---", "python_version": "1.6", "length": 1594, "url": "https://docs.python.org/1.6/dist/about.html"} {"title": "9.5 Creating a ``built'' distribution: the bdist command family", "text": "sdist-cmd.html | ref.html | node42.html | Distributing Python Modules | contents.html\n---\n## 9.5 Creating a ``built'' distribution: the\n`bdist` command family", "python_version": "1.6", "length": 158, "url": "https://docs.python.org/1.6/dist/bdist-cmds.html"} {"title": "9.1.4 build_clib", "text": "build-ext-cmd.html | build-cmds.html | install-cmd.html | Distributing Python Modules | contents.html\n---\n### 9.1.4 `build_clib`", "python_version": "1.6", "length": 128, "url": "https://docs.python.org/1.6/dist/build-clib-cmd.html"} {"title": "9.1.1 build", "text": "build-cmds.html | build-cmds.html | build-py-cmd.html | Distributing Python Modules | contents.html\n---\n### 9.1.1 `build`", "python_version": "1.6", "length": 121, "url": "https://docs.python.org/1.6/dist/build-cmd.html"} {"title": "9.1 Building modules: the build command family", "text": "ref.html | ref.html | build-cmd.html | Distributing Python Modules | contents.html\n---\n## 9.1 Building modules: the `build` command family", "python_version": "1.6", "length": 138, "url": "https://docs.python.org/1.6/dist/build-cmds.html"} {"title": "9.1.3 build_ext", "text": "build-py-cmd.html | build-cmds.html | build-clib-cmd.html | Distributing Python Modules | contents.html\n---\n### 9.1.3 `build_ext`", "python_version": "1.6", "length": 129, "url": "https://docs.python.org/1.6/dist/build-ext-cmd.html"} {"title": "9.1.2 build_py", "text": "build-cmd.html | build-cmds.html | build-ext-cmd.html | Distributing Python Modules | contents.html\n---\n### 9.1.2 `build_py`", "python_version": "1.6", "length": 124, "url": "https://docs.python.org/1.6/dist/build-py-cmd.html"} {"title": "6 Creating Built Distributions", "text": "manifest-options.html | dist.html | examples.html | Distributing Python Modules | contents.html\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 is\ndesigned to enable module developers to concentrate on their\nspecialty--writing code and creating source distributions--while an\nintermediary species of packager springs up to turn source\ndistributions into built distributions for as many platforms as there\nare packagers.\nOf course, the module developer could be his own packager; or the\npackager could be a volunteer ``out there'' somewhere who has access to\na platform which the original developer does not; or it could be\nsoftware periodically grabbing new source distributions and turning them\ninto built distributions for as many platforms as the software has\naccess to. Regardless of the nature of the beast, a packager uses the\nsetup script and the `bdist` command family to generate built\ndistributions.\nAs a simple example, if I run the following command in the Distutils\nsource tree:\n```text\n\npython setup.py bdist\n```\nthen the Distutils builds my module distribution (the Distutils itself\nin this case), does a ``fake'' installation (also in the build\ndirectory), and creates the default type of built distribution for my\nplatform. Currently, the default format for built distributions is a\n``dumb'' archive--tarball on Unix, ZIP file on Windows. (These are\ncalled ``dumb'' built distributions, because they must be unpacked in a\nspecific location to work.)\nThus, the above command on a Unix system creates\nDistutils-0.9.1.plat.tar.gz; unpacking this tarball\nfrom the root of the filesystemq installs the Distutils just as though\nyou had downloaded the source distribution and run `python setup.py\ninstall`. (Assuming that the target system has their Python\ninstallation laid out the same as you do--another reason these are\ncalled ``dumb'' distributions.) Obviously, for pure Python\ndistributions, this isn't a huge win--but for non-pure distributions,\nwhich include extensions that would need to be compiled, it can mean the\ndifference between someone being able to use your extensions or not.\n** filenames are inaccurate here! **\nThe `bdist` command has a --format option,\nsimilar to the `sdist` command, which you can use to select the\ntypes of built distribution to generate: for example,\n```text\n\npython setup.py bdist --format=zip\n```\nwould, when run on a Unix system, create\nDistutils-0.8.plat.zip--again, this archive would be\nunpacked from the root directory to install the Distutils.\nThe available formats for built distributions are:\nNotes:\n(1): default on Unix\n(2): default on Windows ** to-do! **\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:", "python_version": "1.6", "length": 3912, "url": "https://docs.python.org/1.6/dist/built-dist.html"} {"title": "9.3 Cleaning up: the clean command", "text": "install-scripts-cmd.html | ref.html | sdist-cmd.html | Distributing Python Modules | contents.html\n---\n## 9.3 Cleaning up: the `clean` command", "python_version": "1.6", "length": 142, "url": "https://docs.python.org/1.6/dist/clean-cmd.html"} {"title": "2 Concepts & Terminology", "text": "intro.html | dist.html | simple-example.html | Distributing Python Modules | contents.html\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 responsibilites (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.", "python_version": "1.6", "length": 1229, "url": "https://docs.python.org/1.6/dist/concepts.html"} {"title": "Contents", "text": "dist.html | dist.html | intro.html | Distributing Python Modules\n---\n## Contents", "python_version": "1.6", "length": 80, "url": "https://docs.python.org/1.6/dist/contents.html"} {"title": "3.3 Describing extension modules", "text": "listing-modules.html | setup-script.html | node11.html | Distributing Python Modules | contents.html\n---\n## 3.3 Describing extension modules\nJust as writing Python extension modules is a bit more complicated than\nwriting pure Python modules, describing them to the Distutils is a bit\nmore complicated. Unlike pure modules, it's not enough just to list\nmodules or packages and expect the Distutils to go out and find the\nright files; you have to specify the extension name, source file(s), and\nany compile/link requirements (include directories, libraries to link\nwith, etc.).\nAll of this is done through another keyword argument to\nsetup(), the extensions option. extensions\nis just a list of Extension instances, each of which describes a\nsingle extension module. Suppose your distribution includes a single\nextension, called foo and implemented by foo.c. If no\nadditional instructions to the compiler/linker are needed, describing\nthis extension is quite simple:\n```text\n\nExtension(\"foo\", [\"foo.c\"])\n```\nThe Extension class can be imported from\ndistutils.core, along with setup(). Thus, the setup\nscript for a module distribution that contains only this one extension\nand nothing else might be:\n```text\n\nfrom distutils.core import setup, Extension\nsetup(name = \"foo\", version = \"1.0\",\nextensions = [Extension(\"foo\", [\"foo.c\"])])\n```\nThe Extension class (actually, the underlying extension-building\nmachinery implemented by the `built_ext` command) supports a\ngreat deal of flexibility in describing Python extensions, which is\nexplained in the following sections.", "python_version": "1.6", "length": 1565, "url": "https://docs.python.org/1.6/dist/describing-extensions.html"} {"title": "Distributing Python Modules", "text": "../index.html | contents.html | Distributing Python Modules | contents.html\n---\n# Distributing Python Modules\nGreg Ward\nE-mail: gward@python.net\n### Abstract:\nThis document describes the Python Distribution Utilities\n(``Distutils'') from the module developer's point-of-view, describing\nhow to use the Distutils to make Python modules and extensions easily\navailable to a wider audience with very little overhead for\nbuild/release/install mechanics.", "python_version": "1.6", "length": 449, "url": "https://docs.python.org/1.6/dist/dist.html"} {"title": "2.3 Distutils-specific terminology", "text": "python-terms.html | concepts.html | setup-script.html | Distributing Python Modules | contents.html\n---\n## 2.3 Distutils-specific terminology\nThe following terms apply more specifically to the domain of\ndistributing Python modules using the Distutils:\nmodule distribution: a collection of Python modules distributed\ntogether as a single downloadable resource and meant to be installed\nen masse. Examples of some well-known module distributions are\nNumeric Python, PyXML, PIL (the Python Imaging Library), or\nmxDateTime. (This would be called a package, except that term\nis already taken in the Python context: a single module distribution\nmay contain zero, one, or many Python packages.)\npure module distribution: a module distribution that contains only\npure Python modules and packages. Sometimes referred to as a ``pure\ndistribution.''\nnon-pure module distribution: a module distribution that contains\nat least one extension module. Sometimes referred to as a ``non-pure\ndistribution.''\ndistribution root: the top-level directory of your source tree (or\nsource distribution); the directory where setup.py exists and\nis run from", "python_version": "1.6", "length": 1130, "url": "https://docs.python.org/1.6/dist/distutils-term.html"} {"title": "7 Examples", "text": "built-dist.html | dist.html | pure-mod.html | Distributing Python Modules | contents.html\n---\n# 7 Examples", "python_version": "1.6", "length": 106, "url": "https://docs.python.org/1.6/dist/examples.html"} {"title": "8.1 Extending existing commands", "text": "extending.html | extending.html | new-commands.html | Distributing Python Modules | contents.html\n---\n## 8.1 Extending existing commands", "python_version": "1.6", "length": 136, "url": "https://docs.python.org/1.6/dist/extend-existing.html"} {"title": "8 Extending the Distutils", "text": "node25.html | dist.html | extend-existing.html | Distributing Python Modules | contents.html\n---\n# 8 Extending the Distutils", "python_version": "1.6", "length": 124, "url": "https://docs.python.org/1.6/dist/extending.html"} {"title": "Distributing Python Modules", "text": "../index.html | contents.html | Distributing Python Modules | contents.html\n---\n# Distributing Python Modules\nGreg Ward\nE-mail: gward@python.net\n### Abstract:\nThis document describes the Python Distribution Utilities\n(``Distutils'') from the module developer's point-of-view, describing\nhow to use the Distutils to make Python modules and extensions easily\navailable to a wider audience with very little overhead for\nbuild/release/install mechanics.", "python_version": "1.6", "length": 449, "url": "https://docs.python.org/1.6/dist/index.html"} {"title": "9.2 Installing modules: the install command family", "text": "build-clib-cmd.html | ref.html | install-lib-cmd.html | Distributing Python Modules | contents.html\n---\n## 9.2 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`.", "python_version": "1.6", "length": 308, "url": "https://docs.python.org/1.6/dist/install-cmd.html"} {"title": "9.2.2 install_data", "text": "install-lib-cmd.html | install-cmd.html | install-scripts-cmd.html | Distributing Python Modules | contents.html\n---\n### 9.2.2 `install_data`\nThis command installs all data files provided with the distribution.", "python_version": "1.6", "length": 210, "url": "https://docs.python.org/1.6/dist/install-data-cmd.html"} {"title": "9.2.1 install_lib", "text": "install-cmd.html | install-cmd.html | install-data-cmd.html | Distributing Python Modules | contents.html\n---\n### 9.2.1 `install_lib`", "python_version": "1.6", "length": 133, "url": "https://docs.python.org/1.6/dist/install-lib-cmd.html"} {"title": "9.2.3 install_scripts", "text": "install-data-cmd.html | install-cmd.html | clean-cmd.html | Distributing Python Modules | contents.html\n---\n### 9.2.3 `install_scripts`\nThis command installs all (Python) scripts in the distribution.", "python_version": "1.6", "length": 199, "url": "https://docs.python.org/1.6/dist/install-scripts-cmd.html"} {"title": "1 Introduction", "text": "contents.html | dist.html | concepts.html | Distributing Python Modules | contents.html\n---\n# 1 Introduction\nIn the past, Python module developers have not had much infrastructure\nsupport for distributing modules, nor have Python users had much support\nfor installing and maintaining third-party modules. With the\nintroduction of the Python Distribution Utilities (Distutils for short)\nin Python 1.6, this situation should start to improve.\nThis document only covers using the Distutils to distribute your Python\nmodules. Using the Distutils does not tie you to Python 1.6, though:\nthe Distutils work just fine with Python 1.5.2, and it is reasonable\n(and expected to become commonplace) to expect users of Python 1.5.2 to\ndownload and install the Distutils separately before they can install\nyour modules. Python 1.6 (or later) users, of course, won't have to add\nanything to their Python installation in order to use the Distutils to\ninstall third-party modules.\nThis document concentrates on the role of developer/distributor: if\nyou're looking for information on installing Python modules, you\nshould refer to the Installing Python\nModules (../inst/inst.html) manual.", "python_version": "1.6", "length": 1171, "url": "https://docs.python.org/1.6/dist/intro.html"} {"title": "3.2 Listing individual modules", "text": "listing-packages.html | setup-script.html | describing-extensions.html | Distributing Python Modules | contents.html\n---\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.", "python_version": "1.6", "length": 872, "url": "https://docs.python.org/1.6/dist/listing-modules.html"} {"title": "3.1 Listing whole packages", "text": "setup-script.html | setup-script.html | listing-modules.html | Distributing Python Modules | contents.html\n---\n## 3.1 Listing whole packages\nThe packages option tells the Distutils to process (build,\ndistribute, install, etc.) all pure Python modules found in each package\nmentioned in the packages list. In order to do this, of\ncourse, there has to be a correspondence between package names and\ndirectories in the filesystem. The default correspondence is the most\nobvious one, i.e. package distutils is found in the directory\ndistutils relative to the distribution root. Thus, when you say\n`packages = ['foo']` in your setup script, you are promising that\nthe Distutils will find a file foo/__init__.py (which might\nbe spelled differently on your system, but you get the idea) relative to\nthe directory where your setup script lives. (If you break this\npromise, the Distutils will issue a warning but process the broken\npackage anyways.)\nIf you use a different convention to lay out your source directory,\nthat's no problem: you just have to supply the package_dir\noption to tell the Distutils about your convention. For example, say\nyou keep all Python source under lib, so that modules in the\n``root package'' (i.e., not in any package at all) are right in\nlib, modules in the foo package are in lib/foo,\nand so forth. Then you would put\n```text\n\npackage_dir = {'': 'lib'}\n```\nin your setup script. (The keys to this dictionary are package names,\nand an empty package name stands for the root package. The values are\ndirectory names relative to your distribution root.) In this case, when\nyou say `packages = ['foo']`, you are promising that the file\nlib/foo/__init__.py exists.\nAnother possible convention is to put the foo package right in\nlib, the foo.bar package in lib/bar, etc. This\nwould be written in the setup script as\n```text\n\npackage_dir = {'foo': 'lib'}\n```\nA `package : dir` entry in the package_dir\ndictionary implicitly applies to all packages below package, so\nthe foo.bar case is automatically handled here. In this\nexample, having `packages = ['foo', 'foo.bar']` tells the Distutils\nto look for lib/__init__.py and\nlib/bar/__init__.py. (Keep in mind that although\npackage_dir applies recursively, you must explicitly list all\npackages in packages: the Distutils will not recursively\nscan your source tree looking for any directory with an\n__init__.py file.)", "python_version": "1.6", "length": 2380, "url": "https://docs.python.org/1.6/dist/listing-packages.html"} {"title": "5.2 Manifest-related options", "text": "manifest.html | source-dist.html | built-dist.html | Distributing Python Modules | contents.html\n---\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 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.\nFirst, 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.)\nIf you don't want to use the default file set, you can supply the\n--no-defaults option. If you use\n--no-defaults and don't supply a manifest template (or\nit's empty, or nothing matches the patterns in it), then your source\ndistribution will be empty.", "python_version": "1.6", "length": 1306, "url": "https://docs.python.org/1.6/dist/manifest-options.html"} {"title": "5.1 The manifest and manifest template", "text": "source-dist.html | source-dist.html | manifest-options.html | Distributing Python Modules | contents.html\n---\n## 5.1 The manifest and manifest template\nWithout any additional information, the `sdist` command puts a\nminimal set of files into 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) and setup.py\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\n`sdist` command processes this template and generates a manifest\nfile, MANIFEST. (If you prefer, you can skip the manifest\ntemplate and generate the manifest yourself: it just lists one file per\nline.)\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`. There\nare several other commands available in the manifest template\nmini-language; see section 9.4 (sdist-cmd.html#sdist-cmd).\nThe order of commands in the manifest template very much matters:\ninitially, we have the list of default files as described above, and\neach command in the template adds to or removes from that list of files.\nWhen we have fully processed the manifest template, we have our complete\nlist of files. This list is written to the manifest for future\nreference, and then used to build the source distribution archive(s).\nFollowing the Distutils' own manifest template, let's trace how the\n`sdist` command will build 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)\n2. include test/test*.py (always included)\n3. include README.txt and setup.py (always included)\n4. include *.txt in the distribution root (this will find\nREADME.txt a second time, but such redundancies are weeded out\nlater)\n5. in the sub-tree under examples, include anything matching\n*.txt\n6. in the sub-tree under examples, include anything matching\n*.py\n7. remove all files in the sub-trees starting at directories matching\nexamples/sample?/build--this may exclude files included by the\nprevious two steps, so it's important that the `prune` command in\nthe manifest template comes after the two `recursive-include` commands\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.", "python_version": "1.6", "length": 3549, "url": "https://docs.python.org/1.6/dist/manifest.html"} {"title": "7.4 Multiple extension modules", "text": "single-ext.html | examples.html | node25.html | Distributing Python Modules | contents.html\n---\n## 7.4 Multiple extension modules", "python_version": "1.6", "length": 129, "url": "https://docs.python.org/1.6/dist/multiple-ext.html"} {"title": "8.2 Writing new commands", "text": "extend-existing.html | extending.html | ref.html | Distributing Python Modules | contents.html\n---\n## 8.2 Writing new commands", "python_version": "1.6", "length": 126, "url": "https://docs.python.org/1.6/dist/new-commands.html"} {"title": "3.3.1 Extension names and packages", "text": "describing-extensions.html | describing-extensions.html | node12.html | Distributing Python Modules | contents.html\n---\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\",\nextensions = [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.", "python_version": "1.6", "length": 1081, "url": "https://docs.python.org/1.6/dist/node11.html"} {"title": "3.3.2 Extension source files", "text": "node11.html | describing-extensions.html | node13.html | Distributing Python Modules | contents.html\n---\n### 3.3.2 Extension source files\nThe second argument to the Extension constructor is a list of\nsource files. Since the Distutils currently only support C/C++\nextensions, these are normally C/C++ source files. (Be sure to use\nappropriate extensions to distinguish C++ source files: .cc and\n.cpp seem to be recognized by both Unix and Windows compilers.)\nHowever, you can also include SWIG interface (.i) files in the\nlist; the `build_ext` command knows how to deal with SWIG\nextensions: it will run SWIG on the interface file and compile the\nresulting C/C++ file into your extension.\n** SWIG support is rough around the edges and largely untested;\nespecially SWIG support of C++ extensions! Explain in more detail\nhere when the interface firms up. **\nOn some platforms, you can include non-source files that are processed\nby the compiler and included in your extension. Currently, this just\nmeans Windows resource files for Visual C++. ** get more detail on\nthis feature from Thomas Heller! **", "python_version": "1.6", "length": 1097, "url": "https://docs.python.org/1.6/dist/node12.html"} {"title": "3.3.3 Preprocessor options", "text": "node12.html | describing-extensions.html | node14.html | Distributing Python Modules | contents.html\n---\n### 3.3.3 Preprocessor options\nThree optional arguments to Extension will help if you need to\nspecify include directories to search or preprocessor macros to\ndefine/undefine: `include_dirs`, `define_macros`, and\n`undef_macros`.\nFor example, if your extension requires header files in the\ninclude directory under your distribution root, use the\n`include_dirs` option:\n```text\n\nExtension(\"foo\", [\"foo.c\"], include_dirs=[\"include\"])\n```\nYou can specify absolute directories there; if you know that your\nextension will only be built on Unix systems with X11R6 installed to\n/usr, you can get away with\n```text\n\nExtension(\"foo\", [\"foo.c\"], include_dirs=[\"/usr/include/X11\"])\n```\nYou should avoid this sort of non-portable usage if you plan to\ndistribute your code: it's probably better to write your code to include\n(e.g.) ``.\nIf you need to include header files from some other Python extension,\nyou can take advantage of the fact that the Distutils install extension\nheader files in a consistent way. For example, the Numerical Python\nheader files are installed (on a standard Unix installation) to\n/usr/local/include/python1.5/Numerical. (The exact location will\ndiffer according to your platform and Python installation.) Since the\nPython include directory--/usr/local/include/python1.5 in this\ncase--is always included in the search path when building Python\nextensions, the best approach is to include (e.g.)\n``. If you insist on putting the\nNumerical include directory right into your header search path,\nthough, you can find that directory using the Distutils\nsysconfig module:\n```text\n\nfrom distutils.sysconfig import get_python_inc\nincdir = os.path.join(get_python_inc(plat_specific=1), \"Numerical\")\nsetup(...,\nExtension(..., include_dirs=[incdir]))\n```\nEven though this is quite portable--it will work on any Python\ninstallation, regardless of platform--it's probably easier to just\nwrite your C code in the sensible way.\nYou can define and undefine pre-processor macros with the\n`define_macros` and `undef_macros` options.\n`define_macros` takes a list of `(name, value)` tuples, where\n`name` is the name of the macro to define (a string) and\n`value` is its value: either a string or `None`. (Defining a\nmacro `FOO` to `None` is the equivalent of a bare\n`#define FOO` in your C source: with most compilers, this sets\n`FOO` to the string `1`.) `undef_macros` is just\na list of macros to undefine.\nFor example:\n```text\n\nExtension(...,\ndefine_macros=[('NDEBUG', '1')],\n('HAVE_STRFTIME', None),\nundef_macros=['HAVE_FOO', 'HAVE_BAR'])\n```\nis the equivalent of having this at the top of every C source file:\n```text\n\n#define NDEBUG 1\n#define HAVE_STRFTIME\n#undef HAVE_FOO\n#undef HAVE_BAR\n```", "python_version": "1.6", "length": 2832, "url": "https://docs.python.org/1.6/dist/node13.html"} {"title": "3.3.4 Library options", "text": "node13.html | describing-extensions.html | setup-config.html | Distributing Python Modules | contents.html\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** still undocumented: extra_objects, extra_compile_args,\nextra_link_args, export_symbols--none of which are frequently\nneeded, some of which might be completely unnecessary! **", "python_version": "1.6", "length": 1187, "url": "https://docs.python.org/1.6/dist/node14.html"} {"title": "7.5 Putting it all together", "text": "multiple-ext.html | examples.html | extending.html | Distributing Python Modules | contents.html\n---\n## 7.5 Putting it all together", "python_version": "1.6", "length": 131, "url": "https://docs.python.org/1.6/dist/node25.html"} {"title": "9.5.1 blib", "text": "bdist-cmds.html | bdist-cmds.html | node43.html | Distributing Python Modules | contents.html\n---\n### 9.5.1 `blib`", "python_version": "1.6", "length": 114, "url": "https://docs.python.org/1.6/dist/node42.html"} {"title": "9.5.2 blib_dumb", "text": "node42.html | bdist-cmds.html | node44.html | Distributing Python Modules | contents.html\n---\n### 9.5.2 `blib_dumb`", "python_version": "1.6", "length": 115, "url": "https://docs.python.org/1.6/dist/node43.html"} {"title": "9.5.3 blib_rpm", "text": "node43.html | bdist-cmds.html | node45.html | Distributing Python Modules | contents.html\n---\n### 9.5.3 `blib_rpm`", "python_version": "1.6", "length": 114, "url": "https://docs.python.org/1.6/dist/node44.html"} {"title": "9.5.4 blib_wise", "text": "node44.html | bdist-cmds.html | about.html | Distributing Python Modules | contents.html\n---\n### 9.5.4 `blib_wise`", "python_version": "1.6", "length": 114, "url": "https://docs.python.org/1.6/dist/node45.html"} {"title": "7.1 Pure Python distribution (by module)", "text": "examples.html | examples.html | pure-pkg.html | Distributing Python Modules | contents.html\n---\n## 7.1 Pure Python distribution (by module)", "python_version": "1.6", "length": 139, "url": "https://docs.python.org/1.6/dist/pure-mod.html"} {"title": "7.2 Pure Python distribution (by package)", "text": "pure-mod.html | examples.html | single-ext.html | Distributing Python Modules | contents.html\n---\n## 7.2 Pure Python distribution (by package)", "python_version": "1.6", "length": 142, "url": "https://docs.python.org/1.6/dist/pure-pkg.html"} {"title": "2.2 General Python terminology", "text": "simple-example.html | concepts.html | distutils-term.html | Distributing Python Modules | contents.html\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 implemention: C/C++ for CPython, Java for JPython.\nTypically contained in a single dynamically loadable pre-compiled\nfile, e.g. a shared object (.so) file for CPython extensions on\nUnix, a DLL (given the .pyd extension) for CPython extensions\non Windows, or a Java class file for JPython extensions. (Note that\ncurrently, the Distutils only handles C/C++ extensions for CPython.)\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` can contribute modules to the root package.", "python_version": "1.6", "length": 1901, "url": "https://docs.python.org/1.6/dist/python-terms.html"} {"title": "9 Reference", "text": "new-commands.html | dist.html | build-cmds.html | Distributing Python Modules | contents.html\n---\n# 9 Reference", "python_version": "1.6", "length": 111, "url": "https://docs.python.org/1.6/dist/ref.html"} {"title": "9.4 Creating a source distribution: the sdist command", "text": "clean-cmd.html | ref.html | bdist-cmds.html | Distributing Python Modules | contents.html\n---\n## 9.4 Creating a source distribution: the `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 Mac OS anything except colon.\n** Windows and Mac OS support not there yet **", "python_version": "1.6", "length": 728, "url": "https://docs.python.org/1.6/dist/sdist-cmd.html"} {"title": "4 Writing the Setup Configuration File", "text": "node14.html | dist.html | source-dist.html | Distributing Python Modules | contents.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 need to get some information from the\nuser, or from the user's system, in order to proceed. For example, you\nmight include an optional extension module that provides an interface to\na particular C library. If that library is installed on the user's\nsystem, then you can build your optional extension--but you need to\nknow where to find the header and library file. If it's not installed,\nyou need to know this so you can omit your optional extension.\nThe preferred way to do this, of course, would be for you to tell the\nDistutils which optional features (C libraries, system calls, external\nutilities, etc.) you're looking for, and it would inspect the user's\nsystem and try to find them. This functionality may appear in a future\nversion of the Distutils, but it isn't there now. So, for the time\nbeing, we rely on the user building and installing your software to\nprovide the necessary information. The vehicle for doing so is the\nsetup configuration file, setup.cfg.\n** need more here! **", "python_version": "1.6", "length": 1221, "url": "https://docs.python.org/1.6/dist/setup-config.html"} {"title": "3 Writing the Setup Script", "text": "distutils-term.html | dist.html | listing-packages.html | Distributing Python Modules | contents.html\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/\",\n\npackages = ['distutils', 'distutils.command'],\n)\n```\nThere are only two differences between this and the trivial one-file\ndistribution presented in section 2.1 (simple-example.html#simple-example): more\nmeta-data, and the specification of pure Python modules by package,\nrather than by module. This is important since the Distutils consist of\na couple of dozen modules split into (so far) two packages; an explicit\nlist of every module would be tedious to generate and difficult to\nmaintain.\nNote that any pathnames (files or directories) supplied in the setup\nscript should be written using the Unix convention, i.e.\nslash-separated. The Distutils will take care of converting this\nplatform-neutral representation into whatever is appropriate on your\ncurrent platform before actually using the pathname. This makes your\nsetup script portable across operating systems, which of course is one\nof the major goals of the Distutils. In this spirit, all pathnames in\nthis document are slash-separated (Mac OS programmers should keep in\nmind that the absence of a leading slash indicates a relative\npath, the opposite of the Mac OS convention with colons).", "python_version": "1.6", "length": 2505, "url": "https://docs.python.org/1.6/dist/setup-script.html"} {"title": "2.1 A simple example", "text": "concepts.html | concepts.html | python-terms.html | Distributing Python Modules | contents.html\n---\n## 2.1 A simple example\nThe setup script is usually quite simple, although since it's written in\nPython, there are no arbitrary limits to what you can do with it. If\nall you want to do is distribute a module called foo, contained\nin a file foo.py, then your setup script can be as little as\nthis:\n```text\n\nfrom distutils.core import setup\nsetup (name = \"foo\",\nversion = \"1.0\",\npy_modules = [\"foo\"])\n```\nSome observations:\n- most information that you supply to the Distutils is supplied as\nkeyword arguments to the setup() function\n- those keyword arguments fall into two categories: package\nmeta-data (name, version number) and information about what's in the\npackage (a list of pure Python modules, in this case)\n- modules are specified by module name, not filename (the same will\nhold true for packages and extensions)\n- it's recommended that you supply a little more meta-data, in\nparticular your name, email address and a URL for the project\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.\n** not implemented yet **\n(Another way to create executable installers for Windows is with the\n`bdist_wise` command, which uses Wise--the commercial\ninstaller-generator used to create Python's own installer--to create\nthe installer. Wise-based installers are more appropriate for large,\nindustrial-strength applications that need the full capabilities of a\n``real'' installer. `bdist_wininst` creates a self-extracting\nzip file with a minimal user interface, which is enough for small- to\nmedium-sized module collections. You'll need to have version XXX of\nWise installed on your system for the `bdist_wise` command to\nwork; it's available from http://foo/bar/baz.)\nCurrently (Distutils 0.9.1), the are only other useful built\ndistribution format is RPM, implemented by the `bdist_rpm`\ncommand. For example, the following command will create an RPM file\ncalled Foo-1.0.noarch.rpm:\n```text\n\npython setup.py bdist_rpm\n```\n(This uses the `rpm` command, so has to be run on an RPM-based\nsystem such as Red Hat Linux, SuSE Linux, or Mandrake Linux.)\nYou can find out what distribution formats are available at any time by\nrunning\n```text\n\npython setup.py bdist --help-formats\n```", "python_version": "1.6", "length": 3848, "url": "https://docs.python.org/1.6/dist/simple-example.html"} {"title": "7.3 Single extension module", "text": "pure-pkg.html | examples.html | multiple-ext.html | Distributing Python Modules | contents.html\n---\n## 7.3 Single extension module", "python_version": "1.6", "length": 130, "url": "https://docs.python.org/1.6/dist/single-ext.html"} {"title": "5 Creating a Source Distribution", "text": "setup-config.html | dist.html | manifest.html | Distributing Python Modules | contents.html\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 formats are:\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", "python_version": "1.6", "length": 763, "url": "https://docs.python.org/1.6/dist/source-dist.html"} {"title": "About this document ...", "text": "discussion.html | doc.html | Documenting Python | contents.html\n---\n# About this document ...\nDocumenting Python,\nSeptember 18, 2000, Release 1.6\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ndiscussion.html | doc.html | Documenting Python | contents.html\n---", "python_version": "1.6", "length": 1606, "url": "https://docs.python.org/1.6/doc/about.html"} {"title": "4 Document Classes", "text": "latex-primer.html | doc.html | node6.html | Documenting Python | contents.html\n---\n# 4 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` class 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\nmore broad. 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\nthe standard Macintosh Library Modules (../mac/mac.html)\nand\nUsing\nKerberos from Python (http://starship.python.org/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": "1.6", "length": 1627, "url": "https://docs.python.org/1.6/doc/classes.html"} {"title": "Contents", "text": "doc.html | doc.html | node2.html | Documenting Python\n---\n## Contents", "python_version": "1.6", "length": 69, "url": "https://docs.python.org/1.6/doc/contents.html"} {"title": "8.2 Discussion Forums", "text": "structured.html | futures.html | about.html | Documenting Python | contents.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": "1.6", "length": 721, "url": "https://docs.python.org/1.6/doc/discussion.html"} {"title": "Documenting Python", "text": "../index.html | contents.html | Documenting Python | contents.html\n---\n# Documenting Python\nFred L. Drake, Jr.\nCorporation for National Research Initiatives (CNRI)\n1895 Preston White Drive, Reston, Va 20191, USA\nE-mail: fdrake@acm.org\nSeptember 18, 2000\nRelease 1.6\n### Abstract:\nThe Python language documentation 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": "1.6", "length": 943, "url": "https://docs.python.org/1.6/doc/doc.html"} {"title": "8 Future Directions", "text": "node19.html | doc.html | structured.html | Documenting Python | contents.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": "1.6", "length": 473, "url": "https://docs.python.org/1.6/doc/futures.html"} {"title": "Documenting Python", "text": "../index.html | contents.html | Documenting Python | contents.html\n---\n# Documenting Python\nFred L. Drake, Jr.\nCorporation for National Research Initiatives (CNRI)\n1895 Preston White Drive, Reston, Va 20191, USA\nE-mail: fdrake@acm.org\nSeptember 18, 2000\nRelease 1.6\n### Abstract:\nThe Python language documentation 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": "1.6", "length": 943, "url": "https://docs.python.org/1.6/doc/index.html"} {"title": "5.9 Index-generating Markup", "text": "references.html | node6.html | node16.html | Documenting Python | contents.html\n---\n## 5.9 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 5.2 (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": "1.6", "length": 1695, "url": "https://docs.python.org/1.6/doc/indexing.html"} {"title": "5.2 Information Units", "text": "meta-info.html | node6.html | node9.html | Documenting Python | contents.html\n---\n## 5.2 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": "1.6", "length": 1658, "url": "https://docs.python.org/1.6/doc/info-units.html"} {"title": "3 LATEX Primer", "text": "node3.html | doc.html | classes.html | Documenting Python | contents.html\n---\n# 3 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 the 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 4 (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.\nXXX This section will discuss what the markup looks like, and\nexplain the difference between an environment and a macro.", "python_version": "1.6", "length": 2192, "url": "https://docs.python.org/1.6/doc/latex-primer.html"} {"title": "5.1 Meta-information Markup", "text": "node6.html | node6.html | info-units.html | Documenting Python | contents.html\n---\n## 5.1 Meta-information Markup", "python_version": "1.6", "length": 113, "url": "https://docs.python.org/1.6/doc/meta-info.html"} {"title": "5.4 Inline Markup", "text": "node9.html | node6.html | node11.html | Documenting Python | contents.html\n---\n## 5.4 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": "1.6", "length": 328, "url": "https://docs.python.org/1.6/doc/node10.html"} {"title": "5.5 Module-specific Markup", "text": "node10.html | node6.html | node12.html | Documenting Python | contents.html\n---\n## 5.5 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```", "python_version": "1.6", "length": 562, "url": "https://docs.python.org/1.6/doc/node11.html"} {"title": "5.6 Library-level Markup", "text": "node11.html | node6.html | node13.html | Documenting Python | contents.html\n---\n## 5.6 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": "1.6", "length": 406, "url": "https://docs.python.org/1.6/doc/node12.html"} {"title": "5.7 Table Markup", "text": "node12.html | node6.html | references.html | Documenting Python | contents.html\n---\n## 5.7 Table Markup\nThere are three general-purpose table environments defined which\nshould be used whenever possible. These environments are defined\nto provide tables of specific widths and some convenience for\nformatting. These environments are not meant to be general\nreplacements for the standard LATEX table environments, but can\nbe used for an advantage when the documents are processed using\nthe tools for Python documentation processing. In particular, the\ngenerated HTML looks good! There is also an advantage for the\neventual conversion of the documentation to SGML (see section\n8 (futures.html#futures), ``Future Directions'').\nEach environment is named \\tablecols, where cols\nis the number of columns in the table specified in lower-case\nRoman numerals. Within each of these environments, an additional\nmacro, \\linecols, is defined, where cols\nmatches the cols value of the corresponding table\nenvironment. These are supported for cols values of\n`ii`, `iii`, and `iv`. These environments are all\nbuilt on top of the \\tabular environment.\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.\nAn additional table-like environment is \\synopsistable. The\ntable generated by this environment contains two columns, and each\nrow is defined by an alternate definition of\n\\modulesynopsis. This environment is not normally used by\nauthors, but is created by the \\localmoduletable macro.", "python_version": "1.6", "length": 1682, "url": "https://docs.python.org/1.6/doc/node13.html"} {"title": "6 Special Names", "text": "indexing.html | doc.html | node17.html | Documenting Python | contents.html\n---\n# 6 Special Names\nMany special names are used in the Python documentation, including\nthe names of operating systems, programming languages, standards\nbodies, and the like. Many of these were assigned LATEX macros\nat some point in the distant past, and these macros lived on long\npast their usefulness. In the current markup, these entities are\nnot assigned any special markup, but the preferred spellings are\ngiven here to aid authors in maintaining the consistency of\npresentation in the Python documentation.\nPOSIX: The name assigned to a particular group of standards. This is\nalways uppercase.\nPython: The name of our favorite programming language is always\ncapitalized.\nUnicode: The name of a character set and matching encoding. This is\nalways written capitalized.", "python_version": "1.6", "length": 850, "url": "https://docs.python.org/1.6/doc/node16.html"} {"title": "7 Processing Tools", "text": "node16.html | doc.html | node18.html | Documenting Python | contents.html\n---\n# 7 Processing Tools", "python_version": "1.6", "length": 98, "url": "https://docs.python.org/1.6/doc/node17.html"} {"title": "7.1 External Tools", "text": "node17.html | node17.html | node19.html | Documenting Python | contents.html\n---\n## 7.1 External Tools\nMany tools are needed to be able to process the Python\ndocumentation if all supported formats are required. This\nsection lists the tools used and when each is required. Consult\nthe Doc/README file to see if there are specific version\nrequirements for any of these.\ndvips: This program is a typical part of TEX installations. It is\nused to generate PostScript from the ``device independent''\n.dvi files. It is needed for the conversion to\nPostScript.\nemacs: Emacs is the kitchen sink of programmers' editors, and a damn\nfine kitchen sink it is. It also comes with some of the\nprocessing needed to support the proper menu structures for\nTexinfo documents when an info conversion is desired. This is\nneeded for the info conversion. Using xemacs\ninstead of FSF emacs may lead to instability in the\nconversion, but that's because nobody seems to maintain the\nEmacs Texinfo code in a portable manner.\nlatex: This is a world-class typesetter by Donald Knuth. It is used\nfor the conversion to PostScript, and is needed for the HTML\nconversion as well (LATEX2HTML requires one of the\nintermediate files it creates).\nlatex2html: Probably the longest Perl script anyone ever attempted to\nmaintain. This converts LATEX documents to HTML documents,\nand does a pretty reasonable job. It is required for the\nconversions to HTML and GNU info.\nlynx: This is a text-mode Web browser which includes an\nHTML-to-plain text conversion. This is used to convert\n`howto` documents to text.\nmake: Just about any version should work for the standard documents,\nbut GNU make is required for the experimental\nprocesses in Doc/tools/sgmlconv/, at least while\nthey're experimental.\nmakeindex: This is a standard program for converting LATEX index data\nto a formatted index; it should be included with all LATEX\ninstallations. It is needed for the PDF and PostScript\nconversions.\nmakeinfo: GNU makeinfo is used to convert Texinfo documents to\nGNU info files. Since Texinfo is used as an intermediate\nformat in the info conversion, this program is needed in that\nconversion.\npdflatex: pdfTEX is a relatively new variant of TEX, and is used to\ngenerate the PDF version of the manuals. It is typically\ninstalled as part of most of the large TEX distributions.\npdflatex is pdfTEX using the LATEX format.\nperl: Perl is required for LATEX2HTML and one of the scripts used\nto post-process LATEX2HTML output, as well as the\nHTML-to-Texinfo conversion. This is required for\nthe HTML and GNU info conversions.\npython: Python is used for many of the scripts in the\nDoc/tools/ directory; it is required for all\nconversions. This shouldn't be a problem if you're interested\nin writing documentation for Python!", "python_version": "1.6", "length": 2768, "url": "https://docs.python.org/1.6/doc/node18.html"} {"title": "7.2 Internal Tools", "text": "node18.html | node17.html | futures.html | Documenting Python | contents.html\n---\n## 7.2 Internal Tools\nThis section describes the various scripts that are used to\nimplement various stages of document processing or to orchestrate\nentire build sequences. Most of these tools are only useful\nin the context of building the standard documentation, but some\nare more general.\nmkhowto: This is the primary script used to format third-party\ndocuments. It contains all the logic needed to ``get it\nright.'' The proper way to use this script is to make a\nsymbolic link to it or run it in place; the actual script file\nmust be stored as part of the documentation source tree,\nthough it may be used to format documents outside the\ntree. Use mkhowto --help\nfor a list of\ncommand line options.\nmkhowto can be used for both `howto` and\n`manual` class documents. (For the later, be sure to get\nthe latest version from the Python CVS repository rather than\nthe version distributed in the latex-1.5.2.tgz source\narchive.)\nXXX Need more here.", "python_version": "1.6", "length": 1025, "url": "https://docs.python.org/1.6/doc/node19.html"} {"title": "1 Introduction", "text": "contents.html | doc.html | node3.html | Documenting Python | contents.html\n---\n# 1 Introduction\nPython's documentation has long been considered to be good for a\nfree programming language. There are a number of reasons for this,\nthe most important being the early commitment of Python's creator,\nGuido van Rossum, to providing documentation on the language and its\nlibraries, and the continuing involvement of the user community in\nproviding assistance for creating and maintaining documentation.\nThe involvement of the community takes many forms, from authoring to\nbug reports to just plain complaining when the documentation could\nbe more complete or easier to use. All of these forms of input from\nthe community have proved useful during the time I've been involved\nin maintaining the documentation.\nThis document is aimed at authors and potential authors of\ndocumentation for Python. More specifically, it is for people\ncontributing to the standard documentation and developing additional\ndocuments using the same tools as the standard documents. This\nguide will be less useful for authors using the Python documentation\ntools for topics other than Python, and less useful still for\nauthors not using the tools at all.\nThe material in this guide is intended to assist authors using the\nPython documentation tools. It includes information on the source\ndistribution of the standard documentation, a discussion of the\ndocument types, reference material on the markup defined in the\ndocument classes, a list of the external tools needed for processing\ndocuments, and reference material on the tools provided with the\ndocumentation resources. At the end, there is also a section\ndiscussing future directions for the Python documentation and where\nto turn for more information.", "python_version": "1.6", "length": 1775, "url": "https://docs.python.org/1.6/doc/node2.html"} {"title": "2 Directory Structure", "text": "node2.html | doc.html | latex-primer.html | Documenting Python | contents.html\n---\n# 2 Directory Structure\nThe source distribution for the standard Python documentation\ncontains a large number of directories. While third-party documents\ndo not need to be placed into this structure or need to be placed\nwithin a similar structure, it can be helpful to know where to look\nfor examples and tools when developing new documents using the\nPython documentation tools. This section describes this directory\nstructure.\nThe documentation sources are usually placed within the Python\nsource distribution as the top-level directory Doc/, but\nare not dependent on the Python source distribution in any way.\nThe Doc/ directory contains a few files and several\nsubdirectories. The files are mostly self-explanatory, including a\nREADME and a Makefile. The directories fall into\nthree categories:", "python_version": "1.6", "length": 880, "url": "https://docs.python.org/1.6/doc/node3.html"} {"title": "5 Special Markup Constructs", "text": "classes.html | doc.html | meta-info.html | Documenting Python | contents.html\n---\n# 5 Special Markup Constructs\nThe Python document classes define a lot of new environments and\nmacros. This section contains the reference material for these\nfacilities.", "python_version": "1.6", "length": 251, "url": "https://docs.python.org/1.6/doc/node6.html"} {"title": "5.3 Showing Code Examples", "text": "info-units.html | node6.html | node10.html | Documenting Python | contents.html\n---\n## 5.3 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.\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.\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": "1.6", "length": 1060, "url": "https://docs.python.org/1.6/doc/node9.html"} {"title": "5.8 Reference List Markup", "text": "node13.html | node6.html | indexing.html | Documenting Python | contents.html\n---\n## 5.8 Reference List Markup\nMany sections include a list of references to module documentation\nor external documents. These lists are created using the\n\\seealso environment. This environment defines some\nadditional macros to support creating reference entries in a\nreasonable manner.", "python_version": "1.6", "length": 366, "url": "https://docs.python.org/1.6/doc/references.html"} {"title": "8.1 Structured Documentation", "text": "futures.html | futures.html | discussion.html | Documenting Python | contents.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 is 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.\nXXX Eventual migration to SGML/XML.", "python_version": "1.6", "length": 2550, "url": "https://docs.python.org/1.6/doc/structured.html"} {"title": "About this document ...", "text": "embeddingInCplusplus.html | ext.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# About this document ...\nExtending and Embedding the Python Interpreter,\nSeptember 18, 2000, Release 1.6\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nembeddingInCplusplus.html | ext.html | Extending and Embedding the Python Interpreter | contents.html\n---", "python_version": "1.6", "length": 1710, "url": "https://docs.python.org/1.6/ext/about.html"} {"title": "1.3 Back to the Example", "text": "errors.html | intro.html | methodTable.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.3 Back to the Example\nGoing back to our example function, you should now be able to\nunderstand this statement:\n```text\n\nif (!PyArg_ParseTuple(args, \"s\", &command))\nreturn NULL;\n```\nIt returns NULL (the error indicator for functions returning\nobject pointers) if an error is detected in the argument list, relying\non the exception set by PyArg_ParseTuple(). Otherwise the\nstring value of the argument has been copied to the local variable\ncommand. This is a pointer assignment and you are not supposed\nto modify the string to which it points (so in Standard C, the variable\ncommand should properly be declared as \"const char\n*command\").\nThe next statement is a call to the Unix function\nsystem(), passing it the string we just got from\nPyArg_ParseTuple():\n```text\n\nsts = system(command);\n```\nOur spam.system() function must return the value of\nsts as a Python object. This is done using the function\nPy_BuildValue(), which is something like the inverse of\nPyArg_ParseTuple(): it takes a format string and an\narbitrary number of C values, and returns a new Python object.\nMore info on Py_BuildValue() is given later.\n```text\n\nreturn Py_BuildValue(\"i\", sts);\n```\nIn this case, it will return an integer object. (Yes, even integers\nare objects on the heap in Python!)\nIf you have a C function that returns no useful argument (a function\nreturning void), the corresponding Python function must return\n`None`. You need this idiom to do so:\n```text\n\nPy_INCREF(Py_None);\nreturn Py_None;\n```\nPy_None is the C name for the special Python object\n`None`. It is a genuine Python object rather than a NULL\npointer, which means ``error'' in most contexts, as we have seen.", "python_version": "1.6", "length": 1774, "url": "https://docs.python.org/1.6/ext/backToExample.html"} {"title": "2. Building C and C++ Extensions on Unix", "text": "using-cobjects.html | ext.html | custom-interps.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2. Building C and C++ Extensions on Unix\nStarting in Python 1.4, Python provides a special make file for\nbuilding make files for building dynamically-linked extensions and\ncustom interpreters. The make file make file builds a make file\nthat reflects various system variables determined by configure when\nthe Python interpreter was built, so people building module's don't\nhave to resupply these settings. This vastly simplifies the process\nof building extensions and custom interpreters on Unix systems.\nThe make file make file is distributed as the file\nMisc/Makefile.pre.in in the Python source distribution. The\nfirst step in building extensions or custom interpreters is to copy\nthis make file to a development directory containing extension module\nsource.\nThe make file make file, Makefile.pre.in uses metadata\nprovided in a file named Setup. The format of the Setup\nfile is the same as the Setup (or Setup.in) file\nprovided in the Modules/ directory of the Python source\ndistribution. The Setup file contains variable definitions:\n```text\n\nEC=/projects/ExtensionClass\n```\nand module description lines. It can also contain blank lines and\ncomment lines that start with \"#\".\nA module description line includes a module name, source files,\noptions, variable references, and other input files, such\nas libraries or object files. Consider a simple example:\n```text\n\nExtensionClass ExtensionClass.c\n```\nThis is the simplest form of a module definition line. It defines a\nmodule, ExtensionClass, which has a single source file,\nExtensionClass.c.\nThis slightly more complex example uses an -I option to\nspecify an include directory:\n```text\n\nEC=/projects/ExtensionClass\ncPersistence cPersistence.c -I$(EC)\n```\nThis example also illustrates the format for variable references.\nFor systems that support dynamic linking, the Setup file should\nbegin:\n```text\n\n*shared*\n```\nto indicate that the modules defined in Setup are to be built\nas dynamically linked modules. A line containing only \"*static*\"can be used to indicate the subsequently listed modules should be\nstatically linked.\nHere is a complete Setup file for building a\ncPersistent module:\n```text\n\n# Set-up file to build the cPersistence module.\n# Note that the text should begin in the first column.\n*shared*\n\n# We need the path to the directory containing the ExtensionClass\n# include file.\nEC=/projects/ExtensionClass\ncPersistence cPersistence.c -I$(EC)\n```\nAfter the Setup file has been created, Makefile.pre.in\nis run with the \"boot\" target to create a make file:\n```text\n\nmake -f Makefile.pre.in boot\n```\nThis creates the file, Makefile. To build the extensions, simply\nrun the created make file:\n```text\n\nmake\n```\nIt's not necessary to re-run Makefile.pre.in if the\nSetup file is changed. The make file automatically rebuilds\nitself if the Setup file changes.", "python_version": "1.6", "length": 2944, "url": "https://docs.python.org/1.6/ext/building-on-unix.html"} {"title": "3. Building C and C++ Extensions on Windows", "text": "distributing.html | ext.html | win-cookbook.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3. Building C and C++ Extensions on Windows\nThis chapter briefly explains how to create a Windows extension module\nfor Python using Microsoft Visual C++, and follows with more\ndetailed background information on how it works. The explanatory\nmaterial is useful for both the Windows programmer learning to build\nPython extensions and the Unix programmer interested in producing\nsoftware which can be successfully built on both Unix and Windows.", "python_version": "1.6", "length": 562, "url": "https://docs.python.org/1.6/ext/building-on-windows.html"} {"title": "1.9 The Py_BuildValue() Function", "text": "parseTupleAndKeywords.html | intro.html | refcounts.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.9 The Py_BuildValue() Function\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.\nIn the following description, the quoted form is the format unit; the\nentry in (round) parentheses is the Python object type that the format\nunit will return; and the entry in [square] brackets is the type of\nthe C value(s) to be passed.\nThe characters space, tab, colon and comma are ignored in format\nstrings (but not within format units such as \"s#\"). This can be\nused to make long format strings a tad more readable.\n\"s\" (string) [char *]: Convert a null-terminated C string to a Python object. If the C\nstring pointer is NULL, `None` is returned.\n\"s#\" (string) [char *, int]: Convert a C string and its length to a Python object. If the C string\npointer is NULL, the length is ignored and `None` is\nreturned.\n\"z\" (string or `None`) [char *]: Same as \"s\".\n\"z#\" (string or `None`) [char *, int]: Same as \"s#\".\n\"u\" (Unicode string) [Py_UNICODE *]: Convert a null-terminated buffer of Unicode (UCS-2) data to a Python\nUnicode object. If the Unicode buffer pointer is NULL,\n`None` is returned.\n\"u#\" (Unicode string) [Py_UNICODE *, int]: Convert a Unicode (UCS-2) data buffer and its length to a Python\nUnicode object. If the Unicode buffer pointer is NULL, the length\nis ignored and `None` is returned.\n\"u\" (Unicode string) [Py_UNICODE *]: Convert a null-terminated buffer of Unicode (UCS-2) data to a Python Unicode\nobject. If the Unicode buffer pointer is NULL, `None` is returned.\n\"u#\" (Unicode string) [Py_UNICODE *, int]: Convert a Unicode (UCS-2) data buffer and its length to a Python Unicode\nobject. If the Unicode buffer pointer is NULL, the length is ignored and\n`None` is returned.\n\"i\" (integer) [int]: Convert a plain C int to a Python integer object.\n\"b\" (integer) [char]: Same as \"i\".\n\"h\" (integer) [short int]: Same as \"i\".\n\"l\" (integer) [long int]: Convert a C long int to a Python integer object.\n\"c\" (string of length 1) [char]: Convert a C int representing a character to a Python string of\nlength 1.\n\"d\" (float) [double]: Convert a C double to a Python floating point number.\n\"f\" (float) [float]: Same as \"d\".\n\"O\" (object) [PyObject *]: Pass a Python object untouched (except for its reference count, which\nis incremented by one). If the object passed in is a NULL\npointer, it is assumed that this was caused because the call producing\nthe argument found an error and set an exception. Therefore,\nPy_BuildValue() will return NULL but won't raise an\nexception. If no exception has been raised yet,\nPyExc_SystemError is set.\n\"S\" (object) [PyObject *]: Same as \"O\".\n\"U\" (object) [PyObject *]: Same as \"O\".\n\"N\" (object) [PyObject *]: Same as \"O\", except it doesn't increment the reference count on\nthe object. Useful when the object is created by a call to an object\nconstructor in the argument list.\n\"O&\" (object) [converter, anything]: Convert anything to a Python object through a converter\nfunction. The function is called with anything (which should be\ncompatible with void *) as its argument and should return a\n``new'' Python object, or NULL if an error occurred.\n\"(items)\" (tuple) [matching-items]: Convert a sequence of C values to a Python tuple with the same number\nof items.\n\"[items]\" (list) [matching-items]: Convert a sequence of C values to a Python list with the same number\nof items.\n\"{items}\" (dictionary) [matching-items]: Convert a sequence of C values to a Python dictionary. Each pair of\nconsecutive C values adds one item to the dictionary, serving as key\nand value, respectively.\nIf there is an error in the format string, the\nPyExc_SystemError exception is raised and NULL returned.\nExamples (to the left the call, to the right the resulting Python value):\n```text\n\nPy_BuildValue(\"\") None\nPy_BuildValue(\"i\", 123) 123\nPy_BuildValue(\"iii\", 123, 456, 789) (123, 456, 789)\nPy_BuildValue(\"s\", \"hello\") 'hello'\nPy_BuildValue(\"ss\", \"hello\", \"world\") ('hello', 'world')\nPy_BuildValue(\"s#\", \"hello\", 4) 'hell'\nPy_BuildValue(\"()\") ()\nPy_BuildValue(\"(i)\", 123) (123,)\nPy_BuildValue(\"(ii)\", 123, 456) (123, 456)\nPy_BuildValue(\"(i,i)\", 123, 456) (123, 456)\nPy_BuildValue(\"[i,i]\", 123, 456) [123, 456]\nPy_BuildValue(\"{s:i,s:i}\",\n\"abc\", 123, \"def\", 456) {'abc': 123, 'def': 456}\nPy_BuildValue(\"((ii)(ii)) (ii)\",\n1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))\n```", "python_version": "1.6", "length": 5300, "url": "https://docs.python.org/1.6/ext/buildValue.html"} {"title": "1.6 Calling Python Functions from C", "text": "compilation.html | intro.html | parseTuple.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.6 Calling Python Functions from C\nSo far we have concentrated on making C functions callable from\nPython. The reverse is also useful: calling Python functions from C.\nThis is especially the case for libraries that support so-called\n``callback'' functions. If a C interface makes use of callbacks, the\nequivalent Python often needs to provide a callback mechanism to the\nPython programmer; the implementation will require calling the Python\ncallback functions from a C callback. Other uses are also imaginable.\nFortunately, the Python interpreter is easily called recursively, and\nthere is a standard interface to call a Python function. (I won't\ndwell on how to call the Python parser with a particular string as\ninput -- if you're interested, have a look at the implementation of\nthe -c command line option in Python/pythonmain.c\nfrom the Python source code.)\nCalling a Python function is easy. First, the Python program must\nsomehow pass you the Python function object. You should provide a\nfunction (or some other interface) to do this. When this function is\ncalled, save a pointer to the Python function object (be careful to\nPy_INCREF() it!) in a global variable -- or wherever you\nsee fit. For example, the following function might be part of a module\ndefinition:\n```text\n\nstatic PyObject *my_callback = NULL;\n\nstatic PyObject *\nmy_set_callback(dummy, args)\nPyObject *dummy, *args;\n{\nPyObject *result = NULL;\nPyObject *temp;\n\nif (PyArg_ParseTuple(args, \"O:set_callback\", &temp)) {\nif (!PyCallable_Check(temp)) {\nPyErr_SetString(PyExc_TypeError, \"parameter must be callable\");\nreturn NULL;\n}\nPy_XINCREF(temp); /* Add a reference to new callback */\nPy_XDECREF(my_callback); /* Dispose of previous callback */\nmy_callback = temp; /* Remember new callback */\n/* Boilerplate to return \"None\" */\nPy_INCREF(Py_None);\nresult = Py_None;\n}\nreturn result;\n}\n```\nThis function must be registered with the interpreter using the\nMETH_VARARGS flag; this is described in section\n1.4 (methodTable.html#methodTable), ``The Module's Method Table and Initialization\nFunction.'' The PyArg_ParseTuple() function and its\narguments are documented in section 1.7 (parseTuple.html#parseTuple), ``Format Strings\nfor PyArg_ParseTuple().''\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 section\n1.10 (refcounts.html#refcounts), ``Reference Counts.''\nLater, when it is time to call the function, you call the C function\nPyEval_CallObject(). This function has two arguments, both\npointers to arbitrary Python objects: the Python function, and the\nargument list. The argument list must always be a tuple object, whose\nlength is the number of arguments. To call the Python function with\nno arguments, pass an empty tuple; to call it with one argument, pass\na singleton tuple. Py_BuildValue() returns a tuple when its\nformat string consists of zero or more format codes between\nparentheses. For example:\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": "1.6", "length": 5650, "url": "https://docs.python.org/1.6/ext/callingPython.html"} {"title": "1.5 Compilation and Linkage", "text": "methodTable.html | intro.html | callingPython.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.5 Compilation and Linkage\nThere are two more things to do before you can use your new extension:\ncompiling and linking it with the Python system. If you use dynamic\nloading, the details depend on the style of dynamic loading your\nsystem uses; see the chapters about building extension modules on\nUnix (chapter 2 (building-on-unix.html#building-on-unix)) and Windows (chapter\n3 (building-on-windows.html#building-on-windows)) for more information about this.\nIf you can't use dynamic loading, or if you want to make your module a\npermanent part of the Python interpreter, you will have to change the\nconfiguration setup and rebuild the interpreter. Luckily, this is\nvery simple: just place your file (spammodule.c for example) in\nthe Modules/ directory of an unpacked source distribution, add\na line to the file Modules/Setup.local describing your file:\n```text\n\nspam spammodule.o\n```\nand rebuild the interpreter by running make in the toplevel\ndirectory. You can also run make in the Modules/\nsubdirectory, but then you must first rebuild Makefile\nthere by running `make Makefile'. (This is necessary each\ntime you change the Setup file.)\nIf your module requires additional libraries to link with, these can\nbe listed on the line in the configuration file as well, for instance:\n```text\n\nspam spammodule.o -lX11\n```", "python_version": "1.6", "length": 1439, "url": "https://docs.python.org/1.6/ext/compilation.html"} {"title": "Contents", "text": "front.html | ext.html | intro.html | Extending and Embedding the Python Interpreter\n---\n## Contents", "python_version": "1.6", "length": 99, "url": "https://docs.python.org/1.6/ext/contents.html"} {"title": "1.11 Writing Extensions in C++", "text": "nullPointers.html | intro.html | using-cobjects.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.11 Writing Extensions in C++\nIt is possible to write extension modules in C++. Some restrictions\napply. If the main program (the Python interpreter) is compiled and\nlinked by the C compiler, global or static objects with constructors\ncannot be used. This is not a problem if the main program is linked\nby the C++ compiler. Functions that will be called by the\nPython interpreter (in particular, module initalization functions)\nhave to be declared using `extern \"C\"`.\nIt is unnecessary to enclose the Python header files in\n`extern \"C\" {...}` -- they use this form already if the symbol\n\"__cplusplus\" is defined (all recent C++ compilers define this\nsymbol).", "python_version": "1.6", "length": 783, "url": "https://docs.python.org/1.6/ext/cplusplus.html"} {"title": "2.1 Building Custom Interpreters", "text": "building-on-unix.html | building-on-unix.html | module-defn-options.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2.1 Building Custom Interpreters\nThe make file built by Makefile.pre.in can be run with the\n\"static\" target to build an interpreter:\n```text\n\nmake static\n```\nAny modules defined in the Setup file before the \"*shared*\" line\nwill be statically linked into the interpreter. Typically, a\n\"*shared*\" line is omitted from the Setup file when a custom\ninterpreter is desired.", "python_version": "1.6", "length": 512, "url": "https://docs.python.org/1.6/ext/custom-interps.html"} {"title": "2.4 Distributing your extension modules", "text": "module-defn-example.html | building-on-unix.html | building-on-windows.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2.4 Distributing your extension modules\nWhen distributing your extension modules in source form, make sure to\ninclude a Setup file. The Setup file should be named\nSetup.in in the distribution. The make file make file,\nMakefile.pre.in, will copy Setup.in to Setup.\nDistributing a Setup.in file makes it easy for people to\ncustomize the Setup file while keeping the original in\nSetup.in.\nIt is a good idea to include a copy of Makefile.pre.in for\npeople who do not have a source distribution of Python.\nDo not distribute a make file. People building your modules\nshould use Makefile.pre.in to build their own make file. A\nREADME file included in the package should provide simple\ninstructions to perform the build.\nWork is being done to make building and installing Python extensions\neasier for all platforms; this work in likely to supplant the current\napproach at some point in the future. For more information or to\nparticipate in the effort, refer to\nhttp://www.python.org/sigs/distutils-sig/ on the Python Web\nsite.", "python_version": "1.6", "length": 1165, "url": "https://docs.python.org/1.6/ext/distributing.html"} {"title": "3.2 Differences Between Unix and Windows", "text": "win-cookbook.html | building-on-windows.html | win-dlls.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3.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": "1.6", "length": 2876, "url": "https://docs.python.org/1.6/ext/dynamic-linking.html"} {"title": "4. Embedding Python in Another Application", "text": "win-dlls.html | ext.html | embeddingInCplusplus.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 4. Embedding Python in Another Application\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 MacOS, 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.", "python_version": "1.6", "length": 1412, "url": "https://docs.python.org/1.6/ext/embedding.html"} {"title": "4.1 Embedding Python in C++", "text": "embedding.html | embedding.html | about.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 4.1 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": "1.6", "length": 448, "url": "https://docs.python.org/1.6/ext/embeddingInCplusplus.html"} {"title": "1.2 Intermezzo: Errors and Exceptions", "text": "simpleExample.html | intro.html | backToExample.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.2 Intermezzo: Errors and Exceptions\nAn important convention throughout the Python interpreter is the\nfollowing: when a function fails, it should set an exception condition\nand return an error value (usually a NULL pointer). Exceptions\nare stored in a static global variable inside the interpreter; if this\nvariable is NULL no exception has occurred. A second global\nvariable stores the ``associated value'' of the exception (the second\nargument to raise). A third variable contains the stack\ntraceback in case the error originated in Python code. These three\nvariables are the C equivalents of the Python variables\n`sys.exc_type`, `sys.exc_value` and `sys.exc_traceback` (see\nthe section on module sys in the\nPython Library Reference (../lib/lib.html)). It is\nimportant to know about them to understand how errors are passed\naround.\nThe Python API defines a number of functions to set various types of\nexceptions.\nThe most common one is PyErr_SetString(). Its arguments\nare an exception object and a C string. The exception object is\nusually a predefined object like PyExc_ZeroDivisionError. The\nC string indicates the cause of the error and is converted to a\nPython string object and stored as the ``associated value'' of the\nexception.\nAnother useful function is PyErr_SetFromErrno(), which only\ntakes an exception argument and constructs the associated value by\ninspection of the global variable errno. The most\ngeneral function is PyErr_SetObject(), which takes two object\narguments, the exception and its associated value. You don't need to\nPy_INCREF() the objects passed to any of these functions.\nYou can test non-destructively whether an exception has been set with\nPyErr_Occurred(). This returns the current exception object,\nor NULL if no exception has occurred. You normally don't need\nto call PyErr_Occurred() to see whether an error occurred in a\nfunction call, since you should be able to tell from the return value.\nWhen a function f that calls another function g detects\nthat the latter fails, f should itself return an error value\n(e.g. 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 (e.g. by trying something else or pretending\nnothing happened).\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,\ne.g. PyExc_ZeroDivisionError, which you can use directly. Of\ncourse, 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, e.g.\n```text\n\nstatic PyObject *SpamError;\n```\nand initialize it in your module's initialization function\n(initspam()) with an exception object, e.g. (leaving out\nthe error checking for now):\n```text\n\nvoid\ninitspam()\n{\nPyObject *m, *d;\n\nm = Py_InitModule(\"spam\", SpamMethods);\nd = PyModule_GetDict(m);\nSpamError = PyErr_NewException(\"spam.error\", NULL, NULL);\nPyDict_SetItemString(d, \"error\", SpamError);\n}\n```\nNote that the Python name for the exception object is\nspam.error. The PyErr_NewException() function\nmay create either a string or class, depending on whether the\n-X flag was passed to the interpreter. If\n-X was used, SpamError will be a string object,\notherwise it will be a class object with the base class being\nException, described in the\nPython Library Reference (../lib/lib.html) under ``Built-in\nExceptions.''", "python_version": "1.6", "length": 5647, "url": "https://docs.python.org/1.6/ext/errors.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "../index.html | front.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# Extending and Embedding the Python Interpreter\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 268, "url": "https://docs.python.org/1.6/ext/ext.html"} {"title": "Front Matter", "text": "ext.html | ext.html | contents.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# Front Matter\nBEOPEN.COM TERMS AND CONDITIONS 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 OPEN SOURCE LICENSE AGREEMENT\nPython 1.6 is made available subject to the terms and conditions in\nCNRI's License Agreement. This Agreement together with Python 1.6 may\nbe located on the Internet using the following unique, persistent\nidentifier (known as a handle): 1895.22/1012. This Agreement may also\nbe obtained from a proxy server on the Internet using the following\nURL: http://hdl.handle.net/1895.22/1012.\nCWI PERMISSIONS STATEMENT AND DISCLAIMER\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.\nAcknowledgements\nThe following people have contributed sections to this document: Jim\nFulton, Konrad Hinsen, Chris Phoenix, and Neil Schemenauer.\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": "1.6", "length": 5337, "url": "https://docs.python.org/1.6/ext/front.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "../index.html | front.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# Extending and Embedding the Python Interpreter\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 268, "url": "https://docs.python.org/1.6/ext/index.html"} {"title": "1. Extending Python with C or C++", "text": "contents.html | ext.html | simpleExample.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1. Extending Python with C or C++\nIt is quite easy to add new built-in modules to Python, if you know\nhow to program in C. Such extension modules can do two things\nthat can't be done directly in Python: they can implement new built-in\nobject types, and they can call C library functions and system calls.\nTo support extensions, the Python API (Application Programmers\nInterface) defines a set of functions, macros and variables that\nprovide access to most aspects of the Python run-time system. The\nPython API is incorporated in a C source file by including the header\n`\"Python.h\"`.\nThe compilation of an extension module depends on its intended use as\nwell as on your system setup; details are given in later chapters.", "python_version": "1.6", "length": 836, "url": "https://docs.python.org/1.6/ext/intro.html"} {"title": "1.4 The Module's Method Table and Initialization Function", "text": "backToExample.html | intro.html | compilation.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.4 The Module's Method Table and Initialization Function\nI promised to show how spam_system() is called from Python\nprograms. First, we need to list its name and address in a ``method\ntable'':\n```text\n\nstatic PyMethodDef SpamMethods[] = {\n...\n{\"system\", spam_system, METH_VARARGS},\n...\n{NULL, NULL} /* Sentinel */\n};\n```\nNote the third entry (\"METH_VARARGS\"). This is a flag telling\nthe interpreter the calling convention to be used for the C\nfunction. It should normally always be \"METH_VARARGS\" or\n\"METH_VARARGS | METH_KEYWORDS\"; a value of `0` means that an\nobsolete variant of PyArg_ParseTuple() is used.\nWhen using only \"METH_VARARGS\", the function should expect\nthe Python-level parameters to be passed in as a tuple acceptable for\nparsing via PyArg_ParseTuple(); more information on this\nfunction is provided below.\nThe METH_KEYWORDS bit may be set in the third field if\nkeyword arguments should be passed to the function. In this case, the\nC function should accept a third \"PyObject *\" parameter which\nwill be a dictionary of keywords. Use\nPyArg_ParseTupleAndKeywords() to parse the arguments to\nsuch a function.\nThe method table must be passed to the interpreter in the module's\ninitialization function. The initialization function must be named\ninitname(), where name is the name of the\nmodule, and should be the only non-static item defined in\nthe module file:\n```text\n\nvoid\ninitspam()\n{\n(void) Py_InitModule(\"spam\", SpamMethods);\n}\n```\nNote that for C++, this method must be declared `extern \"C\"`.\nWhen the Python program imports module spam for the first\ntime, initspam() is called. (See below for comments about\nembedding Python.) It calls\nPy_InitModule(), which creates a ``module object'' (which\nis inserted in the dictionary `sys.modules` under the key\n`\"spam\"`), and inserts built-in function objects into the newly\ncreated module based upon the table (an array of PyMethodDef\nstructures) that was passed as its second argument.\nPy_InitModule() returns a pointer to the module object\nthat it creates (which is unused here). It aborts with a fatal error\nif the module could not be initialized satisfactorily, so the caller\ndoesn't need to check for errors.\nWhen embedding Python, the initspam() function is not\ncalled automatically unless there's an entry in the\n_PyImport_Inittab table. The easiest way to handle this is to\nstatically initialize your statically-linked modules by directly\ncalling initspam() after the call to\nPy_Initialize() or PyMac_Initialize():\n```text\n\nint main(int argc, char **argv)\n{\n/* Pass argv[0] to the Python interpreter */\nPy_SetProgramName(argv[0]);\n\n/* Initialize the Python interpreter. Required. */\nPy_Initialize();\n\n/* Add a static module */\ninitspam();\n```\nAnd example may be found in the file Demo/embed/demo.c in the\nPython source distribution.\nNote: Removing 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.\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": "1.6", "length": 3750, "url": "https://docs.python.org/1.6/ext/methodTable.html"} {"title": "2.3 Example", "text": "module-defn-options.html | building-on-unix.html | distributing.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2.3 Example\nHere is a more complicated example from Modules/Setup.in:\n```text\n\nGMP=/ufs/guido/src/gmp\nmpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a\n```\nwhich could also be written as:\n```text\n\nmpz mpzmodule.c -I$(GMP) -L$(GMP) -lgmp\n```", "python_version": "1.6", "length": 371, "url": "https://docs.python.org/1.6/ext/module-defn-example.html"} {"title": "2.2 Module Definition Options", "text": "custom-interps.html | building-on-unix.html | module-defn-example.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 2.2 Module Definition Options\nSeveral compiler options are supported:\nOther compiler options can be included (snuck in) by putting them\nin variables.\nSource files can include files with .c, .C, .cc,\n.cpp, .cxx, and .c++ extensions.\nOther input files include files with .a, .o, .sl,\nand .so extensions.", "python_version": "1.6", "length": 443, "url": "https://docs.python.org/1.6/ext/module-defn-options.html"} {"title": "1.10.4 NULL Pointers", "text": "thinIce.html | refcounts.html | cplusplus.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.4 NULL Pointers\nIn general, functions that take object references as arguments do not\nexpect you to pass them NULL pointers, and will dump core (or\ncause later core dumps) if you do so. Functions that return object\nreferences generally return NULL only to indicate that an\nexception occurred. The reason for not testing for NULL\narguments is that functions often pass the objects they receive on to\nother function -- if each function were to test for NULL,\nthere would be a lot of redundant tests and the code would run slower.\nIt is better to test for NULL only at the ``source'', i.e. when a\npointer that may be NULL is received, e.g. 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 (#foot633)\nIt is a severe error to ever let a NULL pointer ``escape'' to\nthe Python user.", "python_version": "1.6", "length": 1539, "url": "https://docs.python.org/1.6/ext/nullPointers.html"} {"title": "1.10.2 Ownership Rules", "text": "refcountsInPython.html | refcounts.html | thinIce.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.2 Ownership Rules\nWhenever an object reference is passed into or out of a function, it\nis part of the function's interface specification whether ownership is\ntransferred with the reference or not.\nMost functions that return a reference to an object pass on ownership\nwith the reference. In particular, all functions whose function it is\nto create a new object, e.g. PyInt_FromLong() and\nPy_BuildValue(), pass ownership to the receiver. Even if in\nfact, in some cases, you don't receive a reference to a brand new\nobject, you still receive ownership of the reference. For instance,\nPyInt_FromLong() maintains a cache of popular values and can\nreturn a reference to a cached 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": "1.6", "length": 2385, "url": "https://docs.python.org/1.6/ext/ownershipRules.html"} {"title": "1.7 Format Strings for PyArg_ParseTuple()", "text": "callingPython.html | intro.html | parseTupleAndKeywords.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.7 Format Strings for PyArg_ParseTuple()\nThe PyArg_ParseTuple() function is declared as follows:\n```text\n\nint PyArg_ParseTuple(PyObject *arg, char *format, ...);\n```\nThe arg argument must be a tuple object containing an argument\nlist passed from Python to a C function. The format argument\nmust be a format string, whose syntax is explained below. The\nremaining arguments must be addresses of variables whose type is\ndetermined by the format string. For the conversion to succeed, the\narg object must match the format and the format must be\nexhausted.\nNote that while PyArg_ParseTuple() checks that the Python\narguments have the required types, it cannot check the validity of the\naddresses of C variables passed to the call: if you make mistakes\nthere, your code will probably crash or at least overwrite random bits\nin memory. So be careful!\nA format string consists of zero or more ``format units''. A format\nunit describes one Python object; it is usually a single character or\na parenthesized sequence of format units. With a few exceptions, a\nformat unit that is not a parenthesized sequence normally corresponds\nto a single address argument to PyArg_ParseTuple(). In the\nfollowing description, the quoted form is the format unit; the entry\nin (round) parentheses is the Python object type that matches the\nformat unit; and the entry in [square] brackets is the type of the C\nvariable(s) whose address should be passed. (Use the \"&\"operator to pass a variable's address.)\nNote that any Python object references which are provided to the\ncaller are borrowed references; do not decrement their\nreference count!\n\"s\" (string) [char *]: Convert a Python string to a C pointer to a character string. You\nmust not provide storage for the string itself; a pointer to an\nexisting string is stored into the character pointer variable whose\naddress you pass. The C string is null-terminated. The Python string\nmust not contain embedded null bytes; if it does, a TypeError\nexception is raised.\n\"s#\" (string) [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.\n\"z\" (string or `None`) [char *]: Like \"s\", but the Python object may also be `None`, in which\ncase the C pointer is set to NULL.\n\"z#\" (string or `None`) [char *, int]: This is to \"s#\" as \"z\" is to \"s\".\n\"u\" (Unicode string) [Py_UNICODE *]: Convert a Python Unicode object to a C pointer to a null-terminated\nbuffer of Unicode (UCS-2) data. As with \"s\", there is no need\nto provide storage for the Unicode data buffer; a pointer to the\nexisting Unicode data is stored into the Py_UNICODE pointer variable whose\naddress you pass.\n\"u#\" (Unicode string) [Py_UNICODE *, int]: This variant on \"u\" stores into two C variables, the first one\na pointer to a Unicode data buffer, the second one its length.\n\"b\" (integer) [char]: Convert a Python integer to a tiny int, stored in a C char.\n\"h\" (integer) [short int]: Convert a Python integer to a C short int.\n\"i\" (integer) [int]: Convert a Python integer to a plain C int.\n\"l\" (integer) [long int]: Convert a Python integer to a C long int.\n\"c\" (string of length 1) [char]: Convert a Python character, represented as a string of length 1, to a\nC char.\n\"f\" (float) [float]: Convert a Python floating point number to a C float.\n\"d\" (float) [double]: Convert a Python floating point number to a C double.\n\"D\" (complex) [Py_complex]: Convert a Python complex number to a C Py_complex structure.\n\"O\" (object) [PyObject *]: Store a Python object (without any conversion) in a C object pointer.\nThe C program thus receives the actual object that was passed. The\nobject's reference count is not increased. The pointer stored is not\nNULL.\n\"O!\" (object) [typeobject, PyObject *]: Store a Python object in a C object pointer. This is similar to\n\"O\", but takes two C arguments: the first is the address of a\nPython type object, the second is the address of the C variable (of\ntype PyObject *) into which the object pointer is stored.\nIf the Python object does not have the required type,\nTypeError is raised.\n\"O&\" (object) [converter, anything]: Convert a Python object to a C variable through a converter\nfunction. This takes two arguments: the first is a function, the\nsecond is the address of a C variable (of arbitrary type), converted\nto void *. The converter function in turn is called as\nfollows:\nstatus`=`converter`(`object, address`);`\nwhere object is the Python object to be converted and\naddress is the void * argument that was passed to\nPyArg_ConvertTuple(). The returned status should be\n`1` for a successful conversion and `0` if the conversion\nhas failed. When the conversion fails, the converter function\nshould raise an exception.\n\"S\" (string) [PyStringObject *]: Like \"O\" but requires that the Python object is a string object.\nRaises TypeError if the object is not a string object.\nThe C variable may also be declared as PyObject *.\n\"U\" (Unicode string) [PyUnicodeObject *]: Like \"O\" but requires that the Python object is a Unicode object.\nRaises TypeError if the object is not a Unicode object.\nThe C variable may also be declared as PyObject *.\n\"t#\" (read-only character buffer) [char *, int]: Like \"s#\", but accepts any object which implements the read-only\nbuffer interface. The char * variable is set to point to the\nfirst byte of the buffer, and the int is set to the length of\nthe buffer. Only single-segment buffer objects are accepted;\nTypeError is raised for all others.\n\"w\" (read-write character buffer) [char *]: Similar to \"s\", but accepts any object which implements the\nread-write buffer interface. The caller must determine the length of\nthe buffer by other means, or use \"w#\" instead. Only\nsingle-segment buffer objects are accepted; TypeError is\nraised for all others.\n\"w#\" (read-write character buffer) [char *, int]: Like \"s#\", but accepts any object which implements the\nread-write buffer interface. The char * variable is set to\npoint to the first byte of the buffer, and the int is set to\nthe length of the buffer. Only single-segment buffer objects are\naccepted; TypeError is raised for all others.\n\"(items)\" (tuple) [matching-items]: The object must be a Python sequence whose length is the number of\nformat units in items. The C arguments must correspond to the\nindividual format units in items. Format units for sequences\nmay be nested.\nNote: Prior to Python version 1.5.2, this format specifier\nonly accepted a tuple containing the individual parameters, not an\narbitrary sequence. Code which previously caused\nTypeError to be raised here may now proceed without an\nexception. This is not expected to be a problem for existing code.\nIt is possible to pass Python long integers where integers are\nrequested; however no proper range checking is done -- the most\nsignificant bits are silently truncated when the receiving field is\ntoo small to receive the value (actually, the semantics are inherited\nfrom downcasts in C -- your mileage may vary).\nA few other characters have a meaning in a format string. These may\nnot occur inside nested parentheses. They are:\n\"|\": Indicates that the remaining arguments in the Python argument list are\noptional. The C variables corresponding to optional arguments should\nbe initialized to their default value -- when an optional argument is\nnot specified, PyArg_ParseTuple() does not touch the contents\nof the corresponding C variable(s).\n\":\": The list of format units ends here; the string after the colon is used\nas the function name in error messages (the ``associated value'' of\nthe exception that PyArg_ParseTuple() raises).\n\";\": The list of format units ends here; the string after the colon is used\nas the error message instead of the default error message.\nClearly, \":\" and \";\" mutually exclude each other.\nSome example calls:\n```text\n\nint ok;\nint i, j;\nlong k, l;\nchar *s;\nint size;\n\nok = PyArg_ParseTuple(args, \"\"); /* No arguments */\n/* Python call: f() */\n```\n```text\n\nok = PyArg_ParseTuple(args, \"s\", &s); /* A string */\n/* Possible Python call: f('whoops!') */\n```\n```text\n\nok = PyArg_ParseTuple(args, \"lls\", &k, &l, &s); /* Two longs and a string */\n/* Possible Python call: f(1, 2, 'three') */\n```\n```text\n\nok = PyArg_ParseTuple(args, \"(ii)s#\", &i, &j, &s, &size);\n/* A pair of ints and a string, whose size is also returned */\n/* Possible Python call: f((1, 2), 'three') */\n```\n```text\n\n{\nchar *file;\nchar *mode = \"r\";\nint bufsize = 0;\nok = PyArg_ParseTuple(args, \"s|si\", &file, &mode, &bufsize);\n/* A string, and optionally another string and an integer */\n/* Possible Python calls:\nf('spam')\nf('spam', 'w')\nf('spam', 'wb', 100000) */\n}\n```\n```text\n\n{\nint left, top, right, bottom, h, v;\nok = PyArg_ParseTuple(args, \"((ii)(ii))(ii)\",\n&left, &top, &right, &bottom, &h, &v);\n/* A rectangle and a point */\n/* Possible Python call:\nf(((0, 0), (400, 300)), (10, 10)) */\n}\n```\n```text\n\n{\nPy_complex c;\nok = PyArg_ParseTuple(args, \"D:myfunction\", &c);\n/* a complex, also providing a function name for errors */\n/* Possible Python call: myfunction(1+2j) */\n}\n```", "python_version": "1.6", "length": 9218, "url": "https://docs.python.org/1.6/ext/parseTuple.html"} {"title": "1.8 Keyword Parsing with PyArg_ParseTupleAndKeywords()", "text": "parseTuple.html | intro.html | buildValue.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.8 Keyword Parsing with PyArg_ParseTupleAndKeywords()\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.\nNote: Nested 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 \n#include \"Python.h\"\n\nstatic PyObject *\nkeywdarg_parrot(self, args, keywds)\nPyObject *self;\nPyObject *args;\nPyObject *keywds;\n{\nint voltage;\nchar *state = \"a stiff\";\nchar *action = \"voom\";\nchar *type = \"Norwegian Blue\";\n\nstatic char *kwlist[] = {\"voltage\", \"state\", \"action\", \"type\", NULL};\n\nif (!PyArg_ParseTupleAndKeywords(args, keywds, \"i|sss\", kwlist,\n&voltage, &state, &action, &type))\nreturn NULL;\n\nprintf(\"-- This parrot wouldn't %s if you put %i Volts through it.\\n\",\naction, voltage);\nprintf(\"-- Lovely plumage, the %s -- It's %s!\\n\", type, state);\n\nPy_INCREF(Py_None);\n\nreturn Py_None;\n}\n\nstatic PyMethodDef keywdarg_methods[] = {\n/* The cast of the function is necessary since PyCFunction values\n* only take two PyObject* parameters, and keywdarg_parrot() takes\n* three.\n*/\n{\"parrot\", (PyCFunction)keywdarg_parrot, METH_VARARGS|METH_KEYWORDS},\n{NULL, NULL} /* sentinel */\n};\n\nvoid\ninitkeywdarg()\n{\n/* Create the module and add the functions */\nPy_InitModule(\"keywdarg\", keywdarg_methods);\n}\n```", "python_version": "1.6", "length": 2025, "url": "https://docs.python.org/1.6/ext/parseTupleAndKeywords.html"} {"title": "1.10 Reference Counts", "text": "buildValue.html | intro.html | refcountsInPython.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.10 Reference Counts\nIn languages like C or C++, the programmer is responsible for\ndynamic allocation and deallocation of memory on the heap. In C,\nthis is done using the functions malloc() and\nfree(). In C++, the operators new and\ndelete are used with essentially the same meaning; they are\nactually implemented using malloc() and\nfree(), so we'll restrict the following discussion to the\nlatter.\nEvery block of memory allocated with malloc() should\neventually be returned to the pool of available memory by exactly one\ncall to free(). It is important to call\nfree() at the right time. If a block's address is\nforgotten but free() is not called for it, the memory it\noccupies cannot be reused until the program terminates. This is\ncalled a memory leak. On the other hand, if a program calls\nfree() for a block and then continues to use the block, it\ncreates a conflict with re-use of the block through another\nmalloc() call. This is called using freed memory.\nIt has the same bad consequences as referencing uninitialized data --\ncore dumps, wrong results, mysterious crashes.\nCommon causes of memory leaks are unusual paths through the code. For\ninstance, a function may allocate a block of memory, do some\ncalculation, and then free the block again. Now a change in the\nrequirements for the function may add a test to the calculation that\ndetects an error condition and can return prematurely from the\nfunction. It's easy to forget to free the allocated memory block when\ntaking this premature exit, especially when it is added later to the\ncode. Such leaks, once introduced, often go undetected for a long\ntime: the error exit is taken only in a small fraction of all calls,\nand most modern machines have plenty of virtual memory, so the leak\nonly becomes apparent in a long-running process that uses the leaking\nfunction frequently. Therefore, it's important to prevent leaks from\nhappening by having a coding convention or strategy that minimizes\nthis kind of errors.\nSince Python makes heavy use of malloc() and\nfree(), it needs a strategy to avoid memory leaks as well\nas the use of freed memory. The chosen method is called\nreference counting. The principle is simple: every object\ncontains a counter, which is incremented when a reference to the\nobject is stored somewhere, and which is decremented when a reference\nto it is deleted. When the counter reaches zero, the last reference\nto the object has been deleted and the object is freed.\nAn alternative strategy is called automatic garbage collection.\n(Sometimes, reference counting is also referred to as a garbage\ncollection strategy, hence my use of ``automatic'' to distinguish the\ntwo.) The big advantage of automatic garbage collection is that the\nuser doesn't need to call free() explicitly. (Another claimed\nadvantage is an improvement in speed or memory usage -- this is no\nhard fact however.) The disadvantage is that for C, there is no\ntruly portable automatic garbage collector, while reference counting\ncan be implemented portably (as long as the functions malloc()\nand free() are available -- which the C Standard guarantees).\nMaybe some day a sufficiently portable automatic garbage collector\nwill be available for C. Until then, we'll have to live with\nreference counts.", "python_version": "1.6", "length": 3374, "url": "https://docs.python.org/1.6/ext/refcounts.html"} {"title": "1.10.1 Reference Counting in Python", "text": "refcounts.html | refcounts.html | ownershipRules.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.1 Reference Counting in Python\nThere are two macros, `Py_INCREF(x)` and `Py_DECREF(x)`,\nwhich handle the incrementing and decrementing of the reference count.\nPy_DECREF() also frees the object when the count reaches zero.\nFor flexibility, it doesn't call free() directly -- rather, it\nmakes a call through a function pointer in the object's type\nobject. For this purpose (and others), every object also contains a\npointer to its type object.\nThe big question now remains: when to use `Py_INCREF(x)` and\n`Py_DECREF(x)`? Let's first introduce some terms. Nobody\n``owns'' an object; however, you can own a reference to an\nobject. An object's reference count is now defined as the number of\nowned references to it. The owner of a reference is responsible for\ncalling Py_DECREF() when the reference is no longer\nneeded. Ownership of a reference can be transferred. There are three\nways to dispose of an owned reference: pass it on, store it, or call\nPy_DECREF(). Forgetting to dispose of an owned reference\ncreates a memory leak.\nIt is also possible to borrow1.2 (#foot571) 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 (#foot907)\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 (i.e., the new owner must\ndispose of the reference properly, as well as the previous owner).", "python_version": "1.6", "length": 2333, "url": "https://docs.python.org/1.6/ext/refcountsInPython.html"} {"title": "1.1 A Simple Example", "text": "intro.html | intro.html | errors.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.1 A Simple Example\nLet's create an extension module called \"spam\" (the favorite food\nof Monty Python fans...) and let's say we want to create a Python\ninterface to the C library function system().1.1 (#foot883)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).\nAll user-visible symbols defined by `\"Python.h\"` have a prefix of\n\"Py\" or \"PY\", except those defined in standard header files.\nFor convenience, and since they are used extensively by the Python\ninterpreter, `\"Python.h\"` includes a few standard header files:\n``, ``, ``, and\n``. If the latter header file does not exist on your\nsystem, it declares the functions malloc(),\nfree() and realloc() directly.\nThe next thing we add to our module file is the C function that will\nbe called when the Python expression \"spam.system(string)\"is evaluated (we'll see shortly how it ends up being called):\n```text\n\nstatic PyObject *\nspam_system(self, args)\nPyObject *self;\nPyObject *args;\n{\nchar *command;\nint sts;\n\nif (!PyArg_ParseTuple(args, \"s\", &command))\nreturn NULL;\nsts = system(command);\nreturn Py_BuildValue(\"i\", sts);\n}\n```\nThere is a straightforward translation from the argument list in\nPython (e.g. the single expression `\"ls -l\"`) to the arguments\npassed to the C function. The C function always has two arguments,\nconventionally 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": "1.6", "length": 3298, "url": "https://docs.python.org/1.6/ext/simpleExample.html"} {"title": "1.10.3 Thin Ice", "text": "ownershipRules.html | refcounts.html | nullPointers.html | Extending and Embedding the Python Interpreter | contents.html\n---\n## 1.10.3 Thin Ice\nThere are a few situations where seemingly harmless use of a borrowed\nreference can lead to problems. These all have to do with implicit\ninvocations of the interpreter, which can cause the owner of a\nreference to dispose of it.\nThe first and most important case to know about is using\nPy_DECREF() on an unrelated object while borrowing a\nreference to a list item. For instance:\n```text\n\nbug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\n\nPyList_SetItem(list, 1, PyInt_FromLong(0L));\nPyObject_Print(item, stdout, 0); /* BUG! */\n}\n```\nThis function first borrows a reference to `list[0]`, then\nreplaces `list[1]` with the value `0`, and finally prints\nthe borrowed reference. Looks harmless, right? But it's not!\nLet's follow the control flow into PyList_SetItem(). The list\nowns references to all its items, so when item 1 is replaced, it has\nto dispose of the original item 1. Now let's suppose the original\nitem 1 was an instance of a user-defined class, and let's further\nsuppose that the class defined a __del__() method. If this\nclass instance has a reference count of 1, disposing of it will call\nits __del__() method.\nSince it is written in Python, the __del__() method can execute\narbitrary Python code. Could it perhaps do something to invalidate\nthe reference to `item` in bug()? You bet! Assuming\nthat the list passed into bug() is accessible to the\n__del__() method, it could execute a statement to the effect of\n\"del list[0]\", and assuming this was the last reference to that\nobject, it would free the memory associated with it, thereby\ninvalidating `item`.\nThe solution, once you know the source of the problem, is easy:\ntemporarily increment the reference count. The correct version of the\nfunction reads:\n```text\n\nno_bug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\n\nPy_INCREF(item);\nPyList_SetItem(list, 1, PyInt_FromLong(0L));\nPyObject_Print(item, stdout, 0);\nPy_DECREF(item);\n}\n```\nThis is a true story. An older version of Python contained variants\nof this bug and someone spent a considerable amount of time in a C\ndebugger to figure out why his __del__() methods would fail...\nThe second case of problems with a borrowed reference is a variant\ninvolving threads. Normally, multiple threads in the Python\ninterpreter can't get in each other's way, because there is a global\nlock protecting Python's entire object space. However, it is possible\nto temporarily release this lock using the macro\n`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using\n`Py_END_ALLOW_THREADS`. This is common around blocking I/O\ncalls, to let other threads use the CPU while waiting for the I/O to\ncomplete. Obviously, the following function has the same problem as\nthe previous one:\n```text\n\nbug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\nPy_BEGIN_ALLOW_THREADS\n...some blocking I/O call...\nPy_END_ALLOW_THREADS\nPyObject_Print(item, stdout, 0); /* BUG! */\n}\n```", "python_version": "1.6", "length": 3049, "url": "https://docs.python.org/1.6/ext/thinIce.html"} {"title": "1.12 Providing a C API for an Extension Module", "text": "cplusplus.html | intro.html | building-on-unix.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 1.12 Providing a C API for an Extension Module\nMany extension modules just provide new functions and types to be\nused from Python, but sometimes the code in an extension module can\nbe useful for other extension modules. For example, an extension\nmodule could implement a type ``collection'' which works like lists\nwithout order. Just like the standard Python list type has a C API\nwhich permits extension modules to create and manipulate lists, this\nnew collection type should have a set of C functions for direct\nmanipulation from other extension modules.\nAt first sight this seems easy: just write the functions (without\ndeclaring them static, of course), provide an appropriate\nheader file, and document the C API. And in fact this would work if\nall extension modules were always linked statically with the Python\ninterpreter. When modules are used as shared libraries, however, the\nsymbols defined in one module may not be visible to another module.\nThe details of visibility depend on the operating system; some systems\nuse one global namespace for the Python interpreter and all extension\nmodules (e.g. Windows), whereas others require an explicit list of\nimported symbols at module link time (e.g. AIX), or offer a choice of\ndifferent strategies (most Unices). And even if symbols are globally\nvisible, the module whose functions one wishes to call might not have\nbeen 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 (i.e.\npointers) from one extension module to another one: CObjects.\nA CObject is a Python data type which stores a pointer (void\n*). CObjects can only be created and accessed via their C API, but\nthey can be passed around like any other Python object. In particular,\nthey can be assigned to a name in an extension module's namespace.\nOther extension modules can then import this module, retrieve the\nvalue of this name, and then retrieve the pointer from the CObject.\nThere are many ways in which CObjects can be used to export the C API\nof an extension module. Each name could get its own CObject, or all C\nAPI pointers could be stored in an array whose address is published in\na CObject. And the various tasks of storing and retrieving the pointers\ncan be distributed in different ways between the module providing the\ncode and the client modules.\nThe following example demonstrates an approach that puts most of the\nburden on the writer of the exporting module, which is appropriate\nfor commonly used library modules. It stores all C API pointers\n(just one in the example!) in an array of void pointers which\nbecomes the value of a CObject. The header file corresponding to\nthe module provides a macro that takes care of importing the module\nand retrieving its C API pointers; client modules only have to call\nthis macro before accessing the C API.\nThe exporting module is a modification of the spam module from\nsection 1.1 (simpleExample.html#simpleExample). The function spam.system()\ndoes not call the C library function system() directly,\nbut a function PySpam_System(), which would of course do\nsomething more complicated in reality (such as adding ``spam'' to\nevery command). This function PySpam_System() is also\nexported to other extension modules.\nThe function PySpam_System() is a plain C function,\ndeclared static like everything else:\n```text\n\nstatic int\nPySpam_System(command)\nchar *command;\n{\nreturn system(command);\n}\n```\nThe function spam_system() is modified in a trivial way:\n```text\n\nstatic PyObject *\nspam_system(self, args)\nPyObject *self;\nPyObject *args;\n{\nchar *command;\nint sts;\n\nif (!PyArg_ParseTuple(args, \"s\", &command))\nreturn NULL;\nsts = PySpam_System(command);\nreturn Py_BuildValue(\"i\", sts);\n}\n```\nIn the beginning of the module, right after the line\n```text\n\n#include \"Python.h\"\n```\ntwo more lines must be added:\n```text\n\n#define SPAM_MODULE\n#include \"spammodule.h\"\n```\nThe `#define` is used to tell the header file that it is being\nincluded in the exporting module, not a client module. Finally,\nthe module's initialization function must take care of initializing\nthe C API pointer array:\n```text\n\nvoid\ninitspam()\n{\nPyObject *m, *d;\nstatic void *PySpam_API[PySpam_API_pointers];\nPyObject *c_api_object;\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\n/* Create a name for this object in the module's namespace */\nd = PyModule_GetDict(m);\nPyDict_SetItemString(d, \"_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 Py_PROTO((char *command))\n\n/* Total number of C API pointers */\n#define PySpam_API_pointers 1\n\n#ifdef SPAM_MODULE\n/* This section is used when compiling spammodule.c */\n\nstatic PySpam_System_RETURN PySpam_System PySpam_System_PROTO;\n\n#else\n/* This section is used in modules that use spammodule's API */\n\nstatic void **PySpam_API;\n\n#define PySpam_System \\\n(*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])\n\n#define import_spam() \\\n{ \\\nPyObject *module = PyImport_ImportModule(\"spam\"); \\\nif (module != NULL) { \\\nPyObject *module_dict = PyModule_GetDict(module); \\\nPyObject *c_api_object = PyDict_GetItemString(module_dict, \"_C_API\"); \\\nif (PyCObject_Check(c_api_object)) { \\\nPySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \\\n} \\\n} \\\n}\n\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* !defined(Py_SPAMMODULE_H */\n```\nAll that a client module must do in order to have access to the\nfunction PySpam_System() is to call the function (or\nrather macro) import_spam() in its initialization\nfunction:\n```text\n\nvoid\ninitclient()\n{\nPyObject *m;\n\nPy_InitModule(\"client\", ClientMethods);\nimport_spam();\n}\n```\nThe main disadvantage of this approach is that the file\nspammodule.h is rather complicated. However, the\nbasic structure is the same for each function that is\nexported, so it has to be learned only once.\nFinally it should be mentioned that CObjects offer additional\nfunctionality, which is especially useful for memory allocation and\ndeallocation of the pointer stored in a CObject. The details\nare described in the Python/C API\nReference Manual (../api/api.html) in the section ``CObjects'' and in the\nimplementation of CObjects (files Include/cobject.h and\nObjects/cobject.c in the Python source code distribution).", "python_version": "1.6", "length": 7363, "url": "https://docs.python.org/1.6/ext/using-cobjects.html"} {"title": "3.1 A Cookbook Approach", "text": "building-on-windows.html | building-on-windows.html | dynamic-linking.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3.1 A Cookbook Approach\nThis section provides a recipe for building a Python extension on\nWindows.\nGrab the binary installer from http://www.python.org/ and\ninstall Python. The binary installer has all of the required header\nfiles except for config.h.\nGet the source distribution and extract it into a convenient location.\nCopy the config.h from the PC/ directory into the\ninclude/ directory created by the installer.\nCreate a Setup file for your extension module, as described in\nchapter 2 (building-on-unix.html#building-on-unix).\nGet David Ascher's compile.py script from\nhttp://starship.python.net/crew/da/compile/. Run the script to\ncreate Microsoft Visual C++ project files.\nOpen the DSW file in Visual C++ and select Build.\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 Python FAQ\n(http://www.python.org/doc/FAQ.html) for details on why you must\ndo this.", "python_version": "1.6", "length": 1269, "url": "https://docs.python.org/1.6/ext/win-cookbook.html"} {"title": "3.3 Using DLLs in Practice", "text": "dynamic-linking.html | building-on-windows.html | embedding.html | Extending and Embedding the Python Interpreter | contents.html\n---\n# 3.3 Using DLLs in Practice\nWindows Python is built in Microsoft Visual C++; using other\ncompilers may or may not work (though Borland seems to). The rest of\nthis section is MSVC++ specific.\nWhen creating DLLs in Windows, you must pass python15.lib to\nthe linker. To build two DLLs, spam and ni (which uses C functions\nfound in spam), you could use these commands:\n```text\n\ncl /LD /I/python/include spam.c ../libs/python15.lib\ncl /LD /I/python/include ni.c spam.lib ../libs/python15.lib\n```\nThe first command created three files: spam.obj,\nspam.dll and spam.lib. Spam.dll does not contain\nany Python functions (such as PyArg_ParseTuple()), but it\ndoes know how to find the Python code thanks to python15.lib.\nThe second command created ni.dll (and .obj and\n.lib), which knows how to find the necessary functions from\nspam, and also from the Python executable.\nNot every identifier is exported to the lookup table. If you want any\nother modules (including Python) to be able to see your identifiers,\nyou have to say \"_declspec(dllexport)\", as in \"void\n_declspec(dllexport) initspam(void)\" or \"PyObject\n_declspec(dllexport) *NiGetSpamData(void)\".\nDeveloper Studio will throw in a lot of import libraries that you do\nnot really need, adding about 100K to your executable. To get rid of\nthem, use the Project Settings dialog, Link tab, to specify\nignore default libraries. Add the correct\nmsvcrtxx.lib to the list of libraries.", "python_version": "1.6", "length": 1558, "url": "https://docs.python.org/1.6/ext/win-dlls.html"} {"title": "Python 1.6 Documentation - September 18, 2000", "text": "Python Documentation | modindex.html\n---\n# Python Documentation\nRelease 1.6\nSeptember 18, 2000\n---\nSee About the Python Documentation (about.html)\nfor information on suggesting changes.", "python_version": "1.6", "length": 185, "url": "https://docs.python.org/1.6/index.html"} {"title": "About this document ...", "text": "manual-install.html | inst.html | Installing Python Modules | contents.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, 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---\nmanual-install.html | inst.html | Installing Python Modules | contents.html\n---", "python_version": "1.6", "length": 1604, "url": "https://docs.python.org/1.6/inst/about.html"} {"title": "3 Alternate Installation", "text": "node10.html | inst.html | alt-unix-prefix.html | Installing Python Modules | contents.html\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 section applies to you.", "python_version": "1.6", "length": 1096, "url": "https://docs.python.org/1.6/inst/alt-install.html"} {"title": "3.4 Alternate installation: Mac OS", "text": "alt-windows.html | alt-install.html | custom-install.html | Installing Python Modules | contents.html\n---\n## 3.4 Alternate installation: Mac OS\nLike Windows, Mac OS has no notion of home directories (or even of\nusers), and a fairly simple standard Python installation. Thus, only a\n--prefix option is needed. It defines the installation\nbase, and files are installed under it as follows:\n** how do MacPython users run the interpreter with command-line args? **\n** Corran Webster says: ``Modules are found in either :Lib or\n:Mac:Lib, while extensions usually go in\n:Mac:PlugIns''--does this mean that non-pure distributions should\nbe divided between :Mac:PlugIns and :Mac:Lib? If so, that\nchanges the granularity at which we care about modules: instead of\n``modules from pure distributions'' and ``modules from non-pure\ndistributions'', it becomes ``modules from pure distributions'',\n``Python modules from non-pure distributions'', and ``extensions from\nnon-pure distributions''. Is this necessary?!? **", "python_version": "1.6", "length": 1003, "url": "https://docs.python.org/1.6/inst/alt-macos.html"} {"title": "3.2 Alternate installation: Unix (the prefix scheme)", "text": "alt-unix-prefix.html | alt-install.html | alt-windows.html | Installing Python Modules | contents.html\n---\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/python1.X rather than\n/usr/lib/python1.X. This can be done with\n```text\n\n/usr/bin/python setup.py install --prefix=/usr/local\n```\nAnother possibility is a network filesystem where the name used to write\nto a remote directory is different from the name used to read it: for\nexample, the Python interpreter accessed as /usr/local/bin/python\nmight search for modules in /usr/local/lib/python1.X,\nbut those modules would have to be installed to, say,\n/mnt/@server/export/lib/python1.X. This\ncould be done with\n```text\n\n/usr/local/bin/python setup.py install --prefix=/mnt/@server/export\n```\nIn either case, the --prefix option defines the\ninstallation base, and the --exec-prefix option defines\nthe platform-specific installation base, which is used for\nplatform-specific files. (Currently, this just means non-pure module\ndistributions, but could be expanded to C libraries, binary executables,\netc.) If --exec-prefix is not supplied, it defaults to\n--prefix. Files are installed as follows:\nThere is no requirement that --prefix or\n--exec-prefix actually point to an alternate Python\ninstallation; if the directories listed above do not already exist, they\nare created at installation time.\nIncidentally, the real reason the prefix scheme is important is simply\nthat a standard Unix installation uses the prefix scheme, but with\n--prefix and --exec-prefix supplied by\nPython itself (as `sys.prefix` and `sys.exec_prefix`). Thus,\nyou might think you'll never use the prefix scheme, but every time you\nrun `python setup.py install` without any other options, you're\nusing it.\nNote that installing extensions to an alternate Python installation has\nno effect on how those extensions are built: in particular, the Python\nheader files (Python.h and friends) installed with the Python\ninterpreter used to run the setup script will be used in compiling\nextensions. It is your responsibility to ensure that the interpreter\nused to run extensions installed in this way is compatibile with the\ninterpreter used to build them. The best way to do this is to ensure\nthat the two interpreters are the same version of Python (possibly\ndifferent builds, or possibly copies of the same build). (Of course, if\nyour --prefix and --exec-prefix don't even\npoint to an alternate Python installation, this is immaterial.)", "python_version": "1.6", "length": 3252, "url": "https://docs.python.org/1.6/inst/alt-unix-home.html"} {"title": "3.1 Alternate installation: Unix (the home scheme)", "text": "alt-install.html | alt-install.html | alt-unix-home.html | Installing Python Modules | contents.html\n---\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:", "python_version": "1.6", "length": 1091, "url": "https://docs.python.org/1.6/inst/alt-unix-prefix.html"} {"title": "3.3 Alternate installation: Windows", "text": "alt-unix-home.html | alt-install.html | alt-macos.html | Installing Python Modules | contents.html\n---\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 \\Temp directory on the current\ndrive.\nThe installation base is defined by the --prefix option;\nthe --exec-prefix option is not supported under Windows.\nFiles are installed as follows:", "python_version": "1.6", "length": 690, "url": "https://docs.python.org/1.6/inst/alt-windows.html"} {"title": "5 Distutils Configuration Files", "text": "custom-install.html | inst.html | pre-distutils.html | Installing Python Modules | contents.html\n---\n# 5 Distutils Configuration Files\n** not even implemented yet, much less documented! **", "python_version": "1.6", "length": 188, "url": "https://docs.python.org/1.6/inst/config-files.html"} {"title": "Contents", "text": "inst.html | inst.html | intro.html | Installing Python Modules\n---\n## Contents", "python_version": "1.6", "length": 78, "url": "https://docs.python.org/1.6/inst/contents.html"} {"title": "4 Custom Installation", "text": "alt-macos.html | inst.html | config-files.html | Installing Python Modules | contents.html\n---\n# 4 Custom Installation\nSometimes, the alternate installation schemes described in\nsection 3 (alt-install.html#alt-install) just don't do what you want. You might\nwant to tweak just one or two directories while keeping everything under\nthe same base directory, or you might want to completely redefine the\ninstallation scheme. In either case, you're creating a custom\ninstallation scheme.\nYou probably noticed the column of ``override options'' in the tables\ndescribing the alternate installation schemes above. Those options are\nhow you define a custom installation scheme. These override options can\nbe relative, absolute, or explicitly defined in terms of one of the\ninstallation base directories. (There are two installation base\ndirectories, and they are normally the same--they only differ when you\nuse the Unix ``prefix scheme'' and supply different\n--prefix and --exec-prefix options.)\nFor example, say you're installing a module distribution to your home\ndirectory under Unix--but you want scripts to go in\n /scripts rather than  /bin.\nAs you might expect, you can override this directory with the\n--install-scripts option; in this case, it makes most\nsense to supply a relative path, which will be interpreted relative to\nthe installation base directory (your home directory, in this case):\n```text\n\npython setup.py install --home=~ --install-scripts=scripts\n```\nAnother Unix example: suppose your Python installation was built and\ninstalled with a prefix of /usr/local/python, so under a standard\ninstallation scripts will wind up in /usr/local/python/bin. If\nyou want them in /usr/local/bin instead, you would supply this\nabsolute directory for the --install-scripts option:\n```text\n\npython setup.py install --install-scripts=/usr/local/bin\n```\n(This performs an installation using the ``prefix scheme,'' where the\nprefix is whatever your Python interpreter was installed with--\n/usr/local/python in this case.)\nIf you maintain Python on Windows, you might want third-party modules to\nlive in a subdirectory of prefix, rather than right in\nprefix itself. This is almost as easy as customizing the\nscript installation directory--you just have to remember that there are\ntwo types of modules to worry about, pure modules and non-pure modules\n(i.e., modules from a non-pure distribution). For example:\n```text\n\npython setup.py install --install-purelib=Site --install-platlib=Site\n```\nThe specified installation directories are relative to prefix.\nOf course, you also have to ensure that these directories are in\nPython's module search path, e.g. by putting a .pth file in\nprefix (** should have a section describing .pth files and\ncross-ref it here **).\nIf you want to define an entire installation scheme, you just have to\nsupply all of the installation directory options. The recommended way\nto do this is to supply relative paths; for example, if you want to\nmaintain all Python module-related files under python in your\nhome directory, and you want a separate directory for each platform that\nyou use your home directory from, you might define the following\ninstallation scheme:\n```text\n\npython setup.py install --home=~ \\\n--install-purelib=python/lib \\\n--install-platlib=python/lib.$PLAT \\\n--install-scripts=python/scripts\n--install-data=python/data\n```\nor, equivalently,\n```text\n\npython setup.py install --home=~/python \\\n--install-purelib=lib \\\n--install-platlib='lib.$PLAT' \\\n--install-scripts=scripts\n--install-data=data\n```\n`$PLAT` is not (necessarily) an environment variable--it will be\nexpanded by the Distutils as it parses your command line options (just\nas it does when parsing your configuration file(s)).\nObviously, specifying the entire installation scheme every time you\ninstall a new module distribution would be very tedious. Thus, you can\nput these options into your Distutils config file (see\nsection 5 (config-files.html#config-files)):\n```text\n\n[install]\ninstall-base=$HOME\ninstall-purelib=python/lib\ninstall-platlib=python/lib.$PLAT\ninstall-scripts=python/scripts\ninstall-data=python/data\n```\nor, equivalently,\n```text\n\n[install]\ninstall-base=$HOME/python\ninstall-purelib=lib\ninstall-platlib=lib.$PLAT\ninstall-scripts=scripts\ninstall-data=data\n```\nNote that these two are not equivalent if you supply a different\ninstallation base directory when you run the setup script. For example,\n```text\n\npython setup.py --install-base=/tmp\n```\nwould install pure modules to /tmp/python/lib in the first\ncase, and to /tmp/lib in the second case. (For the second\ncase, you probably want to supply an installation base of\n/tmp/python.)\nYou probably noticed the use of `$HOME` and `$PLAT` in the\nsample configuration file input. These are Distutils configuration\nvariables, which bear a strong resemblance to environment variables. In\nfact, you can use environment variables in config files--on platforms\nthat have such a notion--but the Distutils additionally define a few\nextra variables that may not be in your environment, such as\n`$PLAT`. (And of course, you can only use the configuration\nvariables supplied by the Distutils on systems that don't have\nenvironment variables, such as Mac OS (** true? **).) See\nsection 5 (config-files.html#config-files) for details.\n** need some Windows and Mac OS examples--when would custom\ninstallation schemes be needed on those platforms? **", "python_version": "1.6", "length": 5403, "url": "https://docs.python.org/1.6/inst/custom-install.html"} {"title": "Installing Python Modules", "text": "../index.html | contents.html | Installing Python Modules | contents.html\n---\n# Installing Python Modules\nGreg Ward\nE-mail: gward@python.net", "python_version": "1.6", "length": 140, "url": "https://docs.python.org/1.6/inst/index.html"} {"title": "Installing Python Modules", "text": "../index.html | contents.html | Installing Python Modules | contents.html\n---\n# Installing Python Modules\nGreg Ward\nE-mail: gward@python.net", "python_version": "1.6", "length": 140, "url": "https://docs.python.org/1.6/inst/inst.html"} {"title": "1 Introduction", "text": "contents.html | inst.html | trivial-inst.html | Installing Python Modules | contents.html\n---\n# 1 Introduction\nAlthough Python's extensive standard library covers many programming\nneeds, there often comes a time when you need to add some new\nfunctionality to your Python installation in the form of third-party\nmodules. This might be necessary to support your own programming, or to\nsupport an application that you want to use and that happens to be\nwritten in Python.\nIn the past, there has been little support for adding third-party\nmodules to an existing Python installation. With the introduction of\nthe Python Distribution Utilities (Distutils for short) in Python 2.0,\nthis is starting to change. Not everything will change overnight,\nthough, so while this document concentrates on installing module\ndistributions that use the Distutils, we will also spend some time\ndealing with the old ways.\nThis document is aimed primarily at the people who need to install\nthird-party Python modules: end-users and system administrators who just\nneed to get some Python application running, and existing Python\nprogrammers who want to add some new goodies to their toolbox. You\ndon't need to know Python to read this document; there will be some\nbrief forays into using Python's interactive mode to explore your\ninstallation, but that's it. If you're looking for information on how\nto distribute your own Python modules so that others may use them, see\nthe Distributing Python Modules (../dist/dist.html) manual.", "python_version": "1.6", "length": 1506, "url": "https://docs.python.org/1.6/inst/intro.html"} {"title": "6.1 The Makefile.pre.in file", "text": "pre-distutils.html | pre-distutils.html | manual-install.html | Installing Python Modules | contents.html\n---\n## 6.1 The Makefile.pre.in file", "python_version": "1.6", "length": 141, "url": "https://docs.python.org/1.6/inst/makefile-pre-in.html"} {"title": "6.2 Installing modules manually", "text": "makefile-pre-in.html | pre-distutils.html | about.html | Installing Python Modules | contents.html\n---\n## 6.2 Installing modules manually", "python_version": "1.6", "length": 137, "url": "https://docs.python.org/1.6/inst/manual-install.html"} {"title": "1.2 The new standard: Distutils", "text": "trivial-inst.html | intro.html | old-way.html | Installing Python Modules | contents.html\n---\n## 1.2 The new standard: Distutils\nIf you download a module source distribution, you can tell pretty\nquickly if it was packaged and distributed in the standard way, i.e.\nusing the Distutils. First, the distribution's name and version number\nwill be featured prominently in the name of the downloaded archive, e.g.\nfoo-1.0.tar.gz or widget-0.9.7.zip. Next, the archive\nwill unpack into a similarly-named directory: foo-1.0 or\nwidget-0.9.7. Additionally, the distribution will contain a\nsetup script setup.py, and a README.txt (or possibly\nREADME), which should explain that building and installing the\nmodule distribution is a simple matter of running\n```text\n\npython setup.py install\n```\nIf all these things are true, then you already know how to build and\ninstall the modules you've just downloaded: run the command above.\nUnless you need to install things in a non-standard way or customize the\nbuild process, you don't really need this manual. Or rather, the above\ncommand is everything you need to get out of this manual.", "python_version": "1.6", "length": 1119, "url": "https://docs.python.org/1.6/inst/new-standard.html"} {"title": "2.4 How installation works", "text": "node9.html | normal-install.html | alt-install.html | Installing Python Modules | contents.html\n---\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 Windows,\nrun ``Python 2.0 (interpreter)'' ** right? **; under Mac OS, ** ??? **.\nOnce the interpreter is started, you type Python code at the\n\"»> \" prompt. For example, on my Linux system, I type the three\nPython statements shown below, and get the output as shown, to find\nout my prefix and exec-prefix:\n```text\n\nPython 1.6 (#22, Sep 2 2000, 23:54:55) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2\nCopyright (c) 1995-2000 Corporation for National Research Initiatives.\nAll Rights Reserved.\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.\n>>> import sys\n>>> sys.prefix\n'/usr'\n>>> sys.exec_prefix\n'/usr'\n```\nIf you don't want to install to the standard location, or if you don't\nhave permission to write there, then you need to read about alternate\ninstallations in the next section.", "python_version": "1.6", "length": 2445, "url": "https://docs.python.org/1.6/inst/node10.html"} {"title": "2.1 Platform variations", "text": "normal-install.html | normal-install.html | node8.html | Installing Python Modules | contents.html\n---\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 Unix system, the\nnormal 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 unpack the archive before opening the command\nprompt. If you downloaded the archive file to\nC:\\Temp, then it probably unpacked (depending on\nyour software) into\nC:\\Temp\\foo-1.0; from the command\nprompt window, you would then run\n```text\n\ncd c:\\temp\\foo-1.0\npython setup.py install\n```\nOn Mac OS, ... ** again, how do you run Python scripts on Mac OS? **\n** arg, my lovely ``bslash'' macro doesn't work in non-tt fonts! help\nme LATEX, you're my only hope... **", "python_version": "1.6", "length": 1023, "url": "https://docs.python.org/1.6/inst/node7.html"} {"title": "2.2 Splitting the job up", "text": "node7.html | normal-install.html | node9.html | Installing Python Modules | contents.html\n---\n## 2.2 Splitting the job up\nRunning `setup.py install` builds and installs all modules in one\nfell swoop. If you prefer to work incrementally--especially useful if\nyou want to customize the build process, or if things are going\nwrong--you can use the setup script to do one thing at a time. This is\nparticularly helpful when the build and install will be done by\ndifferent users--e.g., you might want to build a module distribution\nand hand it off to a system administrator for installation (or do it\nyourself, with super-user privileges).\nFor example, you can build everything in one step, and then install\neverything in a second step, by invoking the setup script twice:\n```text\n\npython setup.py build\npython setup.py install\n```\n(If you do this, you will notice that running the `install`\ncommand first runs the `build` command, which quickly notices\nthat it has nothing to do, since everything in the build\ndirectory is up-to-date.)\n** concrete reason for splitting things up? **", "python_version": "1.6", "length": 1077, "url": "https://docs.python.org/1.6/inst/node8.html"} {"title": "2.3 How building works", "text": "node8.html | normal-install.html | node10.html | Installing Python Modules | contents.html\n---\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-files.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. The first form, with just a lib directory,\nis used for ``pure module distributions''--that is, module\ndistributions that include only pure Python modules. If a module\ndistribution contains any extensions (modules written in C/C++, or Java\nfor JPython), then the second form, with two `` directories,\nis used. In that case, the temp.plat directory holds\ntemporary files generated by the compile/link process that don't\nactually get installed. 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.", "python_version": "1.6", "length": 1696, "url": "https://docs.python.org/1.6/inst/node9.html"} {"title": "2 Standard Build and Install", "text": "old-way.html | inst.html | node7.html | Installing Python Modules | contents.html\n---\n# 2 Standard Build and Install\nAs described in section 1.2 (new-standard.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 and do it there; on Mac OS ...\n** what the heck do you do on Mac OS? **.", "python_version": "1.6", "length": 491, "url": "https://docs.python.org/1.6/inst/normal-install.html"} {"title": "1.3 The old way: no standards", "text": "new-standard.html | intro.html | normal-install.html | Installing Python Modules | contents.html\n---\n## 1.3 The old way: no standards\nBefore the Distutils, there was no infrastructure to support installing\nthird-party modules in a consistent, standardized way. Thus, it's not\nreally possible to write a general manual for installing Python modules\nthat don't use the Distutils; the only truly general statement that can\nbe made is, ``Read the module's own installation instructions.''\nHowever, if such instructions exist at all, they are often woefully\ninadequate and targeted at experienced Python developers. Such users\nare already familiar with how the Python library is laid out on their\nplatform, and know where to copy various files in order for Python to\nfind them. This document makes no such assumptions, and explains how\nthe Python library is laid out on three major platforms (Unix, Windows,\nand Mac OS), so that you can understand what happens when the Distutils\ndo their job and know how to install modules manually when the\nmodule author fails to provide a setup script.\nAdditionally, while there has not previously been a standard\ninstallation mechanism, Python has had some standard machinery for\nbuilding extensions on Unix since Python ** version? **. This machinery\n(the Makefile.pre.in file) is superseded by the Distutils, but it\nwill no doubt live on in older module distributions for a while. This\nMakefile.pre.in mechanism is documented in the ``Extending &\nEmbedding Python'' manual, but that manual is aimed at module\ndevelopers--hence, we include documentation for builders/installers\nhere.\nAll of the pre-Distutils material is tucked away in\nsection 6 (pre-distutils.html#pre-distutils).", "python_version": "1.6", "length": 1715, "url": "https://docs.python.org/1.6/inst/old-way.html"} {"title": "6 Pre-Distutils Conventions", "text": "config-files.html | inst.html | makefile-pre-in.html | Installing Python Modules | contents.html\n---\n# 6 Pre-Distutils Conventions", "python_version": "1.6", "length": 130, "url": "https://docs.python.org/1.6/inst/pre-distutils.html"} {"title": "1.1 Best case: trivial installation", "text": "intro.html | intro.html | new-standard.html | Installing Python Modules | contents.html\n---\n## 1.1 Best case: trivial installation\nIn the best case, someone will have prepared a special version of the\nmodule distribution you want to install that is targeted specifically at\nyour platform and is installed just like any other software on your\nplatform. For example, the module developer might make an executable\ninstaller available for Windows users, an RPM package for users of\nRPM-based Linux systems (Red Hat, SuSE, Mandrake, and many others), a\nDebian package for users of Debian-based Linux systems (Debian proper,\nCaldera, Corel, etc.), and so forth.\nIn that case, you would download the installer appropriate to your\nplatform and do the obvious thing with it: run it if it's an executable\ninstaller, `rpm -install` it if it's an RPM, etc. You don't need\nto run Python or a setup script, you don't need to compile\nanything--you might not even need to read any instructions (although\nit's always a good idea to do so anyways).\nOf course, things will not always be that easy. You might be interested\nin a module distribution that doesn't have an easy-to-use installer for\nyour platform. In that case, you'll have to start with the source\ndistribution released by the module's author/maintainer. Installing\nfrom a source distribution is not too hard, as long as the modules are\npackaged in the standard way. The bulk of this document is about\nbuilding and installing modules from standard source distributions.", "python_version": "1.6", "length": 1512, "url": "https://docs.python.org/1.6/inst/trivial-inst.html"} {"title": "About this document ...", "text": "genindex.html | lib.html | Python Library Reference | contents.html | genindex.html\n---\n# About this document ...\nPython Library Reference,\nSeptember 18, 2000, Release 1.6\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | lib.html | Python Library Reference | contents.html | genindex.html\n---", "python_version": "1.6", "length": 1652, "url": "https://docs.python.org/1.6/lib/about.html"} {"title": "12.6.2 AddressList Objects", "text": "message-objects.html | module-rfc822.html | module-mimetools.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.6.2 AddressList Objects\nAn AddressList instance has the following methods:\nFinally, AddressList instances have one public instance variable:", "python_version": "1.6", "length": 275, "url": "https://docs.python.org/1.6/lib/addresslist-objects.html"} {"title": "16.1.1 Configuration Objects", "text": "module-al.html | module-al.html | al-port-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 16.1.1 Configuration Objects\nConfiguration objects (returned by newconfig() have the\nfollowing methods:", "python_version": "1.6", "length": 224, "url": "https://docs.python.org/1.6/lib/al-config-objects.html"} {"title": "16.1.2 Port Objects", "text": "al-config-objects.html | module-al.html | module-al-constants.html | Python Library Reference | contents.html | genindex.html\n---\n## 16.1.2 Port Objects\nPort objects, as returned by openport(), have the following\nmethods:", "python_version": "1.6", "length": 221, "url": "https://docs.python.org/1.6/lib/al-port-objects.html"} {"title": "6. Generic Operating System Services", "text": "shlex-objects.html | lib.html | module-os.html | Python Library Reference | contents.html | genindex.html\n---\n# 6. Generic Operating System Services\nThe modules described in this chapter provide interfaces to operating\nsystem features that are available on (almost) all operating systems,\nsuch as files and a clock. The interfaces are generally modelled\nafter the Unix or C interfaces, but they are available on most\nother systems as well. Here's an overview:", "python_version": "1.6", "length": 459, "url": "https://docs.python.org/1.6/lib/allos.html"} {"title": "3.16.4 Exceptions and Error Handling", "text": "Querying_ASTs.html | module-parser.html | AST_Objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.16.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": "1.6", "length": 771, "url": "https://docs.python.org/1.6/lib/AST_Errors.html"} {"title": "3.16.6 Examples", "text": "AST_Objects.html | module-parser.html | node55.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.16.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": "1.6", "length": 528, "url": "https://docs.python.org/1.6/lib/AST_Examples.html"} {"title": "3.16.5 AST Objects", "text": "AST_Errors.html | module-parser.html | AST_Examples.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.16.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": "1.6", "length": 339, "url": "https://docs.python.org/1.6/lib/AST_Objects.html"} {"title": "11.16.1 Example basic HTTP client", "text": "module-asyncore.html | module-asyncore.html | netdata.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.16.1 Example basic HTTP client\nAs a basic example, below is a very basic HTTP client that uses the\ndispatcher class to implement its socket handling:\n```text\n\nclass http_client(asyncore.dispatcher):\ndef __init__(self, host,path):\nasyncore.dispatcher.__init__(self)\nself.path = path\nself.create_socket(socket.AF_INET, socket.SOCK_STREAM)\nself.connect( (host, 80) )\nself.buffer = 'GET %s HTTP/1.0\\r\\b\\r\\n' % self.path\n\ndef handle_connect(self):\npass\n\ndef handle_read(self):\ndata = self.recv(8192)\nprint data\n\ndef writeable(self):\nreturn (len(self.buffer) > 0)\n\ndef handle_write(self):\nsent = self.send(self.buffer)\nself.buffer = self.buffer[sent:]\n```", "python_version": "1.6", "length": 777, "url": "https://docs.python.org/1.6/lib/asyncore-example.html"} {"title": "14.4.1 AU_read Objects", "text": "module-sunau.html | module-sunau.html | au-write-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 14.4.1 AU_read Objects\nAU_read objects, as returned by open() above, have the\nfollowing methods:\nThe following two methods define a term ``position'' which is compatible\nbetween them, and is otherwise implementation dependant.\nThe following two functions are defined for compatibility with the\naifc (module-aifc.html), and don't do anything interesting.", "python_version": "1.6", "length": 481, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 14.4.2 AU_write Objects\nAU_write objects, as returned by open() above, have the\nfollowing methods:", "python_version": "1.6", "length": 224, "url": "https://docs.python.org/1.6/lib/au-write-objects.html"} {"title": "17.1.1 Audio Device Objects", "text": "module-sunaudiodev.html | module-sunaudiodev.html | module-sunaudiodev-constants.html | Python Library Reference | contents.html | genindex.html\n---\n## 17.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": "1.6", "length": 726, "url": "https://docs.python.org/1.6/lib/audio-device-objects.html"} {"title": "12.10.1 Notes", "text": "module-binhex.html | module-binhex.html | module-uu.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.10.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": "1.6", "length": 385, "url": "https://docs.python.org/1.6/lib/binhex-notes.html"} {"title": "5.5.1 Example", "text": "module-bisect.html | module-bisect.html | module-array.html | Python Library Reference | contents.html | genindex.html\n---\n## 5.5.1 Example\nThe bisect() function is generally useful for categorizing\nnumeric data. This example uses bisect() to look up a\nletter grade for an exam total (say) based on a set of ordered numeric\nbreakpoints: 85 and up is an `A', 75..84 is a `B', etc.", "python_version": "1.6", "length": 379, "url": "https://docs.python.org/1.6/lib/bisect-example.html"} {"title": "2.1.4.1 Bit-string Operations on Integer Types", "text": "typesnumeric.html | typesnumeric.html | typesseq.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.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": "1.6", "length": 1065, "url": "https://docs.python.org/1.6/lib/bitstring-ops.html"} {"title": "2.1.7.5 Code Objects", "text": "typesmethods.html | typesother.html | bltin-type-objects.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.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": "1.6", "length": 738, "url": "https://docs.python.org/1.6/lib/bltin-code-objects.html"} {"title": "2.1.7.8 The Ellipsis Object", "text": "bltin-null-object.html | typesother.html | bltin-file-objects.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.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": "1.6", "length": 397, "url": "https://docs.python.org/1.6/lib/bltin-ellipsis-object.html"} {"title": "2.1.7.9 File Objects", "text": "bltin-ellipsis-object.html | typesother.html | typesinternal.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.9 File Objects\nFile objects are implemented using C's `stdio`package and can be created with the built-in function\nopen() described in section\n2.3 (built-in-funcs.html#built-in-funcs), ``Built-in Functions.'' They are also returned\nby some other built-in functions and methods, e.g.,\nposix.popen() and posix.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:\nFile objects also offer the following attributes:", "python_version": "1.6", "length": 815, "url": "https://docs.python.org/1.6/lib/bltin-file-objects.html"} {"title": "2.1.7.7 The Null Object", "text": "bltin-type-objects.html | typesother.html | bltin-ellipsis-object.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.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": "1.6", "length": 362, "url": "https://docs.python.org/1.6/lib/bltin-null-object.html"} {"title": "2.1.7.6 Type Objects", "text": "bltin-code-objects.html | typesother.html | bltin-null-object.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.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": "1.6", "length": 425, "url": "https://docs.python.org/1.6/lib/bltin-type-objects.html"} {"title": "2.1.2 Boolean Operations", "text": "truth.html | types.html | comparisons.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.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": "1.6", "length": 429, "url": "https://docs.python.org/1.6/lib/boolean.html"} {"title": "7.11.1 Hash, BTree and Record Objects", "text": "module-bsddb.html | module-bsddb.html | module-zlib.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.11.1 Hash, BTree and Record Objects\nOnce instantiated, hash, btree and record objects support the following\nmethods:\nExample:", "python_version": "1.6", "length": 250, "url": "https://docs.python.org/1.6/lib/bsddb-objects.html"} {"title": "2.3 Built-in Functions", "text": "module-exceptions.html | builtin.html | python.html | Python Library Reference | contents.html | genindex.html\n---\n# 2.3 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": "1.6", "length": 273, "url": "https://docs.python.org/1.6/lib/built-in-funcs.html"} {"title": "2. Built-in Types, Exceptions and Functions", "text": "intro.html | lib.html | types.html | Python Library Reference | contents.html | genindex.html\n---\n# 2. Built-in Types, Exceptions and Functions\nNames for built-in exceptions and functions are found in a separate\nsymbol table. This table is searched last when the interpreter looks\nup the meaning of a name, so local and global\nuser-defined names can override built-in names. Built-in types are\ndescribed together here for easy reference.2.1 (#foot127)\nThe tables in this chapter document the priorities of operators by\nlisting them in order of ascending priority (within a table) and\ngrouping operators that have the same priority in the same box.\nBinary operators of the same priority group from left to right.\n(Unary operators group from right to left, but there you have no real\nchoice.) See Chapter 5 of the Python\nReference Manual (../ref/ref.html) for the complete picture on operator priorities.\n---\n#### Footnotes", "python_version": "1.6", "length": 921, "url": "https://docs.python.org/1.6/lib/builtin.html"} {"title": "3.29.1 Python Byte Code Instructions", "text": "module-dis.html | module-dis.html | module-new.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.29.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.\nThe slice opcodes take up to three parameters.\nSlice assignment needs even an additional parameter. As any statement,\nthey put nothing on the stack.\nAll of the following opcodes expect arguments. An argument is two\nbytes, with the more significant byte last.", "python_version": "1.6", "length": 771, "url": "https://docs.python.org/1.6/lib/bytecodes.html"} {"title": "16.3.2 Parser Objects", "text": "player-objects.html | module-cd.html | module-fl.html | Python Library Reference | contents.html | genindex.html\n---\n## 16.3.2 Parser Objects\nParser objects (returned by createparser()) have the\nfollowing methods:", "python_version": "1.6", "length": 213, "url": "https://docs.python.org/1.6/lib/cd-parser-objects.html"} {"title": "11.1.1 Introduction", "text": "module-cgi.html | module-cgi.html | Using_the_cgi_module.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.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```\n(It may not be fully legal HTML according to the letter of the\nstandard, but any browser will understand it.)", "python_version": "1.6", "length": 1883, "url": "https://docs.python.org/1.6/lib/cgi-intro.html"} {"title": "5.10.1 Cmd Objects", "text": "module-cmd.html | module-cmd.html | module-shlex.html | Python Library Reference | contents.html | genindex.html\n---\n## 5.10.1 Cmd Objects\nA Cmd instance has the following methods:\nInstances of Cmd subclasses have some public instance variables:", "python_version": "1.6", "length": 245, "url": "https://docs.python.org/1.6/lib/Cmd-objects.html"} {"title": "2.1.3 Comparisons", "text": "boolean.html | types.html | typesnumeric.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.3 Comparisons\nComparison operations are supported by all objects. They all have the\nsame priority (which is higher than that of the Boolean operations).\nComparisons can be chained arbitrarily; for example, `x < y <= z` is equivalent to `x < y and y <= z`, except that y is evaluated only once (but\nin both cases z is not evaluated at all when `x < y` is found to be false).\nThis table summarizes the comparison operations:\nNotes:\n(1): `<>` and `!=` are alternate spellings for the same operator.\n(I couldn't choose between ABC and C! :-)\n`!=` is the preferred spelling; `<>` is obsolescent.\nObjects of different types, except different numeric types, never\ncompare equal; such objects are ordered consistently but arbitrarily\n(so that sorting a heterogeneous array yields a consistent result).\nFurthermore, some types (for example, file objects) support only a\ndegenerate notion of comparison where any two objects of that type are\nunequal. Again, such objects are ordered arbitrarily but\nconsistently.\nInstances of a class normally compare as non-equal unless the class\ndefines the __cmp__() method. Refer to the Python\nReference Manual for information on the use of this method to effect\nobject 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": "1.6", "length": 1633, "url": "https://docs.python.org/1.6/lib/comparisons.html"} {"title": "7.15.1 Completer Objects", "text": "module-rlcompleter.html | module-rlcompleter.html | unix.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.15.1 Completer Objects\nCompleter objects have the following method:", "python_version": "1.6", "length": 197, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 7.5.3 Condition Objects\nA condition variable is always associated with some kind of lock;\nthis can be passed in or one will be created by default. (Passing\none in is useful when several condition variables must share the\nsame lock.)\nA condition variable has acquire() and release()\nmethods that call the corresponding methods of the associated lock.\nIt also has a wait() method, and notify() and\nnotifyAll() methods. These three must only be called when\nthe calling thread has acquired the lock.\nThe wait() method releases the lock, and then blocks until it\nis awakened by a notify() or notifyAll() call for\nthe same condition variable in another thread. Once awakened, it\nre-acquires the lock and returns. It is also possible to specify a\ntimeout.\nThe notify() method wakes up one of the threads waiting for\nthe condition variable, if any are waiting. The notifyAll()\nmethod wakes up all threads waiting for the condition variable.\nNote: the notify() and notifyAll() methods don't\nrelease the lock; this means that the thread or threads awakened will\nnot return from their wait() call immediately, but only when\nthe thread that called notify() or notifyAll()\nfinally relinquishes ownership of the lock.\nTip: the typical programming style using condition variables uses the\nlock to synchronize access to some shared state; threads that are\ninterested in a particular change of state call wait()\nrepeatedly until they see the desired state, while threads that modify\nthe state call notify() or notifyAll() when they\nchange the state in such a way that it could possibly be a desired\nstate for one of the waiters. For example, the following code is a\ngeneric producer-consumer situation with unlimited buffer capacity:\n```text\n\n# Consume one item\ncv.acquire()\nwhile not an_item_is_available():\ncv.wait()\nget_an_available_item()\ncv.release()\n\n# Produce one item\ncv.acquire()\nmake_an_item_available()\ncv.notify()\ncv.release()\n```\nTo choose between notify() and notifyAll(), consider\nwhether one state change can be interesting for only one or several\nwaiting threads. E.g. in a typical producer-consumer situation,\nadding one item to the buffer only needs to wake up one consumer\nthread.", "python_version": "1.6", "length": 2317, "url": "https://docs.python.org/1.6/lib/condition-objects.html"} {"title": "5.7.1 ConfigParser Objects", "text": "module-ConfigParser.html | module-ConfigParser.html | module-fileinput.html | Python Library Reference | contents.html | genindex.html\n---\n## 5.7.1 ConfigParser Objects\nConfigParser instances have the following methods:", "python_version": "1.6", "length": 219, "url": "https://docs.python.org/1.6/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 | genindex.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": "1.6", "length": 328, "url": "https://docs.python.org/1.6/lib/console-objects.html"} {"title": "Contents", "text": "front.html | lib.html | intro.html | Python Library Reference | genindex.html\n---\n## Contents", "python_version": "1.6", "length": 93, "url": "https://docs.python.org/1.6/lib/contents.html"} {"title": "4.2.3 Module Contents", "text": "matching-searching.html | module-re.html | re-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 4.2.3 Module Contents\nThe module defines the following functions and constants, and an exception:", "python_version": "1.6", "length": 222, "url": "https://docs.python.org/1.6/lib/Contents_of_Module_re.html"} {"title": "4.3.2 Module Contents", "text": "node91.html | module-regex.html | module-regsub.html | Python Library Reference | contents.html | genindex.html\n---\n## 4.3.2 Module Contents\nThe module defines these functions, and an exception:\nCompiled regular expression objects support these methods:\nCompiled regular expressions support these data attributes:", "python_version": "1.6", "length": 313, "url": "https://docs.python.org/1.6/lib/Contents_of_Module_regex.html"} {"title": "3.16.2 Converting AST Objects", "text": "Creating_ASTs.html | module-parser.html | Querying_ASTs.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.16.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": "1.6", "length": 406, "url": "https://docs.python.org/1.6/lib/Converting_ASTs.html"} {"title": "3.16.1 Creating AST Objects", "text": "module-parser.html | module-parser.html | Converting_ASTs.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.16.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": "1.6", "length": 335, "url": "https://docs.python.org/1.6/lib/Creating_ASTs.html"} {"title": "15. Cryptographic Services", "text": "module-sndhdr.html | lib.html | module-md5.html | Python Library Reference | contents.html | genindex.html\n---\n# 15. Cryptographic Services\nThe modules described in this chapter implement various algorithms of\na cryptographic nature. They are available at the discretion of the\ninstallation. Here's an overview:\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": "1.6", "length": 589, "url": "https://docs.python.org/1.6/lib/crypto.html"} {"title": "6.11.1 Constants and Functions", "text": "module-curses.html | module-curses.html | curses-window-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.11.1 Constants and Functions\nThe curses module defines the following data members:\nThe module curses defines the following exception:\nNote: Whenever 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": "1.6", "length": 490, "url": "https://docs.python.org/1.6/lib/curses-functions.html"} {"title": "6.11.2 Window Objects", "text": "curses-functions.html | module-curses.html | module-getopt.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.11.2 Window Objects\nWindow objects, as returned by initscr() and\nnewwin() above, have the\nfollowing methods:", "python_version": "1.6", "length": 240, "url": "https://docs.python.org/1.6/lib/curses-window-objects.html"} {"title": "7.9.1 Database Objects", "text": "module-dbhash.html | module-dbhash.html | module-whichdb.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.9.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": "1.6", "length": 322, "url": "https://docs.python.org/1.6/lib/dbhash-objects.html"} {"title": "9.1 Debugger Commands", "text": "module-pdb.html | module-pdb.html | node209.html | Python Library Reference | contents.html | genindex.html\n---\n# 9.1 Debugger Commands\nThe debugger recognizes the following commands. Most commands can be\nabbreviated to one or two letters; e.g. \"h(elp)\" means that\neither \"h\" or \"help\" can be used to enter the help\ncommand (but not \"he\" or \"hel\", nor \"H\" or\n\"Help\" or \"HELP\"). Arguments to commands must be\nseparated by whitespace (spaces or tabs). Optional arguments are\nenclosed in square brackets (\"[]\") in the command syntax; the\nsquare brackets must not be typed. Alternatives in the command syntax\nare separated by a vertical bar (\"|\").\nEntering a blank line repeats the last command entered. Exception: if\nthe last command was a \"list\" command, the next 11 lines are\nlisted.\nCommands that the debugger doesn't recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged. Python statements can also be prefixed with an exclamation\npoint (\"!\"). This is a powerful way to inspect the program\nbeing debugged; it is even possible to change a variable or call a\nfunction. When an\nexception occurs in such a statement, the exception name is printed\nbut the debugger's state is not changed.\nMultiple commands may be entered on a single line, separated by\n\";;\". (A single \";\" is not used as it is\nthe separator for multiple commands in a line that is passed to\nthe Python parser.)\nNo intelligence is applied to separating the commands;\nthe input is split at the first \";;\" pair, even if it is in\nthe middle of a quoted string.\nThe debugger supports aliases. Aliases can have parameters which\nallows one a certain level of adaptability to the context under\nexamination.\nIf a file .pdbrc\nexists in the user's home directory or in the current directory, it is\nread in and executed as if it had been typed at the debugger prompt.\nThis is particularly useful for aliases. If both files exist, the one\nin the home directory is read first and aliases defined there can be\noverriden 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\n$PAGER is defined, the file is piped through that command\ninstead. Since the command argument must be an identifier,\n\"help exec\" must be entered to get help on the \"!\" command.\nw(here): Print a stack trace, with the most recent frame at the bottom. An\narrow indicates the current frame, which determines the context of\nmost commands.\nd(own): Move the current frame one level down in the stack trace\n(to an newer frame).\nu(p): Move the current frame one level up in the stack trace\n(to a older frame).\nb(reak) [[filename:]lineno`|`function[, condition]]: With a lineno argument, set a break there in the current\nfile. With a function argument, set a break at the first\nexecutable statement within that function.\nThe line number may be prefixed with a filename and a colon,\nto specify a breakpoint in another file (probably one that\nhasn't been loaded yet). The file is searched on `sys.path`.\nNote that each breakpoint is assigned a number to which all the other\nbreakpoint commands refer.\nIf a second argument is present, it is an expression which must\nevaluate to true before the breakpoint is honored.\nWithout argument, list all breaks, including for each breakpoint,\nthe number of times that breakpoint has been hit, the current\nignore count, and the associated condition if any.\ntbreak [[filename:]lineno`|`function[, condition]]: Temporary breakpoint, which is removed automatically when it is\nfirst hit. The arguments are the same as break.\ncl(ear) [bpnumber [bpnumber ...]]: With a space separated list of breakpoint numbers, clear those\nbreakpoints. Without argument, clear all breaks (but first\nask confirmation).\ndisable [bpnumber [bpnumber ...]]: Disables the breakpoints given as a space separated list of\nbreakpoint numbers. Disabling a breakpoint means it cannot cause\nthe program to stop execution, but unlike clearing a breakpoint, it\nremains in the list of breakpoints and can be (re-)enabled.\nenable [bpnumber [bpnumber ...]]: Enables the breakpoints specified.\nignore bpnumber [count]: Sets the ignore count for the given breakpoint number. If\ncount is omitted, the ignore count is set to 0. A breakpoint\nbecomes active when the ignore count is zero. When non-zero,\nthe count is decremented each time the breakpoint is reached\nand the breakpoint is not disabled and any associated condition\nevaluates to true.\ncondition bpnumber [condition]: Condition is an expression which must evaluate to true before\nthe breakpoint is honored. If condition is absent, any existing\ncondition is removed; i.e., the breakpoint is made unconditional.\ns(tep): Execute the current line, stop at the first possible occasion\n(either in a function that is called or on the next line in the\ncurrent function).\nn(ext): Continue execution until the next line in the current function\nis reached or it returns. (The difference between \"next\" and\n\"step\" is that \"step\" stops inside a called function, while\n\"next\" executes called functions at (nearly) full speed, only\nstopping at the next line in the current function.)\nr(eturn): Continue execution until the current function returns.\nc(ont(inue)): Continue execution, only stop when a breakpoint is encountered.\nl(ist) [first[, last]]: List source code for the current file. Without arguments, list 11\nlines around the current line or continue the previous listing. With\none argument, list 11 lines around at that line. With two arguments,\nlist the given range; if the second argument is less than the first,\nit is interpreted as a count.\na(rgs): Print the argument list of the current function.\np expression: Evaluate the expression in the current context and print its\nvalue. (Note: \"print\" can also be used, but is not a debugger\ncommand -- this executes the Python print statement.)\nalias [name [command]]: Creates an alias called name that executes command. The\ncommand must not be enclosed in quotes. Replaceable parameters\ncan be indicated by \"%1\", \"%2\", and so on, while \"%*\" is\nreplaced by all the parameters. If no command is given, the current\nalias for name is shown. If no arguments are given, all\naliases are listed.\nAliases may be nested and can contain anything that can be\nlegally typed at the pdb prompt. Note that internal pdb commands\ncan be overridden by aliases. Such a command is\nthen hidden until the alias is removed. Aliasing is recursively\napplied to the first word of the command line; all other words\nin the line are left alone.\nAs an example, here are two useful aliases (especially when placed\nin the .pdbrc file):\n```text\n\n#Print instance variables (usage \"pi classInst\")\nalias pi for k in %1.__dict__.keys(): print \"%1.\",k,\"=\",%1.__dict__[k]\n#Print instance variables in self\nalias ps pi self\n```\nunalias name: Deletes the specified alias.\n[!]statement: Execute the (one-line) statement in the context of\nthe current stack frame.\nThe exclamation point can be omitted unless the first word\nof the statement resembles a debugger command.\nTo set a global variable, you can prefix the assignment\ncommand with a \"global\" command on the same line, e.g.:\n```text\n\n(Pdb) global list_options; list_options = ['-l']\n(Pdb)\n```\nq(uit): Quit from the debugger.\nThe program being executed is aborted.", "python_version": "1.6", "length": 7413, "url": "https://docs.python.org/1.6/lib/debugger-commands.html"} {"title": "10.4 What Is Deterministic Profiling?", "text": "profile-instant.html | profile.html | module-profile.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.4 What Is Deterministic Profiling?\nDeterministic profiling is meant to reflect the fact that all\nfunction call, function return, and exception events\nare monitored, and precise timings are made for the intervals between\nthese events (during which time the user's code is executing). In\ncontrast, statistical profiling (which is not done by this\nmodule) randomly samples the effective instruction pointer, and\ndeduces where time is being spent. The latter technique traditionally\ninvolves less overhead (as the code does not need to be instrumented),\nbut provides only relative indications of where time is being spent.\nIn Python, since there is an interpreter active during execution, the\npresence of instrumented code is not required to do deterministic\nprofiling. Python automatically provides a hook (optional\ncallback) for each event. In addition, the interpreted nature of\nPython tends to add so much overhead to execution, that deterministic\nprofiling tends to only add small processing overhead in typical\napplications. The result is that deterministic profiling is not that\nexpensive, yet provides extensive run time statistics about the\nexecution of a Python program.\nCall count statistics can be used to identify bugs in code (surprising\ncounts), and to identify possible inline-expansion points (high call\ncounts). Internal time statistics can be used to identify ``hot\nloops'' that should be carefully optimized. Cumulative time\nstatistics should be used to identify high level errors in the\nselection of algorithms. Note that the unusual handling of cumulative\ntimes in this profiler allows statistics for recursive implementations\nof algorithms to be directly compared to iterative implementations.", "python_version": "1.6", "length": 1838, "url": "https://docs.python.org/1.6/lib/Deterministic_Profiling.html"} {"title": "8.5.1 Dl Objects", "text": "module-dl.html | module-dl.html | module-dbm.html | Python Library Reference | contents.html | genindex.html\n---\n## 8.5.1 Dl Objects\nDl objects, as returned by open() above, have the\nfollowing methods:", "python_version": "1.6", "length": 201, "url": "https://docs.python.org/1.6/lib/dl-objects.html"} {"title": "6.18.2 For extension writers and programs that embed Python", "text": "node145.html | module-locale.html | module-mutex.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.18.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 progammer the impression that you can manipulate the\nLC_NUMERIC locale setting, but this not the case at the C\nlevel: C code will always find that the LC_NUMERIC locale\nsetting is \"C\". This is because too much would break when the\ndecimal point character is set to something else than a period\n(e.g. the Python parser would break). Caveat: threads that run\nwithout holding Python's global interpreter lock may occasionally find\nthat the numeric locale setting differs; this is because the only\nportable way to implement this feature is to set the numeric locale\nsettings to what the user requests, extract the relevant\ncharacteristics, and then restore the \"C\" numeric locale.", "python_version": "1.6", "length": 1422, "url": "https://docs.python.org/1.6/lib/embedding-locale.html"} {"title": "7.5.5 Event Objects", "text": "semaphore-objects.html | module-threading.html | thread-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.5.5 Event Objects\nThis is one of the simplest mechanisms for communication between\nthreads: one thread signals an event and one or more other threads\nare waiting for it.\nAn event object manages an internal flag that can be set to true with\nthe set() method and reset to false with the clear() method. The\nwait() method blocks until the flag is true.", "python_version": "1.6", "length": 486, "url": "https://docs.python.org/1.6/lib/event-objects.html"} {"title": "3.15.1 Examples", "text": "module-imp.html | module-imp.html | module-parser.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.15.1 Examples\nThe following function emulates what was the standard import statement\nup to Python 1.4 (i.e., 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 import 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": "1.6", "length": 922, "url": "https://docs.python.org/1.6/lib/examples-imp.html"} {"title": "16.4.1 Functions Defined in Module fl", "text": "module-fl.html | module-fl.html | form-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 16.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": "1.6", "length": 316, "url": "https://docs.python.org/1.6/lib/FL_Functions.html"} {"title": "16.4.2 Form Objects", "text": "FL_Functions.html | module-fl.html | forms-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 16.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": "1.6", "length": 706, "url": "https://docs.python.org/1.6/lib/form-objects.html"} {"title": "12.5.2 Formatter Implementations", "text": "formatter-interface.html | module-formatter.html | writer-interface.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.5.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": "1.6", "length": 325, "url": "https://docs.python.org/1.6/lib/formatter-impls.html"} {"title": "12.5.1 The Formatter Interface", "text": "module-formatter.html | module-formatter.html | formatter-impls.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.5.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": "1.6", "length": 492, "url": "https://docs.python.org/1.6/lib/formatter-interface.html"} {"title": "16.4.3 FORMS Objects", "text": "form-objects.html | module-fl.html | module-fl-constants.html | Python Library Reference | contents.html | genindex.html\n---\n## 16.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": "1.6", "length": 333, "url": "https://docs.python.org/1.6/lib/forms-objects.html"} {"title": "Front Matter", "text": "lib.html | lib.html | contents.html | Python Library Reference | contents.html | genindex.html\n---\n# Front Matter\nBEOPEN.COM TERMS AND CONDITIONS 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 OPEN SOURCE LICENSE AGREEMENT\nPython 1.6 is made available subject to the terms and conditions in\nCNRI's License Agreement. This Agreement together with Python 1.6 may\nbe located on the Internet using the following unique, persistent\nidentifier (known as a handle): 1895.22/1012. This Agreement may also\nbe obtained from a proxy server on the Internet using the following\nURL: http://hdl.handle.net/1895.22/1012.\nCWI PERMISSIONS STATEMENT AND DISCLAIMER\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.\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 WWW 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": "1.6", "length": 5770, "url": "https://docs.python.org/1.6/lib/front.html"} {"title": "11.4.1 FTP Objects", "text": "module-ftplib.html | module-ftplib.html | module-gopherlib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.4.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": "1.6", "length": 417, "url": "https://docs.python.org/1.6/lib/ftp-objects.html"} {"title": "11.1.4 Functions", "text": "node226.html | module-cgi.html | node228.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.4 Functions\nThese are useful if you want more control, or if you want to employ\nsome of the algorithms implemented in this module in other\ncircumstances.", "python_version": "1.6", "length": 270, "url": "https://docs.python.org/1.6/lib/Functions_in_cgi_module.html"} {"title": "Index", "text": "modindex.html | lib.html | about.html | Python Library Reference | contents.html\n---\n## Index\n---\n. (#letter-.) |\n= (#letter-=) |\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\nj (#letter-j) |\nk (#letter-k) |\nl (#letter-l) |\nm (#letter-m) |\nn (#letter-n) |\no (#letter-o) |\np (#letter-p) |\nq (#letter-q) |\nr (#letter-r) |\ns (#letter-s) |\nt (#letter-t) |\nu (#letter-u) |\nv (#letter-v) |\nw (#letter-w) |\nx (#letter-x) |\ny (#letter-y) |\nz (#letter-z)\n---\n## . (dot)\n---\n## =\n---\n## _ (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": "1.6", "length": 839, "url": "https://docs.python.org/1.6/lib/genindex.html"} {"title": "12.2.1 HTMLParser Objects", "text": "module-htmllib.html | module-htmllib.html | module-htmlentitydefs.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.2.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": "1.6", "length": 295, "url": "https://docs.python.org/1.6/lib/html-parser-objects.html"} {"title": "11.3.2 Example", "text": "node237.html | module-httplib.html | module-ftplib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.3.2 Example\nHere is an example session:", "python_version": "1.6", "length": 164, "url": "https://docs.python.org/1.6/lib/HTTP_Example.html"} {"title": "11.7.2 IMAP4 Example", "text": "imap4-objects.html | module-imaplib.html | module-nntplib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.7.2 IMAP4 Example\nHere is a minimal example (without error checking) that opens a\nmailbox and retrieves and prints all messages:", "python_version": "1.6", "length": 260, "url": "https://docs.python.org/1.6/lib/imap4-example.html"} {"title": "11.7.1 IMAP4 Objects", "text": "module-imaplib.html | module-imaplib.html | imap4-example.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.7.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.\nEach command returns a tuple: `( type , [ data ,\n...])` where type is usually `'OK'` or `'NO'`,\nand data is either the text from the command response, or\nmandated results from the command.\nAn IMAP4 instance has the following methods:\nThe following attributes are defined on instances of IMAP4:", "python_version": "1.6", "length": 920, "url": "https://docs.python.org/1.6/lib/imap4-objects.html"} {"title": "Python Library Reference", "text": "../index.html | front.html | Python Library Reference | contents.html | genindex.html\n---\n# Python Library Reference\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 240, "url": "https://docs.python.org/1.6/lib/index.html"} {"title": "11. Internet Protocols and Support", "text": "profile-HotProfile.html | lib.html | module-cgi.html | Python Library Reference | contents.html | genindex.html\n---\n# 11. Internet Protocols and Support\nThe modules described in this chapter implement Internet protocols and\nsupport for related technology. They are all implemented in Python.\nMost of these modules require the presence of the system-dependent\nmodule socket (module-socket.html), which is currently\nsupported on most popular platforms. Here is an overview:", "python_version": "1.6", "length": 471, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 3.23.1 Interactive Interpreter Objects", "python_version": "1.6", "length": 163, "url": "https://docs.python.org/1.6/lib/interpreter-objects.html"} {"title": "1. Introduction", "text": "contents.html | lib.html | builtin.html | Python Library Reference | contents.html | genindex.html\n---\n# 1. Introduction\nThe ``Python library'' contains several different kinds of components.\nIt contains data types that would normally be considered part of the\n``core'' of a language, such as numbers and lists. For these types,\nthe Python language core defines the form of literals and places some\nconstraints on their semantics, but does not fully define the\nsemantics. (On the other hand, the language core does define\nsyntactic properties like the spelling and priorities of operators.)\nThe library also contains built-in functions and exceptions --\nobjects that can be used by all Python code without the need of an\nimport statement. Some of these are defined by the core\nlanguage, but many are not essential for the core semantics and are\nonly described here.\nThe bulk of the library, however, consists of a collection of modules.\nThere are many ways to dissect this collection. Some modules are\nwritten in C and built in to the Python interpreter; others are\nwritten in Python and imported in source form. Some modules provide\ninterfaces that are highly specific to Python, like printing a stack\ntrace; some provide interfaces that are specific to particular\noperating systems, such as access to specific hardware; others provide\ninterfaces that are\nspecific to a particular application domain, like the World-Wide Web.\nSome modules are avaiable 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": "1.6", "length": 2900, "url": "https://docs.python.org/1.6/lib/intro.html"} {"title": "Python Library Reference", "text": "../index.html | front.html | Python Library Reference | contents.html | genindex.html\n---\n# Python Library Reference\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 240, "url": "https://docs.python.org/1.6/lib/lib.html"} {"title": "7.5.1 Lock Objects", "text": "module-threading.html | module-threading.html | rlock-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.5.1 Lock Objects\nA primitive lock is a synchronization primitive that is not owned\nby a particular thread when locked. In Python, it is currently\nthe lowest level synchronization primitive available, implemented\ndirectly by the thread (module-thread.html) extension module.\nA primitive lock is in one of two states, ``locked'' or ``unlocked''.\nIt is created in the unlocked state. It has two basic methods,\nacquire() and release(). When the state is\nunlocked, acquire() changes the state to locked and returns\nimmediately. When the state is locked, acquire() blocks\nuntil a call to release() in another thread changes it to\nunlocked, then the acquire() call resets it to locked and\nreturns. The release() method should only be called in the\nlocked state; it changes the state to unlocked and returns\nimmediately. When more than one thread is blocked in\nacquire() waiting for the state to turn to unlocked, only one\nthread proceeds when a release() call resets the state to\nunlocked; which one of the waiting threads proceeds is not defined,\nand may vary across implementations.\nAll methods are executed atomically.", "python_version": "1.6", "length": 1249, "url": "https://docs.python.org/1.6/lib/lock-objects.html"} {"title": "12.18.1 Mailbox Objects", "text": "module-mailbox.html | module-mailbox.html | module-mhlib.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.18.1 Mailbox Objects\nAll implementations of Mailbox objects have one externally visible\nmethod:", "python_version": "1.6", "length": 226, "url": "https://docs.python.org/1.6/lib/mailbox-objects.html"} {"title": "4.2.5 Match Objects", "text": "re-objects.html | module-re.html | module-regex.html | Python Library Reference | contents.html | genindex.html\n---\n## 4.2.5 Match Objects\nMatchObject instances support the following methods and attributes:", "python_version": "1.6", "length": 206, "url": "https://docs.python.org/1.6/lib/match-objects.html"} {"title": "4.2.2 Matching vs. Searching", "text": "re-syntax.html | module-re.html | Contents_of_Module_re.html | Python Library Reference | contents.html | genindex.html\n---\n## 4.2.2 Matching vs. Searching\nPython offers two different primitive operations based on regular\nexpressions: match and search. If you are accustomed to Perl's\nsemantics, the search operation is what you're looking for. See the\nsearch() function and corresponding method of compiled\nregular expression objects.\nNote that match may differ from search using a regular expression\nbeginning with \"^\": \"^\" matches only at the\nstart of the string, or in MULTILINE mode also immediately\nfollowing a newline. The ``match'' operation succeeds only if the\npattern matches at the start of the string regardless of mode, or at\nthe starting position given by the optional pos argument\nregardless of whether a newline precedes it.\n```text\n\nre.compile(\"a\").match(\"ba\", 1) # succeeds\nre.compile(\"^a\").search(\"ba\", 1) # fails; 'a' not at start\nre.compile(\"^a\").search(\"\\na\", 1) # fails; 'a' not at start\nre.compile(\"^a\", re.M).search(\"\\na\", 1) # succeeds\nre.compile(\"^a\", re.M).search(\"ba\", 1) # fails; no preceding \\n\n```", "python_version": "1.6", "length": 1130, "url": "https://docs.python.org/1.6/lib/matching-searching.html"} {"title": "12.6.1 Message Objects", "text": "module-rfc822.html | module-rfc822.html | addresslist-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.6.1 Message Objects\nA Message instance has the following methods:\nMessage instances also support a read-only 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 .has_key(name)`, `m .keys()`,\n`m .values()` and `m .items()` act as expected\n(and consistently).\nFinally, Message instances have two public instance variables:", "python_version": "1.6", "length": 549, "url": "https://docs.python.org/1.6/lib/message-objects.html"} {"title": "12.19.2 Folder Objects", "text": "mh-objects.html | module-mhlib.html | mh-message-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.19.2 Folder Objects\nFolder instances represent open folders and have the following\nmethods:", "python_version": "1.6", "length": 222, "url": "https://docs.python.org/1.6/lib/mh-folder-objects.html"} {"title": "12.19.3 Message Objects", "text": "mh-folder-objects.html | module-mhlib.html | module-mimify.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.19.3 Message Objects\nThe Message class adds one method to those of\nmimetools.Message:", "python_version": "1.6", "length": 218, "url": "https://docs.python.org/1.6/lib/mh-message-objects.html"} {"title": "12.19.1 MH Objects", "text": "module-mhlib.html | module-mhlib.html | mh-folder-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.19.1 MH Objects\nMH instances have the following methods:", "python_version": "1.6", "length": 188, "url": "https://docs.python.org/1.6/lib/mh-objects.html"} {"title": "12.7.1 Additional Methods of Message objects", "text": "module-mimetools.html | module-mimetools.html | module-MimeWriter.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.7.1 Additional Methods of Message objects\nThe Message class defines the following methods in\naddition to the rfc822.Message methods:", "python_version": "1.6", "length": 272, "url": "https://docs.python.org/1.6/lib/mimetools.Message_Methods.html"} {"title": "12.8.1 MimeWriter Objects", "text": "module-MimeWriter.html | module-MimeWriter.html | module-multifile.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.8.1 MimeWriter Objects\nMimeWriter instances have the following methods:", "python_version": "1.6", "length": 212, "url": "https://docs.python.org/1.6/lib/MimeWriter-objects.html"} {"title": "5. Miscellaneous Services", "text": "module-codecs.html | lib.html | module-math.html | Python Library Reference | contents.html | genindex.html\n---\n# 5. Miscellaneous Services\nThe modules described in this chapter provide miscellaneous services\nthat are available in all Python versions. Here's an overview:", "python_version": "1.6", "length": 271, "url": "https://docs.python.org/1.6/lib/misc.html"} {"title": "14. Multimedia Services", "text": "module-Bastion.html | lib.html | module-audioop.html | Python Library Reference | contents.html | genindex.html\n---\n# 14. Multimedia Services\nThe modules described in this chapter implement various algorithms or\ninterfaces that are mainly useful for multimedia applications. They\nare available at the discretion of the installation. Here's an overview:", "python_version": "1.6", "length": 352, "url": "https://docs.python.org/1.6/lib/mmedia.html"} {"title": "Module Index", "text": "node367.html | lib.html | genindex.html | Python Library Reference | contents.html | genindex.html\n---\n## Module Index\nSome module names are followed by an annotation indicating what\nplatform they are available on.", "python_version": "1.6", "length": 214, "url": "https://docs.python.org/1.6/lib/modindex.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 | genindex.html\n---\n# 14.3 aifc --\nRead and write AIFF and AIFC files\nThis module provides support for reading and writing AIFF and AIFF-C\nfiles. AIFF is Audio Interchange File Format, a format for storing\ndigital audio samples in a file. AIFF-C is a newer version of the\nformat that includes the ability to compress the audio data.\nCaveat: Some operations may only work under IRIX; these will\nraise ImportError when attempting to import the\ncl module, which is only available on IRIX.\nAudio files have a number of parameters that describe the audio data.\nThe sampling rate or frame rate is the number of times per second the\nsound is sampled. The number of channels indicate if the audio is\nmono, stereo, or quadro. Each frame consists of one sample per\nchannel. The sample size is the size in bytes of each sample. Thus a\nframe consists of nchannels*samplesize bytes, and a\nsecond's worth of audio consists of\nnchannels*samplesize*framerate bytes.\nFor example, CD quality audio has a sample size of two bytes (16\nbits), uses two channels (stereo) and has a frame rate of 44,100\nframes/second. This gives a frame size of 4 bytes (2*2), and a\nsecond's worth occupies 2*2*44100 bytes, i.e. 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": "1.6", "length": 1814, "url": "https://docs.python.org/1.6/lib/module-aifc.html"} {"title": "16.2 AL -- Constants used with the al module", "text": "al-port-objects.html | sgi.html | module-cd.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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": "1.6", "length": 480, "url": "https://docs.python.org/1.6/lib/module-al-constants.html"} {"title": "16.1 al -- Audio functions on the SGI", "text": "sgi.html | sgi.html | al-config-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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: the 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": "1.6", "length": 1257, "url": "https://docs.python.org/1.6/lib/module-al.html"} {"title": "7.7 anydbm -- Generic access to DBM-style databases", "text": "QueueObjects.html | someos.html | module-dumbdbm.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.7 anydbm --\nGeneric access to DBM-style databases\nanydbm is a generic interface to variants of the DBM\ndatabase -- dbhash (module-dbhash.html) (requires\nbsddb (module-bsddb.html)),\ngdbm (module-gdbm.html), or\ndbm (module-dbm.html). If none of these modules is\ninstalled, the slow-but-simple implementation in module\ndumbdbm (module-dumbdbm.html) will be used.\nThe object returned by open() supports most of the same\nfunctionality as dictionaries; keys and their corresponding values can\nbe stored, retrieved, and deleted, and the has_key() and\nkeys() methods are available. Keys and values must always be\nstrings.\nSee Also:", "python_version": "1.6", "length": 744, "url": "https://docs.python.org/1.6/lib/module-anydbm.html"} {"title": "5.6 array -- Efficient arrays of numeric values", "text": "bisect-example.html | misc.html | module-ConfigParser.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.6 array --\nEfficient arrays of numeric values\nThis module defines a new object type which can efficiently represent\nan array of basic values: characters, integers, floating point\nnumbers. Arrays are sequence types and behave very much\nlike lists, except that the type of objects stored in them is\nconstrained. The type is specified at object creation time by using a\ntype code, which is a single character. The following type\ncodes are defined:\nThe actual representation of values is determined by the machine\narchitecture (strictly speaking, by the C implementation). The actual\nsize can be accessed through the itemsize attribute. The values\nstored for `'L'` and `'I'` items will be represented as\nPython long integers when retrieved, because Python's plain integer\ntype cannot represent the full range of C's unsigned (long) integers.\nThe module defines the following function and type object:\nArray objects support the following data items and methods:\nWhen an array object is printed or converted to a string, it is\nrepresented as `array( typecode , initializer )`. The\ninitializer is omitted if the array is empty, otherwise it is a\nstring if the typecode is `'c'`, otherwise it is a list of\nnumbers. The string is guaranteed to be able to be converted back to\nan array with the same type and value using reverse quotes\n(````), so long as the array() function has been\nimported using \"from array import array\". Examples:\n```text\n\narray('l')\narray('c', 'hello world')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.14])\n```", "python_version": "1.6", "length": 1659, "url": "https://docs.python.org/1.6/lib/module-array.html"} {"title": "11.16 asyncore -- Asynchronous socket handler", "text": "module-CGIHTTPServer.html | internet.html | asyncore-example.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.16 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 CPU bound, then pre-emptive scheduled threads are probably what\nyou really need. Network servers are rarely CPU-bound, however.\nIf your operating system supports the select() system call\nin its I/O library (and nearly all do), then you can use it to juggle\nmultiple communication channels at once; doing other work while your\nI/O is taking place in the ``background.'' Although this strategy can\nseem strange and complex, especially at first, it is in many ways\neasier to understand and control than multi-threaded programming.\nThe module documented here solves many of the difficult problems for\nyou, making the task of building sophisticated high-performance\nnetwork servers and clients a snap.\nThis set of user-level events is larger than the basics. The\nfull set of methods that can be overridden in your subclass are:\nIn addition, there are the basic methods needed to construct and\nmanipulate ``channels,'' which are what we will call the socket\nconnections in this context. Note that most of these are nearly\nidentical to their socket partners.", "python_version": "1.6", "length": 1748, "url": "https://docs.python.org/1.6/lib/module-asyncore.html"} {"title": "14.1 audioop -- Manipulate raw audio data", "text": "mmedia.html | mmedia.html | module-imageop.html | Python Library Reference | contents.html | genindex.html\n---\n# 14.1 audioop --\nManipulate raw audio data\nThe audioop module contains some useful operations on sound\nfragments. It operates on sound fragments consisting of signed\ninteger samples 8, 16 or 32 bits wide, stored in Python strings. This\nis the same format as used by the al (module-al.html) and sunaudiodev (module-sunaudiodev.html)\nmodules. All scalar items are integers, unless specified otherwise.\nThis module provides support for u-LAW and Intel/DVI ADPCM encodings.\nA few of the more complicated operations only take 16-bit samples,\notherwise the sample size (in bytes) is always a parameter of the\noperation.\nThe module defines the following variables and functions:\nNote that operations such as mul() or max() make\nno distinction between mono and stereo fragments, i.e. all samples\nare treated equal. If this is a problem the stereo fragment should be\nsplit into two mono fragments first and recombined later. Here is an\nexample of how to do that:\n```text\n\ndef mul_stereo(sample, width, lfactor, rfactor):\nlsample = audioop.tomono(sample, width, 1, 0)\nrsample = audioop.tomono(sample, width, 0, 1)\nlsample = audioop.mul(sample, width, lfactor)\nrsample = audioop.mul(sample, width, rfactor)\nlsample = audioop.tostereo(lsample, width, 1, 0)\nrsample = audioop.tostereo(rsample, width, 0, 1)\nreturn audioop.add(lsample, rsample, width)\n```\nIf you use the ADPCM coder to build network packets and you want your\nprotocol to be stateless (i.e. to be able to tolerate packet loss)\nyou should not only transmit the data but also the state. Note that\nyou should send the initial state (the one you passed to\nlin2adpcm()) along to the decoder, not the final state (as\nreturned by the coder). If you want to use struct.struct()\nto store the state in binary you can code the first element (the\npredicted value) in 16 bits and the second (the delta index) in 8.\nThe ADPCM coders have never been tried against other ADPCM coders,\nonly against themselves. It could well be that I misinterpreted the\nstandards in which case they will not be interoperable with the\nrespective standards.\nThe find*() routines might look a bit funny at first sight.\nThey are primarily meant to do echo cancellation. A reasonably\nfast way to do this is to pick the most energetic piece of the output\nsample, locate that in the input sample and subtract the whole output\nsample from the input sample:", "python_version": "1.6", "length": 2479, "url": "https://docs.python.org/1.6/lib/module-audioop.html"} {"title": "12.16 base64 -- Encode and decode MIME base64 data", "text": "module-mimetypes.html | netdata.html | module-quopri.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.16 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 emailed or posted. The\nencoding scheme is defined in RFC 1521 (http://www.ietf.org/rfc/rfc1521.txt) (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": "1.6", "length": 814, "url": "https://docs.python.org/1.6/lib/module-base64.html"} {"title": "11.13 BaseHTTPServer -- Basic HTTP server.", "text": "module-SocketServer.html | internet.html | module-SimpleHTTPServer.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.13 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\nSimpleHTTPServer and\nCGIHTTPServer (module-CGIHTTPServer.html) modules.\nThe first class, HTTPServer, is a\nSocketServer.TCPServer subclass. It creates and listens at the\nweb 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": "1.6", "length": 1035, "url": "https://docs.python.org/1.6/lib/module-BaseHTTPServer.html"} {"title": "13.2 Bastion -- Restricting access to objects", "text": "node309.html | restricted.html | mmedia.html | Python Library Reference | contents.html | genindex.html\n---\n# 13.2 Bastion --\nRestricting access to objects\nAccording to the dictionary, a bastion is ``a fortified area or\nposition'', or ``something that is considered a stronghold.'' It's a\nsuitable name for this module, which provides a way to forbid access\nto certain attributes of an object. It must always be used with the\nrexec (module-rexec.html) module, in order to allow restricted-mode programs\naccess to certain safe attributes of an object, while denying access\nto other, unsafe attributes.", "python_version": "1.6", "length": 600, "url": "https://docs.python.org/1.6/lib/module-Bastion.html"} {"title": "12.12 binascii -- Convert between binary and ASCII", "text": "module-uu.html | netdata.html | module-xdrlib.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.12 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-manipuation of large amounts of data is slow in\nPython.\nThe binascii module defines the following functions:", "python_version": "1.6", "length": 579, "url": "https://docs.python.org/1.6/lib/module-binascii.html"} {"title": "12.10 binhex -- Encode and decode binhex4 files", "text": "multifile-example.html | netdata.html | binhex-notes.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.10 binhex --\nEncode and decode binhex4 files\nThis module encodes and decodes files in binhex4 format, a format\nallowing representation of Macintosh files in ASCII. On the Macintosh,\nboth forks of a file and the finder information are encoded (or\ndecoded), on other platforms only the data fork is handled.\nThe binhex module defines the following functions:\nSee Also:", "python_version": "1.6", "length": 492, "url": "https://docs.python.org/1.6/lib/module-binhex.html"} {"title": "5.5 bisect -- Array bisection algorithm", "text": "module-whrandom.html | misc.html | bisect-example.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.5 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 (i.e., the boundary conditions are already right!).\nThe following functions are provided:", "python_version": "1.6", "length": 652, "url": "https://docs.python.org/1.6/lib/module-bisect.html"} {"title": "7.11 bsddb -- Interface to Berkeley DB library", "text": "module-whichdb.html | someos.html | bsddb-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.11 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.\nThe bsddb module is only available on Unix systems, so it\nis not built by default in the standard Python distribution. Also,\nthere are two incompatible versions of the underlying library.\nVersion 1.85 is widely available, but has some known bugs. Version 2\nis not quite as widely used, but does offer some improvements. The\nbsddb module uses the 1.85 interface. Users wishing to use\nversion 2 of the Berkeley DB library will have to modify the source\nfor the module to include db_185.h instead of\ndb.h (db_185.h contains the version 1.85 compatibility\ninterface).\nThe bsddb module defines the following functions that create\nobjects that access the appropriate type of Berkeley DB file. The\nfirst two arguments of each function are the same. For ease of\nportability, only the first two arguments should be used in most\ninstances.\nSee Also:", "python_version": "1.6", "length": 1438, "url": "https://docs.python.org/1.6/lib/module-bsddb.html"} {"title": "3.33 __builtin__ -- Built-in functions", "text": "module-user.html | python.html | module-main.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.33 __builtin__ --\nBuilt-in functions", "python_version": "1.6", "length": 153, "url": "https://docs.python.org/1.6/lib/module-builtin.html"} {"title": "5.9 calendar -- General calendar-related functions", "text": "module-fileinput.html | misc.html | module-cmd.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.9 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.", "python_version": "1.6", "length": 303, "url": "https://docs.python.org/1.6/lib/module-calendar.html"} {"title": "16.3 cd -- CD-ROM access on SGI systems", "text": "module-al-constants.html | sgi.html | player-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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": "1.6", "length": 1583, "url": "https://docs.python.org/1.6/lib/module-cd.html"} {"title": "11.1 cgi -- Common Gateway Interface support.", "text": "internet.html | internet.html | cgi-intro.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.1 cgi --\nCommon Gateway Interface support.\nSupport module for CGI (Common Gateway Interface) scripts.\nThis module defines a number of utilities for use by CGI scripts\nwritten in Python.", "python_version": "1.6", "length": 300, "url": "https://docs.python.org/1.6/lib/module-cgi.html"} {"title": "11.15 CGIHTTPServer -- A Do-Something Request Handler", "text": "module-SimpleHTTPServer.html | internet.html | module-asyncore.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.15 CGIHTTPServer --\nA Do-Something Request Handler\nAvailability: Unix.\nThe CGIHTTPServer module defines a request-handler class,\ninterface compatible with\nBaseHTTPServer.BaseHTTPRequestHandler and inherits behaviour\nfrom SimpleHTTPServer.SimpleHTTPRequestHandler but can also\nrun CGI scripts.\nNote: This module is Unix dependent since it creates the\nCGI process using os.fork() and os.exec().\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": "1.6", "length": 909, "url": "https://docs.python.org/1.6/lib/module-CGIHTTPServer.html"} {"title": "14.6 chunk -- Read IFF chunked data", "text": "Wave-write-objects.html | mmedia.html | module-colorsys.html | Python Library Reference | contents.html | genindex.html\n---\n# 14.6 chunk --\nRead IFF chunked data\nThis module provides an interface for reading files that use EA IFF 85\nchunks.14.1 (#foot33585) This format is used\nin at least the Audio Interchange File Format\n(AIFF/AIFF-C) and the Real Media 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": "1.6", "length": 1188, "url": "https://docs.python.org/1.6/lib/module-chunk.html"} {"title": "5.2 cmath -- Mathematical functions for complex numbers", "text": "module-math.html | misc.html | module-random.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.2 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:", "python_version": "1.6", "length": 340, "url": "https://docs.python.org/1.6/lib/module-cmath.html"} {"title": "5.10 cmd -- Build line-oriented command interpreters.", "text": "module-calendar.html | misc.html | Cmd-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.10 cmd --\nBuild 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": "1.6", "length": 402, "url": "https://docs.python.org/1.6/lib/module-cmd.html"} {"title": "3.23 code -- Interpreter base classes", "text": "pyclbr-class-objects.html | python.html | interpreter-objects.html | Python Library Reference | contents.html | genindex.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": "1.6", "length": 393, "url": "https://docs.python.org/1.6/lib/module-code.html"} {"title": "4.9 codecs -- Codec registry and base classes", "text": "module-cStringIO.html | strings.html | misc.html | Python Library Reference | contents.html | genindex.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 lookup process.\nIt defines the following functions:\nTo simplify working with encoded files or stream, the module\nalso defines these utility functions:\n...XXX document codec base classes...\nThe module also provides the following constants which are useful\nfor reading and writing to platform dependent files:", "python_version": "1.6", "length": 633, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 3.24 codeop --\nCompile Python code\nThe codeop module provides a function to compile Python code\nwith hints on whether it is certainly complete, possibly complete or\ndefinitely incomplete. This is used by the code (module-code.html) module\nand should not normally be used directly.\nThe codeop module defines the following function:", "python_version": "1.6", "length": 451, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 14.7 colorsys --\nConversions between color systems\nThe colorsys module defines bidirectional conversions of\ncolor values between colors expressed in the RGB (Red Green Blue)\ncolor space used in computer monitors and three other coordinate\nsystems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation\nValue). Coordinates in all of these color spaces are floating point\nvalues. In the YIQ space, the Y coordinate is between 0 and 1, but\nthe I and Q coordinates can be positive or negative. In all other\nspaces, the coordinates are all between 0 and 1.\nMore information about color spaces can be found at\nhttp://www.inforamp.net/%7epoynton/ColorFAQ.html.\nThe colorsys module defines the following functions:\nExample:", "python_version": "1.6", "length": 839, "url": "https://docs.python.org/1.6/lib/module-colorsys.html"} {"title": "8.19 commands -- Utilities for running commands", "text": "popen3-objects.html | unix.html | module-pdb.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.19 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": "1.6", "length": 818, "url": "https://docs.python.org/1.6/lib/module-commands.html"} {"title": "3.28 compileall -- Byte-compile Python libraries", "text": "module-pycompile.html | python.html | module-dis.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.28 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": "1.6", "length": 567, "url": "https://docs.python.org/1.6/lib/module-compileall.html"} {"title": "5.7 ConfigParser -- Configuration file parser", "text": "module-array.html | misc.html | ConfigParser-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.7 ConfigParser --\nConfiguration file parser\nThis module defines the class ConfigParser.\nThe ConfigParser class implements a basic configuration file\nparser language which provides a structure similar to what you would\nfind on Microsoft Windows INI files. You can use this to write Python\nprograms which can be customized by end users easily.\nThe configuration file consists of sections, lead by a\n\"[section]\" header and followed by \"name: value\" entries,\nwith continuations in the style of RFC 822 (http://www.ietf.org/rfc/rfc0822.txt); \"name=value\" is\nalso accepted. Note that leading whitespace is removed from values.\nThe optional values can contain format strings which refer to other\nvalues in the same section, or values in a special\n`DEFAULT` section. Additional defaults can be provided upon\ninitialization and retrieval. Lines beginning with \"#\" or\n\";\" are ignored and may be used to provide comments.\nFor example:\n```text\n\nfoodir: %(dir)s/whatever\ndir=frob\n```\nwould resolve the \"%(dir)s\" to the value of\n\"dir\" (\"frob\" in this case). All reference expansions are\ndone on demand.\nDefault values can be specified by passing them into the\nConfigParser constructor as a dictionary. Additional defaults\nmay be passed into the get() method which will override all\nothers.\nSee Also:", "python_version": "1.6", "length": 1410, "url": "https://docs.python.org/1.6/lib/module-ConfigParser.html"} {"title": "3.13 copy -- Shallow and deep copy operations", "text": "module-shelve.html | python.html | module-marshal.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.13 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": "1.6", "length": 2486, "url": "https://docs.python.org/1.6/lib/module-copy.html"} {"title": "3.11 copy_reg -- Register pickle support functions", "text": "module-cPickle.html | python.html | module-shelve.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.11 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": "1.6", "length": 516, "url": "https://docs.python.org/1.6/lib/module-copyreg.html"} {"title": "3.10 cPickle -- Alternate implementation of pickle", "text": "pickle-example.html | python.html | module-copyreg.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.10 cPickle --\nAlternate implementation of pickle\nThe cPickle module provides a similar interface and identical\nfunctionality as the pickle (module-pickle.html) module,\nbut can be up to 1000 times faster since it is implemented in C. The\nonly other important difference to note is that Pickler()\nand Unpickler() are functions and not classes, and so\ncannot be subclassed. This should not be an issue in most cases.\nThe format of the pickle data is identical to that produced using the\npickle (module-pickle.html) module, so it is possible to use pickle (module-pickle.html) and\ncPickle interchangably with existing pickles.", "python_version": "1.6", "length": 745, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.4 crypt --\nFunction to check Unix passwords\nAvailability: Unix.\nThis module implements an interface to the\ncrypt(3) routine, which is a one-way hash\nfunction based upon a modified 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": "1.6", "length": 536, "url": "https://docs.python.org/1.6/lib/module-crypt.html"} {"title": "4.8 cStringIO -- Faster version of StringIO", "text": "module-StringIO.html | strings.html | module-codecs.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.8 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.\nThe following data objects are provided as well:", "python_version": "1.6", "length": 662, "url": "https://docs.python.org/1.6/lib/module-cStringIO.html"} {"title": "6.11 curses -- Terminal independant console handling", "text": "module-getpass.html | allos.html | curses-functions.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.11 curses --\nTerminal independant console handling\nThe curses module provides an interface to the curses Unix\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. The\nextension module has not been tested with all available versions of\ncurses.\nSee Also:\nTutorial material on using curses with Python is available\non the Python Web site as Andrew Kuchling's\nCurses\nProgramming with Python (http://www.python.org/doc/howto/curses/curses.html), at\nhttp://www.python.org/doc/howto/curses/curses.html.", "python_version": "1.6", "length": 770, "url": "https://docs.python.org/1.6/lib/module-curses.html"} {"title": "7.9 dbhash -- DBM-style interface to the BSD database library", "text": "module-dumbdbm.html | someos.html | dbhash-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.9 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": "1.6", "length": 534, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.6 dbm --\nSimple ``database'' interface\nAvailability: Unix.\nThe dbm module provides an interface to the Unix\n`(n)dbm` library. Dbm objects behave like mappings\n(dictionaries), except that keys and values are always strings.\nPrinting a dbm object doesn't print the keys and values, and the\nitems() and values() methods are not supported.\nSee also the gdbm (module-gdbm.html) module, which\nprovides a similar interface using the GNU GDBM library.\nThe module defines the following constant and functions:", "python_version": "1.6", "length": 614, "url": "https://docs.python.org/1.6/lib/module-dbm.html"} {"title": "16.9 DEVICE -- Constants used with the gl module", "text": "module-gl.html | sgi.html | module-gl-constants.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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": "1.6", "length": 368, "url": "https://docs.python.org/1.6/lib/module-DEVICE.html"} {"title": "6.3 dircache -- Cached directory listings", "text": "module-os.path.html | allos.html | module-stat.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.3 dircache --\nCached directory listings\nThe dircache module defines a function for reading directory listing\nusing a cache, and cache invalidation using the mtime of the directory.\nAdditionally, it defines a function to annotate directories by appending\na slash.\nThe dircache module defines the following functions:", "python_version": "1.6", "length": 434, "url": "https://docs.python.org/1.6/lib/module-dircache.html"} {"title": "3.29 dis -- Disassembler.", "text": "module-compileall.html | python.html | bytecodes.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.29 dis --\nDisassembler.\nThe dis module supports the analysis of Python byte code by\ndisassembling it. Since there is no Python assembler, this module\ndefines the Python assembly language. The Python byte code which\nthis module takes as an input is defined in the file\nInclude/opcode.h and used by the compiler and the interpreter.\nExample: Given the function myfunc:\n```text\n\ndef myfunc(alist):\nreturn len(alist)\n```\nthe following command can be used to get the disassembly of\nmyfunc():\n```text\n\n>>> dis.dis(myfunc)\n0 SET_LINENO 1\n\n3 SET_LINENO 2\n6 LOAD_GLOBAL 0 (len)\n9 LOAD_FAST 0 (alist)\n12 CALL_FUNCTION 1\n15 RETURN_VALUE\n16 LOAD_CONST 0 (None)\n19 RETURN_VALUE\n```\nThe dis module defines the following functions:", "python_version": "1.6", "length": 837, "url": "https://docs.python.org/1.6/lib/module-dis.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 | genindex.html\n---\n# 8.5 dl --\nCall C functions in shared objects\nAvailability: Unix.\nThe dl module defines an interface to the\ndlopen() function, which is the most common interface on\nUnix platforms for handling dynamically linked libraries. It allows\nthe program to call arbitary functions in such a library.\nNote: This module will not work unless\n```text\n\nsizeof(int) == sizeof(long) == sizeof(char *)\n```\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": "1.6", "length": 976, "url": "https://docs.python.org/1.6/lib/module-dl.html"} {"title": "7.8 dumbdbm -- Portable DBM implementation", "text": "module-anydbm.html | someos.html | module-dbhash.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.8 dumbdbm --\nPortable DBM implementation\nA simple and slow database implemented entirely in Python. This\nshould only be used when no other DBM-style database is available.", "python_version": "1.6", "length": 292, "url": "https://docs.python.org/1.6/lib/module-dumbdbm.html"} {"title": "6.14 errno -- Standard errno system symbols.", "text": "module-tempfile.html | allos.html | module-glob.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.14 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. Symbols available can\ninclude:", "python_version": "1.6", "length": 597, "url": "https://docs.python.org/1.6/lib/module-errno.html"} {"title": "2.2 Built-in Exceptions", "text": "specialattrs.html | builtin.html | built-in-funcs.html | Python Library Reference | contents.html | genindex.html\n---\n# 2.2 Built-in Exceptions\nExceptions can be class objects or string objects. While\ntraditionally, most exceptions have been string objects, in Python\n1.5, all standard exceptions have been converted to class objects,\nand users are encouraged to do the same. The source code for those\nexceptions is present in the standard library module\nexceptions; this module never needs to be imported explicitly.\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 following exceptions are only used as base classes for other\nexceptions.\nThe following exceptions are the exceptions that are actually raised.\nThey are class objects, except when the -X option is used\nto revert back to string-based standard exceptions.", "python_version": "1.6", "length": 2565, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.12 fcntl --\nThe fcntl() and ioctl() system calls\nAvailability: Unix.\nThis module performs file control and I/O control on file descriptors.\nIt is an interface to the fcntl() and ioctl()\nUnix routines. File descriptors can be obtained with the\nfileno() method of a file or socket object.\nThe module defines the following functions:\nIf the library modules FCNTL or\nIOCTL are missing, you can find the\nopcodes in the C include files `` and\n``. You can create the modules yourself with the\nh2py script, found in the Tools/scripts/ directory.\nExamples (all on a SVR4 compliant system):\n```text\n\nimport struct, fcntl, FCNTL\n\nfile = open(...)\nrv = fcntl(file.fileno(), FCNTL.O_NDELAY, 1)\n\nlockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0)\nrv = fcntl.fcntl(file.fileno(), FCNTL.F_SETLKW, lockdata)\n```", "python_version": "1.6", "length": 947, "url": "https://docs.python.org/1.6/lib/module-fcntl.html"} {"title": "6.7 filecmp -- File Comparisons", "text": "module-statvfs.html | allos.html | module-time.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.7 filecmp --\nFile Comparisons\nThe filecmp module defines a function to compare files, taking all\nsort of short-cuts to make it a highly efficient operation.\nThe filecmp module defines the following function:\nExample:", "python_version": "1.6", "length": 335, "url": "https://docs.python.org/1.6/lib/module-filecmp.html"} {"title": "5.8 fileinput -- Iterate over lines from multiple input streams", "text": "ConfigParser-objects.html | misc.html | module-calendar.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.8 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.\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": "1.6", "length": 2194, "url": "https://docs.python.org/1.6/lib/module-fileinput.html"} {"title": "16.5 FL -- Constants used with the fl module", "text": "forms-objects.html | sgi.html | module-flp.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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": "1.6", "length": 519, "url": "https://docs.python.org/1.6/lib/module-fl-constants.html"} {"title": "16.4 fl -- FORMS library interface for GUI applications", "text": "cd-parser-objects.html | sgi.html | FL_Functions.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.4 fl --\nFORMS library interface for GUI applications\nAvailability: IRIX.\nThis module provides an interface to the FORMS Library by 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": "1.6", "length": 1773, "url": "https://docs.python.org/1.6/lib/module-fl.html"} {"title": "16.6 flp -- Functions for loading stored FORMS designs", "text": "module-fl-constants.html | sgi.html | module-fm.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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": "1.6", "length": 464, "url": "https://docs.python.org/1.6/lib/module-flp.html"} {"title": "16.7 fm -- Font Manager interface", "text": "module-flp.html | sgi.html | module-gl.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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": "1.6", "length": 714, "url": "https://docs.python.org/1.6/lib/module-fm.html"} {"title": "6.16 fnmatch -- Unix filename pattern matching", "text": "module-glob.html | allos.html | module-shutil.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.16 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": "1.6", "length": 714, "url": "https://docs.python.org/1.6/lib/module-fnmatch.html"} {"title": "12.5 formatter -- Generic output formatting", "text": "xml-namespace.html | netdata.html | formatter-interface.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.5 formatter --\nGeneric output formatting\nThis module supports two interface definitions, each with mulitple\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": "1.6", "length": 1422, "url": "https://docs.python.org/1.6/lib/module-formatter.html"} {"title": "4.6 fpformat -- Floating point conversions", "text": "module-struct.html | strings.html | module-StringIO.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.6 fpformat --\nFloating point conversions\nThe fpformat module defines functions for dealing with\nfloating point numbers representations in 100% pure\nPython. Note: This 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": "1.6", "length": 462, "url": "https://docs.python.org/1.6/lib/module-fpformat.html"} {"title": "11.4 ftplib -- FTP protocol client", "text": "HTTP_Example.html | internet.html | ftp-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.4 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.ietf.org/rfc/rfc0959.txt).\nHere's a sample session using the ftplib module:\n```text\n\n>>> from ftplib import FTP\n>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port\n>>> ftp.login() # user anonymous, passwd user@hostname\n>>> ftp.retrlines('LIST') # list directory contents\ntotal 24418\ndrwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .\ndr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..\n-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX\n.\n.\n.\n>>> ftp.retrbinary('RETR README', open('README', 'wb').write)\n'226 Transfer complete.'\n>>> ftp.quit()\n```\nThe module defines the following items:\nSee Also:\nThe file Tools/scripts/ftpmirror.py\nin 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": "1.6", "length": 1398, "url": "https://docs.python.org/1.6/lib/module-ftplib.html"} {"title": "8.7 gdbm -- GNU's reinterpretation of dbm", "text": "module-dbm.html | unix.html | module-termios.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.7 gdbm --\nGNU's reinterpretation of dbm\nAvailability: Unix.\nThis module is quite similar to the dbm (module-dbm.html)\nmodule, 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": "1.6", "length": 810, "url": "https://docs.python.org/1.6/lib/module-gdbm.html"} {"title": "6.12 getopt -- Parser for command line options.", "text": "curses-window-objects.html | allos.html | module-tempfile.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.12 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, string\n>>> args = string.split('-a -b -cfoo -d bar a1 a2')\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>>>\n```\nUsing long option names is equally easy:", "python_version": "1.6", "length": 931, "url": "https://docs.python.org/1.6/lib/module-getopt.html"} {"title": "6.10 getpass -- Portable password input", "text": "scheduler-objects.html | allos.html | module-curses.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.10 getpass\n-- Portable password input\nThe getpass module provides two functions:", "python_version": "1.6", "length": 204, "url": "https://docs.python.org/1.6/lib/module-getpass.html"} {"title": "16.10 GL -- Constants used with the gl module", "text": "module-DEVICE.html | sgi.html | module-imgfile.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.10 GL --\nConstants used with the gl module\nAvailability: IRIX.", "python_version": "1.6", "length": 182, "url": "https://docs.python.org/1.6/lib/module-gl-constants.html"} {"title": "16.8 gl -- Graphics Library interface", "text": "module-fm.html | sgi.html | module-DEVICE.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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 interpreter to dump\ncore.\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!')`and\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:\nAn interface to OpenGL is also available; see\ninformation about David Ascher's\nPyOpenGL online at\nhttp://starship.python.net/crew/da/PyOpenGL/. This may\nbe a better option if support for SGI hardware from before about\n1996 is not required.", "python_version": "1.6", "length": 2608, "url": "https://docs.python.org/1.6/lib/module-gl.html"} {"title": "6.15 glob -- Unix style pathname pattern expansion", "text": "module-errno.html | allos.html | module-fnmatch.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.15 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": "1.6", "length": 971, "url": "https://docs.python.org/1.6/lib/module-glob.html"} {"title": "11.5 gopherlib -- Gopher protocol client", "text": "ftp-objects.html | internet.html | module-poplib.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.5 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": "1.6", "length": 390, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.3 grp --\nThe group database\nAvailability: Unix.\nThis module provides access to the Unix group database.\nIt is available on all Unix versions.\nGroup database entries are reported as 4-tuples containing the\nfollowing items from the group database (see ``), in order:\nThe gid is an integer, name and password are strings, and the member\nlist is a list of strings.\n(Note that most users are not explicitly listed as members of the\ngroup they are in according to the password database.)\nKeyError is raised if the entry asked for cannot be found.\nIt defines the following items:", "python_version": "1.6", "length": 694, "url": "https://docs.python.org/1.6/lib/module-grp.html"} {"title": "7.13 gzip -- Support for gzip files", "text": "module-zlib.html | someos.html | node175.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.13 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": "1.6", "length": 663, "url": "https://docs.python.org/1.6/lib/module-gzip.html"} {"title": "12.3 htmlentitydefs -- Definitions of HTML general entities", "text": "html-parser-objects.html | netdata.html | module-xmllib.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.3 htmlentitydefs --\nDefinitions of HTML general entities\nThis module defines a single dictionary, `entitydefs`, which is\nused by the htmllib (module-htmllib.html) module to provide the\nentitydefs member of the HTMLParser class. The\ndefinition provided here contains all the entities defined by HTML 2.0\nthat can be handled using simple textual substitution in the Latin-1\ncharacter set (ISO-8859-1).", "python_version": "1.6", "length": 528, "url": "https://docs.python.org/1.6/lib/module-htmlentitydefs.html"} {"title": "12.2 htmllib -- A parser for HTML documents", "text": "module-sgmllib.html | netdata.html | html-parser-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.2 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.ietf.org/rfc/rfc1866.txt). 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 `

`... `

`, 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": "1.6", "length": 2348, "url": "https://docs.python.org/1.6/lib/module-htmllib.html"} {"title": "11.3 httplib -- HTTP protocol client", "text": "Urllib_Examples.html | internet.html | node237.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.3 httplib --\nHTTP protocol client\nThis module defines a class which implements the client side of the\nHTTP protocol. It is normally not used directly -- the module\nurllib (module-urllib.html) uses it to handle URLs that\nuse HTTP.\nThe module defines one class, HTTP:", "python_version": "1.6", "length": 385, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 14.2 imageop --\nManipulate raw image data\nThe imageop module contains some useful operations on images.\nIt operates on images consisting of 8 or 32 bit pixels stored in\nPython strings. This is the same format as used by\ngl.lrectwrite() and the imgfile (module-imgfile.html) module.\nThe module defines the following variables and functions:", "python_version": "1.6", "length": 457, "url": "https://docs.python.org/1.6/lib/module-imageop.html"} {"title": "11.7 imaplib -- IMAP4 protocol client", "text": "pop3-example.html | internet.html | imap4-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.7 imaplib --\nIMAP4 protocol client\nThis module defines a class, IMAP4, which encapsulates a\nconnection to an IMAP4 server and implements the IMAP4rev1 client\nprotocol as defined in RFC 2060 (http://www.ietf.org/rfc/rfc2060.txt). It is backward compatible with\nIMAP4 (RFC 1730 (http://www.ietf.org/rfc/rfc1730.txt)) servers, but note that the \"STATUS\" command is\nnot supported in IMAP4.\nA single class is provided by the imaplib module:\nTwo exceptions are defined as attributes of the IMAP4 class:\nThe following utility functions are defined:\nNote that IMAP4 message numbers change as the mailbox changes, so it\nis highly advisable to use UIDs 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": "1.6", "length": 1108, "url": "https://docs.python.org/1.6/lib/module-imaplib.html"} {"title": "16.11 imgfile -- Support for SGI imglib files", "text": "module-gl-constants.html | sgi.html | module-jpeg.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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": "1.6", "length": 510, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 14.9 imghdr --\nDetermine the type of an image.\nThe imghdr module determines the type of image contained in a\nfile or byte stream.\nThe imghdr module defines the following function:\nThe following image types are recognized, as listed below with the\nreturn value from what():\nYou can extend the list of file types imghdr can recognize by\nappending to this variable:\nExample:", "python_version": "1.6", "length": 490, "url": "https://docs.python.org/1.6/lib/module-imghdr.html"} {"title": "3.15 imp -- Access the import internals", "text": "module-marshal.html | python.html | examples-imp.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.15 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": "1.6", "length": 599, "url": "https://docs.python.org/1.6/lib/module-imp.html"} {"title": "16.12 jpeg -- Read and write JPEG files", "text": "module-imgfile.html | sgi.html | sunos.html | Python Library Reference | contents.html | genindex.html\n---\n# 16.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:\nJPEG Still Image Data Compression Standard, by\nPennebaker and Mitchell, is the canonical reference for the JPEG\nimage format.\nThe ISO standard for JPEG is also published as ITU T.81.\nThis is available in PDF form at\nhttp://www.w3.org/Graphics/JPEG/itu-t81.pdf.", "python_version": "1.6", "length": 1007, "url": "https://docs.python.org/1.6/lib/module-jpeg.html"} {"title": "3.19 keyword -- Testing for Python keywords", "text": "module-token.html | python.html | module-tokenize.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.19 keyword --\nTesting for Python keywords\nThis module allows a Python program to determine if a string is a\nkeyword. A single function is provided:", "python_version": "1.6", "length": 269, "url": "https://docs.python.org/1.6/lib/module-keyword.html"} {"title": "3.8 linecache -- Random access to text lines", "text": "traceback-example.html | python.html | module-pickle.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.8 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": "1.6", "length": 539, "url": "https://docs.python.org/1.6/lib/module-linecache.html"} {"title": "6.18 locale -- Internationalization services", "text": "shutil-example.html | allos.html | node145.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.18 locale --\nInternationalization services\nThe locale module opens access to the POSIX locale database\nand functionality. The POSIX locale mechanism allows programmers\nto deal with certain cultural issues in an application, without\nrequiring the programmer to know all the specifics of each country\nwhere the software is executed.\nThe locale module is implemented on top of the\n_locale module, which in turn uses an\nANSI C locale implementation if available.\nThe locale module defines the following exception and\nfunctions:\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\\344n\", \"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": "1.6", "length": 1079, "url": "https://docs.python.org/1.6/lib/module-locale.html"} {"title": "12.18 mailbox -- Read various mailbox formats", "text": "module-quopri.html | netdata.html | mailbox-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.18 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.", "python_version": "1.6", "length": 280, "url": "https://docs.python.org/1.6/lib/module-mailbox.html"} {"title": "12.14 mailcap -- Mailcap file handling.", "text": "xdr-exceptions.html | netdata.html | module-mimetypes.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.14 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.ietf.org/rfc/rfc1524.txt), ``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": "1.6", "length": 955, "url": "https://docs.python.org/1.6/lib/module-mailcap.html"} {"title": "3.34 __main__ -- Top-level script environment.", "text": "module-builtin.html | python.html | strings.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.34 __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 or from a script file.", "python_version": "1.6", "length": 331, "url": "https://docs.python.org/1.6/lib/module-main.html"} {"title": "3.14 marshal -- Alternate Python object serialization", "text": "module-copy.html | python.html | module-imp.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.14 marshal --\nAlternate 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.1 (#foot5464)\nThis is not a general ``persistency'' module. For general persistency\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.\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\nis possible to create plain Python integers that are longer than 32\nbits. Since the current marshal module uses 32 bits to\ntransfer plain Python integers, such values are silently truncated.\nThis particularly affects the use of very long integer literals in\nPython modules -- these will be accepted by the parser on such\nmachines, but will be silently be truncated when the module is read\nfrom the .pyc instead.3.2 (#foot5517)\nThere are functions that read/write files as well as functions\noperating on strings.\nThe module defines these functions:", "python_version": "1.6", "length": 2128, "url": "https://docs.python.org/1.6/lib/module-marshal.html"} {"title": "5.1 math -- Mathematical functions", "text": "misc.html | misc.html | module-cmath.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.1 math --\nMathematical functions\nThis module is always available. It provides access to the\nmathematical functions defined by the C standard.\nThese functions cannot be used with complex numbers; use the functions\nof the same name from the cmath (module-cmath.html) module if you require\nsupport for complex numbers. The distinction between functions which\nsupport complex numbers and those which don't is made since most users\ndo not want to learn quite as much mathematics as required to\nunderstand complex numbers. Receiving an exception instead of a\ncomplex result allows earlier detection of the unexpected complex\nnumber used as a parameter, so that the programmer can determine how\nand why it was generated in the first place.\nThe following functions provided by this module:\nNote that frexp() and modf() have a different\ncall/return pattern than their C equivalents: they take a single\nargument and return a pair of values, rather than returning their\nsecond return value through an `output parameter' (there is no such\nthing in Python).\nThe module also defines two mathematical constants:", "python_version": "1.6", "length": 1205, "url": "https://docs.python.org/1.6/lib/module-math.html"} {"title": "15.1 md5 -- MD5 message digest algorithm", "text": "crypto.html | crypto.html | module-sha.html | Python Library Reference | contents.html | genindex.html\n---\n# 15.1 md5 --\nMD5 message digest algorithm\nThis module implements the interface to RSA's MD5 message digest\nalgorithm (see also Internet RFC 1321 (http://www.ietf.org/rfc/rfc1321.txt)). Its use is quite\nstraightforward: use the 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 contatenation 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'\\273d\\234\\203\\335\\036\\245\\311\\331\\336\\311\\241\\215\\360\\377\\351'\n```\nMore condensed:\n```text\n\n>>> md5.new(\"Nobody inspects the spammish repetition\").digest()\n'\\273d\\234\\203\\335\\036\\245\\311\\331\\336\\311\\241\\215\\360\\377\\351'\n```\nAn md5 object has the following methods:", "python_version": "1.6", "length": 1120, "url": "https://docs.python.org/1.6/lib/module-md5.html"} {"title": "12.19 mhlib -- Access to MH mailboxes", "text": "mailbox-objects.html | netdata.html | mh-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.19 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": "1.6", "length": 423, "url": "https://docs.python.org/1.6/lib/module-mhlib.html"} {"title": "12.7 mimetools -- Tools for parsing MIME messages", "text": "addresslist-objects.html | netdata.html | mimetools.Message_Methods.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.7 mimetools --\nTools for parsing MIME messages\nThis module defines a subclass of the\nrfc822 (module-rfc822.html) module's\nMessage class and a number of utility functions that are\nuseful for the manipulation for MIME multipart or encoded message.\nIt defines the following items:\nSee Also:", "python_version": "1.6", "length": 428, "url": "https://docs.python.org/1.6/lib/module-mimetools.html"} {"title": "12.15 mimetypes -- Map filenames to MIME types", "text": "module-mailcap.html | netdata.html | module-base64.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.15 mimetypes --\nMap filenames to MIME types\nThe mimetypes converts between a filename or URL and the MIME\ntype associated with the filename extension. Conversions are provided\nfrom filename to MIME type and from MIME type to filename extension;\nencodings are not supported for the later conversion.\nThe functions described below provide the primary interface for this\nmodule. If the module has not been initialized, they will call\ninit().\nSome additional functions and data items are available for controlling\nthe behavior of the module.", "python_version": "1.6", "length": 661, "url": "https://docs.python.org/1.6/lib/module-mimetypes.html"} {"title": "12.8 MimeWriter -- Generic MIME file writer", "text": "mimetools.Message_Methods.html | netdata.html | MimeWriter-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.8 MimeWriter --\nGeneric MIME file writer\nThis module defines the class MimeWriter. The\nMimeWriter class implements a basic formatter for creating\nMIME multi-part files. It doesn't seek around the output file nor\ndoes it use large amounts of buffer space. You must write the parts\nout in the order that they should occur in the final\nfile. MimeWriter does buffer the headers you add, allowing you\nto rearrange their order.", "python_version": "1.6", "length": 561, "url": "https://docs.python.org/1.6/lib/module-MimeWriter.html"} {"title": "12.20 mimify -- MIME processing of mail messages", "text": "mh-message-objects.html | netdata.html | module-netrc.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.20 mimify --\nMIME processing of mail messages\nThe mimify module defines two functions to convert mail messages to\nand from MIME format. The mail message can be either a simple message\nor a so-called multipart message. Each part is treated separately.\nMimifying (a part of) a message entails encoding the message as\nquoted-printable if it contains any characters that cannot be\nrepresented using 7-bit ASCII. Unmimifying (a part of) a message\nentails undoing the quoted-printable encoding. Mimify and unmimify\nare especially useful when a message has to be edited before being\nsent. Typical use would be:\n```text\n\nunmimify message\nedit message\nmimify message\nsend message\n```\nThe modules defines the following user-callable functions and\nuser-settable variables:\nThis module can also be used from the command line. Usage is as\nfollows:\n```text\n\nmimify.py -e [-l length] [infile [outfile]]\nmimify.py -d [-b] [infile [outfile]]\n```\nto encode (mimify) and decode (unmimify) respectively. infile\ndefaults to standard input, outfile defaults to standard output.\nThe same file can be specified for input and output.\nIf the -l option is given when encoding, if there are any lines\nlonger than the specified length, the containing part will be\nencoded.\nIf the -b option is given when decoding, any base64 parts will\nbe decoded as well.", "python_version": "1.6", "length": 1453, "url": "https://docs.python.org/1.6/lib/module-mimify.html"} {"title": "15.3 mpz -- GNU arbitrary magnitude integers", "text": "module-sha.html | crypto.html | module-rotor.html | Python Library Reference | contents.html | genindex.html\n---\n# 15.3 mpz --\nGNU arbitrary magnitude integers\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 numbers can 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": "1.6", "length": 1484, "url": "https://docs.python.org/1.6/lib/module-mpz.html"} {"title": "18.1 msvcrt - Useful routines from the MS VC++ runtime", "text": "node355.html | node355.html | msvcrt-files.html | Python Library Reference | contents.html | genindex.html\n---\n# 18.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": "1.6", "length": 575, "url": "https://docs.python.org/1.6/lib/module-msvcrt.html"} {"title": "12.9 multifile -- Support for files containing distinct parts", "text": "MimeWriter-objects.html | netdata.html | MultiFile-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.9 multifile --\nSupport for files containing distinct parts\nThe MultiFile object enables you to treat sections of a text\nfile as file-like input objects, with `''` being returned by\nreadline() when a given delimiter pattern is encountered. The\ndefaults of this class are designed to make it useful for parsing\nMIME multipart messages, but by subclassing it and overriding methods\nit can be easily adapted for more general use.\nIt will be useful to know that in MultiFile's view of the world, text\nis composed of three kinds of lines: data, section-dividers, and\nend-markers. MultiFile is designed to support parsing of\nmessages that may have multiple nested message parts, each with its\nown pattern for section-divider and end-marker lines.", "python_version": "1.6", "length": 871, "url": "https://docs.python.org/1.6/lib/module-multifile.html"} {"title": "6.19 mutex -- Mutual exclusion support", "text": "embedding-locale.html | allos.html | mutex-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.19 mutex --\nMutual exclusion support\nThe mutex defines a class that allows mutual-exclusion\nvia aquiring 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": "1.6", "length": 399, "url": "https://docs.python.org/1.6/lib/module-mutex.html"} {"title": "12.21 netrc -- netrc file processing", "text": "module-mimify.html | netdata.html | netrc-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.21 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": "1.6", "length": 292, "url": "https://docs.python.org/1.6/lib/module-netrc.html"} {"title": "3.30 new -- Runtime implementation object creation", "text": "bytecodes.html | python.html | module-site.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.30 new --\nRuntime implementation object creation\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": "1.6", "length": 559, "url": "https://docs.python.org/1.6/lib/module-new.html"} {"title": "8.16 nis -- Interface to Sun's NIS (Yellow Pages)", "text": "node201.html | unix.html | module-syslog.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.16 nis --\nInterface to Sun's NIS (Yellow Pages)\nAvailability: UNIX.\nThe nis module gives a thin wrapper around the NIS library, useful\nfor central administration of several hosts.\nBecause NIS exists only on Unix systems, this module is\nonly available for Unix.\nThe nis module defines the following functions:\nThe nis module defines the following exception:", "python_version": "1.6", "length": 469, "url": "https://docs.python.org/1.6/lib/module-nis.html"} {"title": "11.8 nntplib -- NNTP protocol client", "text": "imap4-example.html | internet.html | nntp-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.8 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.ietf.org/rfc/rfc0977.txt).\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": "1.6", "length": 1740, "url": "https://docs.python.org/1.6/lib/module-nntplib.html"} {"title": "3.6 operator -- Standard operators as functions.", "text": "module-UserString.html | python.html | module-traceback.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.6 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 operator module defines the following functions:\nExample: Build a dictionary that maps the ordinals from `0` to\n`256` to their character equivalents.", "python_version": "1.6", "length": 656, "url": "https://docs.python.org/1.6/lib/module-operator.html"} {"title": "6.1 os -- Miscellaneous OS interfaces", "text": "allos.html | allos.html | os-procinfo.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.1 os --\nMiscellaneous OS interfaces\nThis module provides a more portable way of using operating system\n(OS) dependent functionality than importing an OS dependent built-in\nmodule like posix (module-posix.html) or nt.\nThis module searches for an OS 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 OS dependent\nmodules is such that as long as the same functionality is available,\nit uses the same interface; e.g., 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 OS are also available through the\nos module, but using them is of course a threat to\nportability!\nNote that after the first time os is imported, there is\nno performance penalty in using functions from os\ninstead of directly from the OS dependent built-in module, so there\nshould 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": "1.6", "length": 1271, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 6.2 os.path --\nCommon pathname manipulations\nThis module implements some useful functions on pathnames.", "python_version": "1.6", "length": 217, "url": "https://docs.python.org/1.6/lib/module-os.path.html"} {"title": "3.16 parser -- Access Python parse trees", "text": "examples-imp.html | python.html | Creating_ASTs.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.16 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`represents 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": "1.6", "length": 4379, "url": "https://docs.python.org/1.6/lib/module-parser.html"} {"title": "9. The Python Debugger", "text": "module-commands.html | lib.html | debugger-commands.html | Python Library Reference | contents.html | genindex.html\n---\n# 9. The Python Debugger\nThe module pdb defines an interactive source code\ndebugger for 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).\nA primitive windowing version of the debugger also exists -- this is\nmodule wdb, which requires\nstdwin.\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 (innermost 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": "1.6", "length": 1723, "url": "https://docs.python.org/1.6/lib/module-pdb.html"} {"title": "3.9 pickle -- Python object serialization", "text": "module-linecache.html | python.html | pickle-example.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.9 pickle --\nPython object serialization\nThe pickle module implements a basic but powerful algorithm\nfor ``pickling'' (a.k.a. serializing, marshalling or flattening)\nnearly arbitrary Python objects. This is the act of converting\nobjects to a stream of bytes (and back: ``unpickling''). This is a\nmore primitive notion than persistency -- although pickle\nreads and writes file objects, it does not handle the issue of naming\npersistent objects, nor the (even more complicated) area of concurrent\naccess to persistent objects. The pickle module can\ntransform a complex object into a byte stream and it can transform the\nbyte stream into an object with the same internal structure. The most\nobvious thing to do with these byte streams is to write them onto a\nfile, but it is also conceivable to send them across a network or\nstore them in a database. The module\nshelve (module-shelve.html) provides a simple interface\nto pickle and unpickle objects on DBM-style database files.\nNote: The pickle module is rather slow. A\nreimplementation of the same algorithm in C, which is up to 1000 times\nfaster, is available as the\ncPickle (module-cPickle.html) module. This has the same\ninterface except that Pickler and Unpickler are\nfactory functions, not classes (so they cannot be used as base classes\nfor inheritance).\nAlthough the pickle module can use the built-in module\nmarshal (module-marshal.html) internally, it differs from\nmarshal (module-marshal.html) in the way it handles certain kinds of data:\n- Recursive objects (objects containing references to themselves):\npickle keeps track of the objects it has already\nserialized, so later references to the same object won't be\nserialized again. (The marshal (module-marshal.html) module breaks for\nthis.)\n- Object sharing (references to the same object in different\nplaces): This is similar to self-referencing objects;\npickle stores the object once, and ensures that all\nother references point to the master copy. Shared objects\nremain shared, which can be very important for mutable objects.\n- User-defined classes and their instances: marshal (module-marshal.html)\ndoes not support these at all, but pickle can save\nand restore class instances transparently. The class definition\nmust be importable and live in the same module as when the\nobject was stored.\nThe data format used by pickle is Python-specific. This has\nthe advantage that there are no restrictions imposed by external\nstandards such as\nXDR (which can't\nrepresent pointer sharing); however it means that non-Python programs\nmay not be able to reconstruct pickled Python objects.\nBy default, the pickle data format uses a printable ASCII\nrepresentation. This is slightly more voluminous than a binary\nrepresentation. The big advantage of using printable ASCII (and of\nsome other characteristics of pickle's representation) is that\nfor debugging or recovery purposes it is possible for a human to read\nthe pickled file with a standard text editor.\nA binary format, which is slightly more efficient, can be chosen by\nspecifying a nonzero (true) value for the bin argument to the\nPickler constructor or the dump() and dumps()\nfunctions. The binary format is not the default because of backwards\ncompatibility with the Python 1.4 pickle module. In a future version,\nthe default may change to binary.\nThe pickle module doesn't handle code objects, which the\nmarshal (module-marshal.html) module does. I suppose\npickle could, and maybe it should, but there's probably no\ngreat need for it right now (as long as marshal (module-marshal.html) continues\nto be used for reading and writing code objects), and at least this\navoids the possibility of smuggling Trojan horses into a program.\nFor the benefit of persistency modules written using pickle, it\nsupports the notion of a reference to an object outside the pickled\ndata stream. Such objects are referenced by a name, which is an\narbitrary string of printable ASCII characters. The resolution of\nsuch names is not defined by the pickle module -- the\npersistent object module will have to implement a method\npersistent_load(). To write references to persistent objects,\nthe persistent module must define a method persistent_id() which\nreturns either `None` or the persistent ID of the object.\nThere are some restrictions on the pickling of class instances.\nFirst of all, the class must be defined at the top level in a module.\nFurthermore, all its instance variables must be picklable.\nWhen a pickled class instance is unpickled, its __init__() method\nis normally not invoked. Note: This is a deviation\nfrom previous versions of this module; the change was introduced in\nPython 1.5b2. The reason for the change is that in many cases it is\ndesirable to have a constructor that requires arguments; it is a\n(minor) nuisance to have to provide a __getinitargs__() method.\nIf it is desirable that the __init__() method be called on\nunpickling, a class can define a method __getinitargs__(),\nwhich should return a tuple containing the arguments to be\npassed to the class constructor (__init__()). This method is\ncalled at pickle time; the tuple it returns is incorporated in the\npickle for the instance.\nClasses can further influence how their instances are pickled -- if\nthe class\ndefines the method __getstate__(), it is called and the return\nstate is pickled as the contents for the instance, and if the class\ndefines the method __setstate__(), it is called with the\nunpickled state. (Note that these methods can also be used to\nimplement copying class instances.) If there is no\n__getstate__() method, the instance's __dict__ is\npickled. If there is no __setstate__() method, the pickled\nobject must be a dictionary and its items are assigned to the new\ninstance's dictionary. (If a class defines both __getstate__()\nand __setstate__(), the state object needn't be a dictionary\n-- these methods can do what they want.) This protocol is also used\nby the shallow and deep copying operations defined in the\ncopy (module-copy.html) module.\nNote that 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 and still load objects that were created with an earlier\nversion of the class. If you plan to have long-lived objects that\nwill see many versions of a class, it may be worthwhile to put a version\nnumber in the objects so that suitable conversions can be made by the\nclass's __setstate__() method.\nWhen a class itself is pickled, only its name is pickled -- the class\ndefinition is not pickled, but re-imported by the unpickling process.\nTherefore, the restriction that the class must be defined at the top\nlevel in a module applies to pickled classes as well.\nThe interface can be summarized as follows.\nTo pickle an object `x` onto a file `f`, open for writing:\n```text\n\np = pickle.Pickler(f)\np.dump(x)\n```\nA shorthand for this is:\n```text\n\npickle.dump(x, f)\n```\nTo unpickle an object `x` from a file `f`, open for reading:\n```text\n\nu = pickle.Unpickler(f)\nx = u.load()\n```\nA shorthand is:\n```text\n\nx = pickle.load(f)\n```\nThe Pickler class only calls the method `f.write()` with a\nstring argument. The Unpickler calls the methods `f.read()`(with an integer argument) and `f.readline()` (without argument),\nboth returning a string. It is explicitly allowed to pass non-file\nobjects here, as long as they have the right methods.\nThe constructor for the Pickler class has an optional second\nargument, bin. If this is present and true, the binary\npickle format is used; if it is absent or false, the (less efficient,\nbut backwards compatible) text pickle format is used. The\nUnpickler class does not have an argument to distinguish\nbetween binary and text pickle formats; it accepts either format.\nThe following types can be pickled:\n- `None`\n- integers, long integers, floating point 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 (by name\nreference, not storage of the implementation)\n- built-in functions\n- classes that are defined at the top level in a module\n- instances of such classes whose __dict__ or\n__setstate__() is picklable\nAttempts to pickle unpicklable objects will raise the\nPicklingError exception; when this happens, an unspecified\nnumber of bytes may have been written to the file.\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 all\nyield references to the same object. Warning: this is intended\nfor pickling multiple objects without intervening modifications to the\nobjects or their parts. If you modify an object and then pickle it\nagain using the same Pickler instance, the object is not\npickled again -- a reference to it is pickled and the\nUnpickler will return the old value, not the modified one.\n(There are two problems here: (a) detecting changes, and (b)\nmarshalling a minimal set of changes. I have no answers. Garbage\nCollection may also become a problem here.)\nApart from the Pickler and Unpickler classes, the\nmodule defines the following functions, and an exception:\nSee Also:", "python_version": "1.6", "length": 9471, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.13 pipes --\nInterface to shell pipelines\nAvailability: Unix.\nThe pipes module defines a class to abstract the concept of\na pipeline -- a sequence of convertors from one file to\nanother.\nBecause the module uses /bin/sh command lines, a POSIX or\ncompatible shell for os.system() and os.popen()\nis required.\nThe pipes module defines the following class:\nExample:\n```text\n\n>>> import pipes\n>>> t=pipes.Template()\n>>> t.append('tr a-z A-Z', '--')\n>>> f=t.open('/tmp/1', 'w')\n>>> f.write('hello world')\n>>> f.close()\n>>> open('/tmp/1').read()\n'HELLO WORLD'\n```", "python_version": "1.6", "length": 675, "url": "https://docs.python.org/1.6/lib/module-pipes.html"} {"title": "8.18 popen2 -- Subprocesses with accessible I/O streams", "text": "module-syslog.html | unix.html | popen3-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.18 popen2 --\nSubprocesses with accessible I/O streams\nAvailability: Unix.\nThis module allows you to spawn processes and connect their\ninput/output/error pipes and obtain their return codes under Unix.\nSimilar functionality exists for Windows platforms using the\nwin32pipe module provided as part of Mark Hammond's Windows\nextensions.\nThe primary interface offered by this module is a pair of factory\nfunctions:\nThe class defining the objects returned by the factory functions is\nalso available:", "python_version": "1.6", "length": 614, "url": "https://docs.python.org/1.6/lib/module-popen2.html"} {"title": "11.6 poplib -- POP3 protocol client", "text": "module-gopherlib.html | internet.html | pop3-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.6 poplib --\nPOP3 protocol client\nThis module defines a class, POP3, which encapsulates a\nconnection to an POP3 server and implements protocol as defined in\nRFC 1725 (http://www.ietf.org/rfc/rfc1725.txt). The POP3 class supports both the minmal and\noptional command sets.\nA single class is provided by the poplib module:\nOne exception is defined as an attribute of the poplib module:", "python_version": "1.6", "length": 508, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.1 posix --\nThe most common POSIX system calls\nAvailability: Unix.\nThis module provides access to operating system functionality that is\nstandardized by the C Standard and the POSIX standard (a thinly\ndisguised Unix interface).\nDo not import this module directly. Instead, import the\nmodule os (module-os.html), which provides a portable version of this\ninterface. On Unix, the os (module-os.html) module provides a superset of\nthe posix interface. On non-Unix operating systems the\nposix module is not available, but a subset is always\navailable through the os (module-os.html) interface. Once os (module-os.html) is\nimported, there is no performance penalty in using it instead\nof posix. In addition, os (module-os.html)\nprovides 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": "1.6", "length": 1350, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.14 posixfile --\nFile-like objects with locking support\nAvailability: Unix.\nNote: This module will become obsolete in a future release.\nThe locking operation that it provides is done better and more\nportably by the fcntl.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": "1.6", "length": 1859, "url": "https://docs.python.org/1.6/lib/module-posixfile.html"} {"title": "3.25 pprint -- Data pretty printer.", "text": "module-codeop.html | python.html | PrettyPrinter_Objects.html | Python Library Reference | contents.html | genindex.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": "1.6", "length": 1255, "url": "https://docs.python.org/1.6/lib/module-pprint.html"} {"title": "10.5 Reference Manual", "text": "Deterministic_Profiling.html | profile.html | profile-stats.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.5 Reference Manual\nThe primary entry point for the profiler is the global function\nprofile.run(). It is typically used to create any profile\ninformation. The reports are formatted and printed using methods of\nthe class pstats.Stats. The following is a description of all\nof these standard entry points and functions. For a more in-depth\nview of some of the code, consider reading the later section on\nProfiler Extensions, which includes discussion of how to derive\n``better'' profilers from the classes presented, or reading the source\ncode for these modules.\nAnalysis of the profiler data is done using this class from the\npstats module:", "python_version": "1.6", "length": 771, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.11 pty --\nPseudo-terminal utilities\nAvailability: IRIX, Linux.\nThe pty module defines operations for handling the\npseudo-terminal concept: starting another process and being able to\nwrite to and read from its controlling terminal programmatically.\nBecause pseudo-terminal handling is highly platform dependant, there\nis code to do it only for SGI and Linux. (The Linux code is supposed\nto work on other platforms, but hasn't been tested yet.)\nThe pty module defines the following functions:", "python_version": "1.6", "length": 605, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.2 pwd --\nThe password database\nAvailability: Unix.\nThis module provides access to the Unix user account and password\ndatabase. It is available on all Unix versions.\nPassword database entries are reported as 7-tuples containing the\nfollowing items from the password database (see ``), in order:\nThe uid and gid items are integers, all others are strings.\nKeyError is raised if the entry asked for cannot be found.\nNote: In 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": "1.6", "length": 969, "url": "https://docs.python.org/1.6/lib/module-pwd.html"} {"title": "3.22 pyclbr -- Python class browser support", "text": "module-tabnanny.html | python.html | pyclbr-class-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.22 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": "1.6", "length": 672, "url": "https://docs.python.org/1.6/lib/module-pyclbr.html"} {"title": "3.27 py_compile -- Compile Python source files", "text": "subclassing-reprs.html | python.html | module-compileall.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.27 py_compile --\nCompile Python source files\nThe py_compile module provides a single function to generate\na byte-code file from a source file.\nThough not often needed, this function can be useful when installing\nmodules for shared use, especially if some of the users may not have\npermission to write the byte-code cache files in the directory\ncontaining the source code.", "python_version": "1.6", "length": 500, "url": "https://docs.python.org/1.6/lib/module-pycompile.html"} {"title": "7.6 Queue -- A synchronized queue class.", "text": "thread-objects.html | someos.html | QueueObjects.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.6 Queue --\nA synchronized queue class.\nThe Queue module implements a multi-producer, multi-consumer\nFIFO queue. It is especially useful in threads programming when\ninformation must be exchanged safely between multiple threads. The\nQueue class in this module implements all the required locking\nsemantics. It depends on the availability of thread support in\nPython.\nThe Queue module defines the following class and exception:", "python_version": "1.6", "length": 545, "url": "https://docs.python.org/1.6/lib/module-Queue.html"} {"title": "12.17 quopri -- Encode and decode MIME quoted-printable data", "text": "module-base64.html | netdata.html | module-mailbox.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.17 quopri --\nEncode and decode MIME quoted-printable data\nThis module performs quoted-printable transport encoding and decoding,\nas defined in RFC 1521 (http://www.ietf.org/rfc/rfc1521.txt): ``MIME (Multipurpose Internet Mail Extensions)\nPart One''. The quoted-printable encoding is designed for data where\nthere are relatively few nonprintable characters; the base64 encoding\nscheme available via the base64 (module-base64.html) module is more compact if there\nare many such characters, as when sending a graphics file.", "python_version": "1.6", "length": 644, "url": "https://docs.python.org/1.6/lib/module-quopri.html"} {"title": "5.3 random -- Generate pseudo-random numbers", "text": "module-cmath.html | misc.html | rng-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.3 random --\nGenerate pseudo-random numbers\nThis module implements pseudo-random number generators for various\ndistributions: on the real line, there are functions to compute normal\nor Gaussian, lognormal, negative exponential, gamma, and beta\ndistributions. For generating distribution of angles, the circular\nuniform and von Mises distributions are available.\nThe random module supports the Random Number\nGenerator interface, described in section 5.3.1 (rng-objects.html#rng-objects). This\ninterface of the module, as well as the distribution-specific\nfunctions described below, all use the pseudo-random generator\nprovided by the whrandom (module-whrandom.html) module.\nThe following functions are defined to support specific distributions,\nand all return real values. Function parameters are named after the\ncorresponding variables in the distribution's equation, as used in\ncommon mathematical practice; most of these equations can be found in\nany statistics text. These are expected to become part of the Random\nNumber Generator interface in a future release.\nSee Also:", "python_version": "1.6", "length": 1190, "url": "https://docs.python.org/1.6/lib/module-random.html"} {"title": "4.2 re -- Perl-style regular expression operations.", "text": "module-string.html | strings.html | re-syntax.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.2 re --\nPerl-style regular expression operations.\nThis module provides regular expression matching operations similar to\nthose found in Perl. It's 8-bit clean: the strings being processed\nmay contain both null bytes and characters whose high bit is set. Regular\nexpression pattern strings may not contain null bytes, but can specify\nthe null byte using the `\\ number` notation.\nCharacters with the high bit set may be included. The re\nmodule 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.", "python_version": "1.6", "length": 1443, "url": "https://docs.python.org/1.6/lib/module-re.html"} {"title": "4.3 regex -- Regular expression search and match operations.", "text": "match-objects.html | strings.html | node91.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.3 regex --\nRegular expression search and match operations.\nThis module provides regular expression matching operations similar to\nthose found in Emacs.\nObsolescence note:\nThis module is obsolete as of Python version 1.5; it is still being\nmaintained because much existing code still uses it. All new code in\nneed of regular expressions should use the new\n`re` module, which supports the more powerful\nand regular Perl-style regular expressions. Existing code should be\nconverted. The standard library module\n`reconvert` helps in converting\n`regex` style regular expressions to `re`\nstyle regular expressions. (For more conversion help, see Andrew\nKuchling's ``regex-to-re HOWTO'' at\nhttp://www.python.org/doc/howto/regex-to-re/.)\nBy default the patterns are Emacs-style regular expressions\n(with one exception). There is\na way to change the syntax to match that of several well-known\nUnix utilities. The exception is that Emacs' \"\\s\"pattern is not supported, since the original implementation references\nthe Emacs syntax tables.\nThis module is 8-bit clean: both patterns and strings may contain null\nbytes and characters whose high bit is set.\nPlease note: There is a little-known fact about Python string\nliterals which means that you don't usually have to worry about\ndoubling backslashes, even though they are used to escape special\ncharacters in string literals as well as in regular expressions. This\nis because Python doesn't remove backslashes from string literals if\nthey are followed by an unrecognized escape character.\nHowever, if you want to include a literal backslash in a\nregular expression represented as a string literal, you have to\nquadruple it or enclose it in a singleton character class.\nE.g. to extract LATEX \"\\section{ ...}\" headers\nfrom a document, you can use this pattern:\n`'[\\]section{\\(.*\\)}'`. Another exception:\nthe escape sequece \"\\b\" is significant in string literals\n(where it means the ASCII bell character) as well as in Emacs regular\nexpressions (where it stands for a word boundary), so in order to\nsearch for a word boundary, you should use the pattern `'\\\\b'`.\nSimilarly, a backslash followed by a digit 0-7 should be doubled to\navoid interpretation as an octal escape.", "python_version": "1.6", "length": 2324, "url": "https://docs.python.org/1.6/lib/module-regex.html"} {"title": "4.4 regsub -- String operations using regular expressions", "text": "Contents_of_Module_regex.html | strings.html | module-struct.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.4 regsub --\nString operations using regular expressions\nThis module defines a number of functions useful for working with\nregular expressions (see built-in module regex (module-regex.html)).\nWarning: these functions are not thread-safe.\nObsolescence note:\nThis module is obsolete as of Python version 1.5; it is still being\nmaintained because much existing code still uses it. All new code in\nneed of regular expressions should use the new re (module-re.html) module, which\nsupports the more powerful and regular Perl-style regular expressions.\nExisting code should be converted. The standard library module\nreconvert helps in converting regex (module-regex.html) style regular\nexpressions to re (module-re.html) style regular expressions. (For more\nconversion help, see Andrew Kuchling's\n``regex-to-re HOWTO'' at\nhttp://www.python.org/doc/howto/regex-to-re/.)", "python_version": "1.6", "length": 993, "url": "https://docs.python.org/1.6/lib/module-regsub.html"} {"title": "3.26 repr -- Alternate repr() implementation.", "text": "PrettyPrinter_Objects.html | python.html | Repr-objects.html | Python Library Reference | contents.html | genindex.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": "1.6", "length": 431, "url": "https://docs.python.org/1.6/lib/module-repr.html"} {"title": "8.15 resource -- Resource usage information", "text": "module-posixfile.html | unix.html | node200.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.15 resource --\nResource usage information\nAvailability: Unix.\nThis module provides basic mechanisms for measuring and controlling\nsystem resources utilized by a program.\nSymbolic constants are used to specify particular system resources and\nto request usage information about either the current process or its\nchildren.\nA single exception is defined for errors:", "python_version": "1.6", "length": 477, "url": "https://docs.python.org/1.6/lib/module-resource.html"} {"title": "13.1 rexec -- Restricted execution framework", "text": "restricted.html | restricted.html | node309.html | Python Library Reference | contents.html | genindex.html\n---\n# 13.1 rexec --\nRestricted execution framework\nThis module contains the RExec class, which supports\nr_eval(), r_execfile(), r_exec(), and\nr_import() methods, which are restricted versions of the standard\nPython functions eval(), execfile() and\nthe exec and import statements.\nCode executed in this restricted environment will\nonly have access to modules and functions that are deemed safe; you\ncan subclass RExec to add or remove capabilities as desired.\nNote: The RExec class can prevent code from performing\nunsafe operations like reading or writing disk files, or using TCP/IP\nsockets. However, it does not protect against code using extremely\nlarge amounts of memory or CPU time.\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.\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": "1.6", "length": 1712, "url": "https://docs.python.org/1.6/lib/module-rexec.html"} {"title": "12.6 rfc822 -- Parse RFC 822 mail headers", "text": "writer-impls.html | netdata.html | message-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.6 rfc822 --\nParse RFC 822 mail headers\nThis module defines a class, Message, which represents a\ncollection of ``email headers'' as defined by the Internet standard\nRFC 822 (http://www.ietf.org/rfc/rfc0822.txt). It is used in various contexts, usually to read such\nheaders from a file. This module also defines a helper class\nAddressList for parsing RFC 822 (http://www.ietf.org/rfc/rfc0822.txt) addresses. Please refer to\nthe RFC for information on the specific syntax of RFC 822 (http://www.ietf.org/rfc/rfc0822.txt) headers.\nThe mailbox (module-mailbox.html) module provides classes\nto read mailboxes produced by various end-user mail programs.\nSee Also:", "python_version": "1.6", "length": 780, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 14.8 rgbimg --\nRead and write ``SGI RGB'' files\nThe rgbimg module allows Python programs to access SGI imglib image\nfiles (also known as .rgb files). The module is far from\ncomplete, but is provided anyway since the functionality that there is\nenough in some cases. Currently, colormap files are not supported.\nThe module defines the following variables and functions:", "python_version": "1.6", "length": 489, "url": "https://docs.python.org/1.6/lib/module-rgbimg.html"} {"title": "7.15 rlcompleter -- Completion function for readline", "text": "zipfile-objects.html | someos.html | completer-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.15 rlcompleter --\nCompletion function for readline\nThe rlcompleter module defines a completion function for\nthe readline module by completing valid Python identifiers and\nkeyword.\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": "1.6", "length": 1072, "url": "https://docs.python.org/1.6/lib/module-rlcompleter.html"} {"title": "12.22 robotparser -- Parser for robots.txt", "text": "netrc-objects.html | netdata.html | restricted.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.22 robotparser --\nParser for robots.txt\nThis module provides a single class, RobotFileParser, which answers\nquestions about whether or not a particular user agent can fetch a URL on\nthe web site that published the robots.txt file. For more details on\nthe structure of robots.txt files, see\nhttp://info.webcrawler.com/mak/projects/robots/norobots.html.\nThe following example demonstrates basic use of the RobotFileParser class.\n```text\n\n>>> import robotparser\n>>> rp = robotparser.RobotFileParser()\n>>> rp.set_url(\"http://www.musi-cal.com/robots.txt\")\n>>> rp.read()\n>>> rp.can_fetch(\"*\", \"http://www.musi-cal.com/cgi-bin/search?city=San+Francisco\")\n0\n>>> rp.can_fetch(\"*\", \"http://www.musi-cal.com/\")\n1\n```", "python_version": "1.6", "length": 825, "url": "https://docs.python.org/1.6/lib/module-robotparser.html"} {"title": "15.4 rotor -- Enigma-like encryption and decryption.", "text": "module-mpz.html | crypto.html | sgi.html | Python Library Reference | contents.html | genindex.html\n---\n# 15.4 rotor --\nEnigma-like encryption and decryption.\nThis module implements a rotor-based encryption algorithm, contributed by\nLance Ellinghouse. The design is derived\nfrom the Enigma device, a machine\nused during World War II to encipher messages. A rotor is simply a\npermutation. For example, if the character `A' is the origin of the rotor,\nthen a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on.\nTo encrypt, we choose several different rotors, and set the origins of the\nrotors to known positions; their initial position is the ciphering key. To\nencipher a character, we permute the original character by the first rotor,\nand then apply the second rotor's permutation to the result. We continue\nuntil we've applied all the rotors; the resulting character is our\nciphertext. We then change the origin of the final rotor by one position,\nfrom `A' to `B'; if the final rotor has made a complete revolution, then we\nrotate the next-to-last rotor by one position, and apply the same procedure\nrecursively. In other words, after enciphering one character, we advance\nthe rotors in the same fashion as a car's odometer. Decoding works in the\nsame way, except we reverse the permutations and apply them in the opposite\norder.\nThe available functions in this module are:\nRotor objects have the following methods:\nAn example usage:\n```text\n\n>>> import rotor\n>>> rt = rotor.newrotor('key', 12)\n>>> rt.encrypt('bar')\n'\\2534\\363'\n>>> rt.encryptmore('bar')\n'\\357\\375$'\n>>> rt.encrypt('bar')\n'\\2534\\363'\n>>> rt.decrypt('\\2534\\363')\n'bar'\n>>> rt.decryptmore('\\357\\375$')\n'bar'\n>>> rt.decrypt('\\357\\375$')\n'l(\\315'\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 skilful 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": "1.6", "length": 2996, "url": "https://docs.python.org/1.6/lib/module-rotor.html"} {"title": "6.9 sched -- Event scheduler", "text": "module-time.html | allos.html | scheduler-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.9 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": "1.6", "length": 654, "url": "https://docs.python.org/1.6/lib/module-sched.html"} {"title": "7.3 select -- Waiting for I/O completion", "text": "Socket_Example.html | someos.html | module-thread.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.3 select --\nWaiting for I/O completion\nThis module provides access to the function select()\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": "1.6", "length": 538, "url": "https://docs.python.org/1.6/lib/module-select.html"} {"title": "12.1 sgmllib -- Simple SGML parser", "text": "netdata.html | netdata.html | module-htmllib.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.1 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)\nmodule.\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": "1.6", "length": 811, "url": "https://docs.python.org/1.6/lib/module-sgmllib.html"} {"title": "15.2 sha -- SHA message digest algorithm", "text": "module-md5.html | crypto.html | module-mpz.html | Python Library Reference | contents.html | genindex.html\n---\n# 15.2 sha --\nSHA message digest algorithm\nThis module implements the interface to NIST's secure hash\nalgorithm, known as SHA. It is used in\nthe same way as the md5 (module-md5.html) module: use the 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 contatenation of the strings fed to it\nso far. SHA digests are 160 bits instead of 128\nbits.\nThe following values are provided as constants in the module and as\nattributes of the sha objects returned by new():\nA sha object has all the methods the md5 objects have, plus one:", "python_version": "1.6", "length": 741, "url": "https://docs.python.org/1.6/lib/module-sha.html"} {"title": "3.12 shelve -- Python object persistency", "text": "module-copyreg.html | python.html | module-copy.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.12 shelve --\nPython object persistency\nA ``shelf'' is a persistent, dictionary-like object. The difference\nwith ``dbm'' databases is that the values (not the keys!) in a shelf\ncan be essentially arbitrary Python objects -- anything that the\npickle (module-pickle.html) module can handle. This includes most class\ninstances, recursive data types, and objects containing lots of shared\nsub-objects. The keys are ordinary strings.\nTo summarize the interface (`key` is a string, `data` is an\narbitrary object):\n```text\n\nimport shelve\n\nd = shelve.open(filename) # open, with (g)dbm filename -- no suffix\n\nd[key] = data # store data at key (overwrites old data if\n# using an existing key)\ndata = d[key] # retrieve data at key (raise KeyError if no\n# such key)\ndel d[key] # delete data stored at key (raises KeyError\n# if no such key)\nflag = d.has_key(key) # true if the key exists\nlist = d.keys() # a list of all existing keys (slow!)\n\nd.close() # close it\n```\nRestrictions:\n- The choice of which database package will be used\n(e.g. dbm (module-dbm.html) or gdbm (module-gdbm.html)) depends on which interface\nis available. Therefore it is not safe to open the database directly\nusing dbm (module-dbm.html). The database is also (unfortunately) subject\nto the limitations of dbm (module-dbm.html), if it is used -- this means\nthat (the pickled representation of) the objects stored in the\ndatabase should be fairly small, and in rare cases key collisions may\ncause the database to refuse updates.\n- Dependent on the implementation, closing a persistent dictionary may\nor may not be necessary to flush changes to disk.\n- The shelve module does not support concurrent read/write\naccess to shelved objects. (Multiple simultaneous read accesses are\nsafe.) When a program has a shelf open for writing, no other program\nshould have it open for reading or writing. Unix file locking can\nbe used to solve this, but this differs across Unix versions and\nrequires knowledge about the database implementation used.", "python_version": "1.6", "length": 2117, "url": "https://docs.python.org/1.6/lib/module-shelve.html"} {"title": "5.11 shlex -- Simple lexical analysis", "text": "Cmd-objects.html | misc.html | shlex-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.11 shlex --\nSimple lexical analysis\nNew in version 1.5.2.\nThe shlex class makes it easy to write lexical analyzers for\nsimple syntaxes resembling that of the Unix shell. This will often\nbe useful for writing minilanguages, e.g. in run control files for\nPython applications.\nSee Also:", "python_version": "1.6", "length": 400, "url": "https://docs.python.org/1.6/lib/module-shlex.html"} {"title": "6.17 shutil -- High-level file operations", "text": "module-fnmatch.html | allos.html | shutil-example.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.17 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": "1.6", "length": 511, "url": "https://docs.python.org/1.6/lib/module-shutil.html"} {"title": "7.1 signal -- Set handlers for asynchronous events.", "text": "someos.html | someos.html | Signal_Example.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.1 signal --\nSet handlers for asynchronous events.\nThis module provides mechanisms to use signal handlers in Python.\nSome general rules for working with signals and their handlers:\n- A handler for a particular signal, once set, remains installed until\nit is explicitly reset (i.e. 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(e.g. 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 interthread\ncommunication. Use locks instead.\nThe variables defined in the signal module are:\nThe signal module defines the following functions:", "python_version": "1.6", "length": 2430, "url": "https://docs.python.org/1.6/lib/module-signal.html"} {"title": "11.14 SimpleHTTPServer -- A Do-Something Request Handler", "text": "module-BaseHTTPServer.html | internet.html | module-CGIHTTPServer.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.14 SimpleHTTPServer --\nA Do-Something 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": "1.6", "length": 550, "url": "https://docs.python.org/1.6/lib/module-SimpleHTTPServer.html"} {"title": "3.31 site -- Site-specific configuration hook", "text": "module-new.html | python.html | module-user.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.31 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/pythonversion/site-packages and then\nlib/site-python (on Unix). For each of the distinct\nhead-tail combinations, it sees if it refers to an existing directory,\nand if so, adds to `sys.path`, and also inspected for path\nconfiguration files.\nA path configuration file is a file whose name has the form\npackage.pth; its contents are additional items (one\nper line) to be added to `sys.path`. Non-existing items are\nnever added to `sys.path`, but no check is made that the item\nrefers to a directory (rather than a file). No item is added to\n`sys.path` more than once. Blank lines and lines beginning with\n`#` are skipped.\nFor example, suppose `sys.prefix` and `sys.exec_prefix` are\nset to /usr/local. The Python 1.6 library is then\ninstalled in /usr/local/lib/python1.5 (note that only the first\nthree characters of `sys.version` are used to form the path\nname). Suppose this has a subdirectory\n/usr/local/lib/python1.5/site-packages with three\nsubsubdirectories, foo, bar and spam, and two\npath configuration files, foo.pth and bar.pth. Assume\nfoo.pth contains the following:\n```text\n\n# foo package configuration\n\nfoo\nbar\nbletch\n```\nand bar.pth contains:\n```text\n\n# bar package configuration\n\nbar\n```\nThen the following directories are added to `sys.path`, in this\norder:\n```text\n\n/usr/local/lib/python1.5/site-packages/bar\n/usr/local/lib/python1.5/site-packages/foo\n```\nNote that bletch is omitted because it doesn't exist; the\nbar directory precedes the foo directory because\nbar.pth comes alphabetically before foo.pth; and\nspam is omitted because it is not mentioned in either path\nconfiguration file.\nAfter these path manipulations, an attempt is made to import a module\nnamed sitecustomize, which can\nperform arbitrary site-specific customizations. If this import fails\nwith an ImportError exception, it is silently ignored.", "python_version": "1.6", "length": 2582, "url": "https://docs.python.org/1.6/lib/module-site.html"} {"title": "11.9 smtplib -- SMTP protocol client", "text": "nntp-objects.html | internet.html | SMTP-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.9 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.ietf.org/rfc/rfc0821.txt) (Simple Mail Transfer Protocol) and RFC 1869 (http://www.ietf.org/rfc/rfc1869.txt)\n(SMTP Service Extensions).\nA nice selection of exceptions is defined as well:\nSee Also:\nInternet RFC 821 (http://www.ietf.org/rfc/rfc0821.txt), Simple Mail Transfer Protocol.\nAvailable online at\nhttp://info.internet.isi.edu/in-notes/rfc/files/rfc821.txt.\nInternet RFC 1869 (http://www.ietf.org/rfc/rfc1869.txt), SMTP Service Extensions.\nAvailable online at\nhttp://info.internet.isi.edu/in-notes/rfc/files/rfc1869.txt.", "python_version": "1.6", "length": 901, "url": "https://docs.python.org/1.6/lib/module-smtplib.html"} {"title": "14.10 sndhdr -- Determine type of sound file.", "text": "module-imghdr.html | mmedia.html | crypto.html | Python Library Reference | contents.html | genindex.html\n---\n# 14.10 sndhdr --\nDetermine type of sound file.\nThe sndhdr provides utility functions which attempt to\ndetermine the type of sound data which is in a file. When these\nfunctions are able to determine what type of sound data is stored in a\nfile, they return a tuple `( type , sampling_rate , channels , frames , bits_per_sample )`. The value for\ntype indicates the data type and will be one of the strings\n`'aifc'`, `'aiff'`, `'au'`, `'hcom'`,\n`'sndr'`, `'sndt'`, `'voc'`, `'wav'`,\n`'8svx'`, `'sb'`, `'ub'`, or `'ul'`. The\nsampling_rate will be either the actual value or `0` if\nunknown or difficult to decode. Similarly, channels will be\neither the number of channels or `0` if it cannot be determined\nor if the value is difficult to decode. The value for frames\nwill be either the number of frames or `-1`. The last item in\nthe tuple, bits_per_sample, will either be the sample size in\nbits or `'A'` for A-LAW or `'U'` for\nu-LAW.", "python_version": "1.6", "length": 1039, "url": "https://docs.python.org/1.6/lib/module-sndhdr.html"} {"title": "7.2 socket -- Low-level networking interface", "text": "Signal_Example.html | someos.html | socket-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.2 socket --\nLow-level networking interface\nThis module provides access to the BSD socket interface.\nIt is available on all modern Unix systems, Windows, MacOS, BeOS,\nOS/2, and probably additional platforms.\nFor an introduction to socket programming (in C), see the following\npapers: An Introductory 4.3BSD Interprocess Communication\nTutorial, by Stuart Sechrest and An Advanced 4.3BSD\nInterprocess Communication Tutorial, by Samuel J. Leffler et al,\nboth in the Unix Programmer's Manual, Supplementary Documents 1\n(sections PS1:7 and PS1:8). The platform-specific reference material\nfor the various socket-related system calls are also a valuable source\nof information on the details of socket semantics. For Unix, refer\nto the manual pages; for Windows, see the WinSock (or Winsock 2)\nspecification.\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 a single string for the\nAF_UNIX address family and as a pair\n`( host , port )` for the AF_INET address\nfamily, where host is a string representing\neither a hostname in Internet domain notation like\n`'daring.cwi.nl'` or an IP address like `'100.50.200.5'`,\nand port is an integral port number. Other address families are\ncurrently not supported. The address format required by a particular\nsocket object is automatically selected based on the address family\nspecified when the socket object was created.\nFor IP addresses, two special forms are accepted instead of a host\naddress: the empty string represents INADDR_ANY, and the string\n`''` represents INADDR_BROADCAST.\nAll errors raise exceptions. The normal exceptions for invalid\nargument types and out-of-memory conditions can be raised; errors\nrelated to socket or address semantics raise the error\nsocket.error.\nNon-blocking mode is supported through the\nsetblocking() method.\nThe module socket exports the following constants and functions:", "python_version": "1.6", "length": 2446, "url": "https://docs.python.org/1.6/lib/module-socket.html"} {"title": "11.12 SocketServer -- A framework for network servers.", "text": "module-urlparse.html | internet.html | module-BaseHTTPServer.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.12 SocketServer --\nA framework for network servers.\nThe SocketServer module simplifies the task of writing network\nservers.\nThere are four basic server classes: TCPServer uses the\nInternet TCP protocol, which provides for continuous streams of data\nbetween the client and server. UDPServer uses datagrams, which\nare discrete packets of information that may arrive out of order or be\nlost while in transit. The more infrequently used\nUnixStreamServer and UnixDatagramServer classes are\nsimilar, but use Unix domain sockets; they're not available on\nnon-Unix platforms. For more details on network programming, consult\na book such as W. Richard Steven's UNIX Network Programming\nor Ralph Davis's Win32 Network Programming.\nThese four classes process requests synchronously; each request\nmust be completed before the next request can be started. This isn't\nsuitable if each request takes a long time to complete, because it\nrequires a lot of computation, or because it returns a lot of data\nwhich the client is slow to process. The solution is to create a\nseparate process or thread to handle each request; the\nForkingMixIn and ThreadingMixIn mix-in classes can be\nused to support asynchronous behaviour.\nCreating a server requires several steps. First, you must create a\nrequest handler class by subclassing the BaseRequestHandler\nclass and overriding its handle() method; this method will\nprocess incoming requests. Second, you must instantiate one of the\nserver classes, passing it the server's address and the request\nhandler class. Finally, call the handle_request() or\nserve_forever() method of the server object to process one or\nmany requests.\nServer classes have the same external methods and attributes, no\nmatter what network protocol they use:\nThe server classes support the following class variables:\nThere are various server methods that can be overridden by subclasses\nof base server classes like TCPServer; these methods aren't\nuseful to external users of the server object.\nThe request handler class must define a new handle() method,\nand can override any of the following methods. A new instance is\ncreated for each request.", "python_version": "1.6", "length": 2273, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 6.4 stat --\nInterpreting stat() results\nThe stat module defines constants and functions for\ninterpreting the results of os.stat(),\nos.fstat() and os.lstat() (if they exist). For\ncomplete details about the stat(), fstat() and\nlstat() calls, consult the documentation for your system.\nThe stat module defines the following functions to test for\nspecific file types:\nTwo additional functions are defined for more general manipulation of\nthe file's mode:\nNormally, you would use the os.path.is*() functions for\ntesting the type of a file; the functions here are useful when you are\ndoing multiple tests of the same file and wish to avoid the overhead of\nthe stat() system call for each test. These are also\nuseful when checking for information about a file that isn't handled\nby os.path (module-os.path.html), like the tests for block and character\ndevices.\nAll the variables below are simply symbolic indexes into the 10-tuple\nreturned by os.stat(), os.fstat() or\nos.lstat().\nExample:", "python_version": "1.6", "length": 1104, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 6.5 statcache --\nAn optimization of os.stat()\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": "1.6", "length": 410, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 6.6 statvfs --\nConstants used with os.statvfs()\nThe statvfs module defines constants so interpreting the result\nif os.statvfs(), which returns a tuple, can be made without\nremembering ``magic numbers.'' Each of the constants defined in this\nmodule is the index of the entry in the tuple returned by\nos.statvfs() that contains the specified information.", "python_version": "1.6", "length": 474, "url": "https://docs.python.org/1.6/lib/module-statvfs.html"} {"title": "4.1 string -- Common string operations", "text": "strings.html | strings.html | module-re.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.1 string --\nCommon string operations\nThis module defines some constants useful for checking character\nclasses and some useful string functions. See the module\nre (module-re.html) for string functions based on regular\nexpressions.\nThe constants defined in this module are are:\nThe functions defined in this module are:", "python_version": "1.6", "length": 429, "url": "https://docs.python.org/1.6/lib/module-string.html"} {"title": "4.7 StringIO -- Read and write strings as files", "text": "module-fpformat.html | strings.html | module-cStringIO.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.7 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 on file objects for operations (section\n2.1.7 (bltin-file-objects.html#bltin-file-objects)).\nThe following methods of StringIO objects require special\nmention:", "python_version": "1.6", "length": 472, "url": "https://docs.python.org/1.6/lib/module-StringIO.html"} {"title": "4.5 struct -- Interpret strings as packed binary data", "text": "module-regsub.html | strings.html | module-fpformat.html | Python Library Reference | contents.html | genindex.html\n---\n# 4.5 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 \"I\" conversion code will convert to a Python long if\nthe C int is the same size as a C long, which is\ntypical on most modern systems. If a C int is smaller than\na C long, an Python integer will be created instead.\nA format character may be preceded by an integral repeat count;\ne.g. 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; e.g. `'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 can be used to encode a Pascal\nstring. The first byte is the length of the stored string, with the\nbytes of the string following. If count is given, it is used as the\ntotal number of bytes used, including the length byte. If the string\npassed in to pack() is too long, the stored representation\nis truncated. If the string is too short, padding is used to ensure\nthat exactly enough bytes are used to satisfy the count.\nFor the \"I\" and \"L\" format characters, the return\nvalue 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 (e.g. Motorola and Sun are big-endian; Intel and DEC are\nlittle-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); short is 2 bytes;\nint and long are 4 bytes. float and\ndouble are 32-bit and 64-bit IEEE floating point numbers,\nrespectively.\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 (i.e. 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'\\000\\001\\000\\002\\000\\000\\000\\003'\n>>> unpack('hhl', '\\000\\001\\000\\002\\000\\000\\000\\003')\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, e.g. the format `'llh0l'` specifies two\npad bytes at the end, assuming longs are aligned on 4-byte boundaries.\nThis only works when native size and alignment are in effect;\nstandard size and alignment does not enforce any alignment.", "python_version": "1.6", "length": 5051, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 14.4 sunau --\nRead and write Sun AU files\nThe sunau module provides a convenient interface to the Sun AU sound\nformat. Note that this module is interface-compatible with the modules\naifc (module-aifc.html) and wave (module-wave.html).\nThe sunau module defines the following functions:\nThe sunau module defines the following exception:\nThe sunau module defines the following data item:", "python_version": "1.6", "length": 503, "url": "https://docs.python.org/1.6/lib/module-sunau.html"} {"title": "17.2 SUNAUDIODEV -- Constants used with sunaudiodev", "text": "audio-device-objects.html | sunos.html | node355.html | Python Library Reference | contents.html | genindex.html\n---\n# 17.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": "1.6", "length": 475, "url": "https://docs.python.org/1.6/lib/module-sunaudiodev-constants.html"} {"title": "17.1 sunaudiodev -- Access to Sun audio hardware", "text": "sunos.html | sunos.html | audio-device-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 17.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-LAW format 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": "1.6", "length": 606, "url": "https://docs.python.org/1.6/lib/module-sunaudiodev.html"} {"title": "3.17 symbol -- Constants used with Python parse trees", "text": "node56.html | python.html | module-token.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.17 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 defintions 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": "1.6", "length": 599, "url": "https://docs.python.org/1.6/lib/module-symbol.html"} {"title": "3.1 sys -- System-specific parameters and functions", "text": "python.html | python.html | module-types.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.1 sys --\nSystem-specific parameters and functions\nThis module provides access to some variables used or maintained by the\ninterpreter and to functions that interact strongly with the interpreter.\nIt is always available.", "python_version": "1.6", "length": 332, "url": "https://docs.python.org/1.6/lib/module-sys.html"} {"title": "8.17 syslog -- Unix syslog library routines", "text": "module-nis.html | unix.html | module-popen2.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.17 syslog --\nUnix syslog library routines\nAvailability: Unix.\nThis module provides an interface to the Unix `syslog` library\nroutines. Refer to the Unix manual pages for a detailed description\nof the `syslog` facility.\nThe module defines the following functions:\nThe module defines the following constants:", "python_version": "1.6", "length": 422, "url": "https://docs.python.org/1.6/lib/module-syslog.html"} {"title": "3.21 tabnanny -- Detection of ambiguous indentation", "text": "module-tokenize.html | python.html | module-pyclbr.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.21 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: The API provided by this module is likely to change\nin future releases; such changes may not be backward compatible.", "python_version": "1.6", "length": 461, "url": "https://docs.python.org/1.6/lib/module-tabnanny.html"} {"title": "11.10 telnetlib -- Telnet client", "text": "SMTP-example.html | internet.html | telnet-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.10 telnetlib --\nTelnet client\nThe telnetlib module provides a Telnet class that\nimplements the Telnet protocol. See RFC 854 (http://www.ietf.org/rfc/rfc0854.txt) for details about the\nprotocol.\nSee Also:", "python_version": "1.6", "length": 327, "url": "https://docs.python.org/1.6/lib/module-telnetlib.html"} {"title": "6.13 tempfile -- Generate temporary file names", "text": "module-getopt.html | allos.html | module-errno.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.13 tempfile --\nGenerate temporary file names\nThis module generates temporary file names. It is not Unix specific,\nbut it may require some help on non-Unix systems.\nNote: the modules does not create temporary files, nor does it\nautomatically remove them when the current process exits or dies.\nThe module defines a single user-callable function:\nThe module uses two global variables that tell it how to construct a\ntemporary name. The caller may assign values to them; by default they\nare initialized at the first call to mktemp().", "python_version": "1.6", "length": 649, "url": "https://docs.python.org/1.6/lib/module-tempfile.html"} {"title": "8.8 termios -- POSIX style tty control", "text": "module-gdbm.html | unix.html | termios_Example.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.8 termios --\nPOSIX style tty control\nAvailability: Unix.\nThis module provides an interface to the POSIX calls for tty I/O\ncontrol. For a complete description of these calls, see the POSIX or\nUnix manual pages. It is only available for those Unix versions\nthat support POSIX termios style tty I/O control (and then\nonly if configured at installation time).\nAll functions in this module take a file descriptor fd as their\nfirst argument. This must be an integer file descriptor, such as\nreturned by `sys.stdin.fileno()`.\nThis module should be used in conjunction with the\nTERMIOS (module-TERMIOSuppercase.html) module,\nwhich defines the relevant symbolic constants (see the next section).\nThe module defines the following functions:\nSee Also:", "python_version": "1.6", "length": 859, "url": "https://docs.python.org/1.6/lib/module-termios.html"} {"title": "8.9 TERMIOS -- Constants used with the termios module", "text": "termios_Example.html | unix.html | module-tty.html | Python Library Reference | contents.html | genindex.html\n---\n# 8.9 TERMIOS --\nConstants used with the termios module\nAvailability: Unix.\nThis module defines the symbolic constants required to use the\ntermios (module-termios.html) module (see the previous\nsection). See the POSIX or Unix manual pages (or the source)\nfor a list of those constants.", "python_version": "1.6", "length": 399, "url": "https://docs.python.org/1.6/lib/module-TERMIOSuppercase.html"} {"title": "7.4 thread -- Multiple threads of control", "text": "module-select.html | someos.html | module-threading.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.4 thread --\nMultiple threads of control\nThis module provides low-level primitives for working with multiple\nthreads (a.k.a. light-weight processes or tasks) -- multiple\nthreads of control sharing their global data space. For\nsynchronization, simple locks (a.k.a. mutexes or binary\nsemaphores) are provided.\nThe module is optional. It is supported on Windows NT and '95, SGI\nIRIX, Solaris 2.x, as well as on systems that have a POSIX thread\n(a.k.a. ``pthread'') implementation.\nIt defines the following constant and functions:\nLock objects have the following methods:\nCaveats:", "python_version": "1.6", "length": 699, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 7.5 threading --\nHigher-level threading interface\nThis module constructs higher-level threading interfaces on top of the\nlower level thread (module-thread.html) module.\nThis module is safe for use with \"from threading import *\". It\ndefines the following functions and objects:\nDetailed interfaces for the objects are documented below.\nThe design of this module is loosely based on Java's threading model.\nHowever, where Java makes locks and condition variables basic behavior\nof every object, they are separate objects in Python. Python's Thread\nclass supports a subset of the behavior of Java's Thread class;\ncurrently, there are no priorities, no thread groups, and threads\ncannot be destroyed, stopped, suspended, resumed, or interrupted. The\nstatic methods of Java's Thread class, when implemented, are mapped to\nmodule-level functions.\nAll of the methods described below are executed atomically.", "python_version": "1.6", "length": 1018, "url": "https://docs.python.org/1.6/lib/module-threading.html"} {"title": "6.8 time -- Time access and conversions", "text": "module-filecmp.html | allos.html | module-sched.html | Python Library Reference | contents.html | genindex.html\n---\n# 6.8 time --\nTime access and conversions\nThis module provides various time-related functions.\nIt is always available, but not all functions are available\non all platforms.\nAn explanation of some terminology and conventions is in order.\n- The epoch is the point where the time starts. On\nJanuary 1st of that year, at 0 hours, the ``time since the epoch'' is\nzero. For Unix, the epoch is 1970. To find out what the epoch is,\nlook at `gmtime(0)`.\n- The functions in this module do not handle dates and times before the\nepoch or far in the future. The cut-off point in the future is\ndetermined by the C library; for Unix, it is typically in\n2038.\n- Year 2000 (Y2K) issues: Python\ndepends on the platform's C library, which generally doesn't have year\n2000 issues, since all dates and times are represented internally as\nseconds since the epoch. Functions accepting a time tuple (see below)\ngenerally require a 4-digit year. For backward compatibility, 2-digit\nyears are supported if the module variable `accept2dyear` is a\nnon-zero integer; this variable is initialized to `1` unless the\nenvironment variable $PYTHONY2K is set to a non-empty string,\nin which case it is initialized to `0`. Thus, you can set\n$PYTHONY2K 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- UTC is Coordinated Universal Time (formerly known as Greenwich Mean\nTime, or GMT). The acronym UTC is not a\nmistake but a compromise between English and French.\n- DST is Daylight Saving Time, an adjustment\nof the timezone by (usually) one hour during part of the year. DST\nrules are magic (determined by local law) and can change from year to\nyear. The C library has a table containing the local rules (often it\nis read from a system file for flexibility) and is the only source of\nTrue Wisdom in this respect.\n- The precision of the various real-time functions may be less than\nsuggested by the units in which their value or argument is expressed.\nE.g. on most Unix systems, the clock ``ticks'' only 50 or 100 times a\nsecond, and on the Mac, times are only accurate to whole seconds.\n- On the other hand, the precision of time() and\nsleep() is better than their Unix equivalents: times are\nexpressed as floating point numbers, time() returns the\nmost accurate time available (using Unix gettimeofday()\nwhere available), and sleep() will accept a time with a\nnonzero fraction (Unix select() is used to implement\nthis, where available).\n- The time tuple as returned by gmtime(),\nlocaltime(), and strptime(), and accepted by\nasctime(), mktime() and strftime(),\nis a tuple of 9 integers:\nNote that unlike the C structure, the month value is a\nrange of 1-12, not 0-11. A year value will be handled as described\nunder ``Year 2000 (Y2K) issues'' above. A `-1` argument as\ndaylight savings flag, passed to mktime() will usually\nresult in the correct daylight savings state to be filled in.\nThe module defines the following functions and data items:", "python_version": "1.6", "length": 3409, "url": "https://docs.python.org/1.6/lib/module-time.html"} {"title": "3.18 token -- Constants used with Python parse trees", "text": "module-symbol.html | python.html | module-keyword.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.18 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 defintions\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": "1.6", "length": 634, "url": "https://docs.python.org/1.6/lib/module-token.html"} {"title": "3.20 tokenize -- Tokenizer for Python source", "text": "module-keyword.html | python.html | module-tabnanny.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.20 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 scanner is exposed by a single function:\nAll constants from the token (module-token.html) module are also exported from\ntokenize, as is one additional token type value that might be\npassed to the tokeneater function by tokenize():", "python_version": "1.6", "length": 658, "url": "https://docs.python.org/1.6/lib/module-tokenize.html"} {"title": "3.7 traceback -- Print or retrieve a stack traceback", "text": "module-operator.html | python.html | traceback-example.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.7 traceback --\nPrint or retrieve a stack traceback\nThis module provides a standard interface to extract, format and print\nstack traces of Python programs. It exactly mimics the behavior of\nthe Python interpreter when it prints a stack trace. This is useful\nwhen you want to print stack traces under program control, e.g. in a\n``wrapper'' around the interpreter.\nThe module uses traceback objects -- this is the object type\nthat is stored in the variables `sys.exc_traceback` and\n`sys.last_traceback` and returned as the third item from\nsys.exc_info().\nThe module defines the following functions:", "python_version": "1.6", "length": 722, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n# 8.10 tty --\nTerminal control functions\nAvailability: Unix.\nThe tty module defines functions for putting the tty into\ncbreak and raw modes.\nBecause it requires the termios (module-termios.html) module, it will work\nonly on Unix.\nThe tty module defines the following functions:", "python_version": "1.6", "length": 399, "url": "https://docs.python.org/1.6/lib/module-tty.html"} {"title": "3.2 types -- Names for all built-in types", "text": "module-sys.html | python.html | module-UserDict.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.2 types --\nNames for all built-in types\nThis module defines names for all object types that are used by the\nstandard Python interpreter, but not for the types defined by various\nextension modules. It is safe to use \"from types import *\" --\nthe module does not export any names besides the ones listed here.\nNew names exported by future versions of this module will all end in\n\"Type\".\nTypical use is for functions that do different things depending on\ntheir argument types, like the following:\n```text\n\nfrom types import *\ndef delete(list, item):\nif type(item) is IntType:\ndel list[item]\nelse:\nlist.remove(item)\n```\nThe module defines the following names:", "python_version": "1.6", "length": 774, "url": "https://docs.python.org/1.6/lib/module-types.html"} {"title": "11.2 urllib -- Open an arbitrary resource by URL", "text": "node232.html | internet.html | urlopener-objs.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.2 urllib --\nOpen an arbitrary resource by URL\nThis module provides a high-level interface for fetching data across\nthe World-Wide Web. In particular, the urlopen() function\nis similar to the built-in function open(), but accepts\nUniversal Resource Locators (URLs) instead of filenames. Some\nrestrictions apply -- it can only open URLs for reading, and no seek\noperations are available.\nIt defines the following public functions:\nThe public functions urlopen() and urlretrieve()\ncreate an instance of the FancyURLopener class and use it to perform\ntheir requested actions. To override this functionality, programmers can\ncreate a subclass of URLopener or FancyURLopener, then\nassign that class to the urllib._urlopener variable before calling the\ndesired function. For example, applications may want to specify a different\n`user-agent` header than URLopener defines. This can be\naccomplished with the following code:\n```text\n\nclass AppURLopener(urllib.FancyURLopener):\ndef __init__(self, *args):\napply(urllib.FancyURLopener.__init__, (self,) + args)\nself.version = \"App/1.7\"\n\nurllib._urlopener = AppURLopener\n```\nRestrictions:\n- Currently, only the following protocols are supported: HTTP, (versions\n0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.\n- The caching feature of urlretrieve() has been disabled\nuntil I find the time to hack proper processing of Expiration time\nheaders.\n- There should be a function to query whether a particular URL is in\nthe cache.\n- For backward compatibility, if a URL appears to point to a local file\nbut the file can't be opened, the URL is re-interpreted using the FTP\nprotocol. This can sometimes cause confusing error messages.\n- The urlopen() and urlretrieve() functions can\ncause arbitrarily long delays while waiting for a network connection\nto be set up. This means that it is difficult to build an interactive\nweb client using these functions without using threads.\n- The data returned by urlopen() or urlretrieve()\nis the raw data returned by the server. This may be binary data\n(e.g. an image), plain text or (for example) HTML. The\nHTTP protocol provides type information in the\nreply header, which can be inspected by looking at the\n`content-type` header. For the Gopher\nprotocol, type information is encoded in the URL; there is currently\nno easy way to extract it. If the returned data is HTML, you can use\nthe module htmllib (module-htmllib.html) to parse it.\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": "1.6", "length": 2729, "url": "https://docs.python.org/1.6/lib/module-urllib.html"} {"title": "11.11 urlparse -- Parse URLs into components.", "text": "telnet-example.html | internet.html | module-SocketServer.html | Python Library Reference | contents.html | genindex.html\n---\n# 11.11 urlparse --\nParse URLs into components.\nThis module defines a standard interface to break URL strings up in\ncomponents (addessing scheme, network location, path etc.), to combine\nthe components back into a URL string, and to convert a ``relative\nURL'' to an absolute URL given a ``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!). Refer to RFC 1808 (http://www.ietf.org/rfc/rfc1808.txt) for details on relative\nURLs and RFC 1738 (http://www.ietf.org/rfc/rfc1738.txt) for information on basic URL syntax.\nIt defines the following functions:", "python_version": "1.6", "length": 773, "url": "https://docs.python.org/1.6/lib/module-urlparse.html"} {"title": "3.32 user -- User-specific configuration hook", "text": "module-site.html | python.html | module-builtin.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.32 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, exececutes it (using\nexecfile()) in its own (i.e. 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": "1.6", "length": 2279, "url": "https://docs.python.org/1.6/lib/module-user.html"} {"title": "3.3 UserDict -- Class wrapper for dictionary objects", "text": "module-types.html | python.html | module-UserList.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.3 UserDict --\nClass wrapper for dictionary objects\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 behaviours to dictionaries.\nThe UserDict module defines the UserDict class:\nIn addition to supporting the methods and operations of mappings (see\nsection 2.1.6 (typesmapping.html#typesmapping)), UserDict instances provide the\nfollowing attribute:", "python_version": "1.6", "length": 664, "url": "https://docs.python.org/1.6/lib/module-UserDict.html"} {"title": "3.4 UserList -- Class wrapper for list objects", "text": "module-UserDict.html | python.html | module-UserString.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.4 UserList --\nClass wrapper for list objects\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 behaviours to lists.\nThe UserList module defines the UserList class:\nIn addition to supporting the methods and operations of mutable\nsequences (see section 2.1.5 (typesseq.html#typesseq)), UserList instances\nprovide the following attribute:", "python_version": "1.6", "length": 645, "url": "https://docs.python.org/1.6/lib/module-UserList.html"} {"title": "3.5 UserString -- Class wrapper for string objects", "text": "module-UserList.html | python.html | module-operator.html | Python Library Reference | contents.html | genindex.html\n---\n# 3.5 UserString --\nClass wrapper for string objects\nThis module defines a class that acts as a wrapper around\nstring objects. It is a useful base class for\nyour own string-like classes, which can inherit from\nthem and override existing methods or add new ones. In this way one\ncan add new behaviours to strings.\nThe UserString module defines the UserString class:\nIn addition to supporting the methods and operations of string or\nUnicode objects (see section 2.1.5 (typesseq.html#typesseq)), UserString instances\nprovide the following attribute:", "python_version": "1.6", "length": 667, "url": "https://docs.python.org/1.6/lib/module-UserString.html"} {"title": "12.11 uu -- Encode and decode uuencode files", "text": "binhex-notes.html | netdata.html | module-binascii.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.11 uu --\nEncode and decode uuencode files\nThis module encodes and decodes files in uuencode format, allowing\narbitrary binary data to be transferred over ascii-only connections.\nWherever a file argument is expected, the methods accept a file-like\nobject. For backwards compatibility, a string containing a pathname\nis also accepted, and the corresponding file will be opened for\nreading and writing; the pathname `'-'` is understood to mean the\nstandard input or output. However, this interface is deprecated; it's\nbetter for the caller to open the file itself, and be sure that, when\nrequired, the mode is `'rb'` or `'wb'` on Windows or DOS.\nThis code was contributed by Lance Ellinghouse, and modified by Jack\nJansen.\nThe uu module defines the following functions:", "python_version": "1.6", "length": 890, "url": "https://docs.python.org/1.6/lib/module-uu.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 | genindex.html\n---\n# 14.5 wave --\nRead and write WAV files\nThe wave module provides a convenient interface to the WAV sound\nformat. It does not support compression/decompression, but it does support\nmono/stereo.\nThe wave module defines the following function and exception:", "python_version": "1.6", "length": 378, "url": "https://docs.python.org/1.6/lib/module-wave.html"} {"title": "7.10 whichdb -- Guess which DBM module created a database", "text": "dbhash-objects.html | someos.html | module-bsddb.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.10 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": "1.6", "length": 400, "url": "https://docs.python.org/1.6/lib/module-whichdb.html"} {"title": "5.4 whrandom -- Pseudo-random number generator", "text": "rng-objects.html | misc.html | module-bisect.html | Python Library Reference | contents.html | genindex.html\n---\n# 5.4 whrandom --\nPseudo-random number generator\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 5.3.1 (rng-objects.html#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": "1.6", "length": 874, "url": "https://docs.python.org/1.6/lib/module-whrandom.html"} {"title": "18.2 winsound -- Sound-playing interface for Windows", "text": "msvcrt-other.html | node355.html | undoc.html | Python Library Reference | contents.html | genindex.html\n---\n# 18.2 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": "1.6", "length": 361, "url": "https://docs.python.org/1.6/lib/module-winsound.html"} {"title": "12.13 xdrlib -- Encode and decode XDR data.", "text": "module-binascii.html | netdata.html | xdr-packer-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.13 xdrlib --\nEncode and decode XDR data.\nThe xdrlib module supports the External Data Representation\nStandard as described in RFC 1014 (http://www.ietf.org/rfc/rfc1014.txt), 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.", "python_version": "1.6", "length": 584, "url": "https://docs.python.org/1.6/lib/module-xdrlib.html"} {"title": "12.4 xmllib -- A parser for XML documents", "text": "module-htmlentitydefs.html | netdata.html | xml-namespace.html | Python Library Reference | contents.html | genindex.html\n---\n# 12.4 xmllib --\nA parser for XML documents\nChanged in version 1.5.2:\n.\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:\nThe XML specification, published by the World Wide Web\nConsortium (W3C), is available online at\nhttp://www.w3.org/TR/REC-xml. References to\nadditional material on XML are available at\nhttp://www.w3.org/XML/.\nThe Python XML Topic Guide provides a great deal of information\non using XML from Python and links to other sources of information\non XML. It's located on the Web at\nhttp://www.python.org/topics/xml/.\nThe Python XML Special Interest Group is developing substantial\nsupport for processing XML from Python. See\nhttp://www.python.org/sigs/xml-sig/ for more information.\n---\n#### Footnotes", "python_version": "1.6", "length": 1011, "url": "https://docs.python.org/1.6/lib/module-xmllib.html"} {"title": "7.12 zlib -- Compression compatible with gzip", "text": "bsddb-objects.html | someos.html | module-gzip.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.12 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.cdrom.com/pub/infozip/zlib/. Version 1.1.3 is the\nmost recent version as of April 1999; 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 a single attribute:", "python_version": "1.6", "length": 770, "url": "https://docs.python.org/1.6/lib/module-zlib.html"} {"title": "18.1.2 Console I/O", "text": "msvcrt-files.html | module-msvcrt.html | msvcrt-other.html | Python Library Reference | contents.html | genindex.html\n---\n## 18.1.2 Console I/O", "python_version": "1.6", "length": 143, "url": "https://docs.python.org/1.6/lib/msvcrt-console.html"} {"title": "18.1.1 File Operations", "text": "module-msvcrt.html | module-msvcrt.html | msvcrt-console.html | Python Library Reference | contents.html | genindex.html\n---\n## 18.1.1 File Operations", "python_version": "1.6", "length": 150, "url": "https://docs.python.org/1.6/lib/msvcrt-files.html"} {"title": "18.1.3 Other Functions", "text": "msvcrt-console.html | module-msvcrt.html | module-winsound.html | Python Library Reference | contents.html | genindex.html\n---\n## 18.1.3 Other Functions", "python_version": "1.6", "length": 152, "url": "https://docs.python.org/1.6/lib/msvcrt-other.html"} {"title": "12.9.2 MultiFile Example", "text": "MultiFile-objects.html | module-multifile.html | module-binhex.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.9.2 MultiFile Example", "python_version": "1.6", "length": 158, "url": "https://docs.python.org/1.6/lib/multifile-example.html"} {"title": "12.9.1 MultiFile Objects", "text": "module-multifile.html | module-multifile.html | multifile-example.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.9.1 MultiFile Objects\nA MultiFile instance has the following methods:\nFinally, MultiFile instances have two public instance variables:", "python_version": "1.6", "length": 274, "url": "https://docs.python.org/1.6/lib/MultiFile-objects.html"} {"title": "6.19.1 Mutex Objects", "text": "module-mutex.html | module-mutex.html | someos.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.19.1 Mutex Objects\nmutex objects have following methods:", "python_version": "1.6", "length": 176, "url": "https://docs.python.org/1.6/lib/mutex-objects.html"} {"title": "12. Internet Data Handling", "text": "asyncore-example.html | lib.html | module-sgmllib.html | Python Library Reference | contents.html | genindex.html\n---\n# 12. Internet Data Handling\nThis chapter describes modules which support handling data formats\ncommonly used on the internet. Some, like SGML and XML, may be useful\nfor other applications as well.", "python_version": "1.6", "length": 315, "url": "https://docs.python.org/1.6/lib/netdata.html"} {"title": "12.21.1 netrc Objects", "text": "module-netrc.html | module-netrc.html | module-robotparser.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.21.1 netrc Objects\nA netrc instance has the following methods:\nInstances of netrc have public instance variables:", "python_version": "1.6", "length": 246, "url": "https://docs.python.org/1.6/lib/netrc-objects.html"} {"title": "11.8.1 NNTP Objects", "text": "module-nntplib.html | module-nntplib.html | module-smtplib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.8.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": "1.6", "length": 444, "url": "https://docs.python.org/1.6/lib/nntp-objects.html"} {"title": "6.18.1 Background, details, hints, tips and caveats", "text": "module-locale.html | module-locale.html | embedding-locale.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.18.1 Background, details, hints, tips and caveats\nThe C standard defines the locale as a program-wide property that may\nbe relatively expensive to change. On top of that, some\nimplementation are broken in such a way that frequent locale changes\nmay cause core dumps. This makes the locale somewhat painful to use\ncorrectly.\nInitially, when a program is started, the locale is the \"C\" locale, no\nmatter what the user's preferred locale is. The program must\nexplicitly say that it wants the user's preferred locale settings by\ncalling `setlocale(LC_ALL, \"\")`.\nIt is generally a bad idea to call setlocale() in some library\nroutine, since as a side effect it affects the entire program. Saving\nand restoring it is almost as bad: it is expensive and affects other\nthreads that happen to run before the settings have been restored.\nIf, when coding a module for general use, you need a locale\nindependent version of an operation that is affected by the locale\n(e.g. string.lower(), or certain formats used with\ntime.strftime())), you will have to find a way to do it\nwithout using the standard library routine. Even better is convincing\nyourself that using locale settings is okay. Only as a last resort\nshould you document that your module is not compatible with\nnon-\"C\" locale settings.\nThe case conversion functions in the\nstring (module-string.html) and\nstrop modules are affected by the locale\nsettings. When a call to the setlocale() function changes\nthe LC_CTYPE settings, the variables\n`string.lowercase`, `string.uppercase` and\n`string.letters` (and their counterparts in strop) are\nrecalculated. Note that this code that uses these variable through\n`from ... import ...', e.g. `from string\nimport letters`, is not affected by subsequent setlocale()\ncalls.\nThe only way to perform numeric operations according to the locale\nis to use the special functions defined by this module:\natof(), atoi(), format(),\nstr().", "python_version": "1.6", "length": 2047, "url": "https://docs.python.org/1.6/lib/node145.html"} {"title": "7.14 zipfile -- Work with ZIP archives", "text": "module-gzip.html | someos.html | zipfile-objects.html | Python Library Reference | contents.html | genindex.html\n---\n# 7.14 zipfile --\nWork with ZIP archives\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.\nThe available attributes of this module are:\nSee Also:\nXXX point to ZIP format definition\nXXX point to Info-ZIP home page; mention WiZ", "python_version": "1.6", "length": 438, "url": "https://docs.python.org/1.6/lib/node175.html"} {"title": "8.15.1 Resource Limits", "text": "module-resource.html | module-resource.html | node201.html | Python Library Reference | contents.html | genindex.html\n---\n## 8.15.1 Resource Limits\nResources usage can be limited using the setrlimit() function\ndescribed below. Each resource is controlled by a pair of limits: a\nsoft limit and a hard limit. The soft limit is the current limit, and\nmay be lowered or raised by a process over time. The soft limit can\nnever exceed the hard limit. The hard limit can be lowered to any\nvalue greater than the soft limit, but not raised. (Only processes with\nthe effective UID of the super-user can raise a hard limit.)\nThe specific resources that can be limited are system dependent. They\nare described in the getrlimit(2) man page. The resources\nlisted below are supported when the underlying operating system\nsupports them; resources which cannot be checked or controlled by the\noperating system are not defined in this module for those platforms.\nThese symbols define resources whose consumption can be controlled\nusing the setrlimit() and getrlimit() functions\ndescribed below. The values of these symbols are exactly the constants\nused by C programs.\nThe Unix man page for getrlimit(2) lists the available\nresources. Note that not all systems use the same symbol or same\nvalue to denote the same resource.", "python_version": "1.6", "length": 1306, "url": "https://docs.python.org/1.6/lib/node200.html"} {"title": "8.15.2 Resource Usage", "text": "node200.html | module-resource.html | module-nis.html | Python Library Reference | contents.html | genindex.html\n---\n## 8.15.2 Resource Usage\nThese functiona are used to retrieve resource usage information:\nThe following RUSAGE_* symbols are passed to the\ngetrusage() function to specify which processes information\nshould be provided for.", "python_version": "1.6", "length": 339, "url": "https://docs.python.org/1.6/lib/node201.html"} {"title": "9.2 How It Works", "text": "debugger-commands.html | module-pdb.html | profile.html | Python Library Reference | contents.html | genindex.html\n---\n# 9.2 How It Works\nSome changes were made to the interpreter:\n- `sys.settrace( func )` sets the global trace function\n- there can also a local trace function (see later)\nTrace functions have three arguments: frame, event, and\narg. frame is the current stack frame. event is a\nstring: `'call'`, `'line'`, `'return'` or\n`'exception'`. arg depends on the event type.\nThe global trace function is invoked (with event set to\n`'call'`) whenever a new local scope is entered; it should return\na reference to the local trace function to be used that scope, or\n`None` if the scope shouldn't be traced.\nThe local trace function should return a reference to itself (or to\nanother function for further tracing in that scope), or `None` to\nturn off tracing in that scope.\nInstance methods are accepted (and very useful!) as trace functions.\nThe events have the following meaning:\n`'call'`: A function is called (or some other code block entered). The global\ntrace function is called; arg is the argument list to the function;\nthe return value specifies the local trace function.\n`'line'`: The interpreter is about to execute a new line of code (sometimes\nmultiple line events on one line exist). The local trace function is\ncalled; arg in None; the return value specifies the new local trace\nfunction.\n`'return'`: A function (or other code block) is about to return. The local trace\nfunction is called; arg is the value that will be returned. The trace\nfunction's return value is ignored.\n`'exception'`: An exception has occurred. The local trace function is called; arg is\na triple (exception, value, traceback); the return value specifies the\nnew local trace function\nNote that as an exception is propagated down the chain of callers, an\n`'exception'` event is generated at each level.\nFor more information on code and frame objects, refer to the\nPython Reference Manual (../ref/ref.html).", "python_version": "1.6", "length": 1997, "url": "https://docs.python.org/1.6/lib/node209.html"} {"title": "11.1.3 Old classes", "text": "Using_the_cgi_module.html | module-cgi.html | Functions_in_cgi_module.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.3 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": "1.6", "length": 865, "url": "https://docs.python.org/1.6/lib/node226.html"} {"title": "11.1.5 Caring about security", "text": "Functions_in_cgi_module.html | module-cgi.html | node229.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.5 Caring about security\nThere's one important rule: if you invoke an external program (e.g.\nvia the os.system() or os.popen() functions),\nmake very sure you don't pass arbitrary strings received from the\nclient to the shell. This is a well-known security hole whereby\nclever hackers anywhere on the web can exploit a gullible CGI script\nto invoke arbitrary shell commands. Even parts of the URL or field\nnames cannot be trusted, since the request doesn't have to come from\nyour form!\nTo be on the safe side, if you must pass a string gotten from a form\nto a shell command, you should make sure the string contains only\nalphanumeric characters, dashes, underscores, and periods.", "python_version": "1.6", "length": 810, "url": "https://docs.python.org/1.6/lib/node228.html"} {"title": "11.1.6 Installing your CGI script on a Unix system", "text": "node228.html | module-cgi.html | node230.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.6 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 at login. 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, e.g.:\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": "1.6", "length": 1997, "url": "https://docs.python.org/1.6/lib/node229.html"} {"title": "11.1.7 Testing your CGI script", "text": "node229.html | module-cgi.html | node231.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.7 Testing your CGI script\nUnfortunately, a CGI script will generally not run when you try it\nfrom the command line, and a script that works perfectly from the\ncommand line may fail mysteriously when run from the server. There's\none reason why you should still test your script from the command\nline: if it contains a syntax error, the Python interpreter won't\nexecute it at all, and the HTTP server will most likely send a cryptic\nerror to the client.\nAssuming your script has no syntax errors, yet it does not work, you\nhave no choice but to read the next section.", "python_version": "1.6", "length": 682, "url": "https://docs.python.org/1.6/lib/node230.html"} {"title": "11.1.8 Debugging CGI scripts", "text": "node230.html | module-cgi.html | node232.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.8 Debugging CGI scripts\nFirst of all, check for trivial installation errors -- reading the\nsection above on installing your CGI script carefully can save you a\nlot of time. If you wonder whether you have understood the\ninstallation procedure correctly, try installing a copy of this module\nfile (cgi.py) as a CGI script. When invoked as a script, the file\nwill dump its environment and the contents of the form in HTML form.\nGive it the right mode etc, and send it a request. If it's installed\nin the standard cgi-bin directory, it should be possible to send it a\nrequest by entering a URL into your browser of the form:\n```text\n\nhttp://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home\n```\nIf this gives an error of type 404, the server cannot find the script\n- perhaps you need to install it in a different directory. If it\ngives another error (e.g. 500), there's an installation problem that\nyou should fix before trying to go any further. If you get a nicely\nformatted listing of the environment and form content (in this\nexample, the fields should be listed as ``addr'' with value ``At Home''\nand ``name'' with value ``Joe Blow''), the cgi.py script has been\ninstalled correctly. If you follow the same procedure for your own\nscript, you should now be able to debug it.\nThe next step could be to call the cgi module's\ntest() function from your script: replace its main code\nwith the single statement\n```text\n\ncgi.test()\n```\nThis should produce the same results as those gotten from installing\nthe cgi.py file itself.\nWhen an ordinary Python script raises an unhandled exception\n(e.g. because of a typo in a module name, a file that can't be opened,\netc.), the Python interpreter prints a nice traceback and exits.\nWhile the Python interpreter will still do this when your CGI script\nraises an exception, most likely the traceback will end up in one of\nthe HTTP server's log file, or be discarded altogether.\nFortunately, once you have managed to get your script to execute\nsome code, it is easy to catch exceptions and cause a traceback\nto be printed. The test() function below in this module is\nan example. Here are the rules:\n1. Import the traceback module before entering the try\n... except statement\n2. Assign `sys.stderr` to be `sys.stdout`\n3. Make sure you finish printing the headers and the blank line\nearly\n4. Wrap all remaining code in a try ... except\nstatement\n5. In the except clause, call traceback.print_exc()\nFor example:\n```text\n\nimport sys\nimport traceback\nprint \"Content-type: text/html\"\nprint\nsys.stderr = sys.stdout\ntry:\n...your code here...\nexcept:\nprint \"\\n\\n

\"\ntraceback.print_exc()\n```\nNotes: The assignment to `sys.stderr` is needed because the\ntraceback prints to `sys.stderr`.\nThe `print \"\\n\\n
\"` statement is necessary to\ndisable the word wrapping in HTML.\nIf you suspect that there may be a problem in importing the traceback\nmodule, you can use an even more robust approach (which only uses\nbuilt-in modules):\n```text\n\nimport sys\nsys.stderr = sys.stdout\nprint \"Content-type: text/plain\"\nprint\n...your code here...\n```\nThis relies on the Python interpreter to print the traceback. The\ncontent type of the output is set to plain text, which disables all\nHTML processing. If your script works, the raw HTML will be displayed\nby your client. If it raises an exception, most likely after the\nfirst two lines have been printed, a traceback will be displayed.\nBecause no HTML interpretation is going on, the traceback will\nreadable.", "python_version": "1.6", "length": 3591, "url": "https://docs.python.org/1.6/lib/node231.html"}
{"title": "11.1.9 Common problems and solutions", "text": "node231.html | module-cgi.html | module-urllib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.9 Common problems and solutions", "python_version": "1.6", "length": 154, "url": "https://docs.python.org/1.6/lib/node232.html"}
{"title": "11.3.1 HTTP Objects", "text": "module-httplib.html | module-httplib.html | HTTP_Example.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.3.1 HTTP Objects\nHTTP instances have the following methods:", "python_version": "1.6", "length": 190, "url": "https://docs.python.org/1.6/lib/node237.html"}
{"title": "13.1.1 An example", "text": "module-rexec.html | module-rexec.html | module-Bastion.html | Python Library Reference | contents.html | genindex.html\n---\n## 13.1.1 An example\nLet us say that we want a slightly more relaxed policy than the\nstandard RExec class. For example, if we're willing to allow\nfiles in /tmp to be written, we can subclass the RExec\nclass:", "python_version": "1.6", "length": 330, "url": "https://docs.python.org/1.6/lib/node309.html"}
{"title": "18. MS Windows Specific Services", "text": "module-sunaudiodev-constants.html | lib.html | module-msvcrt.html | Python Library Reference | contents.html | genindex.html\n---\n# 18. MS Windows Specific Services\nThis chapter describes modules that are only available on MS Windows\nplatforms.", "python_version": "1.6", "length": 243, "url": "https://docs.python.org/1.6/lib/node355.html"}
{"title": "19.1 Frameworks", "text": "undoc.html | undoc.html | node363.html | Python Library Reference | contents.html | genindex.html\n---\n# 19.1 Frameworks\nFrameworks tend to be harder to document, but are well worth the\neffort spent.\nTkinter: -- Interface to Tcl/Tk for graphical user interfaces; Fredrik Lundh\nis working on this one! See\nAn Introduction to\nTkinter (http://www.pythonware.com/library.htm) at http://www.pythonware.com/library.htm for on-line\nreference material.\nTkdnd: -- Drag-and-drop support for Tkinter.\nturtle: -- Turtle graphics in a Tk window.\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 module.", "python_version": "1.6", "length": 705, "url": "https://docs.python.org/1.6/lib/node362.html"}
{"title": "19.2 Miscellaneous useful utilities", "text": "node362.html | undoc.html | node364.html | Python Library Reference | contents.html | genindex.html\n---\n# 19.2 Miscellaneous useful utilities\nSome of these are very old and/or not very robust; marked with ``hmm.''\ndircmp: -- Class to build directory diff tools on (may become a demo or tool).\nDeprecated since release 1.6.\nThe filecmp (module-filecmp.html) module will replace\ndircmp.\nbdb: -- A generic Python debugger base class (used by pdb)\nihooks: -- Import hook support (for rexec (module-rexec.html); may become obsolete)\ntzparse: -- Parse a timezone specification (unfinished; may disappear in the\nfuture)", "python_version": "1.6", "length": 612, "url": "https://docs.python.org/1.6/lib/node363.html"}
{"title": "19.3 Platform specific modules", "text": "node363.html | undoc.html | node365.html | Python Library Reference | contents.html | genindex.html\n---\n# 19.3 Platform specific modules\nThese modules are used to implement the os.path (module-os.path.html) module,\nand are not documented beyond this mention. There's little need to\ndocument these.\ndospath: -- implementation of os.path on MS-DOS\nntpath: -- implementation on os.path on 32-bit Windows\nposixpath: -- implementation on os.path on POSIX", "python_version": "1.6", "length": 449, "url": "https://docs.python.org/1.6/lib/node364.html"}
{"title": "19.4 Multimedia", "text": "node364.html | undoc.html | obsolete-modules.html | Python Library Reference | contents.html | genindex.html\n---\n# 19.4 Multimedia\naudiodev: -- Platform-independent API for playing audio data\nsunaudio: -- Interpret Sun audio headers (may become obsolete or a tool/demo)\ntoaiff: -- Convert \"arbitrary\" sound files to AIFF files; should probably\nbecome a tool or demo. Requires the external program sox.", "python_version": "1.6", "length": 401, "url": "https://docs.python.org/1.6/lib/node365.html"}
{"title": "19.6 Extension modules", "text": "obsolete-modules.html | undoc.html | modindex.html | Python Library Reference | contents.html | genindex.html\n---\n# 19.6 Extension modules\nstdwin: -- Interface to STDWIN (an old, unsupported\nplatform-independent GUI package). Obsolete; use Tkinter for\na platform-independent GUI instead.\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": "1.6", "length": 511, "url": "https://docs.python.org/1.6/lib/node367.html"}
{"title": "3.16.6.1 Emulation of compile()", "text": "AST_Examples.html | AST_Examples.html | node56.html | Python Library Reference | contents.html | genindex.html\n---\n### 3.16.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": "1.6", "length": 1072, "url": "https://docs.python.org/1.6/lib/node55.html"}
{"title": "3.16.6.2 Information Discovery", "text": "node55.html | AST_Examples.html | module-symbol.html | Python Library Reference | contents.html | genindex.html\n---\n### 3.16.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\ndocstrings without\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.\\012\"\"\"'))))))))))))))))),\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.\\012\"\"\"'}\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 overriden 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 repesentation 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": "1.6", "length": 13272, "url": "https://docs.python.org/1.6/lib/node56.html"}
{"title": "4.3.1 Regular Expressions", "text": "module-regex.html | module-regex.html | Contents_of_Module_regex.html | Python Library Reference | contents.html | genindex.html\n---\n## 4.3.1 Regular Expressions\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 an regular expression. If a string p\nmatches A and another string q matches B, the string pq\nwill match AB. Thus, complex expressions can easily be constructed\nfrom simpler ones like the primitives described here. For details of\nthe theory and implementation of regular expressions, consult almost\nany textbook about compiler construction.\nA brief explanation of the format of regular expressions follows.\nRegular expressions can contain both special and ordinary characters.\nOrdinary characters, like '`A`', '`a`', or '`0`', are\nthe simplest regular expressions; they simply match themselves. You\ncan concatenate ordinary characters, so '`last`' matches the\ncharacters 'last'. (In the rest of this section, we'll write RE's in\n`this special font`, usually without quotes, and strings to be\nmatched 'in single quotes'.)\nSpecial characters either stand for classes of ordinary characters, or\naffect how the regular expressions around them are interpreted.\nThe special characters are:\n`.`: (Dot.) Matches any character except a newline.\n`^`: (Caret.) Matches the start of the string.\n`$`: Matches the end of the string.\n`foo` matches both 'foo' and 'foobar', while the regular\nexpression '`foo$`' matches only 'foo'.\n`*`: Causes the resulting RE to\nmatch 0 or more repetitions of the preceding RE. `ab*` will\nmatch 'a', 'ab', or 'a' followed by any number of 'b's.\n`+`: Causes the\nresulting RE to match 1 or more repetitions of the preceding RE.\n`ab+` will match 'a' followed by any non-zero number of 'b's; it\nwill not match just 'a'.\n`?`: Causes the resulting RE to\nmatch 0 or 1 repetitions of the preceding RE. `ab?` will\nmatch either 'a' or 'ab'.\n`\\`: Either escapes special characters (permitting you to match\ncharacters like '*?+&$'), or signals a special sequence; special\nsequences are discussed below. Remember that Python also uses the\nbackslash as an escape sequence in string literals; if the escape\nsequence isn't recognized by Python's parser, the backslash and\nsubsequent character are included in the resulting string. However,\nif Python would recognize the resulting sequence, the backslash should\nbe repeated twice.\n`[]`: Used to indicate a set of characters. Characters can\nbe listed individually, or a range is indicated by giving two\ncharacters and separating them by a '-'. Special characters are\nnot active inside sets. For example, `[akm$]`will match any of the characters 'a', 'k', 'm', or '$'; `[a-z]` will\nmatch any lowercase letter.\nIf you want to include a `]` inside a\nset, it must be the first character of the set; to include a `-`,\nplace it as the first or last character.\nCharacters not within a range can be matched by including a\n`^` as the first character of the set; `^` elsewhere will\nsimply match the '`^`' character.\nThe special sequences consist of '`\\`' and a character\nfrom the list below. If the ordinary character is not on the list,\nthen the resulting RE will match the second character. For example,\n`\\$` matches the character '$'. Ones where the backslash\nshould be doubled in string literals are indicated.\n`\\|`: `A\\|B`, where A and B can be arbitrary REs,\ncreates a regular expression that will match either A or B. This can\nbe used inside groups (see below) as well.\n`\\( \\)`: Indicates the start and end of a group; the\ncontents of a group can be matched later in the string with the\n`\\[1-9]` special sequence, described next.\n`\\\\1, ... \\\\7, \\8, \\9`: Matches the contents of the group of the same\nnumber. For example, `\\(.+\\) \\\\1` matches 'the the' or\n'55 55', but not 'the end' (note the space after the group). This\nspecial sequence can only be used to match one of the first 9 groups;\ngroups with higher numbers can be matched using the `\\v`sequence. (`\\8` and `\\9` don't need a double backslash\nbecause they are not octal digits.)\n`\\\\b`: Matches the empty string, but only at the\nbeginning or end of a word. A word is defined as a sequence of\nalphanumeric characters, so the end of a word is indicated by\nwhitespace or a non-alphanumeric character.\n`\\B`: Matches the empty string, but when it is not at the\nbeginning or end of a word.\n`\\v`: Must be followed by a two digit decimal number, and\nmatches the contents of the group of the same number. The group\nnumber must be between 1 and 99, inclusive.\n`\\w`: Matches any alphanumeric character; this is\nequivalent to the set `[a-zA-Z0-9]`.\n`\\W`: Matches any non-alphanumeric character; this is\nequivalent to the set `[â-zA-Z0-9]`.\n`\\<`: Matches the empty string, but only at the beginning of a\nword. A word is defined as a sequence of alphanumeric characters, so\nthe end of a word is indicated by whitespace or a non-alphanumeric\ncharacter.\n`\\>`: Matches the empty string, but only at the end of a\nword.\n`\\\\\\\\`: Matches a literal backslash.\n`\\``: Like `^`, this only matches at the start of the\nstring.\n`\\\\'`: Like `$`, this only matches at the end of\nthe string.", "python_version": "1.6", "length": 5431, "url": "https://docs.python.org/1.6/lib/node91.html"}
{"title": "19.5 Obsolete", "text": "node365.html | undoc.html | node367.html | Python Library Reference | contents.html | genindex.html\n---\n# 19.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\n$PYTHONPATH.\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\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)\ndump: -- Print python code that reconstructs a variable\nfmt: -- text formatting abstractions (too slow)\nlockfile: -- wrapper around FCNTL file locking (use\nfcntl.lockf()/flock() intead; see fcntl (module-fcntl.html))\nnewdir: -- New dir() function (the standard dir() is\nnow just as good)\nPara: -- helper for fmt.py\npoly: -- Polynomials\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.)\nutil: -- Useful functions that don't fit elsewhere.\nwdb: -- A primitive windowing debugger based on STDWIN.\nwhatsound: -- Recognize sound files; use sndhdr (module-sndhdr.html) instead.\nzmod: -- Compute properties of mathematical \"fields\"\nThe following modules are obsolete, but are likely re-surface as tools\nor scripts.\nfind: -- find files matching pattern in directory tree\ngrep: -- grep\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.\nrand: -- Old interface to the random number generator.\nsoundex: -- Algorithm for collapsing names which sound similar to a shared\nkey. (This is an extension module.)", "python_version": "1.6", "length": 2703, "url": "https://docs.python.org/1.6/lib/obsolete-modules.html"}
{"title": "6.1.3 File Descriptor Operations", "text": "os-newstreams.html | module-os.html | os-file-dir.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.1.3 File Descriptor Operations\nThese functions operate on I/O streams referred to\nusing file descriptors.\nThe following data items are available for use in constructing the\nflags parameter to the open() function.", "python_version": "1.6", "length": 335, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 6.1.4 Files and Directories", "python_version": "1.6", "length": 143, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 6.1.2 File Object Creation\nThese functions create new file objects.", "python_version": "1.6", "length": 184, "url": "https://docs.python.org/1.6/lib/os-newstreams.html"}
{"title": "6.1.6 Miscellanenous System Information", "text": "os-process.html | module-os.html | module-os.path.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.1.6 Miscellanenous 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": "1.6", "length": 364, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 6.1.5 Process Management\nThese functions may be used to create and manage processes.\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": "1.6", "length": 372, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 6.1.1 Process Parameters\nThese functions and data items provide information and operate on the\ncurrent process and user.", "python_version": "1.6", "length": 239, "url": "https://docs.python.org/1.6/lib/os-procinfo.html"}
{"title": "3.9.1 Example", "text": "module-pickle.html | module-pickle.html | module-cPickle.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.9.1 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\n# illustrate __setstate__ and __getstate__ methods\n# used in pickling.\n\nclass TextReader:\n\"Print and number lines in a text file.\"\ndef __init__(self,file):\nself.file = file\nself.fh = open(file,'r')\nself.lineno = 0\n\ndef readline(self):\nself.lineno = self.lineno + 1\nline = self.fh.readline()\nif not line:\nreturn None\nreturn \"%d: %s\" % (self.lineno,line[:-1])\n\n# return data representation for pickled object\ndef __getstate__(self):\nodict = self.__dict__ # get attribute dictionary\ndel odict['fh'] # remove filehandle entry\nreturn odict\n\n# restore object state from data representation generated\n# by __getstate__\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\ndict['fh'] = fh # create filehandle entry\nself.__dict__ = dict # make dict our attribute dictionary\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\n(start another Python session)\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```", "python_version": "1.6", "length": 2012, "url": "https://docs.python.org/1.6/lib/pickle-example.html"}
{"title": "16.3.1 Player Objects", "text": "module-cd.html | module-cd.html | cd-parser-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 16.3.1 Player Objects\nPlayer objects (returned by open()) have the following\nmethods:", "python_version": "1.6", "length": 208, "url": "https://docs.python.org/1.6/lib/player-objects.html"}
{"title": "11.6.2 POP3 Example", "text": "pop3-objects.html | module-poplib.html | module-imaplib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.6.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": "1.6", "length": 469, "url": "https://docs.python.org/1.6/lib/pop3-example.html"}
{"title": "11.6.1 POP3 Objects", "text": "module-poplib.html | module-poplib.html | pop3-example.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.6.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": "1.6", "length": 317, "url": "https://docs.python.org/1.6/lib/pop3-objects.html"}
{"title": "8.18.1 Popen3 Objects", "text": "module-popen2.html | module-popen2.html | module-commands.html | Python Library Reference | contents.html | genindex.html\n---\n## 8.18.1 Popen3 Objects\nInstances of the Popen3 class have the following methods:\nThe following attributes of Popen3 objects are also available:", "python_version": "1.6", "length": 271, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 8.1.2 Module Contents\nModule posix defines the following data item:", "python_version": "1.6", "length": 194, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 8.1.1 Large File Support\nSeveral operating systems (including AIX, HPUX, Irix and Solaris)\nprovide support for files that are larger than 2 Gb from a C\nprogramming model where int and long are 32-bit\nvalues. This is typically accomplished by defining the relevant size\nand offset types as 64-bit values. Such files are sometimes referred\nto as large files.\nLarge file support is enabled in Python when the size of an\noff_t is larger than a long and the long long\ntype is available and is at least as large as an off_t. Python\nlongs are then used to represent file sizes, offsets and other values\nthat can exceed the range of a Python int. It may be necessary to\nconfigure and compile Python with certain compiler flags to enable\nthis mode. For example, it is enabled by default with recent versions\nof Irix, but with Solaris 2.6 and 2.7 you need to do something like:\n```text\n\nCFLAGS=\"`getconf LFS_CFLAGS`\" OPT=\"-g -O2 $CFLAGS\" \\\nconfigure\n```", "python_version": "1.6", "length": 1069, "url": "https://docs.python.org/1.6/lib/posix-large-files.html"}
{"title": "3.25.1 PrettyPrinter Objects", "text": "module-pprint.html | module-pprint.html | module-repr.html | Python Library Reference | contents.html | genindex.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.", "python_version": "1.6", "length": 426, "url": "https://docs.python.org/1.6/lib/PrettyPrinter_Objects.html"}
{"title": "10.7 Calibration", "text": "profile-limits.html | profile.html | Profiler_Extensions.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.7 Calibration\nThe profiler class has a hard coded constant that is added to each\nevent handling time to compensate for the overhead of calling the time\nfunction, and socking away the results. The following procedure can\nbe used to obtain this constant for a given platform (see discussion\nin section Limitations above).\n```text\n\nimport profile\npr = profile.Profile()\nprint pr.calibrate(100)\nprint pr.calibrate(100)\nprint pr.calibrate(100)\n```\nThe argument to calibrate() is the number of times to try to\ndo the sample calls to get the CPU times. If your computer is\nvery fast, you might have to do:\n```text\n\npr.calibrate(1000)\n```\nor even:\n```text\n\npr.calibrate(10000)\n```\nThe object of this exercise is to get a fairly consistent result.\nWhen you have a consistent answer, you are ready to use that number in\nthe source code. For a Sun Sparcstation 1000 running Solaris 2.3, the\nmagical number is about .00053. If you have a choice, you are better\noff with a smaller constant, and your results will ``less often'' show\nup as negative in profile statistics.\nThe following shows how the trace_dispatch() method in the Profile\nclass should be modified to install the calibration constant on a Sun\nSparcstation 1000:\n```text\n\ndef trace_dispatch(self, frame, event, arg):\nt = self.timer()\nt = t[0] + t[1] - self.t - .00053 # Calibration constant\n\nif self.dispatch[event](frame,t):\nt = self.timer()\nself.t = t[0] + t[1]\nelse:\nr = self.timer()\nself.t = r[0] + r[1] - t # put back unrecorded delta\nreturn\n```\nNote that if there is no calibration constant, then the line\ncontaining the callibration constant should simply say:\n```text\n\nt = t[0] + t[1] - self.t # no calibration constant\n```\nYou can also achieve the same results using a derived class (and the\nprofiler will actually run equally fast!!), but the above method is\nthe simplest to use. I could have made the profiler ``self\ncalibrating'', but it would have made the initialization of the\nprofiler class slower, and would have required some very fancy\ncoding, or else the use of a variable where the constant \".00053\"was placed in the code shown. This is a VERY critical\nperformance section, and there is no reason to use a variable lookup\nat this point, when a constant can be used.", "python_version": "1.6", "length": 2367, "url": "https://docs.python.org/1.6/lib/profile-calibration.html"}
{"title": "10.8.2 HotProfile Class", "text": "profile-old.html | Profiler_Extensions.html | internet.html | Python Library Reference | contents.html | genindex.html\n---\n## 10.8.2 HotProfile Class\nThis profiler is the fastest derived profile example. It does not\ncalculate caller-callee relationships, and does not calculate\ncumulative time under a function. It only calculates time spent in a\nfunction, so it runs very quickly (re: very low overhead). In truth,\nthe basic profiler is so fast, that is probably not worth the savings\nto give up the data, but this class still provides a nice example.\n```text\n\nclass HotProfile(Profile):\n\ndef trace_dispatch_exception(self, frame, t):\nrt, rtt, rfn, rframe, rcur = self.cur\nif rcur and not rframe is frame:\nreturn self.trace_dispatch_return(rframe, t)\nreturn 0\n\ndef trace_dispatch_call(self, frame, t):\nself.cur = (t, 0, frame, self.cur)\nreturn 1\n\ndef trace_dispatch_return(self, frame, t):\nrt, rtt, frame, rcur = self.cur\n\nrfn = `frame.f_code`\n\npt, ptt, pframe, pcur = rcur\nself.cur = pt, ptt+rt, pframe, pcur\n\nif self.timings.has_key(rfn):\nnc, tt = self.timings[rfn]\nself.timings[rfn] = nc + 1, rt + rtt + tt\nelse:\nself.timings[rfn] = 1, rt + rtt\n\nreturn 1\n\ndef snapshot_stats(self):\nself.stats = {}\nfor func in self.timings.keys():\nnc, tt = self.timings[func]\nnor_func = self.func_normalize(func)\nself.stats[nor_func] = nc, nc, tt, 0, {}\n```", "python_version": "1.6", "length": 1344, "url": "https://docs.python.org/1.6/lib/profile-HotProfile.html"}
{"title": "10.3 Instant Users Manual", "text": "Profiler_Changes.html | profile.html | Deterministic_Profiling.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.3 Instant Users Manual\nThis section is provided for users that ``don't want to read the\nmanual.'' It provides a very brief overview, and allows a user to\nrapidly perform profiling on an existing application.\nTo profile an application with a main entry point of \"foo()\", you\nwould add the following to your module:\n```text\n\nimport profile\nprofile.run('foo()')\n```\nThe above action would cause \"foo()\" to be run, and a series of\ninformative lines (the profile) to be printed. The above approach is\nmost useful when working with the interpreter. If you would like to\nsave the results of a profile into a file for later examination, you\ncan supply a file name as the second argument to the run()\nfunction:\n```text\n\nimport profile\nprofile.run('foo()', 'fooprof')\n```\nThe file profile.py can also be invoked as\na script to profile another script. For example:\n```text\n\npython /usr/local/lib/python1.5/profile.py myscript.py\n```\nWhen you wish to review the profile, you should use the methods in the\npstats module. Typically you would load the statistics data as\nfollows:\n```text\n\nimport pstats\np = pstats.Stats('fooprof')\n```\nThe class Stats (the above code just created an instance of\nthis class) has a variety of methods for manipulating and printing the\ndata that was just read into \"p\". When you ran\nprofile.run() above, what was printed was the result of three\nmethod calls:\n```text\n\np.strip_dirs().sort_stats(-1).print_stats()\n```\nThe first method removed the extraneous path from all the module\nnames. The second method sorted all the entries according to the\nstandard module/line/name string that is printed (this is to comply\nwith the semantics of the old profiler). The third method printed out\nall the statistics. You might try the following sort calls:\n```text\n\np.sort_stats('name')\np.print_stats()\n```\nThe first call will actually sort the list by function name, and the\nsecond call will print out the statistics. The following are some\ninteresting calls to experiment with:\n```text\n\np.sort_stats('cumulative').print_stats(10)\n```\nThis sorts the profile by cumulative time in a function, and then only\nprints the ten most significant lines. If you want to understand what\nalgorithms are taking time, the above line is what you would use.\nIf you were looking to see what functions were looping a lot, and\ntaking a lot of time, you would do:\n```text\n\np.sort_stats('time').print_stats(10)\n```\nto sort according to time spent within each function, and then print\nthe statistics for the top ten functions.\nYou might also try:\n```text\n\np.sort_stats('file').print_stats('__init__')\n```\nThis will sort all the statistics by file name, and then print out\nstatistics for only the class init methods ('cause they are spelled\nwith \"__init__\" in them). As one final example, you could try:\n```text\n\np.sort_stats('time', 'cum').print_stats(.5, 'init')\n```\nThis line sorts statistics with a primary key of time, and a secondary\nkey of cumulative time, and then prints out some of the statistics.\nTo be specific, the list is first culled down to 50% (re: \".5\")\nof its original size, then only lines containing `init` are\nmaintained, and that sub-sub-list is printed.\nIf you wondered what functions called the above functions, you could\nnow (\"p\" is still sorted according to the last criteria) do:\n```text\n\np.print_callers(.5, 'init')\n```\nand you would get a list of callers for each of the listed functions.\nIf you want more functionality, you're going to have to read the\nmanual, or guess what the following functions do:\n```text\n\np.print_callees()\np.add('fooprof')\n```", "python_version": "1.6", "length": 3697, "url": "https://docs.python.org/1.6/lib/profile-instant.html"}
{"title": "10.6 Limitations", "text": "profile-stats.html | profile.html | profile-calibration.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.6 Limitations\nThere are two fundamental limitations on this profiler. The first is\nthat it relies on the Python interpreter to dispatch call,\nreturn, and exception events. Compiled C code does not\nget interpreted, and hence is ``invisible'' to the profiler. All time\nspent in C code (including built-in functions) will be charged to the\nPython function that invoked the C code. If the C code calls out\nto some native Python code, then those calls will be profiled\nproperly.\nThe second limitation has to do with accuracy of timing information.\nThere is a fundamental problem with deterministic profilers involving\naccuracy. The most obvious restriction is that the underlying ``clock''\nis only ticking at a rate (typically) of about .001 seconds. Hence no\nmeasurements will be more accurate that that underlying clock. If\nenough measurements are taken, then the ``error'' will tend to average\nout. Unfortunately, removing this first error induces a second source\nof error...\nThe second problem is that it ``takes a while'' from when an event is\ndispatched until the profiler's call to get the time actually\ngets the state of the clock. Similarly, there is a certain lag\nwhen exiting the profiler event handler from the time that the clock's\nvalue was obtained (and then squirreled away), until the user's code\nis once again executing. As a result, functions that are called many\ntimes, or call many functions, will typically accumulate this error.\nThe error that accumulates in this fashion is typically less than the\naccuracy of the clock (i.e., 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 (i.e., 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": "1.6", "length": 2306, "url": "https://docs.python.org/1.6/lib/profile-limits.html"}
{"title": "10.8.1 OldProfile Class", "text": "Profiler_Extensions.html | Profiler_Extensions.html | profile-HotProfile.html | Python Library Reference | contents.html | genindex.html\n---\n## 10.8.1 OldProfile Class\nThe following derived profiler simulates the old style profiler,\nproviding errant results on recursive functions. The reason for the\nusefulness of this profiler is that it runs faster (i.e., less\noverhead) than the old profiler. It still creates all the caller\nstats, and is quite useful when there is no recursion in the\nuser's code. It is also a lot more accurate than the old profiler, as\nit does not charge all its overhead time to the user's code.\n```text\n\nclass OldProfile(Profile):\n\ndef trace_dispatch_exception(self, frame, t):\nrt, rtt, rct, rfn, rframe, rcur = self.cur\nif rcur and not rframe is frame:\nreturn self.trace_dispatch_return(rframe, t)\nreturn 0\n\ndef trace_dispatch_call(self, frame, t):\nfn = `frame.f_code`\n\nself.cur = (t, 0, 0, fn, frame, self.cur)\nif self.timings.has_key(fn):\ntt, ct, callers = self.timings[fn]\nself.timings[fn] = tt, ct, callers\nelse:\nself.timings[fn] = 0, 0, {}\nreturn 1\n\ndef trace_dispatch_return(self, frame, t):\nrt, rtt, rct, rfn, frame, rcur = self.cur\nrtt = rtt + t\nsft = rtt + rct\n\npt, ptt, pct, pfn, pframe, pcur = rcur\nself.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur\n\ntt, ct, callers = self.timings[rfn]\nif callers.has_key(pfn):\ncallers[pfn] = callers[pfn] + 1\nelse:\ncallers[pfn] = 1\nself.timings[rfn] = tt+rtt, ct + sft, callers\n\nreturn 1\n\ndef snapshot_stats(self):\nself.stats = {}\nfor func in self.timings.keys():\ntt, ct, callers = self.timings[func]\nnor_func = self.func_normalize(func)\nnor_callers = {}\nnc = 0\nfor func_caller in callers.keys():\nnor_callers[self.func_normalize(func_caller)] = \\\ncallers[func_caller]\nnc = nc + callers[func_caller]\nself.stats[nor_func] = nc, nc, tt, ct, nor_callers\n```", "python_version": "1.6", "length": 1825, "url": "https://docs.python.org/1.6/lib/profile-old.html"}
{"title": "10.5.1 The Stats Class", "text": "module-profile.html | module-profile.html | profile-limits.html | Python Library Reference | contents.html | genindex.html\n---\n## 10.5.1 The Stats Class\nStats objects have the following methods:", "python_version": "1.6", "length": 194, "url": "https://docs.python.org/1.6/lib/profile-stats.html"}
{"title": "10. The Python Profiler", "text": "node209.html | lib.html | Profiler_Introduction.html | Python Library Reference | contents.html | genindex.html\n---\n# 10. The Python Profiler\nCopyright © 1994, by InfoSeek Corporation, all rights reserved.\nWritten by James Roskind.10.1 (#foot23359)\nPermission to use, copy, modify, and distribute this Python software\nand its associated documentation for any purpose (subject to the\nrestriction in the following sentence) without fee is hereby granted,\nprovided that the above copyright notice appears in all copies, and\nthat both that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of InfoSeek not be used in\nadvertising or publicity pertaining to distribution of the software\nwithout specific, written prior permission. This permission is\nexplicitly restricted to the copying and modification of the software\nto remain in Python, compiled Python, or other languages (such as C)\nwherein the modified or derived code is exclusively imported into a\nPython module.\nINFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\nSOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY\nSPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER\nRESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF\nCONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\nCONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\nThe profiler was written after only programming in Python for 3 weeks.\nAs a result, it is probably clumsy code, but I don't know for sure yet\n'cause I'm a beginner :-). I did work hard to make the code run fast,\nso that profiling would be a reasonable thing to do. I tried not to\nrepeat code fragments, but I'm sure I did some stuff in really awkward\nways at times. Please send suggestions for improvements to:\njar@netscape.com. I won't promise any support. ...but\nI'd appreciate the feedback.\n---\n#### Footnotes", "python_version": "1.6", "length": 1987, "url": "https://docs.python.org/1.6/lib/profile.html"}
{"title": "10.2 How Is This Profiler Different From The Old Profiler?", "text": "Profiler_Introduction.html | profile.html | profile-instant.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.2 How Is This Profiler Different From The Old Profiler?\n(This section is of historical importance only; the old profiler\ndiscussed here was last seen in Python 1.1.)\nThe big changes from old profiling module are that you get more\ninformation, and you pay less CPU time. It's not a trade-off, it's a\ntrade-up.\nTo be specific:\nBugs removed:: Local stack frame is no longer molested, execution time is now charged\nto correct functions.\nAccuracy increased:: Profiler execution time is no longer charged to user's code,\ncalibration for platform is supported, file reads are not done by\nprofiler during profiling (and charged to user's code!).\nSpeed increased:: Overhead CPU cost was reduced by more than a factor of two (perhaps a\nfactor of five), lightweight profiler module is all that must be\nloaded, and the report generating module (pstats) is not needed\nduring profiling.\nRecursive functions support:: Cumulative times in recursive functions are correctly calculated;\nrecursive entries are counted.\nLarge growth in report generating UI:: Distinct profiles runs can be added together forming a comprehensive\nreport; functions that import statistics take arbitrary lists of\nfiles; sorting criteria is now based on keywords (instead of 4 integer\noptions); reports shows what functions were profiled as well as what\nprofile file was referenced; output format has been improved.", "python_version": "1.6", "length": 1507, "url": "https://docs.python.org/1.6/lib/Profiler_Changes.html"}
{"title": "10.8 Extensions -- Deriving Better Profilers", "text": "profile-calibration.html | profile.html | profile-old.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.8 Extensions -- Deriving Better Profilers\nThe Profile class of module profile was written so that\nderived classes could be developed to extend the profiler. Rather\nthan describing all the details of such an effort, I'll just present\nthe following two examples of derived classes that can be used to do\nprofiling. If the reader is an avid Python programmer, then it should\nbe possible to use these as a model and create similar (and perchance\nbetter) profile classes.\nIf all you want to do is change how the timer is called, or which\ntimer function is used, then the basic class has an option for that in\nthe constructor for the class. Consider passing the name of a\nfunction to call into the constructor:\n```text\n\npr = profile.Profile(your_time_func)\n```\nThe resulting profiler will call `your_time_func()` instead of\nos.times(). The function should return either a single number\nor a list of numbers (like what os.times() returns). If the\nfunction returns a single time number, or the list of returned numbers\nhas length 2, then you will get an especially fast version of the\ndispatch routine.\nBe warned that you should calibrate the profiler class for the\ntimer function that you choose. For most machines, a timer that\nreturns a lone integer value will provide the best results in terms of\nlow overhead during profiling. (os.times() is\npretty bad, 'cause it returns a tuple of floating point values,\nso all arithmetic is floating point in the profiler!). If you want to\nsubstitute a better timer in the cleanest fashion, you should derive a\nclass, and simply put in the replacement dispatch method that better\nhandles your timer call, along with the appropriate calibration\nconstant :-).", "python_version": "1.6", "length": 1817, "url": "https://docs.python.org/1.6/lib/Profiler_Extensions.html"}
{"title": "10.1 Introduction to the profiler", "text": "profile.html | profile.html | Profiler_Changes.html | Python Library Reference | contents.html | genindex.html\n---\n# 10.1 Introduction to the profiler\nA profiler is a program that describes the run time performance\nof a program, providing a variety of statistics. This documentation\ndescribes the profiler functionality provided in the modules\nprofile and pstats. This profiler provides\ndeterministic profiling of any Python programs. It also\nprovides a series of report generation tools to allow users to rapidly\nexamine the results of a profile operation.", "python_version": "1.6", "length": 557, "url": "https://docs.python.org/1.6/lib/Profiler_Introduction.html"}
{"title": "3.22.1 Class Descriptor Objects", "text": "module-pyclbr.html | module-pyclbr.html | module-code.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.22.1 Class Descriptor Objects\nThe class descriptor objects used as values in the dictionary returned\nby readmodule() provide the following data members:", "python_version": "1.6", "length": 279, "url": "https://docs.python.org/1.6/lib/pyclbr-class-objects.html"}
{"title": "3. Python Services", "text": "built-in-funcs.html | lib.html | module-sys.html | Python Library Reference | contents.html | genindex.html\n---\n# 3. Python 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": "1.6", "length": 299, "url": "https://docs.python.org/1.6/lib/python.html"}
{"title": "3.16.3 Queries on AST Objects", "text": "Converting_ASTs.html | module-parser.html | AST_Errors.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.16.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": "1.6", "length": 427, "url": "https://docs.python.org/1.6/lib/Querying_ASTs.html"}
{"title": "7.6.1 Queue Objects", "text": "module-Queue.html | module-Queue.html | module-anydbm.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.6.1 Queue Objects\nClass Queue implements queue objects and has the methods\ndescribed below. This class can be derived from in order to implement\nother queue organizations (e.g. stack) but the inheritable interface\nis not described here. See the source code for details. The public\nmethods are:", "python_version": "1.6", "length": 420, "url": "https://docs.python.org/1.6/lib/QueueObjects.html"}
{"title": "4.2.4 Regular Expression Objects", "text": "Contents_of_Module_re.html | module-re.html | match-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 4.2.4 Regular Expression Objects\nCompiled regular expression objects support the following methods and\nattributes:", "python_version": "1.6", "length": 245, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 4.2.1 Regular Expression Syntax\nA regular expression (or RE) specifies a set of strings that matches\nit; the functions in this module let you check if a particular string\nmatches a given regular expression (or if a given regular expression\nmatches a particular string, which comes down to the same thing).\nRegular expressions can be concatenated to form new regular\nexpressions; if A and B are both regular expressions,\nthen AB is also an regular expression. If a string p\nmatches A and another string q matches B, the string pq\nwill match AB. Thus, complex expressions can easily be constructed\nfrom simpler primitive expressions like the ones described here. For\ndetails of the theory and implementation of regular expressions,\nconsult the Friedl book referenced below, or almost any textbook about\ncompiler 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 \"0\",\nare the simplest regular expressions; they simply match themselves.\nYou can concatenate ordinary characters, so last matches the\nstring `'last'`. (In the rest of this section, we'll write RE's in\nthis special style, usually without quotes, and strings to be\nmatched `'in single quotes'`.)\nSome characters, like \"|\" or \"(\", are special. Special\ncharacters either stand for classes of ordinary characters, or affect\nhow the regular expressions around them are interpreted.\nThe special characters are:\nThe special sequences consist of \"\\\" and a character from the\nlist below. If the ordinary character is not on the list, then the\nresulting RE will match the second character. For example,\n\\$ matches the character \"$\".", "python_version": "1.6", "length": 1989, "url": "https://docs.python.org/1.6/lib/re-syntax.html"}
{"title": "3.26.1 Repr Objects", "text": "module-repr.html | module-repr.html | subclassing-reprs.html | Python Library Reference | contents.html | genindex.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": "1.6", "length": 325, "url": "https://docs.python.org/1.6/lib/Repr-objects.html"}
{"title": "13. Restricted Execution", "text": "module-robotparser.html | lib.html | module-rexec.html | Python Library Reference | contents.html | genindex.html\n---\n# 13. Restricted Execution\nIn general, Python programs have complete access to the underlying\noperating system throug the various functions and classes, For\nexample, a Python program can open any file for reading and writing by\nusing the open() built-in function (provided the underlying\nOS gives you permission!). This is exactly what you want for most\napplications.\nThere exists a class of applications for which this ``openness'' is\ninappropriate. Take Grail: a web browser that accepts ``applets,''\nsnippets of Python code, from anywhere on the Internet for execution\non the local system. This can be used to improve the user interface\nof forms, for instance. Since the originator of the code is unknown,\nit is obvious that it cannot be trusted with the full resources of the\nlocal machine.\nRestricted execution is the basic framework in Python that allows\nfor the segregation of trusted and untrusted code. It is based on the\nnotion that trusted Python code (a supervisor) can create a\n``padded cell' (or environment) with limited permissions, and run the\nuntrusted code within this cell. The untrusted code cannot break out\nof its cell, and can only interact with sensitive system resources\nthrough interfaces defined and managed by the trusted code. The term\n``restricted execution'' is favored over ``safe-Python''\nsince true safety is hard to define, and is determined by the way the\nrestricted environment is created. Note that the restricted\nenvironments can be nested, with inner cells creating subcells of\nlesser, but never greater, privilege.\nAn interesting aspect of Python's restricted execution model is that\nthe interfaces presented to untrusted code usually have the same names\nas those presented to trusted code. Therefore no special interfaces\nneed to be learned to write code designed to run in a restricted\nenvironment. And because the exact nature of the padded cell is\ndetermined by the supervisor, different restrictions can be imposed,\ndepending on the application. For example, it might be deemed\n``safe'' for untrusted code to read any file within a specified\ndirectory, but never to write a file. In this case, the supervisor\nmay redefine the built-in open() function so that it raises\nan exception whenever the mode parameter is `'w'`. It\nmight also perform a chroot()-like operation on the\nfilename parameter, such that root is always relative to some\nsafe ``sandbox'' area of the filesystem. In this case, the untrusted\ncode would still see an built-in open() function in its\nenvironment, with the same calling interface. The semantics would be\nidentical too, with IOErrors being raised when the\nsupervisor determined that an unallowable parameter is being used.\nThe Python run-time determines whether a particular code block is\nexecuting in restricted execution mode based on the identity of the\n`__builtins__` object in its global variables: if this is (the\ndictionary of) the standard __builtin__ (module-builtin.html) module,\nthe code is deemed to be unrestricted, else it is deemed to be\nrestricted.\nPython code executing in restricted mode faces a number of limitations\nthat are designed to prevent it from escaping from the padded cell.\nFor instance, the function object attribute func_globals and\nthe class and instance object attribute __dict__ are\nunavailable.\nTwo modules provide the framework for setting up restricted execution\nenvironments:\nrexec (module-rexec.html) | Basic restricted execution framework.\nBastion (module-Bastion.html) | Providing restricted access to objects.", "python_version": "1.6", "length": 3643, "url": "https://docs.python.org/1.6/lib/restricted.html"}
{"title": "7.5.2 RLock Objects", "text": "lock-objects.html | module-threading.html | condition-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.5.2 RLock Objects\nA reentrant lock is a synchronization primitive that may be\nacquired multiple times by the same thread. Internally, it uses\nthe concepts of ``owning thread'' and ``recursion level'' in\naddition to the locked/unlocked state used by primitive locks. In\nthe locked state, some thread owns the lock; in the unlocked\nstate, no thread owns it.\nTo lock the lock, a thread calls its acquire() method; this\nreturns once the thread owns the lock. To unlock the lock, a\nthread calls its release() method. acquire()/release() call pairs\nmay be nested; only the final release() (i.e. the release() of the\noutermost pair) resets the lock to unlocked and allows another\nthread blocked in acquire() to proceed.", "python_version": "1.6", "length": 847, "url": "https://docs.python.org/1.6/lib/rlock-objects.html"}
{"title": "5.3.1 The Random Number Generator Interface", "text": "module-random.html | module-random.html | module-whrandom.html | Python Library Reference | contents.html | genindex.html\n---\n## 5.3.1 The Random Number Generator Interface\nThe Random Number Generator interface describes the methods\nwhich are available for all random number generators. This will be\nenhanced in future releases of Python.\nIn this release of Python, the modules random (module-random.html),\nwhrandom (module-whrandom.html), and instances of the\nwhrandom.whrandom class all conform to this interface.", "python_version": "1.6", "length": 515, "url": "https://docs.python.org/1.6/lib/rng-objects.html"}
{"title": "6.9.1 Scheduler Objects", "text": "module-sched.html | module-sched.html | module-getpass.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.9.1 Scheduler Objects\nscheduler instances have the following methods:", "python_version": "1.6", "length": 197, "url": "https://docs.python.org/1.6/lib/scheduler-objects.html"}
{"title": "7.5.4 Semaphore Objects", "text": "condition-objects.html | module-threading.html | event-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.5.4 Semaphore Objects\nThis is one of the oldest synchronization primitives in the history of\ncomputer science, invented by the early Dutch computer scientist\nEdsger W. Dijkstra (he used P() and V() instead of\nacquire() and release()).\nA semaphore manages an internal counter which is decremented by each\nacquire() call and incremented by each release()\ncall. The counter can never go below zero; when acquire()\nfinds that it is zero, it blocks, waiting until some other thread\ncalls release().", "python_version": "1.6", "length": 629, "url": "https://docs.python.org/1.6/lib/semaphore-objects.html"}
{"title": "16. SGI IRIX Specific Services", "text": "module-rotor.html | lib.html | module-al.html | Python Library Reference | contents.html | genindex.html\n---\n# 16. 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": "1.6", "length": 277, "url": "https://docs.python.org/1.6/lib/sgi.html"}
{"title": "5.11.1 shlex Objects", "text": "module-shlex.html | module-shlex.html | allos.html | Python Library Reference | contents.html | genindex.html\n---\n## 5.11.1 shlex Objects\nA shlex instance has the following methods:\nInstances of shlex subclasses have some public instance\nvariables which either control lexical analysis or can be used\nfor debugging:\nNote that any character not declared to be a word character,\nwhitespace, or a quote will be returned as a single-character token.\nQuote and comment characters are not recognized within words. Thus,\nthe bare words \"ain't\" and \"ain#t\" would be returned as single\ntokens by the default parser.", "python_version": "1.6", "length": 606, "url": "https://docs.python.org/1.6/lib/shlex-objects.html"}
{"title": "6.17.1 Example", "text": "module-shutil.html | module-shutil.html | module-locale.html | Python Library Reference | contents.html | genindex.html\n---\n## 6.17.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": "1.6", "length": 318, "url": "https://docs.python.org/1.6/lib/shutil-example.html"}
{"title": "7.1.1 Example", "text": "module-signal.html | module-signal.html | module-socket.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.1.1 Example\nHere is a minimal example program. It uses the alarm()\nfunction to limit the time spent waiting to open a file; this is\nuseful if the file is for a serial device that may not be turned on,\nwhich would normally cause the os.open() to hang\nindefinitely. The solution is to set a 5-second alarm before opening\nthe file; if the operation takes too long, the alarm signal will be\nsent, and the handler raises an exception.", "python_version": "1.6", "length": 558, "url": "https://docs.python.org/1.6/lib/Signal_Example.html"}
{"title": "11.9.2 SMTP Example", "text": "SMTP-objects.html | module-smtplib.html | module-telnetlib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.9.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.ietf.org/rfc/rfc0822.txt) headers. In particular, the `To' and\n`From' addresses must be included in the message headers explicitly.", "python_version": "1.6", "length": 582, "url": "https://docs.python.org/1.6/lib/SMTP-example.html"}
{"title": "11.9.1 SMTP Objects", "text": "module-smtplib.html | module-smtplib.html | SMTP-example.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.9.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": "1.6", "length": 451, "url": "https://docs.python.org/1.6/lib/SMTP-objects.html"}
{"title": "7.2.1 Socket Objects", "text": "module-socket.html | module-socket.html | Socket_Example.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.2.1 Socket Objects\nSocket objects have the following methods. Except for\nmakefile() these correspond to Unix system calls\napplicable to sockets.\nNote that there are no methods read() or write();\nuse recv() and send() without flags argument\ninstead.", "python_version": "1.6", "length": 378, "url": "https://docs.python.org/1.6/lib/socket-objects.html"}
{"title": "7.2.2 Example", "text": "socket-objects.html | module-socket.html | module-select.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.2.2 Example\nHere are two 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().\n```text\n\n# Echo server program\nfrom socket import *\nHOST = '' # Symbolic name meaning the local host\nPORT = 50007 # Arbitrary non-privileged server\ns = socket(AF_INET, 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\nfrom socket import *\nHOST = 'daring.cwi.nl' # The remote host\nPORT = 50007 # The same port as used by the server\ns = socket(AF_INET, SOCK_STREAM)\ns.connect((HOST, PORT))\ns.send('Hello, world')\ndata = s.recv(1024)\ns.close()\nprint 'Received', `data`\n```", "python_version": "1.6", "length": 1277, "url": "https://docs.python.org/1.6/lib/Socket_Example.html"}
{"title": "7. Optional Operating System Services", "text": "mutex-objects.html | lib.html | module-signal.html | Python Library Reference | contents.html | genindex.html\n---\n# 7. Optional Operating System Services\nThe modules described in this chapter provide interfaces to operating\nsystem features that are available on selected operating systems only.\nThe interfaces are generally modelled 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": "1.6", "length": 458, "url": "https://docs.python.org/1.6/lib/someos.html"}
{"title": "2.1.8 Special Attributes", "text": "typesinternal.html | types.html | module-exceptions.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.8 Special Attributes\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant:", "python_version": "1.6", "length": 256, "url": "https://docs.python.org/1.6/lib/specialattrs.html"}
{"title": "4. String Services", "text": "module-main.html | lib.html | module-string.html | Python Library Reference | contents.html | genindex.html\n---\n# 4. String Services\nThe modules described in this chapter provide a wide range of string\nmanipulation operations. Here's an overview:", "python_version": "1.6", "length": 246, "url": "https://docs.python.org/1.6/lib/strings.html"}
{"title": "3.26.2 Subclassing Repr Objects", "text": "Repr-objects.html | module-repr.html | module-pycompile.html | Python Library Reference | contents.html | genindex.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": "1.6", "length": 409, "url": "https://docs.python.org/1.6/lib/subclassing-reprs.html"}
{"title": "17. SunOS Specific Services", "text": "module-jpeg.html | lib.html | module-sunaudiodev.html | Python Library Reference | contents.html | genindex.html\n---\n# 17. 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": "1.6", "length": 328, "url": "https://docs.python.org/1.6/lib/sunos.html"}
{"title": "11.10.2 Telnet Example", "text": "telnet-objects.html | module-telnetlib.html | module-urlparse.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.10.2 Telnet Example\nA simple example illustrating typical use:", "python_version": "1.6", "length": 198, "url": "https://docs.python.org/1.6/lib/telnet-example.html"}
{"title": "11.10.1 Telnet Objects", "text": "module-telnetlib.html | module-telnetlib.html | telnet-example.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.10.1 Telnet Objects\nTelnet instances have the following methods:", "python_version": "1.6", "length": 201, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 8.13.1 Template Objects\nTemplate objects following methods:", "python_version": "1.6", "length": 187, "url": "https://docs.python.org/1.6/lib/template-objects.html"}
{"title": "8.8.1 Example", "text": "module-termios.html | module-termios.html | module-TERMIOSuppercase.html | Python Library Reference | contents.html | genindex.html\n---\n## 8.8.1 Example\nHere's a function that prompts for a password with echoing turned\noff. Note the technique using a separate tcgetattr() call\nand a try ... finally statement to ensure that the\nold tty attributes are restored exactly no matter what happens:\n```text\n\ndef getpass(prompt = \"Password: \"):\nimport termios, 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": "1.6", "length": 737, "url": "https://docs.python.org/1.6/lib/termios_Example.html"}
{"title": "7.5.6 Thread Objects", "text": "event-objects.html | module-threading.html | module-Queue.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.5.6 Thread Objects\nThis class represents an activity that is run in a separate thread\nof control. There are two ways to specify the activity: by\npassing a callable object to the constructor, or by overriding the\nrun() method in a subclass. No other methods (except for the\nconstructor) should be overridden in a subclass. In other words,\nonly override the __init__() and run()\nmethods of this class.\nOnce a thread object is created, its activity must be started by\ncalling the thread's start() method. This invokes the\nrun() method in a separate thread of control.\nOnce the thread's activity is started, the thread is considered\n'alive' and 'active' (these concepts are almost, but not quite\nexactly, the same; their definition is intentionally somewhat\nvague). It stops being alive and active when its run()\nmethod terminates - either normally, or by raising an unhandled\nexception. The isAlive() method tests whether the thread is\nalive.\nOther threads can call a thread's join() method. This blocks\nthe calling thread until the thread whose join() method is\ncalled is terminated.\nA thread has a name. The name can be passed to the constructor,\nset with the setName() method, and retrieved with the\ngetName() method.\nA thread can be flagged as a ``daemon thread''. The significance\nof this flag is that the entire Python program exits when only\ndaemon threads are left. The initial value is inherited from the\ncreating thread. The flag can be set with the setDaemon()\nmethod and retrieved with the getDaemon() 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, e.g. 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": "1.6", "length": 2227, "url": "https://docs.python.org/1.6/lib/thread-objects.html"}
{"title": "3.7.1 Traceback Example", "text": "module-traceback.html | module-traceback.html | module-linecache.html | Python Library Reference | contents.html | genindex.html\n---\n## 3.7.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": "1.6", "length": 409, "url": "https://docs.python.org/1.6/lib/traceback-example.html"}
{"title": "2.1.1 Truth Value Testing", "text": "types.html | types.html | boolean.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.1 Truth Value Testing\nAny object can be tested for truth value, for use in an if or\nwhile condition or as operand of the Boolean operations below.\nThe following values are considered false:\n- `None`\n- zero of any numeric type, for example, `0`, `0L`,\n`0.0`, `0j`.\n- any empty sequence, for example, `''`, `()`, `[]`.\n- any empty mapping, for example, `{}`.\n- instances of user-defined classes, if the class defines a\n__nonzero__() or __len__() method, when that\nmethod returns zero.2.2 (#foot1178)\nAll other values are considered true -- so objects of many types are\nalways true.\nOperations and built-in functions that have a Boolean result always\nreturn `0` for false and `1` for true, unless otherwise\nstated. (Important exception: the Boolean operations\n\"or\" and \"and\" always return one of\ntheir operands.)", "python_version": "1.6", "length": 918, "url": "https://docs.python.org/1.6/lib/truth.html"}
{"title": "2.1 Built-in Types", "text": "builtin.html | builtin.html | truth.html | Python Library Reference | contents.html | genindex.html\n---\n# 2.1 Built-in Types\nThe following sections describe the standard types that are built into\nthe interpreter. These are the numeric types, sequence types, and\nseveral others, including types themselves. There is no explicit\nBoolean type; use integers instead.\nSome operations are supported by several object types; in particular,\nall objects can be compared, tested for truth value, and converted to\na string (with the `` ...`` notation). The latter\nconversion is implicitly used when an object is written by the\nprint statement.", "python_version": "1.6", "length": 632, "url": "https://docs.python.org/1.6/lib/types.html"}
{"title": "2.1.7.3 Functions", "text": "typesobjects.html | typesother.html | typesmethods.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.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 name space (this is the\nsame as `m .__dict__` where m is the module in which\nthe function f was defined).", "python_version": "1.6", "length": 788, "url": "https://docs.python.org/1.6/lib/typesfunctions.html"}
{"title": "2.1.7.10 Internal Objects", "text": "bltin-file-objects.html | typesother.html | specialattrs.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.10 Internal Objects\nSee the Python Reference Manual (../ref/ref.html) for this\ninformation. It describes code objects, stack frame objects,\ntraceback objects, and slice objects.", "python_version": "1.6", "length": 312, "url": "https://docs.python.org/1.6/lib/typesinternal.html"}
{"title": "2.1.6 Mapping Types", "text": "typesseq-mutable.html | types.html | typesother.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.6 Mapping Types\nA mapping object maps values of one type (the key type) to\narbitrary objects. Mappings are mutable objects. There is currently\nonly one standard mapping type, the dictionary. A dictionary's keys are\nalmost arbitrary values. The only types of values not acceptable as\nkeys are values containing lists or dictionaries or other mutable\ntypes that are compared by value rather than by object identity.\nNumeric types used for keys obey the normal rules for numeric\ncomparison: if two numbers compare equal (e.g. `1` and\n`1.0`) then they can be used interchangeably to index the same\ndictionary entry.\nDictionaries are created by placing a comma-separated list of\n`key : value` pairs within braces, for example:\n`{'jack': 4098, 'sjoerd': 4127}` or\n`{4098: 'jack', 4127: 'sjoerd'}`.\nThe following operations are defined on mappings (where a and\nb are mappings, k is a key, and v and x are\narbitrary objects):\nNotes:\n(1): Raises a KeyError exception if k is not\nin the map.\n(2): Keys and values are listed in random order. If\nkeys() and values() are called with no intervening\nmodifications to the dictionary, the two lists will directly\ncorrespond. This allows the creation of `( value , key )` pairs using map(): \"pairs = map(None,\na.values(), a.keys())\".\n(3): b must be of the same type as a.\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.", "python_version": "1.6", "length": 1586, "url": "https://docs.python.org/1.6/lib/typesmapping.html"}
{"title": "2.1.7.4 Methods", "text": "typesfunctions.html | typesother.html | bltin-code-objects.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.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 )`.\nSee the Python Reference Manual (../ref/ref.html) for more\ninformation.", "python_version": "1.6", "length": 781, "url": "https://docs.python.org/1.6/lib/typesmethods.html"}
{"title": "2.1.7.1 Modules", "text": "typesother.html | typesother.html | typesobjects.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.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 (i.e., 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": "1.6", "length": 1105, "url": "https://docs.python.org/1.6/lib/typesmodules.html"}
{"title": "2.1.4 Numeric Types", "text": "comparisons.html | types.html | bitstring-ops.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.4 Numeric Types\nThere are four numeric types: plain integers, long integers,\nfloating point numbers, and complex numbers.\nPlain integers (also just called integers)\nare implemented using long in C, which gives them at least 32\nbits of precision. Long integers have unlimited precision. Floating\npoint numbers are implemented using double in C. All bets on\ntheir precision are off unless you happen to know the machine you are\nworking with.\nComplex numbers have a real and imaginary part, which are both\nimplemented using double in C. To extract these parts from\na complex number z, use `z .real` and `z .imag`.\nNumbers are created by numeric literals or as the result of built-in\nfunctions and operators. Unadorned integer literals (including hex\nand octal numbers) yield plain integers. Integer literals with an\n\"L\" or \"l\" suffix yield long integers\n(\"L\" is preferred because \"1l\" looks too much like\neleven!). Numeric literals containing a decimal point or an exponent\nsign yield floating point numbers. Appending \"j\" or\n\"J\" to a numeric literal yields a complex number.\nPython fully supports mixed arithmetic: when a binary arithmetic\noperator has operands of different numeric types, the operand with the\n``smaller'' type is converted to that of the other, where plain\ninteger is smaller than long integer is smaller than floating point is\nsmaller than complex.\nComparisons between numbers of mixed type use the same rule.2.3 (#foot1200) The functions int(), long(), float(),\nand complex() can be used\nto coerce numbers to a specific type.\nAll numeric types support the following operations, sorted by\nascending priority (operations in the same box have the same\npriority; all numeric operations have a higher priority than\ncomparison operations):\nNotes:\n(1): For (plain or long) integer division, the result is an integer.\nThe result is always rounded towards minus infinity: 1/2 is 0,\n(-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result\nis a long integer if either operand is a long integer, regardless of\nthe numeric value.\n(2): Conversion from floating point to (long or plain) integer may round or\ntruncate as in C; see functions floor() and ceil() in\nmodule math (module-math.html) for well-defined conversions.\n(3): See section 2.3 (built-in-funcs.html#built-in-funcs), ``Built-in Functions,'' for a full\ndescription.\n---\n#### Footnotes", "python_version": "1.6", "length": 2485, "url": "https://docs.python.org/1.6/lib/typesnumeric.html"}
{"title": "2.1.7.2 Classes and Class Instances", "text": "typesmodules.html | typesother.html | typesfunctions.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.7.2 Classes and Class Instances\nSee chapters 3 and 7 of the Python\nReference Manual (../ref/ref.html) for these.", "python_version": "1.6", "length": 241, "url": "https://docs.python.org/1.6/lib/typesobjects.html"}
{"title": "2.1.7 Other Built-in Types", "text": "typesmapping.html | types.html | typesmodules.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.7 Other Built-in Types\nThe interpreter supports several other kinds of objects.\nMost of these support only one or two operations.", "python_version": "1.6", "length": 250, "url": "https://docs.python.org/1.6/lib/typesother.html"}
{"title": "2.1.5.2 Mutable Sequence Types", "text": "typesseq-strings.html | typesseq.html | typesmapping.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.5.2 Mutable Sequence Types\nList objects support additional operations that allow in-place\nmodification of the object.\nThese operations would be supported by other mutable sequence types\n(when added to the language) as well.\nStrings and tuples are immutable sequence types and such objects cannot\nbe modified once created.\nThe following operations are defined on mutable sequence types (where\nx is an arbitrary object):\nNotes:\n(1): The C implementation of Python has historically accepted\nmultiple parameters and implicitly joined them into a tuple; this\nwill no longer work in Python 1.6. Use of this misfeature has been\ndeprecated since Python 1.4.\n(2): Raises an exception when x is not a list object. The\nextend() method is experimental and not supported by\nmutable sequence types other than lists.\n(3): Raises ValueError when x is not found in\ns.\n(4): The pop() method is experimental and not supported\nby other mutable sequence types than lists. The optional argument\ni defaults to `-1`, so that by default the last item is\nremoved and returned.\n(5): The sort() and reverse() methods modify the\nlist in place for economy of space when sorting or reversing a large\nlist. They don't return the sorted or reversed list to remind you\nof this side effect.\n(6): The sort() method takes an optional argument\nspecifying a comparison function of two arguments (list items) which\nshould return `-1`, `0` or `1` depending on whether\nthe first argument is considered smaller than, equal to, or larger\nthan the second argument. Note that this slows the sorting process\ndown considerably; e.g. to sort a list in reverse order it is much\nfaster to use calls to the methods sort() and\nreverse() than to use the built-in function\nsort() with a comparison function that reverses the\nordering of the elements.", "python_version": "1.6", "length": 1924, "url": "https://docs.python.org/1.6/lib/typesseq-mutable.html"}
{"title": "2.1.5.1 More String Operations", "text": "typesseq.html | typesseq.html | typesseq-mutable.html | Python Library Reference | contents.html | genindex.html\n---\n### 2.1.5.1 More String Operations\nString objects have one unique built-in operation: the `%`operator (modulo) with a string left argument interprets this string\nas a C sprintf() format string to be applied to the\nright argument, and returns the string resulting from this formatting\noperation.\nThe right argument should be a tuple with one item for each argument\nrequired by the format string; if the string requires a single\nargument, the right argument may also be a single non-tuple\nobject.2.5 (#foot655)The following format characters are understood:\n`%`, `c`, `s`, `i`, `d`, `u`, `o`,\n`x`, `X`, `e`, `E`, `f`, `g`, `G`.\nWidth and precision may be a `*` to specify that an integer argument\nspecifies the actual width or precision. The flag characters\n`-`, `+`, blank, `#` and `0` are understood. The\nsize specifiers `h`, `l` or `L` may be present but are\nignored. The `%s` conversion takes any Python object and\nconverts it to a string using `str()` before formatting it. The\nANSI features `%p` and `%n` are not supported. Since\nPython strings have an explicit length, `%s` conversions don't\nassume 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.6 (#foot686)All other errors raise exceptions.\nIf the right argument is a dictionary (or any kind of mapping), then\nthe formats in the string must have a parenthesized key into that\ndictionary inserted immediately after the \"%\" character,\nand each format formats the corresponding entry from the mapping.\nFor example:\n```text\n\n>>> count = 2\n>>> language = 'Python'\n>>> print '%(language)s has %(count)03d quote types.' % vars()\nPython has 002 quote types.\n```\nIn this case no `*` specifiers may occur in a format (since they\nrequire a sequential parameter list).\nAdditional string operations are defined in standard module\nstring and in built-in module re.", "python_version": "1.6", "length": 2078, "url": "https://docs.python.org/1.6/lib/typesseq-strings.html"}
{"title": "2.1.5 Sequence Types", "text": "bitstring-ops.html | types.html | typesseq-strings.html | Python Library Reference | contents.html | genindex.html\n---\n## 2.1.5 Sequence Types\nThere are three sequence types: strings, lists and tuples.\nStrings literals are written in single or double quotes:\n`'xyzzy'`, `\"frobozz\"`. See chapter 2 of the\nPython Reference Manual (../ref/ref.html) for more about\nstring literals. 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,)`.\nSequence 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.4 (#foot543)\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\ns and t are sequences of the same type; n, i\nand j are integers:\nNotes:\n(1): Values of n less than `0` are treated as\n`0` (which yields an empty sequence of the same type as\ns).\n(2): If i or j is negative, the index is relative to\nthe end of the string, i.e., `len( s ) + i` or\n`len( s ) + j` is substituted. But note that `-0` is\nstill `0`.\n(3): The slice of s from i to j is defined as\nthe sequence of items with index k such that `i <= k < j`. If i or j is greater than\n`len( s )`, use `len( s )`. If i is omitted,\nuse `0`. If j is omitted, use `len( s )`. If\ni is greater than or equal to j, the slice is empty.\n---\n#### Footnotes", "python_version": "1.6", "length": 1735, "url": "https://docs.python.org/1.6/lib/typesseq.html"}
{"title": "19. Undocumented Modules", "text": "module-winsound.html | lib.html | node362.html | Python Library Reference | contents.html | genindex.html\n---\n# 19. 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! (The idea and original contents for this chapter were taken\nfrom a posting by Fredrik Lundh; I have revised some modules' status.)", "python_version": "1.6", "length": 413, "url": "https://docs.python.org/1.6/lib/undoc.html"}
{"title": "8. Unix Specific Services", "text": "completer-objects.html | lib.html | module-posix.html | Python Library Reference | contents.html | genindex.html\n---\n# 8. Unix Specific Services\nThe modules described in this chapter provide interfaces to features\nthat are unique to the Unix operating system, or in some cases to\nsome or many variants of it. Here's an overview:", "python_version": "1.6", "length": 328, "url": "https://docs.python.org/1.6/lib/unix.html"}
{"title": "11.2.2 Examples", "text": "urlopener-objs.html | module-urllib.html | module-httplib.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.2.2 Examples\nHere is an example session that uses the \"GET\" method to retrieve\na URL containing parameters:\n```text\n\n>>> import urllib\n>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n>>> f = urllib.urlopen(\"http://www.musi-cal.com/cgi-bin/query?%s\" % params)\n>>> print f.read()\n```\nThe following example uses the \"POST\" method instead:", "python_version": "1.6", "length": 485, "url": "https://docs.python.org/1.6/lib/Urllib_Examples.html"}
{"title": "11.2.1 URLopener Objects", "text": "module-urllib.html | module-urllib.html | Urllib_Examples.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.2.1 URLopener Objects\nURLopener and FancyURLopener objects have the\nfollowing methodsL", "python_version": "1.6", "length": 218, "url": "https://docs.python.org/1.6/lib/urlopener-objs.html"}
{"title": "11.1.2 Using the cgi module", "text": "cgi-intro.html | module-cgi.html | node226.html | Python Library Reference | contents.html | genindex.html\n---\n## 11.1.2 Using the cgi module\nBegin by writing \"import cgi\". Do not use \"from cgi import\n*\" -- the module defines all sorts of names for its own use or for\nbackward compatibility that you don't want in your namespace.\nIt's best to use the FieldStorage class. The other classes\ndefined in this module are provided mostly for backward compatibility.\nInstantiate it exactly once, without arguments. This reads the form\ncontents from standard input or the environment (depending on the\nvalue of various environment variables set according to the CGI\nstandard). Since it may consume standard input, it should be\ninstantiated only once.\nThe FieldStorage instance can be accessed as if it were a Python\ndictionary. For instance, the following code (which assumes that the\n`content-type` header and blank line have already been printed)\nchecks that the fields `name` and `addr` are both set to a\nnon-empty string:\n```text\n\nform = cgi.FieldStorage()\nform_ok = 0\nif form.has_key(\"name\") and form.has_key(\"addr\"):\nif form[\"name\"].value != \"\" and form[\"addr\"].value != \"\":\nform_ok = 1\nif not form_ok:\nprint \"

Error

\"\nprint \"Please fill in the name and addr fields.\"\nreturn\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).\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. If you expect this possibility\n(i.e., when your HTML form comtains multiple fields with the same\nname), use the type() function to determine whether you\nhave a single instance or a list of instances. For example, here's\ncode that concatenates any number of username fields, separated by\ncommas:\n```text\n\nusername = form[\"username\"]\nif type(username) is type([]):\n# Multiple username fields specified\nusernames = \"\"\nfor item in username:\nif usernames:\n# Next item -- insert comma\nusernames = usernames + \",\" + item.value\nelse:\n# First item -- don't insert comma\nusernames = item.value\nelse:\n# Single username field specified\nusernames = username.value\n```\nIf a field represents an uploaded file, the value attribute 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\nleasure 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 always `None`.", "python_version": "1.6", "length": 3524, "url": "https://docs.python.org/1.6/lib/Using_the_cgi_module.html"} {"title": "14.5.1 Wave_read Objects", "text": "module-wave.html | module-wave.html | Wave-write-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 14.5.1 Wave_read Objects\nWave_read objects, as returned by open(), have the\nfollowing methods:\nThe following two methods are defined for compatibility with the\naifc (module-aifc.html) module, and don't do anything interesting.\nThe following two methods define a term ``position'' which is compatible\nbetween them, and is otherwise implementation dependant.", "python_version": "1.6", "length": 484, "url": "https://docs.python.org/1.6/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 | genindex.html\n---\n## 14.5.2 Wave_write Objects\nWave_write objects, as returned by open(), have the\nfollowing methods:", "python_version": "1.6", "length": 224, "url": "https://docs.python.org/1.6/lib/Wave-write-objects.html"} {"title": "12.5.4 Writer Implementations", "text": "writer-interface.html | module-formatter.html | module-rfc822.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.5.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": "1.6", "length": 340, "url": "https://docs.python.org/1.6/lib/writer-impls.html"} {"title": "12.5.3 The Writer Interface", "text": "formatter-impls.html | module-formatter.html | writer-impls.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.5.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": "1.6", "length": 502, "url": "https://docs.python.org/1.6/lib/writer-interface.html"} {"title": "12.13.3 Exceptions", "text": "xdr-unpacker-objects.html | module-xdrlib.html | module-mailcap.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.13.3 Exceptions\nExceptions in this module are coded as class instances:\nHere is an example of how you would catch one of these exceptions:", "python_version": "1.6", "length": 276, "url": "https://docs.python.org/1.6/lib/xdr-exceptions.html"} {"title": "12.13.1 Packer Objects", "text": "module-xdrlib.html | module-xdrlib.html | xdr-unpacker-objects.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.13.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": "1.6", "length": 644, "url": "https://docs.python.org/1.6/lib/xdr-packer-objects.html"} {"title": "12.13.2 Unpacker Objects", "text": "xdr-packer-objects.html | module-xdrlib.html | xdr-exceptions.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.13.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": "1.6", "length": 545, "url": "https://docs.python.org/1.6/lib/xdr-unpacker-objects.html"} {"title": "12.4.1 XML Namespaces", "text": "module-xmllib.html | module-xmllib.html | module-formatter.html | Python Library Reference | contents.html | genindex.html\n---\n## 12.4.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 (i.e. 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 src'`.", "python_version": "1.6", "length": 868, "url": "https://docs.python.org/1.6/lib/xml-namespace.html"} {"title": "7.14.1 ZipFile Objects", "text": "node175.html | node175.html | module-rlcompleter.html | Python Library Reference | contents.html | genindex.html\n---\n## 7.14.1 ZipFile Objects\nXXX explain the \"extra\" string for the ZIP format\nThe class ZipFile has these methods:", "python_version": "1.6", "length": 229, "url": "https://docs.python.org/1.6/lib/zipfile-objects.html"} {"title": "About this document ...", "text": "genindex.html | mac.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# About this document ...\nMacintosh Library Modules,\nSeptember 18, 2000, Release 1.6\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | mac.html | Macintosh Library Modules | contents.html | genindex.html\n---", "python_version": "1.6", "length": 1655, "url": "https://docs.python.org/1.6/mac/about.html"} {"title": "16.1 AEServer Objects", "text": "module-MiniAEFrame.html | module-MiniAEFrame.html | modindex.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 16.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": "1.6", "length": 425, "url": "https://docs.python.org/1.6/mac/aeserver-objects.html"} {"title": "7.2 Alias Objects", "text": "fsspec-objects.html | module-macfs.html | finfo-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 7.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": "1.6", "length": 435, "url": "https://docs.python.org/1.6/mac/alias-objects.html"} {"title": "15.1 Application Objects", "text": "module-FrameWork.html | module-FrameWork.html | window-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 15.1 Application Objects\nApplication objects have the following methods, among others:", "python_version": "1.6", "length": 221, "url": "https://docs.python.org/1.6/mac/application-objects.html"} {"title": "4.1 Connection Objects", "text": "module-ctb.html | module-ctb.html | module-macconsole.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 4.1 Connection Objects\nFor all connection methods that take a timeout argument, a value\nof `-1` is indefinite, meaning that the command runs to completion.", "python_version": "1.6", "length": 281, "url": "https://docs.python.org/1.6/mac/connection-object.html"} {"title": "Contents", "text": "front.html | mac.html | intro.html | Macintosh Library Modules | genindex.html\n---\n## Contents", "python_version": "1.6", "length": 94, "url": "https://docs.python.org/1.6/mac/contents.html"} {"title": "15.3 ControlsWindow Object", "text": "window-objects.html | module-FrameWork.html | scrolledwindow-object.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 15.3 ControlsWindow Object\nControlsWindow objects have the following methods besides those of\n`Window` objects:", "python_version": "1.6", "length": 251, "url": "https://docs.python.org/1.6/mac/controlswindow-object.html"} {"title": "15.5 DialogWindow Objects", "text": "scrolledwindow-object.html | module-FrameWork.html | module-MiniAEFrame.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 15.5 DialogWindow Objects\nDialogWindow objects have the following methods besides those of\n`Window` objects:", "python_version": "1.6", "length": 252, "url": "https://docs.python.org/1.6/mac/dialogwindow-objects.html"} {"title": "6.1 DNR Result Objects", "text": "module-macdnr.html | module-macdnr.html | module-macfs.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 6.1 DNR Result Objects\nSince the DNR calls all execute asynchronously you do not get the\nresults back immediately. Instead, you get a dnr result object. You\ncan check this object to see whether the query is complete, and access\nits attributes to obtain the information when it is.\nAlternatively, you can also reference the result attributes directly,\nthis will result in an implicit wait for the query to complete.\nThe rtnCode and cname attributes are always\navailable, the others depend on the type of query (address, hinfo or\nmx).\nThe simplest way to use the module to convert names to dotted-decimal\nstrings, without worrying about idle time, etc:", "python_version": "1.6", "length": 777, "url": "https://docs.python.org/1.6/mac/dnr-result-object.html"} {"title": "7.3 FInfo Objects", "text": "alias-objects.html | module-macfs.html | module-ic.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 7.3 FInfo Objects\nSee Inside Macintosh: Files for a complete description of what\nthe various fields mean.", "python_version": "1.6", "length": 228, "url": "https://docs.python.org/1.6/mac/finfo-objects.html"} {"title": "Front Matter", "text": "mac.html | mac.html | contents.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# Front Matter\nBEOPEN.COM TERMS AND CONDITIONS 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 OPEN SOURCE LICENSE AGREEMENT\nPython 1.6 is made available subject to the terms and conditions in\nCNRI's License Agreement. This Agreement together with Python 1.6 may\nbe located on the Internet using the following unique, persistent\nidentifier (known as a handle): 1895.22/1012. This Agreement may also\nbe obtained from a proxy server on the Internet using the following\nURL: http://hdl.handle.net/1895.22/1012.\nCWI PERMISSIONS STATEMENT AND DISCLAIMER\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.\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": "1.6", "length": 4729, "url": "https://docs.python.org/1.6/mac/front.html"} {"title": "7.1 FSSpec objects", "text": "module-macfs.html | module-macfs.html | alias-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 7.1 FSSpec objects", "python_version": "1.6", "length": 144, "url": "https://docs.python.org/1.6/mac/fsspec-objects.html"} {"title": "Index", "text": "modindex.html | mac.html | about.html | Macintosh Library Modules | contents.html\n---\n## Index\n---\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\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) |\nw (#letter-w) |\nx (#letter-x)\n---\n## _ (underscore)\n---\n## A\n---\n## B\n---\n## C\n---\n## D\n---\n## E\n---\n## F\n---\n## G\n---\n## H\n---\n## I\n---\n## L\n---\n## M\n---\n## N\n---\n## O\n---\n## P\n---\n## R\n---\n## S\n---\n## T\n---\n## U\n---\n## V\n---\n## W\n---\n## X", "python_version": "1.6", "length": 659, "url": "https://docs.python.org/1.6/mac/genindex.html"} {"title": "Macintosh Library Modules", "text": "../index.html | front.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# Macintosh Library Modules\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 242, "url": "https://docs.python.org/1.6/mac/index.html"} {"title": "1 Introduction", "text": "contents.html | contents.html | module-mac.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 1 Introduction\nThe modules in this manual are available on the Apple Macintosh only.\nAside from the modules described here there are also interfaces to\nvarious MacOS toolboxes, which are currently not extensively\ndescribed. The toolboxes for which modules exist are:\nAE (Apple Events),\nCm (Component Manager),\nCtl (Control Manager),\nDlg (Dialog Manager),\nEvt (Event Manager),\nFm (Font Manager),\nList (List Manager),\nMenu (Moenu Manager),\nQd (QuickDraw),\nQt (QuickTime),\nRes (Resource Manager and Handles),\nScrap (Scrap Manager),\nSnd (Sound Manager),\nTE (TextEdit),\nWaste (non-Apple TextEdit replacement) and\nWin (Window Manager).\nIf applicable the module will define a number of Python objects for\nthe various structures declared by the toolbox, and operations will be\nimplemented as methods of the object. Other operations will be\nimplemented as functions in the module. Not all operations possible in\nC will also be possible in Python (callbacks are often a problem), and\nparameters will occasionally be different in Python (input and output\nbuffers, especially). All methods and functions have a `__doc__`string describing their arguments and return values, and for\nadditional description you are referred to Inside\nMacintosh or similar works.\nThe following modules are documented here:\nmac (module-mac.html) | Implementations for the os module.\nmacpath (module-macpath.html) | MacOS path manipulation functions.\nctb (module-ctb.html) | Interfaces to the Communications Tool Box. Only the Connection\nManager is supported.\nmacconsole (module-macconsole.html) | Think C's console package.\nmacdnr (module-macdnr.html) | Interfaces to the Macintosh Domain Name Resolver.\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 MacOS specific interpreter features.\nmacostools (module-macostools.html) | Convenience routines for file manipulation.\nfindertools (module-findertools.html) | Wrappers around the finder's Apple Events interface.\nmactcp (module-mactcp.html) | The MacTCP interfaces.\nmacspeech (module-macspeech.html) | Interface to the Macintosh Speech Manager.\nEasyDialogs (module-EasyDialogs.html) | Basic Macintosh dialogs.\nFrameWork (module-FrameWork.html) | Interactive application framework.\nMiniAEFrame (module-MiniAEFrame.html) | Support to act as an Open Scripting Architecture (OSA) server\n(``Apple Events'').", "python_version": "1.6", "length": 2586, "url": "https://docs.python.org/1.6/mac/intro.html"} {"title": "Macintosh Library Modules", "text": "../index.html | front.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# Macintosh Library Modules\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 242, "url": "https://docs.python.org/1.6/mac/mac.html"} {"title": "Module Index", "text": "aeserver-objects.html | mac.html | genindex.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## Module Index\nSome module names are followed by an annotation indicating what\nplatform they are available on.", "python_version": "1.6", "length": 224, "url": "https://docs.python.org/1.6/mac/modindex.html"} {"title": "4 ctb -- Interface to the Communications Tool Box", "text": "module-macpath.html | contents.html | connection-object.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 4 ctb --\nInterface to the Communications Tool Box\nAvailability: Macintosh.\nThis module provides a partial interface to the Macintosh\nCommunications Toolbox. Currently, only Connection Manager tools are\nsupported. It may not be available in all Mac Python versions.", "python_version": "1.6", "length": 391, "url": "https://docs.python.org/1.6/mac/module-ctb.html"} {"title": "14 EasyDialogs -- Basic Macintosh dialogs", "text": "speech-channel-objects.html | contents.html | module-FrameWork.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 14 EasyDialogs --\nBasic Macintosh dialogs\nAvailability: Macintosh.\nThe EasyDialogs module contains some simple dialogs for\nthe Macintosh, modelled after the\nstdwin dialogs with similar names. All\nroutines have an optional parameter id with which you can\noverride the DLOG resource used for the dialog, as long as the item\nnumbers correspond. See the source for details.\nThe EasyDialogs module defines the following functions:", "python_version": "1.6", "length": 559, "url": "https://docs.python.org/1.6/mac/module-EasyDialogs.html"} {"title": "11 findertools -- The finder's Apple Events interface", "text": "module-macostools.html | contents.html | module-mactcp.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 11 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 AppleEvent interface to the finder.\nAll file and folder parameters can be specified either as full\npathnames or as FSSpec objects.\nThe findertools module defines the following functions:", "python_version": "1.6", "length": 544, "url": "https://docs.python.org/1.6/mac/module-findertools.html"} {"title": "15 FrameWork -- Interactive application framework", "text": "module-EasyDialogs.html | contents.html | application-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 15 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.\nThe FrameWork module defines the following functions:", "python_version": "1.6", "length": 956, "url": "https://docs.python.org/1.6/mac/module-FrameWork.html"} {"title": "8 ic -- Access to Internet Config", "text": "finfo-objects.html | contents.html | node18.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 8 ic --\nAccess to Internet Config\nAvailability: Macintosh.\nThis module provides access to Macintosh Internet\nConfig package,\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).\nThere is a low-level companion module\nicglue which 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": "1.6", "length": 1088, "url": "https://docs.python.org/1.6/mac/module-ic.html"} {"title": "2 mac -- Implementations for the os module", "text": "intro.html | contents.html | module-macpath.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 2 mac --\nImplementations for the os module\nAvailability: Macintosh.\nThis module implements the operating system dependent functionality\nprovided by the standard module os. It is\nbest accessed through the os module.\nThe following functions are available in this module:\nchdir(),\nclose(),\ndup(),\nfdopen(),\ngetcwd(),\nlseek(),\nlistdir(),\nmkdir(),\nopen(),\nread(),\nrename(),\nrmdir(),\nstat(),\nsync(),\nunlink(),\nwrite(),\nas well as the exception error. Note that the times\nreturned by stat() are floating-point values, like all time\nvalues in MacPython.\nOne additional function is available:", "python_version": "1.6", "length": 698, "url": "https://docs.python.org/1.6/mac/module-mac.html"} {"title": "5 macconsole -- Think C's console package", "text": "connection-object.html | contents.html | node9.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 5 macconsole --\nThink C's console package\nAvailability: Macintosh.\nThis module is available on the Macintosh, provided Python has been\nbuilt using the Think C compiler. It provides an interface to the\nThink console package, with which basic text windows can be created.", "python_version": "1.6", "length": 387, "url": "https://docs.python.org/1.6/mac/module-macconsole.html"} {"title": "6 macdnr -- Interface to the Macintosh Domain Name Resolver", "text": "node10.html | contents.html | dnr-result-object.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 6 macdnr --\nInterface to the Macintosh Domain Name Resolver\nAvailability: Macintosh.\nThis module provides an interface to the Macintosh Domain Name\nResolver. It is usually used in conjunction with the mactcp (module-mactcp.html)\nmodule, to map hostnames to IP addresses. It may not be available in\nall Mac Python versions.\nThe macdnr module defines the following functions:", "python_version": "1.6", "length": 492, "url": "https://docs.python.org/1.6/mac/module-macdnr.html"} {"title": "7 macfs -- Various file system services", "text": "dnr-result-object.html | contents.html | fsspec-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 7 macfs --\nVarious file system services\nAvailability: Macintosh.\nThis module provides access to Macintosh FSSpec handling, the Alias\nManager, finder aliases and the Standard File package.\nWhenever a function or method expects a file argument, this\nargument can be one of three things: (1) a full or partial Macintosh\npathname, (2) an FSSpec object or (3) a 3-tuple `( wdRefNum , parID , name )` as described in Inside\nMacintosh: Files. A description of aliases and the Standard File\npackage can also be found there.", "python_version": "1.6", "length": 642, "url": "https://docs.python.org/1.6/mac/module-macfs.html"} {"title": "9 MacOS -- Access to MacOS interpreter features", "text": "node18.html | contents.html | module-macostools.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 9 MacOS --\nAccess to MacOS 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 capitalisation of the module name, this is a historical\nartifact.", "python_version": "1.6", "length": 430, "url": "https://docs.python.org/1.6/mac/module-MacOS.html"} {"title": "10 macostools -- Convenience routines for file manipulation", "text": "module-MacOS.html | contents.html | module-findertools.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 10 macostools --\nConvenience routines for file manipulation\nAvailability: Macintosh.\nThis module contains some convenience routines for file-manipulation\non the Macintosh.\nThe macostools module defines the following functions:\nNote that the process of creating finder aliases is not specified in\nthe Apple documentation. Hence, aliases created with mkalias()\ncould conceivably have incompatible behaviour in some cases.", "python_version": "1.6", "length": 545, "url": "https://docs.python.org/1.6/mac/module-macostools.html"} {"title": "3 macpath -- MacOS path manipulation functions", "text": "module-mac.html | contents.html | module-ctb.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 3 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": "1.6", "length": 356, "url": "https://docs.python.org/1.6/mac/module-macpath.html"} {"title": "13 macspeech -- Interface to the Macintosh Speech Manager", "text": "node25.html | contents.html | voice-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 13 macspeech --\nInterface to the Macintosh Speech Manager\nAvailability: Macintosh.\nThis module provides an interface to the Macintosh Speech Manager,\nallowing you to let the Macintosh utter phrases. You need a version of\nthe Speech Manager extension (version 1 and 2 have been tested) in\nyour Extensions folder for this to work. The module does not\nprovide full access to all features of the Speech Manager yet. It may\nnot be available in all Mac Python versions.", "python_version": "1.6", "length": 578, "url": "https://docs.python.org/1.6/mac/module-macspeech.html"} {"title": "12 mactcp -- The MacTCP interfaces", "text": "module-findertools.html | contents.html | node23.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 12 mactcp --\nThe MacTCP interfaces\nAvailability: Macintosh.\nThis module provides an interface to the Macintosh TCP/IP driver MacTCP. There is an accompanying module,\nmacdnr (module-macdnr.html), which provides an interface\nto the name-server (allowing you to translate hostnames to IP\naddresses), a module MACTCPconst\nwhich has symbolic names for constants constants used by MacTCP. Since\nthe built-in module socket is also\navailable on the Macintosh it is usually easier to use sockets instead\nof the Macintosh-specific MacTCP API.\nA complete description of the MacTCP interface can be found in the\nApple MacTCP API documentation.", "python_version": "1.6", "length": 751, "url": "https://docs.python.org/1.6/mac/module-mactcp.html"} {"title": "16 MiniAEFrame -- Open Scripting Architecture server support", "text": "dialogwindow-objects.html | contents.html | aeserver-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n# 16 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.\nThis module is temporary, it will eventually be replaced by a module\nthat handles argument names better and possibly automates making your\napplication scriptable.\nThe MiniAEFrame module defines the following classes:", "python_version": "1.6", "length": 685, "url": "https://docs.python.org/1.6/mac/module-MiniAEFrame.html"} {"title": "5.2 console window object", "text": "node9.html | module-macconsole.html | module-macdnr.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 5.2 console window object", "python_version": "1.6", "length": 149, "url": "https://docs.python.org/1.6/mac/node10.html"} {"title": "8.1 IC Objects", "text": "module-ic.html | module-ic.html | module-MacOS.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 8.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 server 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": "1.6", "length": 874, "url": "https://docs.python.org/1.6/mac/node18.html"} {"title": "12.1 TCP Stream Objects", "text": "module-mactcp.html | module-mactcp.html | node24.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 12.1 TCP Stream Objects", "python_version": "1.6", "length": 144, "url": "https://docs.python.org/1.6/mac/node23.html"} {"title": "12.2 TCP Status Objects", "text": "node23.html | module-mactcp.html | node25.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 12.2 TCP Status Objects\nThis object has no methods, only some members holding information on\nthe connection. A complete description of all fields in this objects\ncan be found in the Apple documentation. The most interesting ones are:", "python_version": "1.6", "length": 347, "url": "https://docs.python.org/1.6/mac/node24.html"} {"title": "12.3 UDP Stream Objects", "text": "node24.html | module-mactcp.html | module-macspeech.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 12.3 UDP Stream Objects\nNote that, unlike the name suggests, there is nothing stream-like\nabout UDP.", "python_version": "1.6", "length": 224, "url": "https://docs.python.org/1.6/mac/node25.html"} {"title": "5.1 macconsole options object", "text": "module-macconsole.html | module-macconsole.html | node10.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 5.1 macconsole options object\nThese options are examined when a window is created:", "python_version": "1.6", "length": 211, "url": "https://docs.python.org/1.6/mac/node9.html"} {"title": "15.4 ScrolledWindow Object", "text": "controlswindow-object.html | module-FrameWork.html | dialogwindow-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 15.4 ScrolledWindow Object\nScrolledWindow objects are ControlsWindow objects with the following\nextra methods:", "python_version": "1.6", "length": 256, "url": "https://docs.python.org/1.6/mac/scrolledwindow-object.html"} {"title": "13.2 Speech Channel Objects", "text": "voice-objects.html | module-macspeech.html | module-EasyDialogs.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 13.2 Speech Channel Objects\nA Speech Channel object allows you to speak strings with slightly more\ncontrol than SpeakString(), and allows you to use multiple\nspeakers at the same time. Please note that channel pitch and rate are\ninterrelated in some way, so that to make your Macintosh sing you will\nhave to adjust both.", "python_version": "1.6", "length": 456, "url": "https://docs.python.org/1.6/mac/speech-channel-objects.html"} {"title": "13.1 Voice Objects", "text": "module-macspeech.html | module-macspeech.html | speech-channel-objects.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 13.1 Voice Objects\nVoice objects contain the description of a voice. It is currently not\nyet possible to access the parameters of a voice.", "python_version": "1.6", "length": 281, "url": "https://docs.python.org/1.6/mac/voice-objects.html"} {"title": "15.2 Window Objects", "text": "application-objects.html | module-FrameWork.html | controlswindow-object.html | Macintosh Library Modules | contents.html | genindex.html\n---\n## 15.2 Window Objects\nWindow objects have the following methods, among others:", "python_version": "1.6", "length": 221, "url": "https://docs.python.org/1.6/mac/window-objects.html"} {"title": "Global Module Index", "text": "./ | Global Module Index\n---\n## Global Module Index\nSome module names are followed by an annotation indicating what\nplatform they are available on.", "python_version": "1.6", "length": 147, "url": "https://docs.python.org/1.6/modindex.html"} {"title": "About this document ...", "text": "genindex.html | ref.html | Python Reference Manual | contents.html | genindex.html\n---\n# About this document ...\nPython Reference Manual,\nSeptember 18, 2000, Release 1.6\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\ngenindex.html | ref.html | Python Reference Manual | contents.html | genindex.html\n---", "python_version": "1.6", "length": 1649, "url": "https://docs.python.org/1.6/ref/about.html"} {"title": "6.2 Assert statements", "text": "exprstmts.html | simple.html | assignment.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.2 Assert statements\nAssert statements are a convenient way to insert\ndebugging assertions into a program:\n```text\n\nassert_statement: \"assert\" expression [\",\" expression]\n```\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.", "python_version": "1.6", "length": 1099, "url": "https://docs.python.org/1.6/ref/assert.html"} {"title": "6.3 Assignment statements", "text": "assert.html | simple.html | pass.html | Python Reference Manual | contents.html | genindex.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```text\n\nassignment_stmt: (target_list \"=\")+ expression_list\ntarget_list: target (\",\" target)* [\",\"]\ntarget: identifier | \"(\" target_list \")\" | \"[\" target_list \"]\"\n| attributeref | subscription | slicing\n```\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": "1.6", "length": 5506, "url": "https://docs.python.org/1.6/ref/assignment.html"} {"title": "5.2.1 Identifiers (Names)", "text": "atoms.html | atoms.html | atom-literals.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.1 Identifiers (Names)\nAn identifier occurring as an atom is a reference to a local, global\nor built-in name binding. If a name is assigned to anywhere in a code\nblock (even in unreachable code), and is not mentioned in a\nglobal statement in that code block, then it refers to a local\nname throughout that code block. When it is not assigned to anywhere\nin the block, or when it is assigned to but also explicitly listed in\na global statement, it refers to a global name if one exists,\nelse to a built-in name (and this binding may dynamically change).\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": "1.6", "length": 1686, "url": "https://docs.python.org/1.6/ref/atom-identifiers.html"} {"title": "5.2.2 Literals", "text": "atom-identifiers.html | atoms.html | parenthesized.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.2 Literals\nPython supports string literals and various numeric literals:\n```text\n\nliteral: stringliteral | integer | longinteger | floatnumber | imagnumber\n```\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": "1.6", "length": 897, "url": "https://docs.python.org/1.6/ref/atom-literals.html"} {"title": "5.2 Atoms", "text": "conversions.html | expressions.html | atom-identifiers.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.2 Atoms\nAtoms are the most basic elements of expressions. The simplest atoms\nare identifiers or literals. Forms enclosed in\nreverse quotes or in parentheses, brackets or braces are also\ncategorized syntactically as atoms. The syntax for atoms is:\n```text\n\natom: identifier | literal | enclosure\nenclosure: parenth_form|list_display|dict_display|string_conversion\n```", "python_version": "1.6", "length": 492, "url": "https://docs.python.org/1.6/ref/atoms.html"} {"title": "3.3.2 Customizing attribute access", "text": "customization.html | specialnames.html | callable-types.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.2 Customizing attribute access\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of `x.name`)\nfor class instances.\nFor performance reasons, these methods are cached in the class object\nat class definition time; therefore, they cannot be changed after the\nclass definition is executed.", "python_version": "1.6", "length": 482, "url": "https://docs.python.org/1.6/ref/attribute-access.html"} {"title": "5.3.1 Attribute references", "text": "primaries.html | primaries.html | subscriptions.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.1 Attribute references\nAn attribute reference is a primary followed by a period and a name:\n```text\n\nattributeref: primary \".\" identifier\n```\nThe primary must evaluate to an object of a type that supports\nattribute references, e.g., a module or a list. This object is then\nasked to produce the attribute whose name is the identifier. If this\nattribute 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": "1.6", "length": 695, "url": "https://docs.python.org/1.6/ref/attribute-references.html"} {"title": "5.6 Binary arithmetic operations", "text": "unary.html | expressions.html | shifting.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.6 Binary arithmetic operations\nThe binary arithmetic operations have the conventional priority\nlevels. Note that some of these operations also apply to certain\nnon-numeric types. Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n```text\n\nm_expr: u_expr | m_expr \"*\" u_expr\n| m_expr \"/\" u_expr | m_expr \"%\" u_expr\na_expr: m_expr | aexpr \"+\" m_expr | aexpr \"-\" m_expr\n```\nThe `*` (multiplication) operator yields the product of its\narguments. The arguments must either both be numbers, or one argument\nmust be a plain integer and the other must be a sequence. In the\nformer case, the numbers are converted to a common type and then\nmultiplied together. In the latter case, sequence repetition is\nperformed; a negative repetition factor yields an empty sequence.\nThe `/` (division) operator yields the quotient of its\narguments. The numeric arguments are first converted to a common\ntype. Plain or long integer division yields an integer of the same\ntype; the result is that of mathematical division with the `floor'\nfunction applied to the result. Division by zero raises the\nZeroDivisionError exception.\nThe `%` (modulo) operator yields the remainder from the\ndivision of the first argument by the second. The numeric arguments\nare first converted to a common type. A zero right argument raises\nthe ZeroDivisionError exception. The arguments may be floating\npoint numbers, e.g., `3.14%0.7` equals `0.34` (since\n`3.14` equals `4*0.7 + 0.34`.) The modulo operator always\nyields a result with the same sign as its second operand (or zero);\nthe absolute value of the result is strictly smaller than the second\noperand.\nThe integer division and modulo operators are connected by the\nfollowing identity: `x == (x/y)*y + (x%y)`. Integer division and\nmodulo are also connected with the built-in function divmod():\n`divmod(x, y) == (x/y, x%y)`. These identities don't hold for\nfloating point and complex numbers; there similar identities hold\napproximately where `x/y` is replaced by `floor(x/y)`) or\n`floor(x/y) - 1` (for floats),5.1 (#foot3338) or `floor((x/y).real)` (for\ncomplex).\nThe `+` (addition) operator yields the sum of its arguments.\nThe arguments must either both be numbers or both sequences of the\nsame type. In the former case, the numbers are converted to a common\ntype and then added together. In the latter case, the sequences are\nconcatenated.\nThe `-` (subtraction) operator yields the difference of its\narguments. The numeric arguments are first converted to a common\ntype.", "python_version": "1.6", "length": 2669, "url": "https://docs.python.org/1.6/ref/binary.html"} {"title": "5.8 Binary bit-wise operations", "text": "shifting.html | expressions.html | comparisons.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.8 Binary bit-wise operations\nEach of the three bitwise operations has a different priority level:\n```text\n\nand_expr: shift_expr | and_expr \"&\" shift_expr\nxor_expr: and_expr | xor_expr \"^\" and_expr\nor_expr: xor_expr | or_expr \"|\" xor_expr\n```\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": "1.6", "length": 811, "url": "https://docs.python.org/1.6/ref/bitwise.html"} {"title": "2.1.6 Blank lines", "text": "implicit-joining.html | line-structure.html | indentation.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.6 Blank lines\nA logical line that contains only spaces, tabs, formfeeds and possibly\na comment, is ignored (i.e., no NEWLINE token is generated). During\ninteractive input of statements, handling of a blank line may differ\ndepending on the implementation of the read-eval-print loop. In the\nstandard implementation, an entirely blank logical line (i.e. one\ncontaining not even whitespace or a comment) terminates a multi-line\nstatement.", "python_version": "1.6", "length": 567, "url": "https://docs.python.org/1.6/ref/blank-lines.html"} {"title": "6.9 The break statement", "text": "raise.html | simple.html | continue.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.9 The break statement\n```text\n\nbreak_stmt: \"break\"\n```\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": "1.6", "length": 614, "url": "https://docs.python.org/1.6/ref/break.html"} {"title": "3.3.3 Emulating callable objects", "text": "attribute-access.html | specialnames.html | sequence-types.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.3 Emulating callable objects", "python_version": "1.6", "length": 161, "url": "https://docs.python.org/1.6/ref/callable-types.html"} {"title": "5.3.4 Calls", "text": "slicings.html | primaries.html | power.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.4 Calls\nA call calls a callable object (e.g., a function) with a possibly empty\nseries of arguments:\n```text\n\ncall: primary \"(\" [argument_list [\",\"]] \")\"\nargument_list: positional_arguments [\",\" keyword_arguments]\n| keyword_arguments\npositional_arguments: expression (\",\" expression)*\nkeyword_arguments: keyword_item (\",\" keyword_item)*\nkeyword_item: identifier \"=\" expression\n```\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.\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 library reference manual for the descriptions of\nbuilt-in functions and methods.\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": "1.6", "length": 4496, "url": "https://docs.python.org/1.6/ref/calls.html"} {"title": "7.6 Class definitions", "text": "function.html | compound.html | top-level.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.6 Class definitions\nA class definition defines a class object (see section 3.2 (types.html#types)):\n```text\n\nclassdef: \"class\" classname [inheritance] \":\" suite\ninheritance: \"(\" [expression_list] \")\"\nclassname: identifier\n```\nA class definition is an executable statement. It first evaluates the\ninheritance list, if present. Each item in the inheritance list\nshould evaluate to a class object. The class's suite is then executed\nin a new execution frame (see section 4.1 (execframes.html#execframes)), using a newly\ncreated local namespace and the original global namespace.\n(Usually, the suite contains only function definitions.) When the\nclass's suite finishes execution, its execution frame is discarded but\nits local namespace is saved. A class object is then created using\nthe inheritance list for the base classes and the saved local\nnamespace for the attribute dictionary. The class name is bound to this\nclass object in the original local namespace.", "python_version": "1.6", "length": 1072, "url": "https://docs.python.org/1.6/ref/class.html"} {"title": "2.1.3 Comments", "text": "physical.html | line-structure.html | explicit-joining.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.3 Comments\nA comment starts with a hash character (`#`) that is not part of\na string literal, and ends at the end of the physical line. A comment\nsignifies the end of the logical line unless the implicit line joining\nrules are invoked.\nComments are ignored by the syntax; they are not tokens.", "python_version": "1.6", "length": 421, "url": "https://docs.python.org/1.6/ref/comments.html"} {"title": "5.9 Comparisons", "text": "bitwise.html | expressions.html | lambda.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.9 Comparisons\nContrary to C, all comparison operations in Python have the same\npriority, which is lower than that of any arithmetic, shifting or\nbitwise operation. Also contrary to C, expressions like\n`a < b < c` have the interpretation that is conventional in\nmathematics:\n```text\n\ncomparison: or_expr (comp_operator or_expr)*\ncomp_operator: \"<\"|\">\"|\"==\"|\">=\"|\"<=\"|\"<>\"|\"!=\"|\"is\" [\"not\"]|[\"not\"] \"in\"\n```\nComparisons yield integer values: `1` for true, `0` for false.\nComparisons can be chained arbitrarily, e.g., `x < y <= z` is\nequivalent to `x < y and y <= z`, except that `y` is\nevaluated only once (but in both cases `z` is not evaluated at all\nwhen `x < y` is found to be false).\nFormally, if a, b, c, ..., y, z are\nexpressions and opa, opb, ..., opy are comparison\noperators, then a opa b opb c ...y opy z is equivalent\nto a opa b and b opb c and ...\ny opy z, except that each expression is evaluated at most once.\nNote that a opa b opb c doesn't imply any kind of comparison\nbetween a and c, so that, e.g., `x < y > z` is\nperfectly legal (though perhaps not pretty).\nThe forms `<>` and `!=` are equivalent; for consistency with\nC, `!=` is preferred; where `!=` is mentioned below\n`<>` is also acceptable. At some point in the (far) future,\n`<>` may become obsolete.\nThe operators \"<\", \">\", \"==\", \">=\", \"<=\", and \"!=\" compare\nthe values of two objects. The objects needn't have the same type.\nIf both are numbers, they are coverted to a common type. Otherwise,\nobjects of different types always compare unequal, and are\nordered consistently but arbitrarily.\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the in and\nnot in operators. In the future, the comparison rules for\nobjects of different types are likely to change.)\nComparison of objects of the same type depends on the type:\n- Numbers are compared arithmetically.\n- Strings are compared lexicographically using the numeric equivalents\n(the result of the built-in function ord()) of their\ncharacters.\n- Tuples and lists are compared lexicographically using comparison of\ncorresponding items.\n- Mappings (dictionaries) are compared through lexicographic\ncomparison of their sorted (key, value) lists.5.2 (#foot3301)\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 sequence\nmembership: if y is a sequence, `x in y` is\ntrue if and only if there exists an index i such that\n`x = y [ i ]`.\n`x not in y` yields the inverse truth value. The\nexception TypeError is raised when y is not a sequence,\nor when y is a string and x is not a string of length\none.5.3 (#foot3122)\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": "1.6", "length": 3068, "url": "https://docs.python.org/1.6/ref/comparisons.html"} {"title": "7. Compound statements", "text": "exec.html | ref.html | if.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7. Compound statements\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way. In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\nThe if, while and for statements implement\ntraditional control flow constructs. try specifies exception\nhandlers and/or cleanup code for a group of statements. Function and\nclass definitions are also syntactically compound statements.\nCompound statements consist of one or more `clauses.' A clause\nconsists of a header and a `suite.' The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon. A suite is a group of statements controlled by a\nclause. A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header's\ncolon, or it can be one or more indented statements on subsequent\nlines. Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn't be\nclear to which if clause a following else clause would\nbelong:\n```text\n\nif test1: if test2: print x\n```\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\nprint statements are executed:\n```text\n\nif x < y < z: print x; print y; print z\n```\nSummarizing:\n```text\n\ncompound_stmt: if_stmt | while_stmt | for_stmt\n| try_stmt | funcdef | classdef\nsuite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\nstatement: stmt_list NEWLINE | compound_stmt\nstmt_list: simple_stmt (\";\" simple_stmt)* [\";\"]\n```\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": "1.6", "length": 2289, "url": "https://docs.python.org/1.6/ref/compound.html"} {"title": "Contents", "text": "front.html | ref.html | introduction.html | Python Reference Manual | genindex.html\n---\n## Contents", "python_version": "1.6", "length": 99, "url": "https://docs.python.org/1.6/ref/contents.html"} {"title": "6.10 The continue statement", "text": "break.html | simple.html | import.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.10 The continue statement\n```text\n\ncontinue_stmt: \"continue\"\n```\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 (#foot4241)It continues with the next cycle of the nearest enclosing loop.", "python_version": "1.6", "length": 400, "url": "https://docs.python.org/1.6/ref/continue.html"} {"title": "5.1 Arithmetic conversions", "text": "expressions.html | expressions.html | atoms.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.1 Arithmetic conversions\nWhen a description of an arithmetic operator below uses the phrase\n``the numeric arguments are converted to a common type,'' the\narguments are coerced using the coercion rules listed at the end of\nchapter 3. If both arguments are standard numeric types, the\nfollowing 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": "1.6", "length": 918, "url": "https://docs.python.org/1.6/ref/conversions.html"} {"title": "3.3.1 Basic customization", "text": "specialnames.html | specialnames.html | attribute-access.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.1 Basic customization", "python_version": "1.6", "length": 152, "url": "https://docs.python.org/1.6/ref/customization.html"} {"title": "3. Data model", "text": "delimiters.html | ref.html | objects.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3. Data model", "python_version": "1.6", "length": 119, "url": "https://docs.python.org/1.6/ref/datamodel.html"} {"title": "6.5 The del statement", "text": "pass.html | simple.html | print.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.5 The del statement\n```text\n\ndel_stmt: \"del\" target_list\n```\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather that spelling it out in full details, here are some\nhints.\nDeletion of a target list recursively deletes each target, from left\nto right.\nDeletion of a name removes the binding of that name (which must exist)\nfrom the local or global namespace, depending on whether the name\noccurs in a global statement in the same code block.\nDeletion of attribute references, subscriptions and slicings\nis passed to the primary object involved; deletion of a slicing\nis in general equivalent to assignment of an empty slice of the\nright type (but even this is determined by the sliced object).", "python_version": "1.6", "length": 829, "url": "https://docs.python.org/1.6/ref/del.html"} {"title": "2.6 Delimiters", "text": "operators.html | lexical.html | datamodel.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.6 Delimiters\nThe following tokens serve as delimiters in the grammar:\n```text\n\n( ) [ ] { }\n, : . ` = ;\n```\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 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": "1.6", "length": 668, "url": "https://docs.python.org/1.6/ref/delimiters.html"} {"title": "5.2.5 Dictionary displays", "text": "lists.html | atoms.html | string-conversions.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.5 Dictionary displays\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n```text\n\ndict_display: \"{\" [key_datum_list] \"}\"\nkey_datum_list: key_datum (\",\" key_datum)* [\",\"]\nkey_datum: expression \":\" expression\n```\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": "1.6", "length": 927, "url": "https://docs.python.org/1.6/ref/dict.html"} {"title": "4.2 Exceptions", "text": "execframes.html | execmodel.html | expressions.html | Python Reference Manual | contents.html | genindex.html\n---\n# 4.2 Exceptions\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is\nraised at the point where the error\nis detected; it may be handled by\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 string objects or class instances.\nSelection of a matching except clause is based on object identity\n(i.e., two different string objects with the same value represent\ndifferent exceptions!) For string exceptions, the except\nclause must reference the same string object. For class exceptions,\nthe except clause must reference the same class or a base\nclass of it.\nWhen an exception is raised, an object (maybe `None`) is passed\nas the exception's ``parameter'' or ``value''; this object does not\naffect the selection of an exception handler, but is passed to the\nselected exception handler as additional information. For class\nexceptions, this object must be an instance of the exception class\nbeing raised.", "python_version": "1.6", "length": 2151, "url": "https://docs.python.org/1.6/ref/exceptions.html"} {"title": "6.13 The exec statement", "text": "global.html | simple.html | compound.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.13 The exec statement\n```text\n\nexec_stmt: \"exec\" expression [\"in\" expression [\",\" expression]]\n```\nThis statement supports dynamic execution of Python code. The first\nexpression should evaluate to either a string, an open file object, or\na code object. If it is a string, the string is parsed as a suite of\nPython statements which is then executed (unless a syntax error\noccurs). If it is an open file, the file is parsed until EOF and\nexecuted. If it is a code object, it is simply executed.\nIn all cases, if the optional parts are omitted, the code is executed\nin the current scope. If only the first expression after in\nis specified, it should be a dictionary, which will be used for both\nthe global and the local variables. If two expressions are given,\nboth must be dictionaries and they are used for the global and local\nvariables, respectively.\nAs a side effect, an implementation may insert additional keys into\nthe dictionaries given besides those corresponding to variable names\nset by the executed code. For example, the current implementation\nmay add a reference to the dictionary of the built-in module\n__builtin__ under the key `__builtins__` (!).\nProgrammer's hints:\ndynamic evaluation of expressions is supported by the built-in\nfunction eval(). The built-in functions\nglobals() and locals() return the current global\nand local dictionary, respectively, which may be useful to pass around\nfor use by exec.\nAlso, in the current implementation, multi-line compound statements must\nend with a newline:\n`exec \"for v in seq:\\n\\tprint v\\n\"` works, but\n`exec \"for v in seq:\\n\\tprint v\"` fails with\nSyntaxError.", "python_version": "1.6", "length": 1727, "url": "https://docs.python.org/1.6/ref/exec.html"} {"title": "4.1 Code blocks, execution frames, and namespaces", "text": "execmodel.html | execmodel.html | exceptions.html | Python Reference Manual | contents.html | genindex.html\n---\n# 4.1 Code blocks, execution frames, and namespaces\nA code block is a piece\nof Python program text that can be executed as a unit, such as a\nmodule, a class definition or a function body. Some code blocks (like\nmodules) are normally executed only once, others (like function\nbodies) may be executed many times. Code blocks may textually contain\nother code blocks. Code blocks may invoke other code blocks (that may\nor may not be textually contained in them) as part of their execution,\ne.g., by invoking (calling) a function.\nThe following are code blocks: A module is a code block. A function\nbody is a code block. A class definition is a code block. Each\ncommand typed interactively is a separate code block; a script file (a\nfile given as standard input to the interpreter or specified on the\ninterpreter command line the first argument) is a code block; a script\ncommand (a command specified on the interpreter command line with the\n`-c' option) is a code block. The file read by the built-in\nfunction execfile() is a code block. The string argument\npassed to the built-in function eval() and to the\nexec statement is a code block. And finally, the expression\nread and evaluated by the built-in function input() is a\ncode block.\nA code block is executed in an execution frame. An execution\nframe contains some administrative\ninformation (used for debugging), determines where and how execution\ncontinues after the code block's execution has completed, and (perhaps\nmost importantly) defines two namespaces, the local and the global\nnamespace, that affect execution of the code block.\nA namespace is a mapping from names\n(identifiers) to objects. A particular namespace may be referenced by\nmore than one execution frame, and from other places as well. Adding\na name to a namespace is called binding a\nname (to an object); changing the mapping of a name is called\nrebinding; removing a name is\nunbinding. Namespaces are functionally\nequivalent to dictionaries (and often implemented as dictionaries).\nThe local namespace of an execution\nframe determines the default place where names are defined and\nsearched. The\nglobal namespace determines the place\nwhere names listed in global statements are\ndefined and searched, and where names that are not bound anywhere in\nthe current code block are searched.\nWhether a name is local or global in a code block is determined by\nstatic inspection of the source text for the code block: in the\nabsence of global statements, a name that is bound anywhere\nin the code block is local in the entire code block; all other names\nare considered global. The global statement forces global\ninterpretation of selected names throughout the code block. The\nfollowing constructs bind names: formal parameters to functions,\nimport statements, class and function definitions (these\nbind the class or function name in the defining block), and targets\nthat are identifiers if occurring in an assignment, for loop\nheader, or in the second position of an except clause\nheader. Local names are searched only on the local namespace; global\nnames are searched only in the global and built-in\nnamespace.4.1 (#foot2677)\nA target occurring in a del statement is also considered bound\nfor this purpose (though the actual semantics are to ``unbind'' the\nname).\nWhen a global name is not found in the global namespace, it is\nsearched in the built-in namespace (which is actually the global\nnamespace of the module\n__builtin__). The built-in\nnamespace associated with the execution of a code block is actually\nfound by looking up the name `__builtins__` is its global\nnamespace; this should be a dictionary or a module (in the latter case\nits dictionary is used). Normally, the `__builtins__` namespace\nis the dictionary of the built-in module __builtin__ (note:\nno `s'); if it isn't, restricted\nexecution mode is in effect. When a\nname is not found at all, a\nNameError exception is raised.\nThe following table lists the meaning of the local and global\nnamespace for various types of code blocks. The namespace for a\nparticular module is automatically created when the module is first\nimported (i.e., when it is loaded). Note that in almost all cases,\nthe global namespace is the namespace of the containing module --\nscopes in Python do not nest!\nNotes:\nn.s.: means namespace\n(1): The main module for a script is always called\n__main__; ``the filename don't enter into it.''\n(2): The global and local namespace for these can be\noverridden with optional extra arguments.\n(3): The exec statement and the eval() and\nexecfile() functions have optional arguments to override\nthe global and local namespace. If only one namespace is specified,\nit is used for both.\nThe built-in functions globals() and locals() returns a\ndictionary representing the current global and local namespace,\nrespectively. The effect of modifications to this dictionary on the\nnamespace are undefined.4.2 (#foot2685)", "python_version": "1.6", "length": 5012, "url": "https://docs.python.org/1.6/ref/execframes.html"} {"title": "4. Execution model", "text": "numeric-types.html | ref.html | execframes.html | Python Reference Manual | contents.html | genindex.html\n---\n# 4. Execution model", "python_version": "1.6", "length": 130, "url": "https://docs.python.org/1.6/ref/execmodel.html"} {"title": "2.1.4 Explicit line joining", "text": "comments.html | line-structure.html | implicit-joining.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.4 Explicit line joining\nTwo or more physical lines may be joined into logical lines using\nbackslash characters (`\\`), as follows: when a physical line ends\nin a backslash that is not part of a string literal or comment, it is\njoined with the following forming a single logical line, deleting the\nbackslash and the following end-of-line character. For example:\n```text\n\nif 1900 < year < 2100 and 1 <= month <= 12 \\\nand 1 <= day <= 31 and 0 <= hour < 24 \\\nand 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date\nreturn 1\n```\nA line ending in a backslash cannot carry a comment. A backslash does\nnot continue a comment. A backslash does not continue a token except\nfor string literals (i.e., tokens other than string literals cannot be\nsplit across physical lines using a backslash). A backslash is\nillegal elsewhere on a line outside a string literal.", "python_version": "1.6", "length": 991, "url": "https://docs.python.org/1.6/ref/explicit-joining.html"} {"title": "8.4 Expression input", "text": "interactive.html | top-level.html | genindex.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.4 Expression input\nThere are two forms of expression input. Both ignore leading\nwhitespace.\nThe string argument to eval() must have the following form:\n```text\n\neval_input: expression_list NEWLINE*\n```\nThe input line read by input() must have the following form:\n```text\n\ninput_input: expression_list NEWLINE\n```\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": "1.6", "length": 571, "url": "https://docs.python.org/1.6/ref/expression-input.html"} {"title": "5. Expressions", "text": "exceptions.html | ref.html | conversions.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5. Expressions\nThis chapter explains the meaning of the elements of expressions in\nPython.\nSyntax Notes: In this and the following chapters, extended\nBNF notation will be used to describe syntax, not lexical\nanalysis. When (one alternative of) a syntax rule has the form\n```text\n\nname: othername\n```\nand no semantics are given, the semantics of this form of `name`are the same as for `othername`.", "python_version": "1.6", "length": 506, "url": "https://docs.python.org/1.6/ref/expressions.html"} {"title": "5.11 Expression lists", "text": "lambda.html | expressions.html | summary.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.11 Expression lists\n```text\n\nexpression_list: expression (\",\" expression)* [\",\"]\n```\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": "1.6", "length": 680, "url": "https://docs.python.org/1.6/ref/exprlists.html"} {"title": "6.1 Expression statements", "text": "simple.html | simple.html | assert.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.1 Expression statements\nExpression statements are used (mostly interactively) to compute and\nwrite a value, or (usually) to call a procedure (a function that\nreturns no meaningful result; in Python, procedures return the value\n`None`). Other uses of expression statements are allowed and\noccasionally useful. The syntax for an expression statement is:\n```text\n\nexpression_stmt: expression_list\n```\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()\nfunction 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 cause\nany output.)", "python_version": "1.6", "length": 922, "url": "https://docs.python.org/1.6/ref/exprstmts.html"} {"title": "8.2 File input", "text": "programs.html | top-level.html | interactive.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.2 File input\nAll input read from non-interactive files has the same form:\n```text\n\nfile_input: (NEWLINE | statement)*\n```\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": "1.6", "length": 438, "url": "https://docs.python.org/1.6/ref/file-input.html"} {"title": "2.4.5 Floating point literals", "text": "integers.html | literals.html | imaginary.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.5 Floating point literals\nFloating point literals are described by the following lexical\ndefinitions:\n```text\n\nfloatnumber: pointfloat | exponentfloat\npointfloat: [intpart] fraction | intpart \".\"\nexponentfloat: (nonzerodigit digit* | pointfloat) exponent\nintpart: nonzerodigit digit* | \"0\"\nfraction: \".\" digit+\nexponent: (\"e\"|\"E\") [\"+\"|\"-\"] digit+\n```\nNote that the integer part of a floating point number cannot look like\nan octal integer, though the exponent may look like an octal literal\nbut will always be interpreted using radix 10. For example,\n\"1e010\" is legal, while \"07.1\" is a syntax error.\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\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": "1.6", "length": 1020, "url": "https://docs.python.org/1.6/ref/floating.html"} {"title": "7.3 The for statement", "text": "while.html | compound.html | try.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.3 The for statement\nThe for statement is used to iterate over the elements of a\nsequence (string, tuple or list):\n```text\n\nfor_stmt: \"for\" target_list \"in\" expression_list \":\" suite\n[\"else\" \":\" suite]\n```\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: There 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": "1.6", "length": 2300, "url": "https://docs.python.org/1.6/ref/for.html"} {"title": "Front Matter", "text": "ref.html | ref.html | contents.html | Python Reference Manual | contents.html | genindex.html\n---\n# Front Matter\nBEOPEN.COM TERMS AND CONDITIONS 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 OPEN SOURCE LICENSE AGREEMENT\nPython 1.6 is made available subject to the terms and conditions in\nCNRI's License Agreement. This Agreement together with Python 1.6 may\nbe located on the Internet using the following unique, persistent\nidentifier (known as a handle): 1895.22/1012. This Agreement may also\nbe obtained from a proxy server on the Internet using the following\nURL: http://hdl.handle.net/1895.22/1012.\nCWI PERMISSIONS STATEMENT AND DISCLAIMER\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.\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": "1.6", "length": 5482, "url": "https://docs.python.org/1.6/ref/front.html"} {"title": "7.5 Function definitions", "text": "try.html | compound.html | class.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.5 Function definitions\nA function definition defines a user-defined function object (see\nsection 3.2 (types.html#types)):\n```text\n\nfuncdef: \"def\" funcname \"(\" [parameter_list] \")\" \":\" suite\nparameter_list: (defparameter \",\")* (\"*\" identifier [, \"**\" identifier]\n| \"**\" identifier\n| defparameter [\",\"])\ndefparameter: parameter [\"=\" expression]\nsublist: parameter (\",\" parameter)* [\",\"]\nparameter: identifier | \"(\" sublist \")\"\nfuncname: identifier\n```\nA function definition is an executable statement. Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function). This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called.\nWhen one or more top-level parameters have the form parameter\n`=` expression, the function is said to have ``default\nparameter values.'' For a parameter with a\ndefault value, the corresponding argument may be omitted from a call,\nin which case the parameter's default value is substituted. If a\nparameter has a default value, all following parameters must also have\na default value -- this is a syntactic restriction that is not\nexpressed by the grammar.\nDefault parameter values are evaluated when the function\ndefinition is executed. This means that the expression is evaluated\nonce, when the function is defined, and that that same\n``pre-computed'' value is used for each call. This is especially\nimportant to understand when a default parameter is a mutable object,\nsuch as a list or a dictionary: if the function modifies the object\n(e.g. by appending an item to a list), the default value is in effect\nmodified. This is generally not what was intended. A way around this\nis to use `None` as the default, and explicitly test for it in\nthe body of the function, e.g.:\n```text\n\ndef whats_on_the_telly(penguin=None):\nif penguin is None:\npenguin = []\npenguin.append(\"property of the zoo\")\nreturn penguin\n```\nFunction call semantics are described in more detail in section\n5.3.4 (calls.html#calls).\nA function call always assigns values to all parameters mentioned in\nthe parameter list, either from position arguments, from keyword\narguments, or from default values. If the form ```*identifier`''\nis present, it is initialized to a tuple receiving any excess\npositional parameters, defaulting to the empty tuple. If the form\n```**identifier`'' is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a\nnew empty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda forms,\ndescribed in section 5.10 (lambda.html#lambda). Note that the lambda form is\nmerely a shorthand for a simplified function definition; a function\ndefined in a ``def'' statement can be passed around or\nassigned to another name just like a function defined by a lambda\nform. The ``def'' form is actually more powerful since it\nallows the execution of multiple statements.\n\nProgrammer's note: a ```def`'' form executed inside a\nfunction definition defines a local function that can be returned or\npassed around. Because of Python's two-scope philosophy, a local\nfunction defined in this way does not have access to the local\nvariables of the function that contains its definition; the same rule\napplies to functions defined by a lambda form. A standard trick to\npass selected local variables into a locally defined function is to\nuse default argument values, like this:\n\n```text\n# Return a function that returns its argument incremented by 'n'\ndef make_incrementer(n):\ndef increment(x, n=n):\nreturn x+n\nreturn increment\nadd1 = make_incrementer(1)\nprint add1(3) # This prints '4'\n```", "python_version": "1.6", "length": 3995, "url": "https://docs.python.org/1.6/ref/function.html"} {"title": "Index", "text": "expression-input.html | ref.html | about.html | Python Reference Manual | contents.html\n---\n## Index\n---\n_ (#letter-_) |\na (#letter-a) |\nb (#letter-b) |\nc (#letter-c) |\nd (#letter-d) |\ne (#letter-e) |\nf (#letter-f) |\ng (#letter-g) |\nh (#letter-h) |\ni (#letter-i) |\nk (#letter-k) |\nl (#letter-l) |\nm (#letter-m) |\nn (#letter-n) |\no (#letter-o) |\np (#letter-p) |\nq (#letter-q) |\nr (#letter-r) |\ns (#letter-s) |\nt (#letter-t) |\nu (#letter-u) |\nv (#letter-v) |\nw (#letter-w) |\nx (#letter-x) |\nz (#letter-z)\n---\n## _ (underscore)\n---\n## A\n---\n## B\n---\n## C\n---\n## D\n---\n## E\n---\n## F\n---\n## G\n---\n## H\n---\n## I\n---\n## K\n---\n## L\n---\n## M\n---\n## N\n---\n## O\n---\n## P\n---\n## Q\n---\n## R\n---\n## S\n---\n## T\n---\n## U\n---\n## V\n---\n## W\n---\n## X\n---\n## Z", "python_version": "1.6", "length": 740, "url": "https://docs.python.org/1.6/ref/genindex.html"} {"title": "6.12 The global statement", "text": "import.html | simple.html | exec.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.12 The global statement\n```text\n\nglobal_stmt: \"global\" identifier (\",\" identifier)*\n```\nThe global statement is a declaration which holds for the\nentire current code block. It means that the listed identifiers are to be\ninterpreted as globals. While using global names is automatic\nif they are not defined in the local scope, assigning to global\nnames would be impossible without global.\nNames listed in a global statement must not be used in the same\ncode block textually preceding that global statement.\nNames listed in a global statement must not be defined as formal\nparameters or in a for loop control target, class\ndefinition, function definition, or import statement.\n(The current implementation does not enforce the latter two\nrestrictions, but programs should not abuse this freedom, as future\nimplementations may enforce them or silently change the meaning of the\nprogram.)\nProgrammer's note:\nthe global is a directive to the parser. It\napplies only to code parsed at the same time as the global\nstatement. In particular, a global statement contained in an\nexec statement does not affect the code block containing\nthe exec statement, and code contained in an exec\nstatement is unaffected by global statements in the code\ncontaining the exec statement. The same applies to the\neval(), execfile() and compile() functions.", "python_version": "1.6", "length": 1433, "url": "https://docs.python.org/1.6/ref/global.html"} {"title": "2.3.2 Reserved classes of identifiers", "text": "keywords.html | identifiers.html | literals.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.3.2 Reserved classes of identifiers\nCertain classes of identifiers (besides keywords) have special\nmeanings. These are:\n(XXX need section references here.)\nNote:\n(1): The special identifier \"_\" is used in the interactive\ninterpreter to store the result of the last evaluation; it is stored\nin the __builtin__ module. When not in interactive mode,\n\"_\" has no special meaning and is not defined.", "python_version": "1.6", "length": 509, "url": "https://docs.python.org/1.6/ref/id-classes.html"} {"title": "2.3 Identifiers and keywords", "text": "other-tokens.html | lexical.html | keywords.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.3 Identifiers and keywords\nIdentifiers (also referred to as names) are described by the following\nlexical definitions:\n```text\n\nidentifier: (letter|\"_\") (letter|digit|\"_\")*\nletter: lowercase | uppercase\nlowercase: \"a\"...\"z\"\nuppercase: \"A\"...\"Z\"\ndigit: \"0\"...\"9\"\n```\nIdentifiers are unlimited in length. Case is significant.", "python_version": "1.6", "length": 438, "url": "https://docs.python.org/1.6/ref/identifiers.html"} {"title": "7.1 The if statement", "text": "compound.html | compound.html | while.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.1 The if statement\nThe if statement is used for conditional execution:\n```text\n\nif_stmt: \"if\" expression \":\" suite\n(\"elif\" expression \":\" suite)*\n[\"else\" \":\" suite]\n```\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section 5.10 (lambda.html#Booleans) for\nthe definition of true and false); then that suite is executed (and no\nother part of the if statement is executed or evaluated). If\nall expressions are false, the suite of the else clause, if\npresent, is executed.", "python_version": "1.6", "length": 644, "url": "https://docs.python.org/1.6/ref/if.html"} {"title": "2.4.6 Imaginary literals", "text": "floating.html | literals.html | operators.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.6 Imaginary literals\nImaginary literals are described by the following lexical definitions:\n```text\n\nimagnumber: (floatnumber | intpart) (\"j\"|\"J\")\n```\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": "1.6", "length": 643, "url": "https://docs.python.org/1.6/ref/imaginary.html"} {"title": "2.1.5 Implicit line joining", "text": "explicit-joining.html | line-structure.html | blank-lines.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.5 Implicit line joining\nExpressions in parentheses, square brackets or curly braces can be\nsplit over more than one physical line without using backslashes.\nFor example:\n```text\n\nmonth_names = ['Januari', 'Februari', 'Maart', # These are the\n'April', 'Mei', 'Juni', # Dutch names\n'Juli', 'Augustus', 'September', # for the months\n'Oktober', 'November', 'December'] # of the year\n```\nImplicitly continued lines can carry comments. The indentation of the\ncontinuation lines is not important. Blank continuation lines are\nallowed. There is no NEWLINE token between implicit continuation\nlines. Implicitly continued lines can also occur within triple-quoted\nstrings (see below); in that case they cannot carry comments.", "python_version": "1.6", "length": 847, "url": "https://docs.python.org/1.6/ref/implicit-joining.html"} {"title": "6.11 The import statement", "text": "continue.html | simple.html | global.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.11 The import statement\n```text\n\nimport_stmt: \"import\" module (\",\" module)*\n| \"from\" module \"import\" identifier (\",\" identifier)*\n| \"from\" module \"import\" \"*\"\nmodule: (identifier \".\")* identifier\n```\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the import statement occurs).\nThe first form (without from) repeats these steps for each\nidentifier in the list. The form with from performs step\n(1) once, and then performs step (2) repeatedly.\nThe system maintains a table of modules that have been initialized,\nindexed by module name. This table table\naccessible as `sys.modules`. When a module name is found in\nthis table, step (1) is finished. If not, a search for a module\ndefinition is started. When a module is found, it is loaded. Details\nof the module searching and loading process are implementation and\nplatform specific. It generally involves searching for a ``built-in''\nmodule with the given name and then searching a list of locations\ngiven as `sys.path`.\nIf a built-in module is found, its built-in initialization code is\nexecuted and step (1) is finished. If no matching file is found,\nImportError is raised. If a file is found, it is parsed,\nyielding an executable code block. If a syntax error occurs,\nSyntaxError is raised. Otherwise, an empty module of the given\nname is created and inserted in the module table, and then the code\nblock is executed in the context of this module. Exceptions during\nthis execution terminate step (1).\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\nThe first form of import statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any. The from form does not bind the\nmodule name: it goes through the list of identifiers, looks each one\nof them up in the module found in step (1), and binds the name in the\nlocal namespace to the object thus found. If a name is not found,\nImportError is raised. If the list of identifiers is replaced\nby a star (\"*\"), all names defined in the module are bound,\nexcept those beginning with an underscore (\"_\").\nNames bound by import statements may not occur in\nglobal statements in the same scope.\nThe from form with \"*\" may only occur in a module scope.\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.)\nHierarchical module names:\nwhen 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.\n[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.]\n[XXX Also should mention __import__().]", "python_version": "1.6", "length": 3260, "url": "https://docs.python.org/1.6/ref/import.html"} {"title": "2.1.7 Indentation", "text": "blank-lines.html | line-structure.html | whitespace.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.7 Indentation\nLeading whitespace (spaces and tabs) at the beginning of a logical\nline is used to compute the indentation level of the line, which in\nturn is used to determine the grouping of statements.\nFirst, tabs are replaced (from left to right) by one to eight spaces\nsuch that the total number of characters up to and including the\nreplacement is a multiple of\neight (this is intended to be the same rule as used by Unix). The\ntotal number of spaces preceding the first non-blank character then\ndetermines the line's indentation. Indentation cannot be split over\nmultiple physical lines using backslashes; the whitespace up to the\nfirst backslash determines the indentation.\nCross-platform compatibility note: because of the nature of\ntext editors on non-UNIX platforms, it is unwise to use a mixture of\nspaces and tabs for the indentation in a single source file.\nA formfeed character may be present at the start of the line; it will\nbe ignored for the indentation calculations above. Formfeed\ncharacters occurring elsewhere in the leading whitespace have an\nundefined effect (for instance, they may reset the space count to\nzero).\nThe indentation levels of consecutive lines are used to generate\nINDENT and DEDENT tokens, using a stack, as follows.\nBefore the first line of the file is read, a single zero is pushed on\nthe stack; this will never be popped off again. The numbers pushed on\nthe stack will always be strictly increasing from bottom to top. At\nthe beginning of each logical line, the line's indentation level is\ncompared to the top of the stack. If it is equal, nothing happens.\nIf it is larger, it is pushed on the stack, and one INDENT token is\ngenerated. If it is smaller, it must be one of the numbers\noccurring on the stack; all numbers on the stack that are larger are\npopped off, and for each number popped off a DEDENT token is\ngenerated. At the end of the file, a DEDENT token is generated for\neach number remaining on the stack that is larger than zero.\nHere is an example of a correctly (though confusingly) indented piece\nof Python code:\n```text\n\ndef perm(l):\n# Compute the list of all permutations of l\nif len(l) <= 1:\nreturn [l]\nr = []\nfor i in range(len(l)):\ns = l[:i] + l[i+1:]\np = perm(s)\nfor x in p:\nr.append(l[i:i+1] + x)\nreturn r\n```\nThe following example shows various indentation errors:\n```text\n\ndef perm(l): # error: first line indented\nfor i in range(len(l)): # error: not indented\ns = l[:i] + l[i+1:]\np = perm(l[:i] + l[i+1:]) # error: unexpected indent\nfor x in p:\nr.append(l[i:i+1] + x)\nreturn r # error: inconsistent dedent\n```\n(Actually, the first three errors are detected by the parser; only the\nlast error is found by the lexical analyzer -- the indentation of\n`return r` does not match a level popped off the stack.)", "python_version": "1.6", "length": 2896, "url": "https://docs.python.org/1.6/ref/indentation.html"} {"title": "Python Reference Manual", "text": "../index.html | front.html | Python Reference Manual | contents.html | genindex.html\n---\n# Python Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 238, "url": "https://docs.python.org/1.6/ref/index.html"} {"title": "2.4.4 Integer and long integer literals", "text": "numbers.html | literals.html | floating.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.4 Integer and long integer literals\nInteger and long integer literals are described by the following\nlexical definitions:\n```text\n\nlonginteger: integer (\"l\"|\"L\")\ninteger: decimalinteger | octinteger | hexinteger\ndecimalinteger: nonzerodigit digit* | \"0\"\noctinteger: \"0\" octdigit+\nhexinteger: \"0\" (\"x\"|\"X\") hexdigit+\nnonzerodigit: \"1\"...\"9\"\noctdigit: \"0\"...\"7\"\nhexdigit: digit|\"a\"...\"f\"|\"A\"...\"F\"\n```\nAlthough both lower case `l' and upper case `L' are allowed as suffix\nfor long integers, it is strongly recommended to always use `L', since\nthe letter `l' looks too much like the digit `1'.\nPlain integer decimal literals must be at most 2147483647 (i.e., the\nlargest positive integer, using 32-bit arithmetic). Plain octal and\nhexadecimal literals may be as large as 4294967295, but values larger\nthan 2147483647 are converted to a negative value by subtracting\n4294967296. There is no limit for long integer literals apart from\nwhat can be stored in available memory.\nSome examples of plain and long integer literals:\n```text\n\n7 2147483647 0177 0x80000000\n3L 79228162514264337593543950336L 0377L 0x100000000L\n```", "python_version": "1.6", "length": 1228, "url": "https://docs.python.org/1.6/ref/integers.html"} {"title": "8.3 Interactive input", "text": "file-input.html | top-level.html | expression-input.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.3 Interactive input\nInput in interactive mode is parsed using the following grammar:\n```text\n\ninteractive_input: [stmt_list] NEWLINE | compound_stmt NEWLINE\n```\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": "1.6", "length": 443, "url": "https://docs.python.org/1.6/ref/interactive.html"} {"title": "1. Introduction", "text": "contents.html | ref.html | notation.html | Python Reference Manual | contents.html | genindex.html\n---\n# 1. Introduction\nThis reference manual describes the Python programming language.\nIt is not intended as a tutorial.\nWhile I am trying to be as precise as possible, I chose to use English\nrather than formal specifications for everything except syntax and\nlexical analysis. This should make the document more understandable\nto the average reader, but will leave room for ambiguities.\nConsequently, if you were coming from Mars and tried to re-implement\nPython from this document alone, you might have to guess things and in\nfact you would probably end up implementing quite a different language.\nOn the other hand, if you are using\nPython and wonder what the precise rules about a particular area of\nthe language are, you should definitely be able to find them here.\nIf you would like to see a more formal definitition 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": "1.6", "length": 1833, "url": "https://docs.python.org/1.6/ref/introduction.html"} {"title": "2.3.1 Keywords", "text": "identifiers.html | identifiers.html | id-classes.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.3.1 Keywords\nThe following identifiers are used as reserved words, or\nkeywords of the language, and cannot be used as ordinary\nidentifiers. They must be spelled exactly as written here:\n```text\n\nand del for is raise\nassert elif from lambda return\nbreak else global not try\nclass except if or while\ncontinue exec import pass\ndef finally in print\n```", "python_version": "1.6", "length": 469, "url": "https://docs.python.org/1.6/ref/keywords.html"} {"title": "5.10 Boolean operations", "text": "comparisons.html | expressions.html | exprlists.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.10 Boolean operations\nBoolean operations have the lowest priority of all Python operations:\n```text\n\nexpression: or_test | lambda_form\nor_test: and_test | or_test \"or\" and_test\nand_test: not_test | and_test \"and\" not_test\nnot_test: comparison | \"not\" not_test\nlambda_form: \"lambda\" [parameter_list]: expression\n```\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: `None`, numeric zero of all types, empty sequences\n(strings, tuples and lists), and empty mappings (dictionaries). All\nother values are interpreted as true.\nThe operator not yields `1` if its argument is false,\n`0` otherwise.\nThe expression `x and y` first evaluates x; if\nx is false, its value is returned; otherwise, y is\nevaluated and the resulting value is returned.\nThe expression `x or y` first evaluates x; if\nx is true, its value is returned; otherwise, y is\nevaluated and the resulting value is returned.\n(Note that neither and nor or restrict the value\nand type they return to `0` and `1`, but rather return the\nlast evaluated argument.\nThis is sometimes useful, e.g., if `s` is a string that should be\nreplaced by a default value if it is empty, the expression\n`s or 'foo'` yields the desired value. Because not has to\ninvent a value anyway, it does not bother to return a value of the\nsame type as its argument, so e.g., `not 'foo'` yields `0`,\nnot `''`.)\nLambda forms (lambda expressions) have the same syntactic position as\nexpressions. They are a shorthand to create anonymous functions; the\nexpression `lambda arguments : expression`yields a function object that behaves virtually identical to one\ndefined with\n```text\n\ndef name(arguments):\nreturn expression\n```\nSee section 7.5 (function.html#function) for the syntax of parameter lists. Note\nthat functions created with lambda forms cannot contain statements.\nProgrammer's note: a lambda form defined inside a function\nhas no access to names defined in the function's namespace. This is\nbecause Python has only two scopes: local and global. A common\nwork-around is to use default argument values to pass selected\nvariables into the lambda's namespace, e.g.:\n```text\n\ndef make_incrementor(increment):\nreturn lambda x, n=increment: x+n\n```", "python_version": "1.6", "length": 2387, "url": "https://docs.python.org/1.6/ref/lambda.html"} {"title": "2. Lexical analysis", "text": "notation.html | ref.html | line-structure.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2. Lexical analysis\nA Python program is read by a parser. Input to the parser is a\nstream of tokens, generated by the lexical analyzer. This\nchapter describes how the lexical analyzer breaks a file into tokens.\nPython uses the 7-bit ASCII character set for program text and string\nliterals. 8-bit characters may be used in string literals and comments\nbut their interpretation is platform dependent; the proper way to\ninsert 8-bit characters in string literals is by using octal or\nhexadecimal escape sequences.\nThe run-time character set depends on the I/O devices connected to the\nprogram but is generally a superset of ASCII.\nFuture compatibility note: It may be tempting to assume that the\ncharacter set for 8-bit characters is ISO Latin-1 (an ASCII\nsuperset that covers most western languages that use the Latin\nalphabet), but it is possible that in the future Unicode text editors\nwill become common. These generally use the UTF-8 encoding, which is\nalso an ASCII superset, but with very different use for the\ncharacters with ordinals 128-255. While there is no consensus on this\nsubject yet, it is unwise to assume either Latin-1 or UTF-8, even\nthough the current implementation appears to favor Latin-1. This\napplies both to the source character set and the run-time character\nset.", "python_version": "1.6", "length": 1400, "url": "https://docs.python.org/1.6/ref/lexical.html"} {"title": "2.1 Line structure", "text": "lexical.html | lexical.html | logical.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.1 Line structure\nA Python program is divided into a number of logical lines.", "python_version": "1.6", "length": 185, "url": "https://docs.python.org/1.6/ref/line-structure.html"} {"title": "5.2.4 List displays", "text": "parenthesized.html | atoms.html | dict.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.4 List displays\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n```text\n\nlist_display: \"[\" [expression_list] \"]\"\n```\nA list display yields a new list object. If it has no expression\nlist, the list object has no items. Otherwise, the elements of the\nexpression list are evaluated from left to right and inserted in the\nlist object in that order.", "python_version": "1.6", "length": 495, "url": "https://docs.python.org/1.6/ref/lists.html"} {"title": "2.4 Literals", "text": "id-classes.html | lexical.html | strings.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.4 Literals\nLiterals are notations for constant values of some built-in types.", "python_version": "1.6", "length": 189, "url": "https://docs.python.org/1.6/ref/literals.html"} {"title": "2.1.1 Logical lines", "text": "line-structure.html | line-structure.html | physical.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.1 Logical lines\nThe end of\na logical line is represented by the token NEWLINE. Statements cannot\ncross logical line boundaries except where NEWLINE is allowed by the\nsyntax (e.g., between statements in compound statements).\nA logical line is constructed from one or more physical lines\nby following the explicit or implicit line joining rules.", "python_version": "1.6", "length": 470, "url": "https://docs.python.org/1.6/ref/logical.html"} {"title": "1.1 Notation", "text": "introduction.html | introduction.html | lexical.html | Python Reference Manual | contents.html | genindex.html\n---\n# 1.1 Notation\nThe descriptions of lexical analysis and syntax use a modified BNF\ngrammar notation. This uses the following style of definition:\n```text\n\nname: lc_letter (lc_letter | \"_\")*\nlc_letter: \"a\"...\"z\"\n```\nThe first line says that a `name` is an `lc_letter` followed by\na sequence of zero or more `lc_letter`s and underscores. An\n`lc_letter` in turn is any of the single characters \"a\"\nthrough \"z\". (This rule is actually adhered to for the\nnames defined in lexical and grammar rules in this document.)\nEach rule begins with a name (which is the name defined by the rule)\nand a colon. A vertical bar (`|`) is used to separate\nalternatives; it is the least binding operator in this notation. A\nstar (`*`) means zero or more repetitions of the preceding item;\nlikewise, a plus (`+`) means one or more repetitions, and a\nphrase enclosed in square brackets (`[ ]`) means zero or one\noccurrences (in other words, the enclosed phrase is optional). The\n`*` and `+` operators bind as tightly as possible;\nparentheses are used for grouping. Literal strings are enclosed in\nquotes. White space is only meaningful to separate tokens.\nRules are normally contained on a single line; rules with many\nalternatives may be formatted alternatively with each line after the\nfirst beginning with a vertical bar.\nIn lexical definitions (as the example above), two more conventions\nare used: Two literal characters separated by three dots mean a choice\nof any single character in the given (inclusive) range of ASCII\ncharacters. A phrase between angular brackets (`<...>`) gives an\ninformal description of the symbol defined; e.g., this could be used\nto describe the notion of `control character' if needed.", "python_version": "1.6", "length": 1808, "url": "https://docs.python.org/1.6/ref/notation.html"} {"title": "2.4.3 Numeric literals", "text": "string-catenation.html | literals.html | integers.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.3 Numeric literals\nThere are four types of numeric literals: plain integers, long\nintegers, floating point numbers, and imaginary numbers. There are no\ncomplex literals (complex numbers can be formed by adding a real\nnumber and an imaginary number).\nNote that numeric literals do not include a sign; a phrase like\n`-1` is actually an expression composed of the unary operator\n``-`' and the literal `1`.", "python_version": "1.6", "length": 526, "url": "https://docs.python.org/1.6/ref/numbers.html"} {"title": "3.3.6 Emulating numeric types", "text": "sequence-methods.html | specialnames.html | execmodel.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.6 Emulating numeric types\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\nCoercion rules: to evaluate x op y, the\nfollowing steps are taken (where __op__() and\n__rop__() are the method names corresponding to op,\ne.g., if varop is ``+`', __add__() and\n__radd__() are used). If an exception occurs at any point,\nthe evaluation is abandoned and exception handling takes over.", "python_version": "1.6", "length": 699, "url": "https://docs.python.org/1.6/ref/numeric-types.html"} {"title": "3.1 Objects, values and types", "text": "datamodel.html | datamodel.html | types.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3.1 Objects, values and types\nObjects are Python's abstraction for data. All data in a Python\nprogram is represented by objects or by relations between objects.\n(In a sense, and in conformance to Von Neumann's model of a\n``stored program computer,'' code is also represented by objects.)\nEvery object has an identity, a type and a value. An object's\nidentity never changes once it has been created; you may think\nof it as the object's address in memory. The ``is`' operator\ncompares the identity of two objects; the\nid() function returns an integer\nrepresenting its identity (currently implemented as its address).\nAn object's type is\nalso unchangeable. It determines the operations that an object\nsupports (e.g., ``does it have a length?'') and also defines the\npossible values for objects of that type. The\ntype() function returns an object's type\n(which is an object itself). The value of some\nobjects can change. Objects whose value can change are said to be\nmutable; objects whose value is unchangeable once they are\ncreated are called immutable.\n(The value of an immutable container object that contains a reference\nto a mutable object can change when the latter's value is changed;\nhowever the container is still considered immutable, because the\ncollection of objects it contains cannot be changed. So, immutability\nis not strictly the same as having an unchangeable value, it is more\nsubtle.)\nAn object's mutability is determined by its type; for instance,\nnumbers, strings and tuples are immutable, while dictionaries and\nlists are mutable.\nObjects are never explicitly destroyed; however, when they become\nunreachable they may be garbage-collected. An implementation is\nallowed to postpone garbage collection or omit it altogether -- it is\na matter of implementation quality how garbage collection is\nimplemented, as long as no objects are collected that are still\nreachable. (Implementation note: the current implementation uses a\nreference-counting scheme which collects most objects as soon as they\nbecome unreachable, but never collects garbage containing circular\nreferences.)\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`are 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": "1.6", "length": 4104, "url": "https://docs.python.org/1.6/ref/objects.html"} {"title": "2.5 Operators", "text": "imaginary.html | lexical.html | delimiters.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.5 Operators\nThe following tokens are operators:\n```text\n\n+ - * ** / %\n<< >> & | ^ ~\n< > <= >= == != <>\n```\nThe comparison operators `<>` and `!=` are alternate\nspellings of the same operator. `!=` is the preferred spelling;\n`<>` is obsolescent.", "python_version": "1.6", "length": 358, "url": "https://docs.python.org/1.6/ref/operators.html"} {"title": "2.2 Other tokens", "text": "whitespace.html | lexical.html | identifiers.html | Python Reference Manual | contents.html | genindex.html\n---\n# 2.2 Other tokens\nBesides NEWLINE, INDENT and DEDENT, the following categories of tokens\nexist: identifiers, keywords, literals,\noperators, and delimiters.\nWhitespace characters (other than line terminators, discussed earlier)\nare not tokens, but serve to delimit tokens.\nWhere\nambiguity exists, a token comprises the longest possible string that\nforms a legal token, when read from left to right.", "python_version": "1.6", "length": 510, "url": "https://docs.python.org/1.6/ref/other-tokens.html"} {"title": "5.2.3 Parenthesized forms", "text": "atom-literals.html | atoms.html | lists.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.3 Parenthesized forms\nA parenthesized form is an optional expression list enclosed in\nparentheses:\n```text\n\nparenth_form: \"(\" [expression_list] \")\"\n```\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": "1.6", "length": 959, "url": "https://docs.python.org/1.6/ref/parenthesized.html"} {"title": "6.4 The pass statement", "text": "assignment.html | simple.html | del.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.4 The pass statement\n```text\n\npass_stmt: \"pass\"\n```\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": "1.6", "length": 459, "url": "https://docs.python.org/1.6/ref/pass.html"} {"title": "2.1.2 Physical lines", "text": "logical.html | line-structure.html | comments.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.2 Physical lines\nA physical line ends in whatever the current platform's convention is\nfor terminating lines. On Unix, this is the ASCII LF (linefeed)\ncharacter. On DOS/Windows, it is the ASCII sequence CR LF (return\nfollowed by linefeed). On Macintosh, it is the ASCII CR (return)\ncharacter.", "python_version": "1.6", "length": 412, "url": "https://docs.python.org/1.6/ref/physical.html"} {"title": "5.4 The power operator", "text": "calls.html | expressions.html | unary.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.4 The power operator\nThe power operator binds more tightly than unary operators on its\nleft; it binds less tightly than unary operators on its right. The\nsyntax is:\n```text\n\npower: primary [\"**\" u_expr]\n```\nThus, in an unparenthesized sequence of power and unary operators, the\noperators are evaluated from right to left (this does not constrain\nthe evaluation order for the operands).\nThe power operator has the same semantics as the built-in\npow() function, when called with two arguments: it yields\nits left argument raised to the power of its right argument. The\nnumeric arguments are first converted to a common type. The result\ntype is that of the arguments after coercion; if the result is not\nexpressible in that type (as in raising an integer to a negative\npower, or a negative floating point number to a broken power), a\nTypeError exception is raised.", "python_version": "1.6", "length": 970, "url": "https://docs.python.org/1.6/ref/power.html"} {"title": "5.3 Primaries", "text": "string-conversions.html | expressions.html | attribute-references.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.3 Primaries\nPrimaries represent the most tightly bound operations of the language.\nTheir syntax is:\n```text\n\nprimary: atom | attributeref | subscription | slicing | call\n```", "python_version": "1.6", "length": 310, "url": "https://docs.python.org/1.6/ref/primaries.html"} {"title": "6.6 The print statement", "text": "del.html | simple.html | return.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.6 The print statement\n```text\n\nprint_stmt: \"print\" [ expression (\",\" expression)* [\",\"] ]\n```\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.)\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`in the built-in module sys. If no such object exists, or if\nit does not have a write() method, a RuntimeError\nexception is raised.", "python_version": "1.6", "length": 1279, "url": "https://docs.python.org/1.6/ref/print.html"} {"title": "8.1 Complete Python programs", "text": "top-level.html | top-level.html | file-input.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8.1 Complete Python programs\nWhile a language specification need not prescribe how the language\ninterpreter is invoked, it is useful to have a notion of a complete\nPython program. A complete Python program is executed in a minimally\ninitialized environment: all built-in and standard modules are\navailable, but none have been initialized, except for sys\n(various system services), __builtin__ (built-in functions,\nexceptions and `None`) and __main__. The latter is used\nto provide the local and global namespace for execution of the\ncomplete program.\nThe syntax for a complete Python program is that for file input,\ndescribed in the next section.\nThe interpreter may also be invoked in interactive mode; in this case,\nit does not read and execute a complete program but reads and executes\none statement (possibly compound) at a time. The initial environment\nis identical to that of a coplete 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": "1.6", "length": 1409, "url": "https://docs.python.org/1.6/ref/programs.html"} {"title": "6.8 The raise statement", "text": "return.html | simple.html | break.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.8 The raise statement\n```text\n\nraise_stmt: \"raise\" [expression [\",\" expression [\",\" expression]]]\n```\nIf no expressions are present, raise re-raises the last\nexpression that was raised in the current scope.\nOtherwise, raise evaluates its first expression, which must yield\na string, class, or instance object. If there is a second expression,\nthis is evaluated, else `None` is substituted. If the first\nexpression is a class object, then the second expression may be an\ninstance of that class or one of its derivatives, and then that\ninstance is raised. If the second expression is not such an instance,\nthe given class is instantiated. The argument list for the\ninstantiation is determined as follows: if the second expression is a\ntuple, it is used as the argument list; if it is `None`, the\nargument list is empty; otherwise, the argument list consists of a\nsingle argument which is the second expression. If the first\nexpression is an instance object, the second expression must be\n`None`.\nIf the first object is a string, it then raises the exception\nidentified by the first object, with the second one (or `None`)\nas its parameter. If the first object is a class or instance,\nit raises the exception identified by the class of the instance\ndetermined in the previous step, with the instance as\nits parameter.\nIf a third object is present, and it is not `None`, it should be\na traceback object (see section 3.2 (types.html#traceback)), and it is\nsubstituted instead of the current location as the place where the\nexception occurred. This is useful to re-raise an exception\ntransparently in an except clause.", "python_version": "1.6", "length": 1717, "url": "https://docs.python.org/1.6/ref/raise.html"} {"title": "Python Reference Manual", "text": "../index.html | front.html | Python Reference Manual | contents.html | genindex.html\n---\n# Python Reference Manual\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 238, "url": "https://docs.python.org/1.6/ref/ref.html"} {"title": "6.7 The return statement", "text": "print.html | simple.html | raise.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6.7 The return statement\n```text\n\nreturn_stmt: \"return\" [expression_list]\n```\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`is 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.", "python_version": "1.6", "length": 599, "url": "https://docs.python.org/1.6/ref/return.html"} {"title": "3.3.5 Additional methods for emulation of sequence types", "text": "sequence-types.html | specialnames.html | numeric-types.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.5 Additional methods for emulation of sequence types\nThe following methods can be defined to further emulate sequence\nobjects. Immutable sequences methods should only define\n__getslice__(); mutable sequences, should define all three\nthree methods.\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used. For slice operations involving extended slice\nnotation, __getitem__(), __setitem__()\nor__delitem__() is called.", "python_version": "1.6", "length": 581, "url": "https://docs.python.org/1.6/ref/sequence-methods.html"} {"title": "3.3.4 Emulating sequence and mapping types", "text": "callable-types.html | specialnames.html | sequence-methods.html | Python Reference Manual | contents.html | genindex.html\n---\n## 3.3.4 Emulating sequence and mapping types\nThe following methods can be defined to emulate sequence or mapping\nobjects. 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, and the method __getslice__() (see below) should be\ndefined. It is also recommended that mappings provide methods\nkeys(), values(), items(),\nhas_key(), get(), clear(), copy(),\nand update() behaving similar to those for\nPython's standard dictionary objects; mutable sequences should provide\nmethods append(), count(), index(),\ninsert(), pop(), remove(), reverse()\nand sort(), like Python standard list objects. Finally,\nsequence types should implement addition (meaning concatenation) and\nmultiplication (meaning repetition) by defining the methods\n__add__(), __radd__(), __mul__() and\n__rmul__() described below; they should not define\n__coerce__() or other numerical operators.", "python_version": "1.6", "length": 1159, "url": "https://docs.python.org/1.6/ref/sequence-types.html"} {"title": "5.7 Shifting operations", "text": "binary.html | expressions.html | bitwise.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.7 Shifting operations\nThe shifting operations have lower priority than the arithmetic\noperations:\n```text\n\nshift_expr: a_expr | shift_expr ( \"<<\" | \">>\" ) a_expr\n```\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": "1.6", "length": 841, "url": "https://docs.python.org/1.6/ref/shifting.html"} {"title": "6. Simple statements", "text": "summary.html | ref.html | exprstmts.html | Python Reference Manual | contents.html | genindex.html\n---\n# 6. Simple statements\nSimple statements are comprised within a single logical line.\nSeveral simple statements may occur on a single line separated\nby semicolons. The syntax for simple statements is:\n```text\n\nsimple_stmt: expression_stmt\n| assert_stmt\n| assignment_stmt\n| pass_stmt\n| del_stmt\n| print_stmt\n| return_stmt\n| raise_stmt\n| break_stmt\n| continue_stmt\n| import_stmt\n| global_stmt\n| exec_stmt\n```", "python_version": "1.6", "length": 508, "url": "https://docs.python.org/1.6/ref/simple.html"} {"title": "5.3.3 Slicings", "text": "subscriptions.html | primaries.html | calls.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.3 Slicings\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list). Slicings may be used as expressions or as\ntargets in assignment or del statements. The syntax for a slicing:\n```text\n\nslicing: simple_slicing | extended_slicing\nsimple_slicing: primary \"[\" short_slice \"]\"\nextended_slicing: primary \"[\" slice_list \"]\"\nslice_list: slice_item (\",\" slice_item)* [\",\"]\nslice_item: expression | proper_slice | ellipsis\nproper_slice: short_slice | long_slice\nshort_slice: [lower_bound] \":\" [upper_bound]\nlong_slice: short_slice \":\" [stride]\nlower_bound: expression\nupper_bound: expression\nstride: expression\nellipsis: \"...\"\n```\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": "1.6", "length": 2725, "url": "https://docs.python.org/1.6/ref/slicings.html"} {"title": "3.3 Special method names", "text": "types.html | datamodel.html | customization.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3.3 Special method names\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. For instance, if a class defines\na method named __getitem__(), and `x` is an instance of\nthis class, then `x[i]` is equivalent to\n`x.__getitem__(i)`. (The reverse is not true -- if `x` is\na list object, `x.__getitem__(i)` is not equivalent to\n`x[i]`.) Except where mentioned, attempts to execute an\noperation raise an exception when no appropriate method is defined.", "python_version": "1.6", "length": 680, "url": "https://docs.python.org/1.6/ref/specialnames.html"} {"title": "2.4.2 String literal concatenation", "text": "strings.html | literals.html | numbers.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.2 String literal concatenation\nMultiple adjacent string literals (delimited by whitespace), possibly\nusing different quoting conventions, are allowed, and their meaning is\nthe same as their concatenation. Thus, `\"hello\" 'world'` is\nequivalent to `\"helloworld\"`. This feature can be used to reduce\nthe number of backslashes needed, to split long strings conveniently\nacross long lines, or even to add comments to parts of strings, for\nexample:\n```text\n\nre.compile(\"[A-Za-z_]\" # letter or underscore\n\"[A-Za-z0-9_]*\" # letter, digit or underscore\n)\n```\nNote that this feature is defined at the syntactical level, but\nimplemented at compile time. The `+' operator must be used to\nconcatenate string expressions at run time. Also note that literal\nconcatenation can use different quoting styles for each component\n(even mixing raw strings and triple quoted strings).", "python_version": "1.6", "length": 974, "url": "https://docs.python.org/1.6/ref/string-catenation.html"} {"title": "5.2.6 String conversions", "text": "dict.html | atoms.html | primaries.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.2.6 String conversions\nA string conversion is an expression list enclosed in reverse (a.k.a.\nbackward) quotes:\n```text\n\nstring_conversion: \"`\" expression_list \"`\"\n```\nA string conversion evaluates the contained expression list and\nconverts the resulting object into a string according to rules\nspecific to its type.\nIf the object is a string, a number, `None`, or a tuple, list or\ndictionary containing only objects whose type is one of these, the\nresulting string is a valid Python expression which can be passed to\nthe built-in function eval() to yield an expression with the\nsame value (or an approximation, if floating point numbers are\ninvolved).\n(In particular, converting a string adds quotes around it and converts\n``funny'' characters to escape sequences that are safe to print.)\nIt is illegal to attempt to convert recursive objects (e.g., lists or\ndictionaries that contain a reference to themselves, directly or\nindirectly.)\nThe built-in function repr() performs exactly the same\nconversion in its argument as enclosing it in parentheses and reverse\nquotes does. The built-in function str() performs a\nsimilar but more user-friendly conversion.", "python_version": "1.6", "length": 1263, "url": "https://docs.python.org/1.6/ref/string-conversions.html"} {"title": "2.4.1 String literals", "text": "literals.html | literals.html | string-catenation.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.4.1 String literals\nString literals are described by the following lexical definitions:\n```text\n\nstringliteral: shortstring | longstring\nshortstring: \"'\" shortstringitem* \"'\" | '\"' shortstringitem* '\"'\nlongstring: \"'''\" longstringitem* \"'''\" | '\"\"\"' longstringitem* '\"\"\"'\nshortstringitem: shortstringchar | escapeseq\nlongstringitem: longstringchar | escapeseq\nshortstringchar: \nlongstringchar: \nescapeseq: \"\\\" \n```\nIn plain English: String literals can be enclosed in matching single\nquotes (`'`) or double quotes (`\"`). They can also be\nenclosed in matching groups of three single or double quotes (these\nare generally referred to as triple-quoted strings). The\nbackslash (`\\`) character is used to escape characters that\notherwise have a special meaning, such as newline, backslash itself,\nor the quote character. String literals may optionally be prefixed\nwith a letter `r' or `R'; such strings are called raw strings and use\ndifferent rules for backslash escape sequences.\nIn triple-quoted strings,\nunescaped newlines and quotes are allowed (and are retained), except\nthat three unescaped quotes in a row terminate the string. (A\n``quote'' is the character used to open the string, i.e. either\n`'` or `\"`.)\nUnless an `r' or `R' prefix is present, escape sequences in strings\nare interpreted according to rules similar\nto those used by Standard C. The recognized escape sequences are:\nIn strict compatibility with Standard C, up to three octal digits are\naccepted, but an unlimited number of hex digits is taken to be part of\nthe hex escape (and then the lower 8 bits of the resulting hex number\nare used in 8-bit implementations).\nUnlike Standard C,\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.)\nWhen an `r' or `R' prefix is present, backslashes are still used to\nquote the following character, but all backslashes are left in\nthe string. For example, the string literal `r\"\\n\"` consists\nof two characters: a backslash and a lowercase `n'. String quotes can\nbe escaped with a backslash, but the backslash remains in the string;\nfor example, `r\"\\\"\"` is a valid string literal consisting of two\ncharacters: a backslash and a double quote; `r\"\\\"` is not a value\nstring literal (even a raw string cannot end in an odd number of\nbackslashes). Specifically, a raw string cannot end in a single\nbackslash (since the backslash would escape the following quote\ncharacter). Note also that a single backslash followed by a newline\nis interpreted as those two characters as part of the string,\nnot as a line continuation.", "python_version": "1.6", "length": 2944, "url": "https://docs.python.org/1.6/ref/strings.html"} {"title": "5.3.2 Subscriptions", "text": "attribute-references.html | primaries.html | slicings.html | Python Reference Manual | contents.html | genindex.html\n---\n## 5.3.2 Subscriptions\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n```text\n\nsubscription: primary \"[\" expression_list \"]\"\n```\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": "1.6", "length": 1153, "url": "https://docs.python.org/1.6/ref/subscriptions.html"} {"title": "5.12 Summary", "text": "exprlists.html | expressions.html | simple.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.12 Summary\nThe following table summarizes the operator\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).", "python_version": "1.6", "length": 498, "url": "https://docs.python.org/1.6/ref/summary.html"} {"title": "8. Top-level components", "text": "class.html | ref.html | programs.html | Python Reference Manual | contents.html | genindex.html\n---\n# 8. Top-level components\nThe Python interpreter can get its input from a number of sources:\nfrom a script passed to it as standard input or as program argument,\ntyped in interactively, from a module source file, etc. This chapter\ngives the syntax used in these cases.", "python_version": "1.6", "length": 368, "url": "https://docs.python.org/1.6/ref/top-level.html"} {"title": "7.4 The try statement", "text": "for.html | compound.html | function.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.4 The try statement\nThe try statement specifies exception handlers and/or cleanup\ncode for a group of statements:\n```text\n\ntry_stmt: try_exc_stmt | try_fin_stmt\ntry_exc_stmt: \"try\" \":\" suite\n(\"except\" [expression [\",\" target]] \":\" suite)+\n[\"else\" \":\" suite]\ntry_fin_stmt: \"try\" \":\" suite\n\"finally\" \":\" suite\n```\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 cancelled\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\nsys module: `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 when no exception occurs\nin the try clause. Exceptions in the else clause are\nnot handled by the preceding 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, break or continue statement,\nthe saved exception is lost. The exception information is not\navailable to the program during execution of the finally\nclause.\nWhen a return or break statement is executed in the\ntry suite of a try...finally statement, the\nfinally clause is also executed `on the way out.' A\ncontinue statement is illegal in the try clause. (The\nreason is a problem with the current implementation -- this\nrestriction may be lifted in the future).", "python_version": "1.6", "length": 4261, "url": "https://docs.python.org/1.6/ref/try.html"} {"title": "3.2 The standard type hierarchy", "text": "objects.html | datamodel.html | specialnames.html | Python Reference Manual | contents.html | genindex.html\n---\n# 3.2 The standard type hierarchy\nBelow is a list of the types that are built into Python. Extension\nmodules written in C can define additional types. Future versions of\nPython may add types to the type hierarchy (e.g., rational\nnumbers, efficiently stored arrays of integers, etc.).\nSome of the type descriptions below contain a paragraph listing\n`special attributes.' These are attributes that provide access to the\nimplementation and are not intended for general use. Their definition\nmay change in the future. There are also some `generic' special\nattributes, not listed with the individual objects: __methods__\nis a list of the method names of a built-in object, if it has any;\n__members__ is a list of the data attribute names of a built-in\nobject, if it has any.\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.\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 and floating point numbers:\nIntegers: These represent elements from the mathematical set of whole numbers.\nThere are two types of integers:\nPlain integers: These represent numbers in the range -2147483648 through 2147483647.\n(The range may be larger on machines with a larger natural word\nsize, but not smaller.)\nWhen the result of an operation would fall outside this range, the\nexception OverflowError is raised.\nFor the purpose of shift and mask operations, integers are assumed to\nhave a binary, 2's complement notation using 32 or more bits, and\nhiding no bits from the user (i.e., all 4294967296 different bit\npatterns correspond to different values).\nLong integers: These represent numbers in an unlimited range, subject to available\n(virtual) memory only. For the purpose of shift and mask operations,\na binary representation is assumed, and negative numbers are\nrepresented in a variant of 2's complement which gives the illusion of\nan infinite string of sign bits extending to the left.\nThe rules for integer representation are intended to give the most\nmeaningful interpretation of shift and mask operations involving\nnegative integers and the least surprises when switching between the\nplain and long integer domains. For any operation except left shift,\nif it yields a result in the plain integer domain without causing\noverflow, it will yield the same result in the long integer domain or\nwhen using mixed operands.\nFloating point numbers: These represent machine-level double precision floating point numbers.\nYou are at the mercy of the underlying machine architecture and\nC implementation for the accepted range and handling of overflow.\nPython does not support single-precision floating point numbers; the\nsavings in CPU and memory usage that are usually the reason for using\nthese is dwarfed by the overhead of using objects in Python, so there\nis no reason to complicate the language with two kinds of floating\npoint numbers.\nComplex numbers: These represent complex numbers as a pair of machine-level double\nprecision floating point numbers. The same caveats apply as for\nfloating point numbers. The real and imaginary value of a complex\nnumber `z` can be retrieved through the attributes `z.real`and `z.imag`.\nSequences: These represent finite ordered sets indexed by natural numbers.\nThe built-in function len() returns the\nnumber of items of a sequence.\nWhen the lenth 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 ]`selects all items with index k such that i `<=`k `<` j. When used as an expression, a slice is a\nsequence of the same type. This implies that the index set is\nrenumbered so that it starts at 0.\nSequences are distinguished according to their mutability:\nImmutable sequences: An object of an immutable sequence type cannot change once it is\ncreated. (If the object contains references to other objects,\nthese other objects may be mutable and may be changed; however,\nthe collection of objects directly referenced by an immutable object\ncannot change.)\nThe following types are immutable sequences:\nStrings: The items of a string are characters. There is no separate\ncharacter type; a character is represented by a string of one item.\nCharacters represent (at least) 8-bit bytes. The built-in\nfunctions chr() and\nord() convert between characters and\nnonnegative integers representing the byte values. Bytes with the\nvalues 0-127 usually represent the corresponding ASCII values, but\nthe interpretation of values is up to the program. The string\ndata type is also used to represent arrays of bytes, e.g., to hold data\nread from a file.\n(On systems whose native character set is not ASCII, strings may use\nEBCDIC in their internal representation, provided the functions\nchr() and ord() implement a mapping between ASCII and\nEBCDIC, and string comparison preserves the ASCII order.\nOr perhaps someone can propose a better rule?)\nUnicode: The items of a Unicode object are Unicode characters. A Unicode\ncharacter is represented by a Unicode object of one item and can hold\na 16-bit value representing a Unicode ordinal. The built-in functions\nunichr() and\nord() convert between characters and\nnonnegative integers representing the Unicode ordinals as defined in\nthe Unicode Standard 3.0. Conversion from and to other encodings are\npossible through the Unicode method encode and the built-in\nfunction unicode().\nTuples: The items of a tuple are arbitrary Python objects.\nTuples of two or more items are formed by comma-separated lists\nof expressions. A tuple of one item (a `singleton') can be formed\nby affixing a comma to an expression (an expression by itself does\nnot create a tuple, since parentheses must be usable for grouping of\nexpressions). An empty tuple can be formed by an empty pair of\nparentheses.\nMutable sequences: Mutable sequences can be changed after they are created. The\nsubscription and slicing notations can be used as the target of\nassignment and del (delete) statements.\nThere is currently a single mutable sequence type:\nLists: The items of a list are arbitrary Python objects. Lists are formed\nby placing a comma-separated list of expressions in square brackets.\n(Note that there are no special cases needed to form lists of length 0\nor 1.)\nThe extension module array provides 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 are created by the\n`{...}` notation (see section 5.2.5 (dict.html#dict), ``Dictionary\nDisplays'').\nThe extension modules dbm,\ngdbm, bsddb\nprovide 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;\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.\nOf these, func_code, func_defaults and\nfunc_doc (and this __doc__) may be writable; the\nothers can never be changed.\nAdditional information about a function's definition can be\nretrieved from its code object; see the description of internal types\nbelow.\nUser-defined methods: A user-defined method object combines a class, a class instance (or\n`None`) and a user-defined function.\nSpecial read-only attributes: im_self is the class instance\nobject, im_func is the function object;\nim_class is the class that defined the method (which may be a\nbase class of the class of which im_self is an instance);\n__doc__ is the method's documentation (same as\n`im_func.__doc__`); __name__ is the method name (same as\n`im_func.__name__`).\nUser-defined method objects are created in two ways: when getting an\nattribute of a class that is a user-defined function object, or when\ngetting an attributes of a class instance that is a user-defined\nfunction object. In the former case (class attribute), the\nim_self attribute is `None`, and the method object is said\nto be unbound; in the latter case (instance attribute), im_self\nis the instance, and the method object is said to be bound. For\ninstance, when C is a class which contains a definition for a\nfunction f(), `C.f` does not yield the function object\n`f`; rather, it yields an unbound method object `m` where\n`m.im_class` is C, `m.im_func` is f(), and\n`m.im_self` is `None`. When `x` is a C\ninstance, `x.f` yields a bound method object `m` where\n`m.im_class` is `C`, `m.im_func` is f(), and\n`m.im_self` is `x`.\nWhen an unbound user-defined method object is called, the underlying\nfunction (im_func) is called, with the restriction that the\nfirst argument must be an instance of the proper class\n(im_class) or of a derived class thereof.\nWhen a bound user-defined method object is called, the underlying\nfunction (im_func) is called, inserting the class instance\n(im_self) in front of the argument list. For instance, when\nC is a class which contains a definition for a function\nf(), and `x` is an instance of C, calling\n`x.f(1)` is equivalent to calling `C.f(x, 1)`.\nNote that the transformation from function object to (unbound or\nbound) method object happens each time the attribute is retrieved from\nthe class or instance. In some cases, a fruitful optimization is to\nassign the attribute to a local variable and call that local variable.\nAlso notice that this transformation only happens for user-defined\nfunctions; other callable objects (and all non-callable objects) are\nretrieved without transformation.\nBuilt-in functions: A built-in function object is a wrapper around a C function. Examples\nof built-in functions are len() and math.sin()\n(math is a standard built-in module).\nThe number and type of the arguments are\ndetermined by the C function.\nSpecial read-only attributes: __doc__ is the function's\ndocumentation string, or `None` if unavailable; __name__\nis the function's name; __self__ is set to `None` (but see\nthe next item).\nBuilt-in methods: This is really a different disguise of a built-in function, this time\ncontaining an object passed to the C function as an implicit extra\nargument. An example of a built-in method is\n`list .append()`, assuming\nlist is a list object.\nIn this case, the special read-only attribute __self__ is set\nto the object denoted by `list`.\nClasses: Class objects are described below. When a class object is called,\na new class instance (also described below) is created and\nreturned. This implies a call to the class's __init__() method\nif it has one. Any arguments are passed on to the __init__()\nmethod. If there is no __init__() method, the class must be called\nwithout arguments.\nClass instances: Class instances are described below. Class instances are callable\nonly when the class has a __call__() method; `x(arguments)`is a shorthand for `x.__call__(arguments)`.\nModules: Modules are imported by the import statement (see section\n6.11 (import.html#import), ``The import statement'').\nA module object has a namespace implemented by a dictionary object\n(this is the dictionary referenced by the func_globals attribute of\nfunctions defined in the module). Attribute references are translated\nto lookups in this dictionary, e.g., `m.x` is equivalent to\n`m.__dict__[\"x\"]`.\nA module object does not contain the code object used to\ninitialize the module (since it isn't needed once the initialization\nis done).\nAttribute assignment updates the module's namespace dictionary,\ne.g., \"m.x = 1\" is equivalent to \"m.__dict__[\"x\"] = 1\".\nSpecial read-only attribute: __dict__ is the module's\nnamespace as a dictionary object.\nPredefined (writable) attributes: __name__\nis the module's name; __doc__ is the\nmodule's documentation string, or\n`None` if unavailable; __file__ is the pathname of the\nfile from which the module was loaded, if it was loaded from a file.\nThe __file__ attribute is not present for C modules that are\nstatically linked into the interpreter; for extension modules loaded\ndynamically from a shared library, it is the pathname of the shared\nlibrary file.\nClasses: Class objects are created by class definitions (see section\n7.6 (class.html#class), ``Class definitions'').\nA class has a namespace implemented by a dictionary object.\nClass attribute references are translated to\nlookups in this dictionary,\ne.g., \"C.x\" is translated to \"C.__dict__[\"x\"]\".\nWhen the attribute name is not found\nthere, the attribute search continues in the base classes. The search\nis depth-first, left-to-right in the order of occurrence in the\nbase class list.\nWhen a class attribute reference would yield a user-defined function\nobject, it is transformed into an unbound user-defined method object\n(see above). The im_class attribute of this method object is the\nclass in which the function object was found, not necessarily the\nclass for which the attribute reference was initiated.\nClass attribute assignments update the class's dictionary, never the\ndictionary of a base class.\nA class object can be called (see above) to yield a class instance (see\nbelow).\nSpecial attributes: __name__ is the class name;\n__module__ is the module name in which the class was defined;\n__dict__ is the dictionary containing the class's namespace;\n__bases__ is a tuple (possibly empty or a singleton)\ncontaining the base classes, in the order of their occurrence in the\nbase class list; __doc__ is the class's documentation string,\nor None if undefined.\nClass instances: A class instance is created by calling a class object (see above).\nA class instance has a namespace implemented as a dictionary which\nis the first place in which\nattribute references are searched. When an attribute is not found\nthere, and the instance's class has an attribute by that name,\nthe search continues with the class attributes. If a class attribute\nis found that is a user-defined function object (and in no other\ncase), it is transformed into an unbound user-defined method object\n(see above). The im_class attribute of this method object is\nthe class in which the function object was found, not necessarily the\nclass of the instance for which the attribute reference was initiated.\nIf no class attribute is found, and the object's class has a\n__getattr__() method, that is called to satisfy the lookup.\nAttribute assignments and deletions update the instance's dictionary,\nnever a class's dictionary. If the class has a __setattr__() or\n__delattr__() method, this is called instead of updating the\ninstance dictionary directly.\nClass instances can pretend to be numbers, sequences, or mappings if\nthey have methods with certain special names. See\nsection 3.3 (specialnames.html#specialnames), ``Special method names.''\nSpecial attributes: __dict__ is the attribute\ndictionary; __class__ is the instance's class.\nFiles: A 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 standard input, 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_code is a\nstring representing the sequence of bytecode instructions;\nco_consts is a tuple containing the literals used by the\nbytecode; co_names is a tuple containing the names used by\nthe bytecode; co_filename is the filename from which the code\nwas compiled; co_firstlineno is the first line number of the\nfunction; co_lnotab is a string encoding the mapping from\nbyte code offsets to line numbers (for detais 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; other bits are used internally\nor reserved for future use. If a code\nobject represents a function, the first item in co_consts is\nthe documentation string of the function, or `None` if undefined.\nFrame objects: Frame objects represent execution frames. They may occur in traceback\nobjects (see below).\nSpecial read-only attributes: f_back is to the previous\nstack frame (towards the caller), or `None` if this is the bottom\nstack frame; f_code is the code object being executed in this\nframe; f_locals is the dictionary used to look up local\nvariables; f_globals is used for global variables;\nf_builtins is used for built-in (intrinsic) names;\nf_restricted is a flag indicating whether the function is\nexecuting in restricted execution mode;\nf_lineno gives the line number and f_lasti gives the\nprecise instruction (this is an index into the bytecode string of\nthe code object).\nSpecial writable attributes: f_trace, if not `None`, is a\nfunction called at the start of each source code line (this is used by\nthe debugger); f_exc_type, f_exc_value,\nf_exc_traceback represent the most recent exception caught in\nthis frame.\nTraceback objects: Traceback objects represent a stack trace of an exception. A\ntraceback object is created when an exception occurs. When the search\nfor an exception handler unwinds the execution stack, at each unwound\nlevel a traceback object is inserted in front of the current\ntraceback. When an exception handler is entered, the stack trace is\nmade available to the program.\n(See section 7.4 (try.html#try), ``The `try` statement.'')\nIt is accessible as `sys.exc_traceback`, and also as the third\nitem of the tuple returned by `sys.exc_info()`. The latter is\nthe preferred interface, since it works correctly when the program is\nusing multiple threads.\nWhen the program contains no suitable handler, the stack trace is written\n(nicely formatted) to the standard error stream; if the interpreter is\ninteractive, it is also made available to the user as\n`sys.last_traceback`.\nSpecial read-only attributes: tb_next is the next level in the\nstack trace (towards the frame where the exception occurred), or\n`None` if there is no next level; tb_frame points to the\nexecution frame of the current level; tb_lineno gives the line\nnumber where the exception occurred; tb_lasti indicates the\nprecise instruction. The line number and last instruction in the\ntraceback may differ from the line number of its frame object if the\nexception occurred in a try statement with no matching\nexcept clause or with a finally clause.\nSlice objects: Slice objects are used to represent slices when extended slice\nsyntax is used. This is a slice using two colons, or multiple slices\nor ellipses separated by commas, e.g., `a[i:j:step]`, `a[i:j,\nk:l]`, or `a[..., i:j])`. They are also created by the built-in\nslice() function.\nSpecial read-only attributes: start is the lowerbound;\nstop is the upperbound; step is the step value; each is\n`None` if omitted. These attributes can have any type.", "python_version": "1.6", "length": 22609, "url": "https://docs.python.org/1.6/ref/types.html"} {"title": "5.5 Unary arithmetic operations", "text": "power.html | expressions.html | binary.html | Python Reference Manual | contents.html | genindex.html\n---\n# 5.5 Unary arithmetic operations\nAll unary arithmetic (and bit-wise) operations have the same priority:\n```text\n\nu_expr: power | \"-\" u_expr | \"+\" u_expr | \"~\" u_expr\n```\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": "1.6", "length": 713, "url": "https://docs.python.org/1.6/ref/unary.html"} {"title": "7.2 The while statement", "text": "if.html | compound.html | for.html | Python Reference Manual | contents.html | genindex.html\n---\n# 7.2 The while statement\nThe while statement is used for repeated execution as long\nas an expression is true:\n```text\n\nwhile_stmt: \"while\" expression \":\" suite\n[\"else\" \":\" suite]\n```\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": "1.6", "length": 739, "url": "https://docs.python.org/1.6/ref/while.html"} {"title": "2.1.8 Whitespace between tokens", "text": "indentation.html | line-structure.html | other-tokens.html | Python Reference Manual | contents.html | genindex.html\n---\n## 2.1.8 Whitespace between tokens\nExcept at the beginning of a logical line or in string literals, the\nwhitespace characters space, tab and formfeed can be used\ninterchangeably to separate tokens. Whitespace is needed between two\ntokens only if their concatenation could otherwise be interpreted as a\ndifferent token (e.g., ab is one token, but a b is two tokens).", "python_version": "1.6", "length": 486, "url": "https://docs.python.org/1.6/ref/whitespace.html"} {"title": "Python Tutorial", "text": "../index.html | node1.html | Python Tutorial | node2.html\n---\n# Python Tutorial\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 203, "url": "https://docs.python.org/1.6/tut/index.html"} {"title": "Front Matter", "text": "tut.html | tut.html | node2.html | Python Tutorial | node2.html\n---\n# Front Matter\nBEOPEN.COM TERMS AND CONDITIONS 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 OPEN SOURCE LICENSE AGREEMENT\nPython 1.6 is made available subject to the terms and conditions in\nCNRI's License Agreement. This Agreement together with Python 1.6 may\nbe located on the Internet using the following unique, persistent\nidentifier (known as a handle): 1895.22/1012. This Agreement may also\nbe obtained from a proxy server on the Internet using the following\nURL: http://hdl.handle.net/1895.22/1012.\nCWI PERMISSIONS STATEMENT AND DISCLAIMER\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.\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": "1.6", "length": 6119, "url": "https://docs.python.org/1.6/tut/node1.html"} {"title": "8. Errors and Exceptions", "text": "node9.html | tut.html | node11.html | Python Tutorial | node2.html\n---\n- 8.1 Syntax Errors (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 1 print 'Hello world'\nFile \"\", line 1\nwhile 1 print 'Hello world'\n^\nSyntaxError: invalid syntax\n```\nThe parser repeats the offending line and displays a little `arrow'\npointing at the earliest point in the line where the error was\ndetected. The error is caused by (or at least detected at) the token\npreceding the arrow: in the example, the error is detected at\nthe keyword print, since a colon (\":\") is missing\nbefore it. File name and line number are printed so you know where to\nlook in case the input came from a script.\n# 8.2 Exceptions\nEven if a statement or expression is syntactically correct, it may\ncause an error when an attempt is made to execute it.\nErrors detected during execution are called exceptions and are\nnot unconditionally fatal: you will soon learn how to handle them in\nPython programs. Most exceptions are not handled by programs,\nhowever, and result in error messages as shown here:\n```text\n\n>>> 10 * (1/0)\nTraceback (innermost last):\nFile \"\", line 1\nZeroDivisionError: integer division or modulo\n>>> 4 + spam*3\nTraceback (innermost last):\nFile \"\", line 1\nNameError: spam\n>>> '2' + 2\nTraceback (innermost last):\nFile \"\", line 1\nTypeError: illegal argument type for built-in operation\n```\nThe last line of the error message indicates what happened.\nExceptions come in different types, and the type is printed as part of\nthe message: the types in the example are\nZeroDivisionError, NameError and\nTypeError.\nThe string printed as the exception type is the name of the built-in\nname for the exception that occurred. This is true for all built-in\nexceptions, but need not be true for user-defined exceptions (although\nit is a useful convention).\nStandard exception names are built-in identifiers (not reserved\nkeywords).\nThe rest of the line is a detail whose interpretation depends on the\nexception type; its meaning is dependent on the exception type.\nThe preceding part of the error message shows the context where the\nexception happened, in the form of a stack backtrace.\nIn general it contains a stack backtrace listing source lines; however,\nit will not display lines read from standard input.\nThe Python Library Reference lists the built-in exceptions and\ntheir meanings.\n# 8.3 Handling Exceptions\nIt is possible to write programs that handle selected exceptions.\nLook at the following example, which asks the user for input until a\nvalid integer has been entered, but allows the user to interrupt the\nprogram (using Control-C or whatever the operating system\nsupports); note that a user-generated interruption is signalled by\nraising the KeyboardInterrupt exception.\n```text\n\n>>> while 1:\n... try:\n... x = int(raw_input(\"Please enter a number: \"))\n... break\n... except ValueError:\n... print \"Oops! That was no valid number. Try again...\"\n...\n```\nThe try statement works as follows.\n- First, the try clause (the statement(s) between the\ntry and except keywords) is executed.\n- If no exception occurs, the except clause is skipped and\nexecution of the try statement is finished.\n- If an exception occurs during execution of the try clause, the rest of\nthe clause is skipped. Then if its type matches the exception named\nafter the except keyword, the rest of the try clause is\nskipped, the except clause is executed, and then execution continues\nafter the try statement.\n- If an exception occurs which does not match the exception named in the\nexcept clause, it is passed on to outer try statements; if\nno handler is found, it is an unhandled exception and execution\nstops with a message as shown above.\nA try statement may have more than one except clause, to\nspecify handlers for different exceptions. At most one handler will\nbe executed. Handlers only handle exceptions that occur in the\ncorresponding try clause, not in other handlers of the same\ntry statement. An except clause may name multiple exceptions\nas a parenthesized list, e.g.:\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 exceptions's argument.\nThe presence and type of the argument depend on the exception type.\nFor exception types which have an argument, the except clause may\nspecify a variable after the exception name (or list) to receive the\nargument's value, as follows:\n```text\n\n>>> try:\n... spam()\n... except NameError, x:\n... print 'name', x, 'undefined'\n...\nname spam undefined\n```\nIf an exception has an argument, it is printed as the last part\n(`detail') of the message for unhandled exceptions.\nException handlers don't just handle exceptions if they occur\nimmediately in the try clause, but also if they occur inside functions\nthat are called (even indirectly) in the try clause.\nFor example:\n```text\n\n>>> def this_fails():\n... x = 1/0\n...\n>>> try:\n... this_fails()\n... except ZeroDivisionError, detail:\n... print 'Handling run-time error:', detail\n...\nHandling run-time error: integer division or modulo\n```\n# 8.4 Raising Exceptions\nThe raise statement allows the programmer to force a\nspecified exception to occur.\nFor example:\n```text\n\n>>> raise NameError, 'HiThere'\nTraceback (innermost last):\nFile \"\", line 1\nNameError: HiThere\n```\nThe first argument to raise names the exception to be\nraised. The optional second argument specifies the exception's\nargument.\n# 8.5 User-defined Exceptions\nPrograms may name their own exceptions by assigning a string to a\nvariable or creating a new exception class. For example:\n```text\n\n>>> class MyError:\n... def __init__(self, value):\n... self.value = value\n... def __str__(self):\n... return `self.value`\n...\n>>> try:\n... raise MyError(2*2)\n... except MyError, e:\n... print 'My exception occurred, value:', e.value\n...\nMy exception occurred, value: 4\n>>> raise MyError, 1\nTraceback (innermost last):\nFile \"\", line 1\n__main__.MyError: 1\n```\nMany standard modules use this to report errors that may occur in\nfunctions they define.\nMore information on classes is presented in chapter 9 (node11.html#classes),\n``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 (innermost last):\nFile \"\", line 2\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.\nA try statement must either have one or more except clauses\nor one finally clause, but not both.", "python_version": "1.6", "length": 8881, "url": "https://docs.python.org/1.6/tut/node10.html"} {"title": "9. Classes", "text": "node10.html | tut.html | node12.html | Python Tutorial | node2.html\n---\n- 9.1 A Word About Terminology (node11.html#SECTION0011100000000000000000)\n 9.2 Python Scopes and Name Spaces (node11.html#SECTION0011200000000000000000)\n 9.3 A First Look at Classes (node11.html#SECTION0011300000000000000000)\n - 9.3.1 Class Definition Syntax (node11.html#SECTION0011310000000000000000)\n 9.3.2 Class Objects (node11.html#SECTION0011320000000000000000)\n 9.3.3 Instance Objects (node11.html#SECTION0011330000000000000000)\n 9.3.4 Method Objects (node11.html#SECTION0011340000000000000000)\n 9.4 Random Remarks (node11.html#SECTION0011400000000000000000)\n 9.5 Inheritance (node11.html#SECTION0011500000000000000000)\n - 9.5.1 Multiple Inheritance (node11.html#SECTION0011510000000000000000)\n 9.6 Private Variables (node11.html#SECTION0011600000000000000000)\n 9.7 Odds and Ends (node11.html#SECTION0011700000000000000000)\n - 9.7.1 Exceptions Can Be Classes (node11.html#SECTION0011710000000000000000)\n---\n# 9. Classes\nPython's class mechanism adds classes to the language with a minimum\nof new syntax and semantics. It is a mixture of the class mechanisms\nfound in C++ and Modula-3. As is true for modules, classes in Python\ndo not put an absolute barrier between definition and user, but rather\nrely on the politeness of the user not to ``break into the\ndefinition.'' The most important features of classes are retained\nwith full power, however: the class inheritance mechanism allows\nmultiple base classes, a derived class can override any methods of its\nbase class or classes, a method can call the method of a base class with the\nsame name. Objects can contain an arbitrary amount of private data.\nIn C++ terminology, all class members (including the data members) are\npublic, and all member functions are virtual. There are\nno special constructors or destructors. As in Modula-3, there are no\nshorthands for referencing the object's members from its methods: the\nmethod function is declared with an explicit first argument\nrepresenting the object, which is provided implicitly by the call. As\nin Smalltalk, classes themselves are objects, albeit in the wider\nsense of the word: in Python, all data types are objects. This\nprovides semantics for importing and renaming. But, just like in\nC++ or Modula-3, built-in types cannot be used as base classes for\nextension by the user. Also, like in C++ but unlike in Modula-3, most\nbuilt-in operators with special syntax (arithmetic operators,\nsubscripting etc.) can be redefined for class instances.\n# 9.1 A Word About Terminology\nLacking universally accepted terminology to talk about classes, I will\nmake occasional use of Smalltalk and C++ terms. (I would use Modula-3\nterms, since its object-oriented semantics are closer to those of\nPython than C++, but I expect that few readers have heard of it.)\nI also have to warn you that there's a terminological pitfall for\nobject-oriented readers: the word ``object'' in Python does not\nnecessarily mean a class instance. Like C++ and Modula-3, and\nunlike Smalltalk, not all types in Python are classes: the basic\nbuilt-in types like integers and lists are not, and even somewhat more\nexotic types like files aren't. However, all Python types\nshare a little bit of common semantics that is best described by using\nthe word object.\nObjects have individuality, and multiple names (in multiple scopes)\ncan be bound to the same object. This is known as aliasing in other\nlanguages. This is usually not appreciated on a first glance at\nPython, and can be safely ignored when dealing with immutable basic\ntypes (numbers, strings, tuples). However, aliasing has an\n(intended!) effect on the semantics of Python code involving mutable\nobjects such as lists, dictionaries, and most types representing\nentities outside the program (files, windows, etc.). This is usually\nused to the benefit of the program, since aliases behave like pointers\nin some respects. For example, passing an object is cheap since only\na pointer is passed by the implementation; and if a function modifies\nan object passed as an argument, the caller will see the change -- this\nobviates the need for two different argument passing mechanisms as in\nPascal.\n# 9.2 Python Scopes and Name Spaces\nBefore introducing classes, I first have to tell you something about\nPython's scope rules. Class definitions play some neat tricks with\nname spaces, and you need to know how scopes and name spaces 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 name space is a mapping from names to objects. Most name\nspaces are currently implemented as Python dictionaries, but that's\nnormally not noticeable in any way (except for performance), and it\nmay change in the future. Examples of name spaces are: the set of\nbuilt-in names (functions such as abs(), and built-in exception\nnames); the global names in a module; and the local names in a\nfunction invocation. In a sense the set of attributes of an object\nalso form a name space. The important thing to know about name\nspaces is that there is absolutely no relation between names in\ndifferent name spaces; for instance, two different modules may both\ndefine a function ``maximize'' without confusion -- users of the\nmodules must prefix 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 name\nspace!9.1 (#foot1279)\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, e.g.\n\"del modname.the_answer\".\nName spaces are created at different moments and have different\nlifetimes. The name space containing the built-in names is created\nwhen the Python interpreter starts up, and is never deleted. The\nglobal name space for a module is created when the module definition\nis read in; normally, module name spaces 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 name space. (The\nbuilt-in names actually also live in a module; this is called\n__builtin__.)\nThe local name space 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 name space.\nA scope is a textual region of a Python program where a name space\nis directly accessible. ``Directly accessible'' here means that an\nunqualified reference to a name attempts to find the name in the name\nspace.\nAlthough scopes are determined statically, they are used dynamically.\nAt any time during execution, exactly three nested scopes are in use\n(i.e., exactly three name spaces are directly accessible): the\ninnermost scope, which is searched first, contains the local names,\nthe middle scope, searched next, contains the current module's global\nnames, and the outermost scope (searched last) is the name space\ncontaining built-in names.\nUsually, the local scope references the local names of the (textually)\ncurrent function. Outside of functions, the local scope references\nthe same name space as the global scope: the module's name space.\nClass definitions place yet another name space 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 name\nspace, no matter from where or by what alias the function is called.\nOn the other hand, the actual search for names is done dynamically, at\nrun time -- however, the language definition is evolving towards\nstatic name resolution, at ``compile'' time, so don't rely on dynamic\nname resolution! (In fact, local variables are already determined\nstatically.)\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 name space\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 name space is created, and\nused as the local scope -- thus, all assignments to local variables\ngo into this new name space. 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 name space 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 name space 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(x):\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, e.g., 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, e.g.:\n```text\n\nx.f()\n```\nIn our example, this will return the string `'hello world'`.\nHowever, it is not necessary to call a method right away:\n`x.f` is a method object, and can be stored away and called at a\nlater time. For example:\n```text\n\nxf = x.f\nwhile 1:\nprint xf()\n```\nwill continue to print \"hello world\" until the end of time.\nWhat exactly happens when a method is called? You may have noticed\nthat `x.f()` was called without an argument above, even though\nthe function definition for f specified an argument. What\nhappened to the argument? Surely Python raises an exception when a\nfunction that requires an argument is called without any -- even if\nthe argument isn't actually used...\nActually, you may have guessed the answer: the special thing about\nmethods is that the object is passed as the first argument of the\nfunction. In our example, the call `x.f()` is exactly equivalent\nto `MyClass.f(x)`. In general, calling a method with a list of\nn arguments is equivalent to calling the corresponding function\nwith an argument list that is created by inserting the method's object\nbefore the first argument.\nIf you still don't understand how methods work, a look at the\nimplementation can perhaps clarify matters. When an instance\nattribute is referenced that isn't a data attribute, its class is\nsearched. If the name denotes a valid class attribute that is a\nfunction object, a method object is created by packing (pointers to)\nthe instance object and the function object just found together in an\nabstract object: this is the method object. When the method object is\ncalled with an argument list, it is unpacked again, a new argument\nlist is constructed from the instance object and the original argument\nlist, and the function object is called with this new argument list.\n# 9.4 Random Remarks\n[These should perhaps be placed more carefully...]\nData attributes override method attributes with the same name; to\navoid accidental name conflicts, which may cause hard-to-find bugs in\nlarge programs, it is wise to use some kind of convention that\nminimizes the chance of conflicts, e.g., capitalize method names,\nprefix data attribute names with a small unique string (perhaps just\nan underscore), or use verbs for methods and 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, e.g.:\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, e.g.,\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, e.g. for the debugger, and that's\none reason why this loophole is not closed. (Buglet: derivation of a\nclass with the same name as the base class makes use of private\nvariables of the base class possible.)\nNotice that code passed to `exec`, `eval()` or\n`evalfile()` does not consider the classname of the invoking\nclass to be the current class; this is similar to the effect of the\n`global` statement, the effect of which is likewise restricted to\ncode that is byte-compiled together. The same restriction applies to\n`getattr()`, `setattr()` and `delattr()`, as well as\nwhen referencing `__dict__` directly.\nHere's an example of a class that implements its own\n`__getattr__` and `__setattr__` methods and stores all\nattributes in a private variable, in a way that works in Python 1.4 as\nwell as in previous versions:\n```text\n\nclass VirtualAttributes:\n__vdict = None\n__vdict_name = locals().keys()[0]\n\ndef __init__(self):\nself.__dict__[self.__vdict_name] = {}\n\ndef __getattr__(self, name):\nreturn self.__vdict[name]\n\ndef __setattr__(self, name, value):\nself.__vdict[name] = value\n```\n# 9.7 Odds and Ends\nSometimes it is useful to have a data type similar to the Pascal\n``record'' or C ``struct'', bundling together a couple of named data\nitems. An empty class definition will do nicely, e.g.:\n```text\n\nclass Employee:\npass\n\njohn = Employee() # Create an empty employee record\n\n# Fill the fields of the record\njohn.name = 'John Doe'\njohn.dept = 'computer lab'\njohn.salary = 1000\n```\nA piece of Python code that expects a particular abstract data type\ncan often be passed a class that emulates the methods of that data\ntype instead. For instance, if you have a function that formats some\ndata from a file object, you can define a class with methods\nread() and readline() that gets the data from a string\nbuffer instead, and pass it as an argument.\nInstance method objects have attributes, too: `m.im_self` is the\nobject of which the method is an instance, and `m.im_func` is the\nfunction object corresponding to the method.\n## 9.7.1 Exceptions Can Be Classes\nUser-defined exceptions are no longer limited to being string objects\n-- they can be identified by classes as well. Using this mechanism it\nis possible to create extensible hierarchies of exceptions.\nThere are two new valid (semantic) forms for the raise statement:\n```text\n\nraise Class, instance\n\nraise instance\n```\nIn the first form, `instance` must be an instance of\nClass or of a class derived from it. The second form is a\nshorthand for:\n```text\n\nraise instance.__class__, instance\n```\nAn except clause may list classes as well as string objects. A class\nin an except clause is compatible with an exception if it is the same\nclass or a base class thereof (but not the other way around -- an\nexcept clause listing a derived class is not compatible with a base\nclass). For example, the following code will print B, C, D in that\norder:\n```text\n\nclass B:\npass\nclass C(B):\npass\nclass D(C):\npass\n\nfor c in [B, C, D]:\ntry:\nraise c()\nexcept D:\nprint \"D\"\nexcept C:\nprint \"C\"\nexcept B:\nprint \"B\"\n```\nNote that if the except clauses were reversed (with\n\"except B\" first), it would have printed B, B, B -- the first\nmatching except clause is triggered.\nWhen an error message is printed for an unhandled exception which is a\nclass, the class name is printed, then a colon and a space, and\nfinally the instance converted to a string using the built-in function\nstr().", "python_version": "1.6", "length": 27781, "url": "https://docs.python.org/1.6/tut/node11.html"} {"title": "10. What Now?", "text": "node11.html | tut.html | node13.html | Python Tutorial | node2.html\n---\n# 10. What Now?\nHopefully reading this tutorial has reinforced your interest in using\nPython. Now what should you do?\nYou should read, or at least page through, the Library Reference,\nwhich gives complete (though terse) reference material about types,\nfunctions, and modules that can save you a lot of time when writing\nPython programs. The standard Python distribution includes a\nlot of code in both C and Python; there are modules to read\nUnix mailboxes, retrieve documents via HTTP, generate random\nnumbers, parse command-line options, write CGI programs, compress\ndata, and a lot more; skimming through the Library Reference will give\nyou an idea of what's available.\nThe major Python Web site is http://www.python.org; it contains\ncode, documentation, and pointers to Python-related pages around the\nWeb. This web site is mirrored in various places around the\nworld, such as Europe, Japan, and Australia; a mirror may be faster\nthan the main site, depending on your geographical location. A more\ninformal site is http://starship.python.net/, which contains a\nbunch of Python-related personal home pages; many people have\ndownloadable software there.\nFor Python-related questions and problem reports, you can post to the\nnewsgroup comp.lang.python (news:comp.lang.python), or send them to the mailing\nlist at python-list@cwi.nl. The newsgroup and mailing list\nare gatewayed, so messages posted to one will automatically be\nforwarded to the other. There are around 35-45 postings a day,\nasking (and answering) questions, suggesting new features, and\nannouncing new modules. Before posting, be sure to check the list of\nFrequently Asked Questions (also called the FAQ), at\nhttp://www.python.org/doc/FAQ.html, or look for it in the\nMisc/ directory of the Python source distribution. The FAQ\nanswers many of the questions that come up again and again, and may\nalready contain the solution for your problem.\nYou can support the Python community by joining the Python Software\nActivity, which runs the python.org web, ftp and email servers, and\norganizes Python workshops. See http://www.python.org/psa/ for\ninformation on how to join.", "python_version": "1.6", "length": 2205, "url": "https://docs.python.org/1.6/tut/node12.html"} {"title": "A. Interactive Input Editing and History Substitution", "text": "node12.html | tut.html | node14.html | Python Tutorial | node2.html\n---\n- A.1 Line Editing (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 of the\nline, C-E to the end, C-B moves it one position to the left, C-F to\nthe right. Backspace erases the character to the left of the cursor,\nC-D the character to its right. C-K kills (erases) the rest of the\nline to the right of the cursor, C-Y yanks back the last killed\nstring. C-underscore undoes the last change you made; it can be\nrepeated for 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. C-P\nmoves one line up (back) in the history buffer, C-N moves one down.\nAny line in the history buffer can be edited; an asterisk appears in\nfront of the prompt to mark a line as modified. Pressing the Return\nkey passes the current line to the interpreter. C-R starts an\nincremental reverse search; C-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$HOME/.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# Edit using a single line:\nset horizontal-scroll-mode On\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 TAB\ninstead of Readline's default filename completion function. If you\ninsist, you can override this by putting\n```text\n\nTAB: complete\n```\nin your $HOME/.inputrc. (Of course, this makes it hard to type\nindented 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 $HOME/.pythonrc.py file:\n```text\n\nimport rlcompleter, readline\nreadline.parse_and_bind('tab: complete')\n```\nThis binds the TAB key to the completion function, so hitting the TAB\nkey twice suggests completions; it looks at Python statement names,\nthe current local variables, and the available module names. For\ndotted expressions such as `string.a`, it will evaluate the the\nexpression up to the final \".\" and then suggest completions\nfrom the attributes of the resulting object. Note that this may\nexecute application-defined code if an object with a\n__getattr__() method is part of the expression.\n# A.4 Commentary\nThis facility is an enormous step forward compared to previous\nversions of the interpreter; however, some wishes are left: It would\nbe nice if the proper indentation were suggested on continuation lines\n(the parser knows if an indent token is required next). The\ncompletion mechanism might use the interpreter's symbol table. A\ncommand to check (or even suggest) matching parentheses, quotes etc.\nwould also be useful.", "python_version": "1.6", "length": 4462, "url": "https://docs.python.org/1.6/tut/node13.html"} {"title": "About this document ...", "text": "node13.html | tut.html | Python Tutorial | node2.html\n---\n# About this document ...\nPython Tutorial,\nSeptember 18, 2000, Release 1.6\nThis document was generated using the LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) translator.\nLaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) is Copyright ©\n1993, 1994, 1995, 1996, 1997, Nikos\nDrakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of\nLeeds, and Copyright © 1997, 1998, Ross\nMoore (http://www.maths.mq.edu.au/~ross/), Mathematics Department, Macquarie University,\nSydney.\nThe application of LaTeX2HTML (http://saftsack.fs.uni-bayreuth.de/~latex2ht/) to the Python\ndocumentation has been heavily tailored by Fred L. Drake,\nJr. Original navigation icons were contributed by Christopher\nPetrilli.\n---\n## Comments and Questions\nGeneral comments and questions regarding this document should\nbe sent by email to python-docs@python.org (mailto:python-docs@python.org). If you find specific errors in\nthis document, please report the bug at the Python Bug\nTracker (http://sourceforge.net/bugs/?group_id=5470) at SourceForge (http://sourceforge.net/).\nQuestions regarding how to use the information in this\ndocument should be sent to the Python news group, comp.lang.python (news:comp.lang.python), or the Python mailing list (http://www.python.org/mailman/listinfo/python-list) (which is gated to the newsgroup and\ncarries the same content).\nFor any of these channels, please be sure not to send HTML email.\nThanks.\n---\nnode13.html | tut.html | Python Tutorial | node2.html\n---", "python_version": "1.6", "length": 1583, "url": "https://docs.python.org/1.6/tut/node14.html"} {"title": "Contents", "text": "node1.html | tut.html | node3.html | Python Tutorial\n---\n## Contents\nTable of Contents\n- - 1.1 Where From Here (node3.html)\n 2.1 Invoking the Interpreter (node4.html)\n - 2.1.1 Argument Passing (node4.html#SECTION004110000000000000000)\n 2.1.2 Interactive Mode (node4.html#SECTION004120000000000000000)\n 2.2 The Interpreter and Its Environment (node4.html#SECTION004200000000000000000)\n - 2.2.1 Error Handling (node4.html#SECTION004210000000000000000)\n 2.2.2 Executable Python Scripts (node4.html#SECTION004220000000000000000)\n 2.2.3 The Interactive Startup File (node4.html#SECTION004230000000000000000)\n 3.1 Using Python as a Calculator (node5.html)\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.1 if Statements (node6.html)\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 5.1 More on Lists (node7.html)\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.2 The del statement (node7.html#SECTION007200000000000000000)\n 5.3 Tuples and Sequences (node7.html#SECTION007300000000000000000)\n 5.4 Dictionaries (node7.html#SECTION007400000000000000000)\n 5.5 More on Conditions (node7.html#SECTION007500000000000000000)\n 5.6 Comparing Sequences and Other Types (node7.html#SECTION007600000000000000000)\n 6.1 More on Modules (node8.html)\n - 6.1.1 The Module Search Path (node8.html#SECTION008110000000000000000)\n 6.1.2 ``Compiled'' Python files (node8.html#SECTION008120000000000000000)\n 6.2 Standard Modules (node8.html#SECTION008200000000000000000)\n 6.3 The dir() Function (node8.html#SECTION008300000000000000000)\n 6.4 Packages (node8.html#SECTION008400000000000000000)\n - 6.4.1 Importing * From a Package (node8.html#SECTION008410000000000000000)\n 6.4.2 Intra-package References (node8.html#SECTION008420000000000000000)\n 7.1 Fancier Output Formatting (node9.html)\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.1 Syntax Errors (node10.html)\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.1 A Word About Terminology (node11.html)\n 9.2 Python Scopes and Name Spaces (node11.html#SECTION0011200000000000000000)\n 9.3 A First Look at Classes (node11.html#SECTION0011300000000000000000)\n - 9.3.1 Class Definition Syntax (node11.html#SECTION0011310000000000000000)\n 9.3.2 Class Objects (node11.html#SECTION0011320000000000000000)\n 9.3.3 Instance Objects (node11.html#SECTION0011330000000000000000)\n 9.3.4 Method Objects (node11.html#SECTION0011340000000000000000)\n 9.4 Random Remarks (node11.html#SECTION0011400000000000000000)\n 9.5 Inheritance (node11.html#SECTION0011500000000000000000)\n - 9.5.1 Multiple Inheritance (node11.html#SECTION0011510000000000000000)\n 9.6 Private Variables (node11.html#SECTION0011600000000000000000)\n 9.7 Odds and Ends (node11.html#SECTION0011700000000000000000)\n - 9.7.1 Exceptions Can Be Classes (node11.html#SECTION0011710000000000000000)\n A.1 Line Editing (node13.html)\n A.2 History Substitution (node13.html#SECTION0013200000000000000000)\n A.3 Key Bindings (node13.html#SECTION0013300000000000000000)\n A.4 Commentary (node13.html#SECTION0013400000000000000000)\nEnd of Table of Contents", "python_version": "1.6", "length": 4736, "url": "https://docs.python.org/1.6/tut/node2.html"} {"title": "1. Whetting Your Appetite", "text": "node2.html | tut.html | node4.html | Python Tutorial | node2.html\n---\n- 1.1 Where From Here (node3.html#SECTION003100000000000000000)\n---\n# 1. Whetting Your Appetite\nIf you ever wrote a large shell script, you probably know this\nfeeling: you'd love to add yet another feature, but it's already so\nslow, and so big, and so complicated; or the feature involves a system\ncall or other function that is only accessible from C ...Usually\nthe problem at hand isn't serious enough to warrant rewriting the\nscript in C; perhaps the problem requires variable-length strings or\nother data types (like sorted lists of file names) that are easy in\nthe shell but lots of work to implement in C, or perhaps you're not\nsufficiently familiar with C.\nAnother situation: perhaps you have to work with several C libraries,\nand the usual C write/compile/test/re-compile cycle is too slow. You\nneed to develop software more quickly. Possibly perhaps you've\nwritten a program that could use an extension language, and you don't\nwant to design a language, write and debug an interpreter for it, then\ntie it into your application.\nIn such cases, Python may be just the language for you. Python is\nsimple to use, but it is a real programming language, offering much\nmore structure and support for large programs than the shell has. On\nthe other hand, it also offers much more error checking than C, and,\nbeing a very-high-level language, it has high-level data types\nbuilt in, such as flexible arrays and dictionaries that would cost you\ndays to implement efficiently in C. Because of its more general data\ntypes Python is applicable to a much larger problem domain than\nAwk or even Perl, yet many things are at least as easy\nin Python as in those languages.\nPython allows you to split up your program in modules that can be\nreused in other Python programs. It comes with a large collection of\nstandard modules that you can use as the basis of your programs -- or\nas examples to start learning to program in Python. There are also\nbuilt-in modules that provide things like file I/O, system calls,\nsockets, and even interfaces to GUI toolkits like Tk.\nPython is an interpreted language, which can save you considerable time\nduring program development because no compilation and linking is\nnecessary. The interpreter can be used interactively, which makes it\neasy to experiment with features of the language, to write throw-away\nprograms, or to test functions during bottom-up program development.\nIt is also a handy desk calculator.\nPython allows writing very compact and readable programs. Programs\nwritten in Python are typically much shorter than equivalent C or\nC++ programs, for several reasons:\n- the high-level data types allow you to express complex operations in a\nsingle statement;\n- statement grouping is done by indentation instead of begin/end\nbrackets;\n- no variable or argument declarations are necessary.\nPython is extensible: if you know how to program in C it is easy\nto add a new built-in function or module to the interpreter, either to\nperform critical operations at maximum speed, or to link Python\nprograms to libraries that may only be available in binary form (such\nas a vendor-specific graphics library). Once you are really hooked,\nyou can link the Python interpreter into an application written in C\nand use it as an extension or command language for that application.\nBy the way, the language is named after the BBC show ``Monty Python's\nFlying Circus'' and has nothing to do with nasty reptiles. Making\nreferences to Monty Python skits in documentation is not only allowed,\nit is encouraged!\n# 1.1 Where From Here\nNow that you are all excited about Python, you'll want to examine it\nin some more detail. Since the best way to learn a language is\nusing it, you are invited here to do so.\nIn the next chapter, the mechanics of using the interpreter are\nexplained. This is rather mundane information, but essential for\ntrying out the examples shown later.\nThe rest of the tutorial introduces various features of the Python\nlanguage and system through examples, beginning with simple\nexpressions, statements and data types, through functions and modules,\nand finally touching upon advanced concepts like exceptions\nand user-defined classes.", "python_version": "1.6", "length": 4240, "url": "https://docs.python.org/1.6/tut/node3.html"} {"title": "2. Using the Python Interpreter", "text": "node3.html | tut.html | node5.html | Python Tutorial | node2.html\n---\n- 2.1 Invoking the Interpreter (node4.html#SECTION004100000000000000000)\n - 2.1.1 Argument Passing (node4.html#SECTION004110000000000000000)\n 2.1.2 Interactive Mode (node4.html#SECTION004120000000000000000)\n 2.2 The Interpreter and Its Environment (node4.html#SECTION004200000000000000000)\n - 2.2.1 Error Handling (node4.html#SECTION004210000000000000000)\n 2.2.2 Executable Python Scripts (node4.html#SECTION004220000000000000000)\n 2.2.3 The Interactive Startup File (node4.html#SECTION004230000000000000000)\n---\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 EOF character (Control-D on Unix, Control-Z on DOS\nor Windows) at the primary prompt causes the interpreter to exit with\na zero exit status. If that doesn't work, you can exit the\ninterpreter by typing the following commands: \"import sys;\nsys.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 for an introduction to the\nkeys. If nothing appears to happen, or if `P` is echoed,\ncommand line editing isn't available; you'll only be able to use\nbackspace to remove characters from the current line.\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, e.g.:\n```text\n\npython\nPython 1.6 (#22, Sep 2 2000, 23:54:55) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2\nCopyright (c) 1995-2000 Corporation for National Research Initiatives.\nAll Rights Reserved.\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.\n>>>\n```\nContinuation lines are needed when entering a multi-line construct.\nAs an example, take a look at this if statement:\n```text\n\n>>> the_world_is_flat = 1\n>>> if the_world_is_flat:\n... print \"Be careful not to fall off!\"\n...\nBe careful not to fall off!\n```\n# 2.2 The Interpreter and Its Environment\n## 2.2.1 Error Handling\nWhen an error occurs, the interpreter prints an error\nmessage and a stack trace. In interactive mode, it then returns to\nthe primary prompt; when input came from a file, it exits with a\nnonzero exit status after printing\nthe stack trace. (Exceptions handled by an `except` clause in a\n`try` statement are not errors in this context.) Some errors are\nunconditionally fatal and cause an exit with a nonzero exit; this\napplies to internal inconsistencies and some cases of running out of\nmemory. All error messages are written to the standard error stream;\nnormal output from the executed commands is written to standard\noutput.\nTyping the interrupt character (usually Control-C or DEL) to the\nprimary or secondary prompt cancels the input and returns to the\nprimary prompt.2.1 (#foot108)Typing an interrupt while a command is executing raises the\n`KeyboardInterrupt` exception, which may be handled by a\n`try` statement.\n## 2.2.2 Executable Python Scripts\nOn BSD'ish Unix systems, Python scripts can be made directly\nexecutable, like shell scripts, by putting the line\n```text\n\n#! /usr/bin/env python\n```\n(assuming that the interpreter is on the user's $PATH) at the\nbeginning of the script and giving the file an executable mode. The\n\"#!\" must be the first two characters of the file. Note that\nthe hash, or pound, character, \"#\", is used to start a\ncomment in Python.\n## 2.2.3 The Interactive Startup File\nWhen you use Python interactively, it is frequently handy to have some\nstandard commands executed every time the interpreter is started. You\ncan do this by setting an environment variable named\n$PYTHONSTARTUP 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 name space 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,\ne.g. \"execfile('.pythonrc.py')\". If\nyou want to use the startup file in a script, you must do this\nexplicitly in the script:\n```text\n\nimport os\nif os.environ.get('PYTHONSTARTUP') \\\nand os.path.isfile(os.environ['PYTHONSTARTUP']):\nexecfile(os.environ['PYTHONSTARTUP'])\n```", "python_version": "1.6", "length": 7694, "url": "https://docs.python.org/1.6/tut/node4.html"} {"title": "3. An Informal Introduction to Python", "text": "node4.html | tut.html | node6.html | Python Tutorial | node2.html\n---\n- 3.1 Using Python as a Calculator (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>>> 4 * 2.5 / 3.3\n3.0303030303\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=1.5+0.5j\n>>> float(a)\nTraceback (innermost last):\nFile \"\", line 1, in ?\nTypeError: can't convert complex to float; use e.g. abs(z)\n>>> a.real\n1.5\n>>> abs(a)\n1.58113883008\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 = 17.5 / 100\n>>> price = 3.50\n>>> price * tax\n0.6125\n>>> price + _\n4.1125\n>>> round(_, 2)\n4.11\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. Newlines can\nbe escaped with backslashes, e.g.:\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```\nwhich 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```\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\nstring.strip('str') 'ing'\n^\nSyntaxError: invalid syntax\n```\nStrings can be subscripted (indexed); like in C, the first character\nof a string has subscript (index) 0. There is no separate character\ntype; a character is simply a string of size one. Like in Icon,\nsubstrings can be specified with the slice notation: two indices\nseparated by a colon.\n```text\n\n>>> word[4]\n'A'\n>>> word[0:2]\n'He'\n>>> word[2:4]\n'lp'\n```\nUnlike a C string, Python strings cannot be changed. Assigning to an\nindexed position in the string results in an error:\n```text\n\n>>> word[0] = 'x'\nTraceback (innermost last):\nFile \"\", line 1, in ?\nTypeError: object doesn't support item assignment\n>>> word[:-1] = 'Splat'\nTraceback (innermost 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[-1:]\n'SplatA'\n```\nSlice indices have useful defaults; an omitted first index defaults to\nzero, an omitted second index defaults to the size of the string being\nsliced.\n```text\n\n>>> word[:2] # The first two characters\n'He'\n>>> word[2:] # All but the first two characters\n'lpA'\n```\nHere's a useful invariant of slice operations:\n`s[:i] + s[i:]` equals `s`.\n```text\n\n>>> word[:2] + word[2:]\n'HelpA'\n>>> word[:3] + word[3:]\n'HelpA'\n```\nDegenerate slice indices are handled gracefully: an index that is too\nlarge is replaced by the string size, an upper bound smaller than the\nlower bound returns an empty string.\n```text\n\n>>> word[1:100]\n'elpA'\n>>> word[10:]\n''\n>>> word[2:1]\n''\n```\nIndices may be negative numbers, to start counting from the right.\nFor example:\n```text\n\n>>> word[-1] # The last character\n'A'\n>>> word[-2] # The last-but-one character\n'p'\n>>> word[-2:] # The last two characters\n'pA'\n>>> word[:-2] # All but the last two characters\n'Hel'\n```\nBut note that -0 is really the same as 0, so it does not count from\nthe right!\n```text\n\n>>> word[-0] # (since -0 equals 0)\n'H'\n```\nOut-of-range negative slice indices are truncated, but don't try this\nfor single-element (non-slice) indices:\n```text\n\n>>> word[-100:]\n'HelpA'\n>>> word[-10] # error\nTraceback (innermost last):\nFile \"\", line 1\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, e.g., 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 1.6 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 intergrates 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 internalization (usually written as \"i18n\" -- \"i\" +\n18 characters + \"n\") of software. Unicode solves these\nproblems 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 HEX ordinal 0x0020 (the space character) at the\ngiven position.\nOther characters are interpreted by using their respective ordinal\nvalue directly as Unicode ordinal. Due to the fact that the lower 256\nUnicode are the same as the standard Latin-1 encoding used in many\nwestern countries, the process of entering Unicode is greatly\nsimplified.\nFor experts, there is also a raw mode just like for normal\nstrings. You have to prepend the string with a small 'r' 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 backslashes\ne.g. in regular expressions.\nApart from these standard encodings, Python provides a whole set of\nother ways of creating Unicod strings on the basis of a known\nencoding.\nThe builtin unicode() provides access\nto all registered Unicode codecs (COders and DECoders). Some of the\nmore well known encodings which these codecs can convert are\nLatin-1, ASCII, UTF-8 and UTF-16. The latter two\nare variable length encodings which permit to store Unicode characters\nin 8 or 16 bits. Python uses UTF-8 as default encoding. This becomes\nnoticable when printing Unicode strings or writing them to files.\n```text\n\n>>> u\"\"\nu'\\344\\366\\374'\n>>> str(u\"\")\n'\\303\\244\\303\\266\\303\\274'\n```\nIf you have data in a specific encoding and want to produce a\ncorresponding Unicode string from it, you can use the\nunicode() builtin with the encoding name as second\nargument.\n```text\n\n>>> unicode('\\303\\244\\303\\266\\303\\274','UTF-8')\nu'\\344\\366\\374'\n```\nTo convert the Unicode string back into a string using the original\nencoding, the objects provide an encode() method.\n```text\n\n>>> u\"\".encode('UTF-8')\n'\\303\\244\\303\\266\\303\\274'\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\nsubsequence 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": "1.6", "length": 17488, "url": "https://docs.python.org/1.6/tut/node5.html"} {"title": "4. More Control Flow Tools", "text": "node5.html | tut.html | node7.html | Python Tutorial | node2.html\n---\n- 4.1 if Statements (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 a number: \"))\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 (e.g., 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, i.e., lists). If\nyou need to modify the list you are iterating over, e.g., duplicate\nselected items, you must iterate over a copy. The slice notation\nmakes 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, e.g.:\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... print n, 'is a prime number'\n...\n2 is a prime number\n3 is a prime number\n4 equals 2 * 2\n5 is a prime number\n6 equals 2 * 3\n7 is a prime number\n8 equals 2 * 4\n9 equals 3 * 3\n```\n# 4.5 pass Statements\nThe pass statement does nothing.\nIt can be used when a statement is required syntactically but the\nprogram requires no action.\nFor example:\n```text\n\n>>> while 1:\n... pass # Busy-wait for keyboard interrupt\n...\n```\n# 4.6 Defining Functions\nWe can create a function that writes the Fibonacci series to an\narbitrary boundary:\n```text\n\n>>> def fib(n): # write Fibonacci series up to n\n... \"Print a Fibonacci series up to n\"\n... a, b = 0, 1\n... while b < n:\n... print b,\n... a, b = b, a+b\n...\n>>> # Now call the function we just defined:\n... fib(2000)\n1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597\n```\nThe keyword def introduces a function definition. It\nmust be followed by the function name and the parenthesized list of\nformal parameters. The statements that form the body of the function\nstart at the next line, and must be indented. The first statement of\nthe function body can optionally be a string literal; this string\nliteral is the function's documentation\nstring, or docstring.\nThere are tools which use docstrings to automatically produce online\nor printed documentation, or to let the user interactively browse\nthrough code; it's good practice to include docstrings in code that\nyou write, so try to make a habit of it.\nThe execution of a function introduces a new symbol table used\nfor the local variables of the function. More precisely, all variable\nassignments in a function store the value in the local symbol table;\nwhereas variable references first look in the local symbol table, then\nin the global symbol table, and then in the table of built-in names.\nThus, global variables cannot be directly assigned a value within a\nfunction (unless named in a global statement), although\nthey may be referenced.\nThe actual parameters (arguments) to a function call are introduced in\nthe local symbol table of the called function when it is called; thus,\narguments are passed using call by value (where the\nvalue is always an object reference, not the value of\nthe object).4.1 (#foot1221) 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 is used to return from\nthe middle of a procedure (falling off the end also returns from a\nprocedure), in which case the `None` value is returned.\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, e.g.\n```text\n\ndef ask_ok(prompt, retries=4, complaint='Yes or no, please!'):\nwhile 1:\nok = raw_input(prompt)\nif ok in ('y', 'ye', 'yes'): return 1\nif ok in ('n', 'no', 'nop', 'nope'): return 0\nretries = retries - 1\nif retries < 0: raise IOError, 'refusenik user'\nprint complaint\n```\nThis function can be called either like this:\n`ask_ok('Do you really want to quit?')` or like this:\n`ask_ok('OK to overwrite the file?', 2)`.\nThe default values are evaluated at the point of function definition\nin the defining scope, so that e.g.\n```text\n\ni = 5\ndef f(arg = i): print arg\ni = 6\nf()\n```\nwill print `5`.\nImportant warning: The default value is evaluated only once.\nThis makes a difference when the default is a mutable object such as a\nlist or dictionary. For example, the following function accumulates\nthe arguments passed to it on subsequent calls:\n```text\n\ndef f(a, l = []):\nl.append(a)\nreturn l\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 (innermost last):\nFile \"\", line 1, in ?\nTypeError: keyword parameter redefined\n```\nWhen a final formal parameter of the form `** name` is\npresent, it receives a dictionary containing all keyword arguments\nwhose keyword doesn't correspond to a formal parameter. This may be\ncombined with a formal parameter of the form\n`* name` (described in the next subsection) which receives a\ntuple containing the positional arguments beyond the formal parameter\nlist. (`* name` must occur before `** name`.)\nFor example, if we define a function like this:\n```text\n\ndef cheeseshop(kind, *arguments, **keywords):\nprint \"-- Do you have any\", kind, '?'\nprint \"-- I'm sorry, we're all out of\", kind\nfor arg in arguments: print arg\nprint '-'*40\nfor kw in keywords.keys(): print kw, ':', keywords[kw]\n```\nIt could be called like this:\n```text\n\ncheeseshop('Limburger', \"It's very runny, sir.\",\n\"It's really very, VERY runny, sir.\",\nclient='John Cleese',\nshopkeeper='Michael Palin',\nsketch='Cheese Shop Sketch')\n```\nand of course it would print:\n```text\n\n-- Do you have any Limburger ?\n-- I'm sorry, we're all out of Limburger\nIt's very runny, sir.\nIt's really very, VERY runny, sir.\n----------------------------------------\nclient : John Cleese\nshopkeeper : Michael Palin\nsketch : Cheese Shop Sketch\n```\n## 4.7.3 Arbitrary Argument Lists\nFinally, the least frequently used option is to specify that a\nfunction can be called with an arbitrary number of arguments. These\narguments will be wrapped up in a tuple. Before the variable number\nof arguments, zero or more normal arguments may occur.\n```text\n\ndef fprintf(file, format, *args):\nfile.write(format % args)\n```\n## 4.7.4 Lambda Forms\nBy popular demand, a few features commonly found in functional\nprogramming languages and Lisp have been added to Python. With the\nlambda keyword, small anonymous functions can be created.\nHere's a function that returns the sum of its two arguments:\n\"lambda a, b: a+b\". Lambda forms can be used wherever function\nobjects are required. They are syntactically restricted to a single\nexpression. Semantically, they are just syntactic sugar for a normal\nfunction definition. Like nested function definitions, lambda forms\ncannot reference variables from the containing scope, but this can be\novercome through the judicious use of default argument values, e.g.\n```text\n\ndef make_incrementor(n):\nreturn lambda x, incr=n: x+incr\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": "1.6", "length": 16186, "url": "https://docs.python.org/1.6/tut/node6.html"} {"title": "5. Data Structures", "text": "node6.html | tut.html | node8.html | Python Tutorial | node2.html\n---\n- 5.1 More on Lists (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.2 The del statement (node7.html#SECTION007200000000000000000)\n 5.3 Tuples and Sequences (node7.html#SECTION007300000000000000000)\n 5.4 Dictionaries (node7.html#SECTION007400000000000000000)\n 5.5 More on Conditions (node7.html#SECTION007500000000000000000)\n 5.6 Comparing Sequences and Other Types (node7.html#SECTION007600000000000000000)\n---\n# 5. Data Structures\nThis chapter describes some things you've learned about already in\nmore detail, and adds some new things as well.\n# 5.1 More on Lists\nThe list data type has some more methods. Here are all of the methods\nof list objects:\n`append(x)`: Add an item to the end of the list;\nequivalent to `a[len(a):] = [x]`.\n`extend(L)`: Extend the list by appending all the items in the given list;\nequivalent to `a[len(a):] = L`.\n`insert(i, x)`: Insert an item at a given position. The first argument is the index of\nthe element before which to insert, so `a.insert(0, x)` inserts at\nthe front of the list, and `a.insert(len(a), x)` is equivalent to\n`a.append(x)`.\n`remove(x)`: Remove the first item from the list whose value is `x`.\nIt is an error if there is no such item.\n`pop( [ i ] )`: Remove the item at the given position in the list, and return it. If\nno index is specified, `a.pop()` returns the last item in the\nlist. The item is also removed from the list.\n`index(x)`: Return the index in the list of the first item whose value is `x`.\nIt is an error if there is no such item.\n`count(x)`: Return the number of times `x` appears in the list.\n`sort()`: Sort the items of the list, in place.\n`reverse()`: Reverse the elements of the list, in place.\nAn example that uses most of the list methods:\n```text\n\n>>> a = [66.6, 333, 333, 1, 1234.5]\n>>> print a.count(333), a.count(66.6), a.count('x')\n2 1 0\n>>> a.insert(2, -1)\n>>> a.append(333)\n>>> a\n[66.6, 333, -1, 333, 1, 1234.5, 333]\n>>> a.index(333)\n1\n>>> a.remove(333)\n>>> a\n[66.6, -1, 333, 1, 1234.5, 333]\n>>> a.reverse()\n>>> a\n[333, 1234.5, 1, 333, -1, 66.6]\n>>> a.sort()\n>>> a\n[-1, 1, 66.6, 333, 333, 1234.5]\n```\n## 5.1.1 Using Lists as Stacks\nThe list methods make it very easy to use a list as a stack, where the\nlast element added is the first element retrieved (``last-in,\nfirst-out''). To add an item to the top of the stack, use\nappend(). To retrieve an item from the top of the stack, use\npop() without an explicit index. For example:\n```text\n\n>>> stack = [3, 4, 5]\n>>> stack.append(6)\n>>> stack.append(7)\n>>> stack\n[3, 4, 5, 6, 7]\n>>> stack.pop()\n7\n>>> stack\n[3, 4, 5, 6]\n>>> stack.pop()\n6\n>>> stack.pop()\n5\n>>> stack\n[3, 4]\n```\n## 5.1.2 Using Lists as Queues\nYou can also use a list conveniently as a queue, where the first\nelement added is the first element retrieved (``first-in,\nfirst-out''). To add an item to the back of the queue, use\nappend(). To retrieve an item from the front of the queue,\nuse pop() with `0` as the index. For example:\n```text\n\n>>> queue = [\"Eric\", \"John\", \"Michael\"]\n>>> queue.append(\"Terry\") # Terry arrives\n>>> queue.append(\"Graham\") # Graham arrives\n>>> queue.pop(0)\n'Eric'\n>>> queue.pop(0)\n'John'\n>>> queue\n['Michael', 'Terry', 'Graham']\n```\n## 5.1.3 Functional Programming Tools\nThere are three built-in functions that are very useful when used with\nlists: filter(), map(), and reduce().\n\"filter(function, sequence)\" returns a sequence (of\nthe same type, if possible) consisting of those items from the\nsequence for which `function ( item )` is true. For\nexample, to compute some primes:\n```text\n\n>>> def f(x): return x % 2 != 0 and x % 3 != 0\n...\n>>> filter(f, range(2, 25))\n[5, 7, 11, 13, 17, 19, 23]\n```\n\"map(function, sequence)\" calls\n`function ( item )` for each of the sequence's items and\nreturns a list of the return values. For example, to compute some\ncubes:\n```text\n\n>>> def cube(x): return x*x*x\n...\n>>> map(cube, range(1, 11))\n[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]\n```\nMore than one sequence may be passed; the function must then have as\nmany arguments as there are sequences and is called with the\ncorresponding item from each sequence (or `None` if some sequence\nis shorter than another). If `None` is passed for the function,\na function returning its argument(s) is substituted.\nCombining these two special cases, we see that\n\"map(None, list1, list2)\" is a convenient way of\nturning a pair of lists into a list of pairs. For example:\n```text\n\n>>> seq = range(8)\n>>> def square(x): return x*x\n...\n>>> map(None, seq, map(square, seq))\n[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]\n```\n\"reduce(func, sequence)\" returns a single value\nconstructed by calling the binary function func on the first two\nitems of the sequence, then on the result and the next item, and so\non. For example, to compute the sum of the numbers 1 through 10:\n```text\n\n>>> def add(x,y): return x+y\n...\n>>> reduce(add, range(1, 11))\n55\n```\nIf there's only one item in the sequence, its value is returned; if\nthe sequence is empty, an exception is raised.\nA third argument can be passed to indicate the starting value. In this\ncase the starting value is returned for an empty sequence, and the\nfunction is first applied to the starting value and the first sequence\nitem, then to the result and the next item, and so on. For example,\n```text\n\n>>> def sum(seq):\n... def add(x,y): return x+y\n... return reduce(add, seq, 0)\n...\n>>> sum(range(1, 11))\n55\n>>> sum([])\n0\n```\n# 5.2 The del statement\nThere is a way to remove an item from a list given its index instead\nof its value: the `del` statement. This can also be used to\nremove slices from a list (which we did earlier by assignment of an\nempty list to the slice). For example:\n```text\n\n>>> a\n[-1, 1, 66.6, 333, 333, 1234.5]\n>>> del a[0]\n>>> a\n[1, 66.6, 333, 333, 1234.5]\n>>> del a[2:4]\n>>> a\n[1, 66.6, 1234.5]\n```\ndel can also be used to delete entire variables:\n```text\n\n>>> del a\n```\nReferencing the name `a` hereafter is an error (at least until\nanother value is assigned to it). We'll find other uses for\ndel later.\n# 5.3 Tuples and Sequences\nWe saw that lists and strings have many common properties, e.g.,\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, e.g., (x, y) coordinate pairs, employee records\nfrom a database, etc. Tuples, like strings, are immutable: it is not\npossible to assign to the individual items of a tuple (you can\nsimulate much of the same effect with slicing and concatenation,\nthough).\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, e.g.:\n```text\n\n>>> x, y, z = t\n```\nThis is called, appropriately enough, tuple unpacking. Tuple\nunpacking requires that the list of variables on the left have the same\nnumber of elements as the length of the tuple. Note that multiple\nassignment is really just a combination of tuple packing and tuple\nunpacking!\nOccasionally, the corresponding operation on lists is useful: list\nunpacking. This is supported by enclosing the list of variables in\nsquare brackets:\n```text\n\n>>> a = ['spam', 'eggs', 100, 1234]\n>>> [a1, a2, a3, a4] = a\n```\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. You can't use lists as keys, since lists can be\nmodified in place using their `append()` method.\nIt is best to think of a dictionary as an unordered set of\nkey:value pairs, with the requirement that the keys are unique\n(within one dictionary).\nA pair of braces creates an empty dictionary: `{}`.\nPlacing a comma-separated list of key:value pairs within the\nbraces adds initial key:value pairs to the dictionary; this is also the\nway dictionaries are written on output.\nThe main operations on a dictionary are storing a value with some key\nand extracting the value given the key. It is also possible to delete\na key:value pair\nwith `del`.\nIf you store using a key that is already in use, the old value\nassociated with that key is forgotten. It is an error to extract a\nvalue using a non-existent key.\nThe `keys()` method of a dictionary object returns a list of all\nthe keys used in the dictionary, in random order (if you want it\nsorted, just apply the `sort()` method to the list of keys). To\ncheck whether a single key is in the dictionary, use the\n`has_key()` method of the dictionary.\nHere is a small example using a dictionary:\n```text\n\n>>> tel = {'jack': 4098, 'sape': 4139}\n>>> tel['guido'] = 4127\n>>> tel\n{'sape': 4139, 'guido': 4127, 'jack': 4098}\n>>> tel['jack']\n4098\n>>> del tel['sape']\n>>> tel['irv'] = 4127\n>>> tel\n{'guido': 4127, 'irv': 4127, 'jack': 4098}\n>>> tel.keys()\n['guido', 'irv', 'jack']\n>>> tel.has_key('guido')\n1\n```\n# 5.5 More on Conditions\nThe conditions used in `while` and `if` statements above can\ncontain other operators besides comparisons.\nThe comparison operators `in` and `not in` check whether a value\noccurs (does not occur) in a sequence. The operators `is` and\n`is not` compare whether two objects are really the same object; this\nonly matters for mutable objects like lists. All comparison operators\nhave the same priority, which is lower than that of all numerical\noperators.\nComparisons can be chained: e.g., `a < b == c` tests whether\n`a` is less than `b` and moreover `b` equals `c`.\nComparisons may be combined by the Boolean operators `and` and\n`or`, and the outcome of a comparison (or of any other Boolean\nexpression) may be negated with `not`. These all have lower\npriorities than comparison operators again; between them, `not` has\nthe highest priority, and `or` the lowest, so that\n`A and not B or C` is equivalent to `(A and (not B)) or C`. Of\ncourse, parentheses can be used to express the desired composition.\nThe Boolean operators `and` and `or` are so-called\nshortcut operators: their arguments are evaluated from left to\nright, and evaluation stops as soon as the outcome is determined.\nE.g., if `A` and `C` are true but `B` is false, `A\nand B and C` does not evaluate the expression C. In general, the\nreturn value of a shortcut operator, when used as a general value and\nnot as a Boolean, is the last evaluated argument.\nIt is possible to assign the result of a comparison or other Boolean\nexpression to a variable. For example,\n```text\n\n>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n>>> non_null = string1 or string2 or string3\n>>> non_null\n'Trondheim'\n```\nNote that in Python, unlike C, assignment cannot occur inside expressions.\nC programmers may grumble about this, but it avoids a common class of\nproblems encountered in C programs: typing `=` in an expression when\n`==` was intended.\n# 5.6 Comparing Sequences and Other Types\nSequence objects may be compared to other objects with the same\nsequence type. The comparison uses lexicographical ordering:\nfirst the first two items are compared, and if they differ this\ndetermines the outcome of the comparison; if they are equal, the next\ntwo items are compared, and so on, until either sequence is exhausted.\nIf two items to be compared are themselves sequences of the same type,\nthe lexicographical comparison is carried out recursively. If all\nitems of two sequences compare equal, the sequences are considered\nequal. If one sequence is an initial subsequence of the other, the\nshorted sequence is the smaller one. Lexicographical ordering for\nstrings uses the ASCII ordering for individual characters. Some\nexamples of comparisons between sequences with the same 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 (#foot596)", "python_version": "1.6", "length": 13827, "url": "https://docs.python.org/1.6/tut/node7.html"} {"title": "6. Modules", "text": "node7.html | tut.html | node9.html | Python Tutorial | node2.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---\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 (#foot617)\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, i.e., 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),\n$PYTHONPATH and the installation-dependent default. This allows\nPython programs that know what they're doing to modify or replace the\nmodule search path. See the section on Standard Modules later.\n## 6.1.2 ``Compiled'' Python files\nAs an important speed-up of the start-up time for short programs that\nuse a lot of standard modules, if a file called spam.pyc exists\nin the directory where spam.py is found, this is assumed to\ncontain an already-``byte-compiled'' version of the module spam.\nThe modification time of the version of spam.py used to create\nspam.pyc is recorded in spam.pyc, and the\n.pyc file is ignored if these don't match.\nNormally, you don't need to do anything to create the\nspam.pyc file. Whenever spam.py is successfully\ncompiled, an attempt is made to write the compiled version to\nspam.pyc. It is not an error if this attempt fails; if for any\nreason the file is not written completely, the resulting\nspam.pyc file will be recognized as invalid and thus ignored\nlater. The contents of the spam.pyc file are platform\nindependent, so a Python module directory can be shared by machines of\ndifferent architectures.\nSome tips for experts:\n- When the Python interpreter is invoked with the -O flag,\noptimized code is generated and stored in .pyo files.\nThe optimizer currently doesn't help much; it only removes\nassert statements and `SET_LINENO` instructions.\nWhen -O is used, all bytecode is optimized;\n`.pyc` files are ignored and `.py` files are compiled to\noptimized bytecode.\n- Passing two -O flags to the Python interpreter\n(-OO) will cause the bytecode compiler to perform\noptimizations that could in some rare cases result in malfunctioning\nprograms. Currently only `__doc__` strings are removed from the\nbytecode, resulting in more compact .pyo files. Since some\nprograms may rely on having these available, you should only use this\noption if you know what you're doing.\n- A program doesn't run any faster when it is read from a .pyc or\n.pyo file than when it is read from a .py file; the only\nthing that's faster about .pyc or .pyo files is the\nspeed with which they are loaded.\n- When a script is run by giving its name on the command line, the\nbytecode for the script is never written to a .pyc or\n.pyo file. Thus, the startup time of a script may be reduced\nby moving most of its code to a module and having a small bootstrap\nscript that imports that module.\n- It is possible to have a file called spam.pyc (or\nspam.pyo when -O is used) without a module\nspam.py in the same module. This can be used to distribute\na library of Python code in a form that is moderately hard to reverse\nengineer.\n- The module compileall can 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; e.g.,\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, e.g.:\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['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',\n'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',\n'stderr', 'stdin', 'stdout', 'version']\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['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',\n'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',\n'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',\n'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',\n'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',\n'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',\n'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',\n'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',\n'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']\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,\ne.g. .wav, .aiff, .au), so you may need to create\nand maintain a growing collection of modules for the conversion\nbetween the various file formats. There are also many different\noperations you might want to perform on sound data (e.g. mixing,\nadding echo, applying an equalizer function, creating an artificial\nstereo effect), so in addition you will be writing a never-ending\nstream of modules to perform these operations. Here's a possible\nstructure for your package (expressed in terms of a hierarchical\nfilesystem):\n```text\n\nSound/ Top-level package\n__init__.py Initialize the sound package\nFormats/ Subpackage for file format conversions\n__init__.py\nwavread.py\nwavwrite.py\naiffread.py\naiffwrite.py\nauread.py\nauwrite.py\n...\nEffects/ Subpackage for sound effects\n__init__.py\necho.py\nsurround.py\nreverse.py\n...\nFilters/ Subpackage for filters\n__init__.py\nequalizer.py\nvocoder.py\nkaraoke.py\n...\n```\nThe __init__.py files are required to make Python treat the\ndirectories as containing packages; this is done to prevent\ndirectories with a common name, such as \"string\", from\nunintentionally hiding valid modules that occur later on the module\nsearch path. In the simplest case, __init__.py can just be an\nempty file, but it can also execute initialization code for the\npackage or set the `__all__` variable, described later.\nUsers of the package can import individual modules from the\npackage, for example:\n```text\n\nimport Sound.Effects.echo\n```\nThis loads the submodule Sound.Effects.echo. It must be referenced\nwith its full name, e.g.\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, e.g.\n```text\n\nimport Sound.Effects.echo\nimport Sound.Effects.surround\nfrom Sound.Effects import *\n```\nIn this example, the echo and surround modules are imported in the\ncurrent namespace because they are defined in the\nSound.Effects package when the `from...import` statement\nis executed. (This also works when `__all__` is defined.)\nNote that in general the practicing of importing * from a module or\npackage is frowned upon, since it often causes poorly readable code.\nHowever, it is okay to use it to save typing in interactive sessions,\nand certain modules are designed to export only names that follow\ncertain patterns.\nRemember, there is nothing wrong with using `from Package\nimport specific_submodule`! In fact, this is the\nrecommended notation unless the importing module needs to use\nsubmodules with the same name from different packages.\n## 6.4.2 Intra-package References\nThe submodules often need to refer to each other. For example, the\nsurround module might use the echo module. In fact, such references\nare so common that the `import` statement first looks in the\ncontaining package before looking in the standard module search path.\nThus, the surround module can simply use `import echo` or\n`from echo import echofilter`. If the imported module is not\nfound in the current package (the package of which the current module\nis a submodule), the `import` statement looks for a top-level module\nwith the given name.\nWhen packages are structured into subpackages (as with the\nSound package in the example), there's no shortcut to refer\nto submodules of sibling packages - the full name of the subpackage\nmust be used. For example, if the module\nSound.Filters.vocoder needs to use the echo module\nin the Sound.Effects package, it can use `from\nSound.Effects import echo`.", "python_version": "1.6", "length": 18030, "url": "https://docs.python.org/1.6/tut/node8.html"} {"title": "7. Input and Output", "text": "node8.html | tut.html | node10.html | Python Tutorial | node2.html\n---\n- 7.1 Fancier Output Formatting (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\nstring contains 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 as a C 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 a way to convert any value to a string: pass it to\nthe repr() function, or just write the value between\nreverse quotes (````). Some examples:\n```text\n\n>>> x = 10 * 3.14\n>>> y = 200*200\n>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'\n>>> print s\nThe value of x is 31.4, and y is 40000...\n>>> # Reverse quotes work on other types besides numbers:\n... p = [x, y]\n>>> ps = repr(p)\n>>> ps\n'[31.4, 40000]'\n>>> # Converting a string adds string quotes and backslashes:\n... hello = 'hello, world\\n'\n>>> hellos = `hello`\n>>> print hellos\n'hello, world\\012'\n>>> # The argument of reverse quotes may be a tuple:\n... `x, y, ('spam', 'eggs')`\n\"(31.4, 40000, ('spam', 'eggs'))\"\n```\nHere are two ways to write a table of squares and cubes:\n```text\n\n>>> import string\n>>> for x in range(1, 11):\n... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),\n... # Note trailing comma on previous line\n... print string.rjust(`x*x*x`, 4)\n...\n1 1 1\n2 4 8\n3 9 27\n4 16 64\n5 25 125\n6 36 216\n7 49 343\n8 64 512\n9 81 729\n10 100 1000\n>>> for x in range(1,11):\n... print '%2d %3d %4d' % (x, x*x, x*x*x)\n...\n1 1 1\n2 4 8\n3 9 27\n4 16 64\n5 25 125\n6 36 216\n7 49 343\n8 64 512\n9 81 729\n10 100 1000\n```\n(Note that one space between each column was added by the way\nprint works: it always adds spaces between its arguments.)\nThis example demonstrates the function string.rjust(),\nwhich right-justifies a string in a field of a given width by padding\nit with spaces on the left. There are similar functions\nstring.ljust() and string.center(). These\nfunctions do not write anything, they just return a new string. If\nthe input string is too long, they don't truncate it, but return it\nunchanged; this will mess up your column lay-out but that's usually\nbetter than the alternative, which would be lying about a value. (If\nyou really want truncation you can always add a slice operation, as in\n\"string.ljust(x, n)[0:n]\".)\nThere is another function, string.zfill(), which pads a\nnumeric string on the left with zeros. It understands about plus and\nminus signs:\n```text\n\n>>> import string\n>>> string.zfill('12', 5)\n'00012'\n>>> string.zfill('-3.14', 7)\n'-003.14'\n>>> string.zfill('3.14159265359', 5)\n'3.14159265359'\n```\nUsing the `%` operator looks like this:\n```text\n\n>>> import math\n>>> print 'The value of PI is approximately %5.3f.' % math.pi\nThe value of PI is approximately 3.142.\n```\nIf there is more than one format in the string you pass a tuple as\nright operand, e.g.\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\nan extension of C formats using the form `%(name)format`, e.g.\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.\\012'\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.\\012'\n>>> f.readline()\n'Second line of the file\\012'\n>>> f.readline()\n''\n```\n`f.readlines()` uses `f.readline()` repeatedly, and returns\na list containing all the lines of data in the file.\n```text\n\n>>> f.readlines()\n['This is the first line of the file.\\012', 'Second line of the file\\012']\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 5th 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 (innermost 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": "1.6", "length": 11504, "url": "https://docs.python.org/1.6/tut/node9.html"} {"title": "Python Tutorial", "text": "../index.html | node1.html | Python Tutorial | node2.html\n---\n# Python Tutorial\nGuido van Rossum\nFred L. Drake, Jr., editor\nBeOpen PythonLabs\nE-mail: python-docs@python.org\nSeptember 18, 2000\nRelease 1.6", "python_version": "1.6", "length": 203, "url": "https://docs.python.org/1.6/tut/tut.html"}